Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Rock, Paper, Scissors game with confirm and prompt not working as expected – how to fix?

I am learning JavaScript to create a "Rock, Paper, Scissors.” game with confirm and prompt.

I have two issues when I run the code.

  1. On prompt, when i click ok without input r,s,p, it doesn’t show "you didn’t choose r,p,s"
  2. The game is working, however, sometimes i will need to enter twice to make the result come out.
let playgame = confirm("Do you want to play game?");
if (playgame) {
  let startgame = prompt("Choose from r, p, s?");
  if (startgame) {
    let playerchoice = startgame.trim().toLowerCase();
    if (playerchoice === "r" || playerchoice === "s" || playerchoice === "p") {
      let compchoice = Math.floor(Math.random() * 3 + 1);
      let computer = compchoice;
      if (compchoice === 1) {
        computer = "r";
      }
      if (compchoice === 2) {
        computer = "s";
      }
      if (compchoice === 3) {
        computer = "p";
      }


      if (playerchoice === computer) {
        alert("tie game");
      }
      if (playerchoice === "r" && computer === "s") {
        alert("computer win");
      }
      if (playerchoice === "p" && computer === "r") {
        alert("player win");
      }
      if (playerchoice === "s" && computer === "p") {
        alert("player win");
      }


    } else {
      alert("you didn't choose r, p, s");
    }
  } else {
    alert("change you mind? not a problem");
  }
} else {
  alert("Got you, Maybe next time");
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. if you click on cancel on prompt dialog startgame variable will be null. If you do not type anything and just click on Ok, startgame variable will be "" (an empty string). In both cases, condition such as:
if (startgame)

Will be always falsy. So you can add condition like if (startgame !== null)

  1. Actuaclly you did not cover all the cases in this block.
  if (playerchoice === computer) {
    alert("tie game");
  }
  if (playerchoice === "r" && computer === "s") {
    alert("computer win");
  }
  if (playerchoice === "p" && computer === "r") {
    alert("player win");
  }
  if (playerchoice === "s" && computer === "p") {
    alert("player win");
  }

For example when computer is "r" and playerchoice is "s", etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading