I am trying to make rock paper scissors in JS, everything is working but its showing error while using else if. My game gives you ten chances to play and the one who scores more points wins the game. Currently, I am trying to make this game play between computer and user 11 time. I tried using if statements for the conditions but I don't know why the computer only played two times and then I tried using else if and then this error was coming. My code is below-
// rock paper scissor
const getRandom = (arr) => {
return arr[Math.floor(Math.random() * arr.length)];
};
console.log("Welcome to rock,paper and scissors. you will play against the computer.You will have ten chances to prove your worth")
let chances = 0
const arr = ["stone", "paper", "scissor"]
let rand = (getRandom(arr));
while (chances <= 11) {
let inp = prompt("Please enter the value")
if (inp == 'stone' && rand == 'scissor')
console.log("you won")
chances = 1
console.log(chances)
// ``````````````````````````````````````````````````````
else if (inp == 'stone' && rand == 'paper')
console.log("you lost")
chances = 1
console.log(chances)
// ``````````````````````````````````````````````````````
else if (inp == 'stone' && rand == 'stone')
console.log("its a tie!!")
chances = 1
console.log(chances)
// `````````````````````````````````````````````````````` paper
else if (inp == 'paper' && rand == 'scissor')
console.log("you lost")
chances = 1
console.log(chances)
// ``````````````````````````````````````````````````````
else if (inp == 'paper' && rand == 'stone')
console.log("you won")
chances = 1
// ``````````````````````````````````````````````````````
else if (inp == 'paper' && rand == 'paper')
console.log("its a tie")
chances = 1
// `````````````````````````````````````````````````````` scissor
else if (inp == 'scissor' && rand == 'stone')
console.log("you lost")
chances = 1
// ``````````````````````````````````````````````````````
else if (inp == 'scissor' && rand == 'paper')
console.log("you won")
chances = 1
// ``````````````````````````````````````````````````````
elseif (inp == 'scissor' && rand == 'scissor')
console.log("its a tie")
chances = 1
}
The error is -
else if (inp == 'stone' && rand == 'paper')
SyntaxError: Unexpected token 'else'
CodePudding user response:
If you want to execute more than one statement in an if
, you need to create a block, using brackets ({ … }
):
if (inp == 'stone' && rand == 'scissor') {
console.log("you won")
chances = 1
console.log(chances)
// ``````````````````````````````````````````````````````
}
else if (inp == 'stone' && rand == 'paper') {
console.log("you lost")
chances = 1
console.log(chances)
}
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else