Help with rock-paper-scissors game

Hi everyone,

In my RPS game there is a function call playGame() which will play the game until the score reaches 5 on click event. So the problem is when it reaches 5 it is not immediately firing the second function which is getWinner(). But it is waiting the button to be clicked. Is there any method which will execute the getWinner() as soon as the score hits 5.

My knowledge in js is basic so please help me out.
Thanks.

It’s because playgame is only called when you click a button thus getWinner can only check the winner BEFORE the score is updated. So in your code it’s checking the score which is 4 and increments it but can’t call getWinnter since that isn’t in your switch case (it’s only called if score is 5)

One way to fix it is to move the getWinnter function call to be in the cases but call it only if the player or computer score is 5. This is the simple fix but you should be able to adjust the code for a more elegant approach.

thanks @Jimbalin


            case (playerScore === 5 || computerScore === 5):
                return getWinner();

i tried the fix you have suggested but it completely ignores the function inside the switch case.

You don’t need another case, you put the code in your existing cases. This means in your getWinner function you need to change it a little bit to make it check if the score is 5

What you have in your case check is what you need in your if statement in the getWinner

@Jimbalin
you mean in each case in switch statement i should check if the score is 5 and if it is 5 call the getWinner function ?
or
add the if statement in getWinner and call it after switch statement is over ?

Something like this for the getWinner:

function getWinner() {
  if (playerScore === 5 ) {
    inform.textContent = "YEY!! you won the game";
  } else if (computerScore === 5) {
    inform.textContent = "OOH!! you lost the game";
  }
}

and something like this for your case statements:

      case e.target.id === "rock" && computerSelection === "paper":
        return (
          playerScore,
          ++computerScore,
          (playerPoint.textContent = playerScore),
          (compPoint.textContent = computerScore),
          (inform.textContent = "You loose! paper beats rock"),
          getWinner() //this is what you need in each case
        );

This isn’t a good solution but use this knowledge to figure a better way to solve it.

1 Like

@Jimbalin
thank you so much !!
it is finally working as i wanted.
and i will learn the better solution :slightly_smiling_face: