JS in HTML Game Won't Run [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to build a Rock/Paper/Scissor game, first-to-five, in a script tag in HTML. As far as I can tell everything is A-ok, but when I run it I receive an error message in the console at my closing script tag.
Can you folks take a look and let me know:
1.) Why I'm getting an error message at the closing script tag, and what I need to do to resolve that and have that code run as I want it to?
2.) If you have any suggestions for my code in general? I'm self taught and trying to soak up as much as possible.
//Game parameters to start
var computerScore = 0
var playerScore = 0
//Game functions
function game() {
while (computerScore >= 5 && playerScore >= 5) {
//Computer Selection
function computerPlay() {
let playerSelection = prompt("Make your choice: rock, paper, or scissors!")
let computerSelection = Math.floor(Math.random() * 3)
//Player Selection
if (playerSelection.toLowerCase() == "rock") {
var playerChoice = 0;
} else if (playerSelection.toLowerCase() == "paper") {
var playerChoice = 1;
} else if (playerSelection.toLowerCase() == "scissors") {
var playerChoice = 2;
} else {
alert("Sorry, that word isn't recognized. Please select rock, paper, or scissors.")
}
//Rock
if (computerSelection == 0) {
var computerChoice = 0
//Paper
} else if (computerSelection == 1) {
var computerChoice = 1
//Scissors
} else if (computerSelection == 2) {
var computerChoice = 2
} else {}
//OUTCOMES
if (computerSelection == 0 && playerChoice == 0 || computerSelection == 1 && playerChoice == 1 || computerSelection == 2 && playerChoice == 2) {
alert("Tie game!")
} else if (computerSelection == 1 && playerChoice == 0) {
alert("Paper beats rock. You lose!")
} else if (computerSelection == 2 && playerChoice == 0) {
alert("Rock beats scissors. You win!")
} else if (computerSelection == 0 && playerChoice == 1) {
alert("Paper beats rock. You win!")
} else if (computerSelection == 0 && playerChoice == 2) {
alert("Rock beats scissors. You lose!")
} else if (computerSelection == 1 && playerChoice == 2) {
alert("Scissors beat paper. You win!")
} else if (computerSelection == 2 && playerChoice == 1) {
alert("Scissors beat paper. You lose!")
} else {}
//Increments
if (computerSelection > playerChoice) {
computerScore++
} else if (computerSelection < playerChoice) {
playerScore++
} else {}
if (computerScore == 5 && playerScore < 5) {
alert("Computer wins, " + computerScore + " to " + playerScore + "!")
} else if (playerScore == 5 && computerScore < 5) {
alert("Player wins, " + playerScore + " to " + computerScore + "!")
} else {}
}
game()

So there's a couple things here,
Firstly your game function has no closing bracket.
Secondly your computerPlay function inside your game function is never called (and it also has no closing bracket but I would suggest removing it anyway)
Thirdly your while condition (line 12) triggers when computer/playerScore is more than 5 but on lines 7 and 8 you set them to 0. You probably want them as less than or equal to instead.
See fixed version below.
<!DOCTYPE HTML >
<html>
<body>
<script>
//Game parameters to start
var computerScore = 0
var playerScore = 0
//Game functions
function game() {
while (computerScore <= 5 && playerScore <= 5) {
//Computer Selection
let playerSelection = prompt("Make your choice: rock, paper, or scissors!")
let computerSelection = Math.floor(Math.random() * 3)
//Player Selection
if (playerSelection.toLowerCase() == "rock") {
var playerChoice = 0;
} else if (playerSelection.toLowerCase() == "paper") {
var playerChoice = 1;
} else if (playerSelection.toLowerCase() == "scissors") {
var playerChoice = 2;
} else {
alert("Sorry, that word isn't recognized. Please select rock, paper, or scissors.")
}
//Rock
if (computerSelection == 0) {
var computerChoice = 0
//Paper
} else if (computerSelection == 1) {
var computerChoice = 1
//Scissors
} else if (computerSelection == 2) {
var computerChoice = 2
} else {}
//OUTCOMES
if (computerSelection == 0 && playerChoice == 0 || computerSelection == 1 && playerChoice == 1 || computerSelection == 2 && playerChoice == 2) {
alert("Tie game!")
} else if (computerSelection == 1 && playerChoice == 0) {
alert("Paper beats rock. You lose!")
} else if (computerSelection == 2 && playerChoice == 0) {
alert("Rock beats scissors. You win!")
} else if (computerSelection == 0 && playerChoice == 1) {
alert("Paper beats rock. You win!")
} else if (computerSelection == 0 && playerChoice == 2) {
alert("Rock beats scissors. You lose!")
} else if (computerSelection == 1 && playerChoice == 2) {
alert("Scissors beat paper. You win!")
} else if (computerSelection == 2 && playerChoice == 1) {
alert("Scissors beat paper. You lose!")
} else {}
//Increments
if (computerSelection > playerChoice) {
computerScore++
} else if (computerSelection < playerChoice) {
playerScore++
} else {}
if (computerScore == 5 && playerScore < 5) {
alert("Computer wins, " + computerScore + " to " + playerScore + "!")
} else if (playerScore == 5 && computerScore < 5) {
alert("Player wins, " + playerScore + " to " + computerScore + "!")
} else {}
}
}
game();
</script>
</body>
</html>

Related

My code is not running but i have no errors

The project is about making a rock paper scissors game using functions and loops etc.
the code below is how the project looks
the first function is to get the randomized computer choice
the second function is to get the user or players choice
the third function is to play the game and check if the player won or the computer won
the final function is to create a for loop to run the third function a certain number of times to see who is the winner of the game
Been working on it since and have no idea why it doesn't work
```
function getComputerChoice() {
let values = ["rock", "paper", "scissors"];
return values[Math.floor(Math.random() * values.length)];
}
function getPlayerChoice() {
let getChoice = "rock";
let value = getChoice.trim();
let lowCase = value.toLowerCase();
let capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
while (!["Rock", "Paper", "Scissors"].includes(capitalize)) {
value = getChoice.trim();
lowCase = value.toLowerCase();
capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
}
return capitalize;
}
function playRound(playerSelection, computerSelection) {
let games = "";
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return (games =
"player loses!! " + computerSelection + " beats " + playerSelection);
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
return (games =
"player Wins!! " + playerSelection + " beats " + computerSelection);
} else if (playerSelection == computerSelection) {
return (games =
"it a tie noice " + playerSelection + " v " + computerSelection);
} else {
return (games = "euphoria");
}
}
function game() {
let playerScores = 0;
let computerScores = 0;
let computerSelection = "";
let playerSelection = "";
computerSelection = getComputerChoice();
playerSelection = getPlayerChoice();
for (let i = 0; i < 5; i++) {
if (
playRound(
"player loses!! " + computerSelection + " beats " + playerSelection
)
) {
computerScores += 1;
console.log(
"you lost this round!! boo hoo!! scores are " +
computerScores +
" v " +
playerScores
);
} else if (
playRound(
"player Wins!! " + playerSelection + " beats " + computerSelection
)
) {
playerScores += 1;
console.log(
"you Won this round!! hurray!! scores are " +
computerScores +
" v " +
playerScores
);
}
}
if (playerScores > computerScores) {
console.log("congratulations you won this round");
} else if (playerScores < computerScores) {
console.log("im sorry you lost this round");
} else {
console.log("there is a problem");
}
}
game();
```
It doesn't seem that playRound() is returning anything:
function playRound(playerSelection, computerSelection) {
let games = '';
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
games = "player loses!! " + computerSelection + " beats " + playerSelection;
// ADD RETURN HERE
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
games = "player Wins!! " + playerSelection + " beats " + computerSelection;
// ADD RETURN HERE
} else if (playerSelection == computerSelection) {
games = "it a tie noice " + playerSelection + " v " + computerSelection;
// ADD RETURN HERE
} else {
games = "euphoria";
// ADD RETURN HERE
}
}
Explanation
In your game() function definition you are checking if(playRound()). playRound is not returning anything so this is interpreted as a void function, hence, the if will always evaluate to false.

I'am making a Rock, Paper, Scissors game and the winnerCheck function doesn't work

// Score //
let computerScore = 0
let playerScore = 0
function playRound() {
//My "choice"//
let Answer = prompt(`Do you choose Rock,Paper or Scissors ?`).toLowerCase();
console.log(Answer);
function computerPlay() {
computerPlay = Math.floor(Math.random() * 3)
if(computerPlay === 0) {
console.log("rock");
} else if (computerPlay === 1) {
console.log("paper");
} else if (computerPlay === 2){
console.log("scissors");
}
}
computerPlay()
//The conditions for the game//
if(Answer == "rock" && computerPlay === 0){
return ("Draw");
}
else if(Answer == "rock" && computerPlay === 1 ){
computerScore += 1
return("You lost");
}
else if(Answer == "rock" && computerPlay === 2){
playerScore += 1
return("You won");
}
if(Answer == "paper" && computerPlay === 0 ) {
playerScore += 1
return("You Won!");
}
else if(Answer == "paper" && computerPlay === 1) {
return("Draw");
}
else if (Answer == "paper" && computerPlay === 2) {
computerScore += 1
return("You Lost!");
}
if(Answer == "scissors" && computerPlay === 0) {
computerScore += 1
return("You Lost!")
}
else if(Answer == "scissors" && computerPlay === 1) {
playerScore += 1
return("You Won!");
}
else if(Answer == "scissors" && computerPlay === 2) {
return("Draw!");
}
}
//so this fucnction doesn't work...| How can I make it work??
V//
function winnerCheck() {
if (computerScore === 5){
console.log("Player won!")
}
else if (playerScore === 5) {
console.log("Computer won!");
}
}
winnerCheck()
playRound()

The counter doesn't change its value in html page

I've put playerScore and computerScore variables in global scope. When user wins or loses these values increment by one number. They do work well. But in my HTML page they do not change dynamically.
Why my playerScore and computerScore values do not change in my HTML page, when I console.log them separately in console they are changed, but not in html page. I've tried to put them in function but it didn't work as expected.
// Selecting all the items with tag button
const buttons = document.querySelectorAll('button');
// Returns random item and assignes it to computerSelection variable
function computerPlay() {
const rps = ['rock', 'paper', 'scissors'];
let numberItem = Math.floor(Math.random() * rps.length);
computerSelection = rps[numberItem];
if (computerSelection === 'rock') {
console.log('computer selections is rock');
return computerSelection;
}
else if (computerSelection === 'paper' ) {
console.log('It is a paper!');
return computerSelection;
}
console.log('it is scissors');
return computerSelection;
}
// Plays game only five rounds;
let computerScore = 0;
let playerScore = 0;
function playRound(playerSelection, computerSelection) {
if(playerScore < 5 && computerScore < 5 ) {
if(((playerSelection == 'rock') && (computerSelection == 'paper')) || ((playerSelection == 'paper') && (computerSelection == 'scissors')) ||
((playerSelection == 'scissors') && (computerSelection == 'rock') )) {
console.log(`${computerSelection} beats ${playerSelection} the ROBOT WINS!`);
playerScore++;
return console.log(playerScore);
}
else if (((playerSelection == 'rock') && (computerSelection == 'scissors')) || ((playerSelection == 'paper') && (computerSelection == 'rock')) ||
((playerSelection == 'scissors') && (computerSelection == 'paper'))) {
console.log(` ${playerSelection} beats ${computerSelection} the PLAYER WINS!`);
computerScore++;
return console.log(computerScore);
}
return console.log('It is a DRAW');;
}
return console.log("GAME OVER!!!");
}
// returns value of clicked button and plays round
function fetchButtonValue(e) {
let itemClicked = e.target.dataset.item;
console.log(` THIS WAS CLICKED ${itemClicked}`);
return playRound(itemClicked, computerPlay());
}
// uses fetchButtonValue
buttons.forEach(function(button) {
button.addEventListener('click', fetchButtonValue);
});
// implement the vlaues to HTML but they doesn't change but the value changes when tracking them in console of browser.
let score= `
<p class = 'playerPoints'>Player: ${playerScore}</p>
<p class = 'computerPoints'>Computer: ${computerScore}</p>
`;
const divScore = document.querySelector('.score');
divScore.insertAdjacentHTML('beforebegin', scoreHTML);

How can I loop the function playRound()?

I am building my first rock paper scissors game. I have not formally done loops as yet but I am trying to apply a for loop to the playRound function so it plays five times. Sadly I am not certain where to apply it. I have tried a few ways but keep getting errors. Anyone able to take a look and provide an option. code is below.
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
}
if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
playerSelection = "rock";
computerSelection = computerPlay();
if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")
) {
return "Player Wins!";
} else if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
If I understood correctly what you want, you can do a while loop with a counter, also I improved a bit your code, making strict equality (from == to ===), and removed redundant code
let counter = 1;
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
} else if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
counter++;
if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "paper") ||
(playerSelection === "paper" && computerSelection === "rock")
) {
return "Player Wins!";
} else if (
(playerSelection === "rock" && computerSelection == "paper") ||
(playerSelection === "paper" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
while (counter < 6) {
console.log(playRound(playerSelection, computerPlay()));
}
Hope this example gives some hint on how to do good programming
// rock = 0
// paper = 1
// scissor = 2
const valueMap = {
0: 'rock',
1: 'paper',
2: 'scissor'
}
function pick() {
return Math.floor(Math.random() * 3)
}
function decide(p1, p2) {
const pool = [p1, p2]
const sortedPool = pool.sort((a, b) => b.value - a.value)
const diff = sortedPool[0].value - sortedPool[1].value
if (diff === 2) {
return sortedPool[1].name
} else if (diff === 0) {
return 'draw'
} else {
return pool.find(v => v.value === sortedPool[0].value).name
}
}
function play(times, cb) {
let n = 1
while (n <= times) {
cb(n)
n++
}
}
play(5, function(n) {
const player1 = {
name: 'Player',
value: pick()
}
const player2 = {
name: 'Computer',
value: pick()
}
const result = decide(player1, player2)
console.log(
`Game ${n}`,
`${player1.name} ${valueMap[player1.value]}`,
` vs `,
`${player2.name} ${valueMap[player2.value]}`,
`>>> Winner ${result}
`
)
})
Add loop for last 3 line
for (i=0; i<5; i++){
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
}
Edit: Please note that you have redundant call function computerPlay() inside playRound function since computer selection is passed in second argument

Need help resolving the loop issue

I recently started learning Javascript, enjoying it a lot. So, after learning some info about loops, i decided to improve a simple Rock, Scissors, Paper game. The improvement is to keep player wins and computer wins values as variables, and than loop the function until playerScore variable reaches value of 10. Im not so good at syntax yet, though trying to get the general logic and where i've made a mistake.
To reach my goal, i've declared two variables - playerScore and computerScore, their initial value is 0. After each player win or computer win i decided to add + 1 to variable.
Than start the game, i've declared a function playGame() and looped it using While. The loop seems infinite and more than that, current results are not logging to console. Any help is much appreciated, will help me to understand the logic much more than any courses i've passed.
Here's the code:
var playerScore = 0;
var computerScore = 0;
function getUserChoice() {
var userInput = prompt('Choose stone, scissors or paper');
userInput = userInput.toLowerCase();
if(userInput === 'stone' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb') {
return userInput;
}
else {
alert('Error! Choose stone, scissors or paper!');
}
}
function getComputerChoice() {
var randomNumber = Math.floor(Math.random() *3);
if(randomNumber === 1) {
return 'stone';
}
else if(randomNumber === 2) {
return 'paper';
}
else {
return 'scissors';
}
}
function determineWinner (userChoice, computerChoice) {
if(userChoice === computerChoice) {
return 'That's a tie!';
}
if(userChoice === 'stone') {
if(computerChoice === 'scissors') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
else {
if(computerChoice === 'paper') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!'
}
}
}
if(userChoice === 'paper') {
if(computerChoice === 'scissors') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'stone') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player wonи!';
}
}
}
if(userChoice === 'scissors') {
if(computerChoice === 'stone') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
}
}
if(userChoice === 'bomb') {
if(computerChoice === 'stone' || computerChoice === 'scissors' || computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
return 'Player won!';
}
}
}
while(playerScore < 10) {
function playGame() {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
playGame() = false;
}
};
playGame();
You need to move your while-loop into the function playGame().
function playGame() {
while(playerScore < 10) {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
}
}

Categories

Resources