I am learning JavaScript to create a "Rock, Paper, Scissors.” game with confirm and prompt.
I have two issues when I run the code.
- On prompt, when i click ok without input r,s,p, it doesn’t show "you didn’t choose r,p,s"
- 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");
}
>Solution :
- 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)
- 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.