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.

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

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 ?
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 === "rock" && computerSelection === "paper":
        return (
          (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

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.