1. Overview
In this short tutorial, we'll see how to create a simple “Rock-Paper-Scissors” game in Java.
2. Create Our “Rock-Paper-Scissors” Game
Our game will allow players to enter “rock”, “paper”, or “scissors” as the value of each move.
First, let's create an enum for the moves:
enum Move {
ROCK("rock"),
PAPER("paper"),
SCISSORS("scissors");
private String value;
//...
}
Then, let's create a method that generates random integers and returns the computer's move:
private static String getComputerMove() {
Random random = new Random();
int randomNumber = random.nextInt(3);
String computerMove = Move.values()[randomNumber].getValue();
System.out.println("Computer move: " + computerMove);
return computerMove;
}
And a method that checks if the player wins:
private static boolean isPlayerWin(String playerMove, String computerMove) {
return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value)
|| (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value))
|| (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value));
}
Finally, we'll use them to form a complete program:
Scanner scanner = new Scanner(System.in);
int wins = 0;
int losses = 0;
System.out.println("Welcome to Rock-Paper-Scissors! Please enter \"rock\", \"paper\", \"scissors\", or \"quit\" to exit.");
while (true) {
System.out.println("-------------------------");
System.out.print("Enter your move: ");
String playerMove = scanner.nextLine();
if (playerMove.equals("quit")) {
System.out.println("You won " + wins + " times and lost " + losses + " times.");
System.out.println("Thanks for playing! See you again.");
break;
}
if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) {
System.out.println("Your move isn't valid!");
continue;
}
String computerMove = getComputerMove();
if (playerMove.equals(computerMove)) {
System.out.println("It's a tie!");
} else if (isPlayerWin(playerMove, computerMove)) {
System.out.println("You won!");
wins++;
} else {
System.out.println("You lost!");
losses++;
}
}
As can be seen above, we use Java Scanner to read the user input value.
Let's play a bit and see the output:
Welcome to Rock-Paper-Scissors! Please enter "rock", "paper", "scissors", or "quit" to exit.
-------------------------
Enter your move: rock
Computer move: scissors
You won!
-------------------------
Enter your move: paper
Computer move: paper
It's a tie!
-------------------------
Enter your move: quit
You won 1 times and lost 0 times.
Thanks for playing! See you again.
3. Conclusion
In this quick tutorial, we've learned how to create a simple “Rock-Paper-Scissors” game in Java.
As always, the example code from this article can be found over on GitHub.
res – REST with Spring (eBook) (everywhere)