In this guide, we’ll walk through creating a simple Rock, Paper, Scissors game in Java. The game pits a user against the computer, and the winner is determined based on standard game rules.
Let’s start by recalling the basic rules of Rock, Paper, Scissors:
- Rock crushes Scissors.
- Scissors cut Paper.
- Paper covers Rock.
- If both players pick the same option, it results in a tie.
Our goal is to implement a Java program that allows the user to compete against the computer, where the winner is declared after a set number of rounds. For simplicity, we’ll use 3 rounds, and whoever wins the most rounds is the overall winner.
Structure of the Game
This game will consist of two participants: the user and the computer. Each player’s choice is independent of the other, and the result is based on the aforementioned rules.
The game runs for a fixed number of rounds, and at the end of those rounds, the player with the higher score wins. If the scores are tied, the game will end in a draw.
Step-by-Step Java Implementation
We’ll begin by defining an array to hold the available options: Rock, Paper, and Scissors. The computer’s choice will be randomly generated using Java’s Random class, and the user will input their choice through the console using the Scanner class.
Generating the Computer’s Move
To simulate the computer’s choice, we’ll generate a random number between 0 and 2, where each number corresponds to an index in our choice array. The Random class in Java allows us to easily generate a random number, and we’ll use its nextInt() method to select a random move for the computer.
Here’s how it works:
- Random class: Part of the
java.util
package, this class helps generate pseudo-random numbers. - nextInt() method: This method generates a random number between 0 (inclusive) and the specified maximum value (exclusive). For example, calling
nextInt(3)
generates a random number between 0 and 2, which we’ll use to pick the computer’s move.
Getting the User’s Move
The user will input their move using the Scanner
class, which is also part of the java.util
package. After prompting the user to make a choice, we will read their input and convert it into an index to compare with the computer’s move.
Comparing Moves and Updating Scores
The decision logic that determines the winner of each round will be handled in a separate method. Using a simple if-else
structure, we’ll compare the moves of the computer and user, update the scores, and display the outcome of each round.
If the choices are the same, the round will be a tie. Otherwise, the winner of the round is determined based on the rules of Rock, Paper, Scissors.
Displaying Results
After each round, both the computer’s and user’s choices will be displayed, along with the current scores. Once all rounds are completed, the final result is calculated based on the players’ scores. If the user’s score is higher, they win; if the computer’s score is higher, it wins. If the scores are equal, the game ends in a tie.
Java Code
import java.util.*; public class RockPaperScissorsGame { static int userScore = 0; static int computerScore = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rounds to play: "); int totalRounds = sc.nextInt(); sc.nextLine(); for (int round = 1; round <= totalRounds; round++) { System.out.println("\nRound " + round + ":"); System.out.print("Choose Rock, Paper, or Scissors: "); String userChoice = sc.nextLine().trim().toLowerCase(); if (!isValidChoice(userChoice)) { System.out.println("Invalid choice. Please try again."); round--; continue; } int userMove = convertChoiceToNumber(userChoice); int computerMove = generateComputerMove(); System.out.println("Computer chose: " + convertNumberToChoice(computerMove)); updateScores(userMove, computerMove); System.out.println("Current score - You: " + userScore + ", Computer: " + computerScore); } sc.close(); printFinalResult(); } public static boolean isValidChoice(String choice) { return choice.equals("rock") || choice.equals("paper") || choice.equals("scissors"); } public static int convertChoiceToNumber(String choice) { switch (choice) { case "rock": return 0; case "paper": return 1; case "scissors": return 2; default: return -1; } } public static String convertNumberToChoice(int move) { String[] moves = { "Rock", "Paper", "Scissors" }; return moves[move]; } public static int generateComputerMove() { Random random = new Random(); return random.nextInt(3); } public static void updateScores(int userMove, int computerMove) { if (userMove == computerMove) { System.out.println("It's a tie this round."); } else if ((userMove == 0 && computerMove == 2) || (userMove == 1 && computerMove == 0) || (userMove == 2 && computerMove == 1)) { System.out.println("You win this round!"); userScore++; } else { System.out.println("Computer wins this round."); computerScore++; } } public static void printFinalResult() { System.out.println("\nFinal Score - You: " + userScore + ", Computer: " + computerScore); if (userScore > computerScore) { System.out.println("You won the game!"); } else if (computerScore > userScore) { System.out.println("The computer won the game."); } else { System.out.println("The game ended in a tie."); } } }
Output
Enter the number of rounds to play: 3 Round 1: Choose Rock, Paper, or Scissors: Rock Computer chose: Scissors You win this round! Current score - You: 1, Computer: 0 Round 2: Choose Rock, Paper, or Scissors: Paper Computer chose: Paper It's a tie this round. Current score - You: 1, Computer: 0 Round 3: Choose Rock, Paper, or Scissors: Scissors Computer chose: Rock Computer wins this round. Current score - You: 1, Computer: 1 Final Score - You: 1, Computer: 1 The game ended in a tie.