Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing a Rock-Paper-Scissors Game in Java

Tech May 8 4

The foundation of a rock-paper-scissors game in Java lies in generating random numbers for the computer's choices. This can be achieved by first importing the java.util package and then using int r = new Random().nextInt(3); where the number 3 indicates three possible outcomes (0, 1, 2).

In the game implementation, we'll use 0, 1, and 2 to represent the three choices. If you prefer to display text representations, you can implement conditional checks to map these numbers to their corresponding choices.

The game will include the following features: ① game mechanics; ② win/loss tracking; ③ player-defined number of rounds; ④ round-by-round results; and ⑤ final statistics based on total wins.

Game Mechanics

The core game logic should be encapsulated in a separate method to keep the main function clean. The computer's choice must be generated within the game loop to ensure different random selections each round.

Use conditional statements to compare player and computer choices. For example: if(playerChoice == 0 && computerChoice == 0) else if(playerChoice == 0 && computerChoice == 1) else if(playerChoice == 0 && computerChoice == 2).

Win/Loss Tracking

Define the game method to return an integer representing the outcome: 0 for loss, 1 for win, and 2 for draw. The main function can then use these return values to track statistics.

Player-Defined Rounds

Allow the player to specify the number of rounds by storing their input and using it as the loop condition.

Round Results

Display the outcome of each round and track wins, losses, and draws separately. The number of draws can be calculated as total rounds minus wins minus losses.

Final Statistics

After all rounds are completed, compare the total wins to determine the final winner.

Implementation Code

Main Class

package games.rockpaperscissors;

import java.util.*;

public class RockPaperScissorsGame {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        GameLogic gameLogic = new GameLogic();
        int result, playerWins = 0, computerWins = 0;
        
        System.out.println("Game Rules: 0 - Rock, 1 - Paper, 2 - Scissors\nHow many rounds would you like to play?");
        int totalRounds = input.nextInt();
        
        for(int round = 1; round <= totalRounds; round++) {
            System.out.print("Round " + round + ". Your choice: ");
            int playerChoice = input.nextInt();
            int computerChoice = new Random().nextInt(3);
            
            switch (playerChoice) {
                case 0:
                case 1:
                case 2:
                    result = gameLogic.determineWinner(playerChoice, computerChoice);
                    if (result == 1)
                        playerWins++;
                    else if(result == 0)
                        computerWins++;
                    break;
                default:
                    System.out.println("Invalid input! Please enter 0, 1, or 2.");
                    round--;
                    break;
            }
        }
        
        System.out.println("Final Results:");
        System.out.println("Your wins: " + playerWins);
        System.out.println("Computer wins: " + computerWins);
        System.out.println("Draws: " + (totalRounds - playerWins - computerWins));
        
        if(playerWins > computerWins)
            System.out.println("Congratulations! You won the game!");
        else if(computerWins > playerWins)
            System.out.println("The computer won this time. Try again!");
        else
            System.out.println("The game ended in a tie!");
    }
}

Game Logic Class

package games.rockpaperscissors;

public class GameLogic {
    public int determineWinner(int player, int computer) {
        if(player == computer) {
            System.out.println("Computer chose " + getChoiceName(computer) + ". It's a draw!");
            return 2; // Draw
        }
        
        // Player wins scenarios
        if((player == 0 && computer == 2) ||  // Rock beats Scissors
           (player == 1 && computer == 0) ||  // Paper beats Rock
           (player == 2 && computer == 1)) {  // Scissors beats Paper
            System.out.println("Computer chose " + getChoiceName(computer) + ". You won this round!");
            return 1; // Player wins
        }
        
        // Computer wins scenarios
        System.out.println("Computer chose " + getChoiceName(computer) + ". Computer won this round!");
        return 0; // Computer wins
    }
    
    private String getChoiceName(int choice) {
        switch(choice) {
            case 0: return "Rock";
            case 1: return "Paper";
            case 2: return "Scissors";
            default: return "Unknown";
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.