Skip to content

Instantly share code, notes, and snippets.

@gitdagray
Created October 8, 2020 18:29
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gitdagray/a709dba6c46fcd2b239a8a5679af4e0e to your computer and use it in GitHub Desktop.
Save gitdagray/a709dba6c46fcd2b239a8a5679af4e0e to your computer and use it in GitHub Desktop.
Rock_Paper_Scissors_v2
// Rock, Paper, Scissors: Refactored with While Loop and an Array
let playGame = confirm("Shall we play rock, paper, or scissors?");
if (playGame) {
//play
while (playGame) {
const playerChoice = prompt("Please enter rock, paper, or scissors.");
if (playerChoice || playerChoice === "") {
const playerOne = playerChoice.trim().toLowerCase();
if (
playerOne === "rock" ||
playerOne === "paper" ||
playerOne === "scissors"
) {
const computerChoice = Math.floor(Math.random() * 3);
const rpsArray = ["rock", "paper", "scissors"];
const computer = rpsArray[computerChoice];
const result =
playerOne === computer
? "Tie game!"
: playerOne === "rock" && computer === "paper"
? `playerOne: ${playerOne}\nComputer: ${computer}\nComputer wins!`
: playerOne === "paper" && computer === "scissors"
? `playerOne: ${playerOne}\nComputer: ${computer}\nComputer wins!`
: playerOne === "scissors" && computer === "rock"
? `playerOne: ${playerOne}\nComputer: ${computer}\nComputer wins!`
: `playerOne: ${playerOne}\nComputer: ${computer}\nplayerOne wins!`;
alert(result);
playGame = confirm("Play Again?");
if (!playGame) alert("Ok, thanks for playing.");
continue;
} else {
alert("You didn't enter rock, paper, or scissors.");
continue;
}
} else {
alert("I guess you changed your mind. Maybe next time.");
break;
}
}
} else {
alert("Ok, maybe next time.");
}
@devlover717
Copy link

Sir, on line 29 why you used playGame instead of playAgain ? whats the point and benefit of this?

@harshraj78
Copy link

@devlover717 there is a while loop present, and it has a parameter of playGame so, as on line 29 its for the user to ask playAgain, if they select ok, then while loop gets an argument as TRUE, so game restarts.

@Fasel-Ergando
Copy link

Fasel-Ergando commented Oct 20, 2023

Thank u again ☺:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment