I made some major headway today on JavaScript but I’ve also encountered some challenges. I think it is slowly starting to sink in. I understand how to use JavaScript to basically update the DOM. But I am having trouble with some aspects of my code. Below represents the game of Rock, Paper, Scissors. However, this code does not work because it goes into an infinite loop without ever loading the user interface.
function getComputerChoice() {
let randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return "rock";
break;
case 1:
return "paper";
break;
case 2:
return "scissors";
break;
}
}
function playRound(humanChoice, computerChoice) {
if (humanChoice == "rock" && computerChoice == "paper") {
computerScore++;
return "You lose! Paper beats rock";
} else if (humanChoice == "rock" && computerChoice == "scissors") {
humanScore++;
return "You win! Rock beats Scissors";
} else if (humanChoice == "rock" && computerChoice == "rock") {
return "It's a tie!";
} else if (humanChoice == "paper" && computerChoice == "scissors") {
computerScore++;
return "You lose! Scissors beats Paper";
} else if (humanChoice == "paper" && computerChoice == "rock") {
humanScore++;
return "You win! Paper beats Rock";
} else if (humanChoice == "paper" && computerChoice == "paper") {
return "It's a tie!";
} else if (humanChoice == "scissors" && computerChoice == "scissors") {
return "It's a tie!";
} else if (humanChoice == "scissors" && computerChoice == "rock") {
computerScore++;
return "You lose! Rock beats Scissors";
} else if (humanChoice == "scissors" && computerChoice == "paper") {
humanScore++;
return "You win! Scissors beats Paper";
}
}
const rockButton = document.querySelector('.rock');
const paperButton = document.querySelector('.paper');
const scissorsButton = document.querySelector('.scissors');
const message = document.querySelector('.message');
let round = "";
let humanScore = 0;
let computerScore = 0;
let gameCount = 0;
while (gameCount <= 5) {
rockButton.addEventListener('click', (event) => {
const computerChoice = getComputerChoice();
round = playRound('rock', computerChoice);
message.textContent = `Human Score: ${humanScore}\nComputer Score: ${computerScore}\n${round}`;
gameCount++;
});
paperButton.addEventListener('click', (event) => {
const computerChoice = getComputerChoice();
round = playRound('paper', computerChoice);
message.textContent = `Human Score: ${humanScore}\nComputer Score: ${computerScore}\n${round}`;
gameCount++;
});
scissorsButton.addEventListener('click', (event) => {
const computerChoice = getComputerChoice();
round = playRound('paper', computerChoice);
message.textContent = `Human Score: ${humanScore}\nComputer Score: ${computerScore}\n${round}`;
gameCount++;
});
}
I am stymied by this because I want to limit the number of times the game is played. I just don’t know how. I am stuck and awaiting help on the forums.