This is my code
let w = 0;
let l = 0;
function playRound (playerSelection, computorSelection) {
if (playerSelection == computorSelection) {
console.log("You tied, try again.");
} else if ((playerSelection - computorSelection + 3) % 3 == 1) {
console.log("You win!");
w++;
} else {
console.log("You lose!");
l++;
}
}
function game() {
playerSelection();
playRound();
if (w == 5) {
console.log("You've won 5 times! Well done!");
} else if (l == 5) {
console.log("You've lost 5 times. Too bad.");
} else {
playerSelection();
playRound();
}
}
There is more code above this but that code all works fine. I want the playRound function to change the value of l and w depending on if the round is a win or a loss and the game function to continue the game until either 5 losses or 5 wins have happened.
When I call the game function the code starts correct, but it always gives a tie as the first round, starts it again and returns undefined. What am I doing wrong?
In your game
function, you're calling playRound()
without passing any arguments to it.
However, playRound
accepts two, playerSelection
and computorSelection
, and in its first line compares the two:
if (playerSelection == computorSelection) {
Since both values are undefined
(due to their not being passed in), that condition evaluates to true
and the function declares a tie and does not increment w
or l
.