Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Created February 14, 2022 11:39
Show Gist options
  • Save ayoubzulfiqar/f01f1ed6709e9cc677c7eb1d87d5b25d to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/f01f1ed6709e9cc677c7eb1d87d5b25d to your computer and use it in GitHub Desktop.
Rock-Paper-Scissors game against computer
void main(){
while (true) {
print("Rock, Paper, Scissors Shoot!");
String playerMove = getPlayerMove();
if (playerMove == "Quit") {
return;
}
print("You played $playerMove");
String computerMove = getComputerMove();
print("Computer played $computerMove");
print(whoWon(playerMove, computerMove));
}
}
String getPlayerMove() {
print("Would you like (R)ock, (P)aper, or (S)cissors?");
String selection = stdin.readLineSync()!.toUpperCase();
switch (selection) {
case "R":
return "Rock";
case "P":
return "Paper";
case "S":
return "Scissors";
default:
return "Quit";
}
}
String getComputerMove() {
Random rand = new Random();
int move = rand.nextInt(3);
switch (move) {
case 0:
return "Rock";
case 1:
return "Paper";
case 2:
return "Scissors";
default:
break;
}
throw Exception();
}
String whoWon(String playerMove, String computerMove) {
if (playerMove == computerMove) {
//if the same, it's a tie
return "Tie";
} else if (playerMove == "Rock" && computerMove == "Scissors") {
return "You Win!";
} else if (playerMove == "Scissors" && computerMove == "Paper") {
return "You Win!";
} else if (playerMove == "Paper" && computerMove == "Rock") {
return "You Win!";
} else {
return "Computer Wins!";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment