In this article, we’ll explore how to implement the "Rock, Paper, Scissors" game in Java, with a demo video provided below. You can download the source code from the included zip file.
The Rock, Paper, Scissors game is a simple hand game usually played between two people, where each player simultaneously forms one of three shapes with their hand: rock, paper, or scissors. In programming, we can simulate this game in Java by comparing a user’s choice against a computer-generated choice and determining the winner based on the game rules.
Game Rules
- Rock crushes Scissors.
- Scissors cut Paper.
- Paper covers Rock.
Each player chooses one of these options. The winner is determined based on the rules above. If both players choose the same option, it’s a tie.
Implementing the Game in Java
Let's break down the steps required to code this game.
Step 1. Import Required Packages
To handle user input, we'll use Scanner from the java.util package.
import java.util.Random;
import java.util.Scanner;
Step 2. Define the Game Logic
We’ll create the main RockPaperScissors class, which will contain the game logic.
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// Game continues until the player decides to quit
while (true) {
System.out.println("Enter your choice (Rock, Paper, or Scissors). To quit, type 'quit': ");
String userChoice = scanner.nextLine().toLowerCase();
// Check if the user wants to quit
if (userChoice.equals("quit")) {
System.out.println("Thanks for playing!");
break;
}
// Validate user input
if (!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Invalid input. Please try again.");
continue;
}
// Generate computer choice
String[] choices = {"rock", "paper", "scissors"};
String computerChoice = choices[random.nextInt(3)];
System.out.println("Computer chose: " + computerChoice);
// Determine the winner
if (userChoice.equals(computerChoice)) {
System.out.println("It's a tie!");
} else if ((userChoice.equals("rock") && computerChoice.equals("scissors")) ||
(userChoice.equals("scissors") && computerChoice.equals("paper")) ||
(userChoice.equals("paper") && computerChoice.equals("rock"))) {
System.out.println("You win!");
} else {
System.out.println("You lose.");
}
}
scanner.close();
}
}
Code explanation
The game asks the user's choice (rock, paper, or scissors). The program uses the Random class to randomly generate the computer's choice. The game logic checks each possible outcome (win, lose, or tie) based on the user’s choice and the computer’s choice. The game runs in a while loop, so after each round, it asks the user if they want to play again or quit by typing "quit".
Output