complete beginner here and I've been doing the foundations course on Odin Project and more specifically the Rock, paper, scissors game in javascript. I've been trying to do the game function with loops to repeat the rounds until someone wins and had some issues. While fiddling with the loops and changing from while to if and for, I was about to give up and ask here. However, I made it kinda work, not completely true though since you can't cancel the game and it doesn't really have 5 rounds but uses a different approach. This is my code:
Edit: The second to last sentence was basically my question, I've tried approaches to making rounds, making a variable rounds, and then putting it into for loop, however the loop counts the rounds to five without making sure player and computer score have reached their goal, and the fact I've forgot to add the option for a tie. I've tried fixing that by adding conditionals into it but it got messy really fast and I got lost and deleted that and made this. The cancel option never really came on my mind until when I started making this question
let playerScore = 0;
let computerScore = 0;
// gives a random value from the array
function computerPlay() {
let choice = ['rock', 'paper', 'scissors'];
let randomPlay = Math.floor(Math.random() * choice.length);
return choice[randomPlay]
}
// plays a round of a game
function round() {
let computerChoice = computerPlay();
let playerChoice = prompt('What do you choose?', ''.toLowerCase());
if (playerChoice === 'rock' & computerChoice === 'paper') {
computerScore += 1;
alert('You lose, paper beats rock!');
} else if (playerChoice === 'paper' & computerChoice === 'scissors') {
computerScore += 1;
alert('You lose, scissors beat paper!');
} else if (playerChoice === 'scissors' & computerChoice === 'paper') {
computerScore += 1;
alert('You lose, rock beats scissors!');
} else if (playerChoice === 'rock' & computerChoice === 'scissors') {
playerScore += 1;
alert('You win, rock beats scissors!');
} else if (playerChoice === 'paper' & computerChoice === 'rock') {
playerScore += 1;
alert('You win, paper beats rock!');
} else if (playerChoice === 'scissors' & computerChoice === 'paper') {
playerScore += 1;
alert('You win, scissors beat paper!');
}
if (playerScore >= 3) {
alert('You win the game!')
} else if (computerScore >= 3) {
alert('Computer wins the game!')
}
}
//repeats rounds until someone wins the game
function game() {
for (i = 1; playerScore < 3 && computerScore < 3; i++) {
round();
}
}
game();
I would recommend using a array system for Rock paper scissor as it is more concise and fast than using loops.
const checker_arr = [['Tie', 'Lost', 'Won'],['Won', 'Tie', 'Lost'],['Lost', 'Won', 'Tie']];
So now if the user chooses 0(which is rock) and the computer chose 2(scissor) then the user win.
Github - Check this out for live code