I'm trying to build a rock scissors paper game And I need to add a scoreboard. So I need the score to increase by 1 every time the player or the computer win a round. How do I get it to do this?
Here's the code I wrote but it is not updating the scoreboard on the screen
function scoreboard() {
computerScore = parseInt(computerScore.textContent);
playerScore = parseInt(playerScore.textContent);
if(playerScore < 5 || computerScore < 5) {
if(playRound(playerSelection, computerSelection) == 'You win! Paper beats Rock' || playRound(playerSelection, computerSelection) == 'You win! Rock beats Scissors' || playRound(playerSelection, computerSelection) == 'You win! Scissors beats Paper') {
return playerScore = 1
} else if(playRound(playerSelection, computerSelection) == 'You lose! Paper beats Rock' || playRound(playerSelection, computerSelection) == 'You lose! Rock beats Scissors' || playRound(playerSelection, computerSelection) == 'You lose! Scissors beats Paper') {
return computerScore = 1
}
} else if(playerScore == 5) {
console.log('Congratulations!');
} else if(computerScore == 5) {
console.log('You lose!');
}
}
Here's is the Html:
<div >
<p> Score Board: </p>
<div >
<P> Computer: <span > 0 </span></P>
<p> Player: <span > 0 </span></p>
</div>
</div>
CodePudding user response:
You can define a function for updating the scoreboard and update text content in it:
function updateScoreboard(computerScore, playerScore) {
document.querySelector('.computer_score').textContent = computerScore;
document.querySelector('.player_score').textContent = playerScore;
}
And then call it after the if-else statement:
if(playerScore < 5 || computerScore < 5) {
if(playRound(playerSelection, computerSelection) == 'You win! Paper beats Rock' || playRound(playerSelection, computerSelection) == 'You win! Rock beats Scissors' || playRound(playerSelection, computerSelection) == 'You win! Scissors beats Paper') {
playerScore = 1 // removed the return statement here
} else if(playRound(playerSelection, computerSelection) == 'You lose! Paper beats Rock' || playRound(playerSelection, computerSelection) == 'You lose! Rock beats Scissors' || playRound(playerSelection, computerSelection) == 'You lose! Scissors beats Paper') {
computerScore = 1 // removed the return statement here
}
return updateScoreboard(computerScore, playerScore);
} else if(playerScore == 5) {
console.log('Congratulations!');
} else if(computerScore == 5) {
console.log('You lose!');
}