Rock Paper Scissors Game in java

Discover how to create a Rock Paper Scissors Game in Java with a fun twist! In this post, we’ll guide you through building the extended Rock-Paper-Scissors-Lizard-Spock version, inspired by The Big Bang Theory. You’ll learn to design an engaging and user-friendly GUI using Java Swing while mastering the game logic step by step.


Overview

This Java program implements the Rock Paper Scissors game in Java with an interactive and user-friendly GUI built using Java Swing. The game extends the classic Rock-Paper-Scissors rules by adding Lizard and Spock, increasing complexity and fun. It features buttons for player choices, real-time result display, and a dynamic scoreboard that tracks wins, losses, and ties. The computer’s moves are generated randomly to ensure unpredictability, and the game logic is implemented with clear, structured conditions. This project serves as an excellent example of GUI development in Java, demonstrating event handling, real-time updates, and modular design for easy scalability.


  • You can get the code of Rock Paper Scissors Game in javaform my GUI repository

Features of the Game

Before diving into the implementation of Rock Paper Scissors Game in java, let’s take a look at the key features of the game:

  1. Interactive GUI:
  • The game features a clean and modern GUI with buttons for user choices, a result display, and a game history panel.
  • The interface is intuitive and user-friendly, making it easy for players to interact with the game.
  1. Dynamic Feedback:
  • The selected choice button changes color to dark blue, providing visual feedback to the user.
  • The result of each round is displayed prominently with color-coded feedback:
    • Dark Blue: User wins.
    • Red: Computer wins.
    • Orange: Tie.
  1. Game History:
  • A scrollable history panel keeps track of all rounds, including the user’s and computer’s choices and the outcome.
  • This allows players to review the progress of the game at any time.
  1. Reset and Rules:
  • The game includes a Reset Game button to start over and a Rules button to display the game rules in a dialog box.
  1. Customizable Winning Condition:
  • The user can set the number of wins required to declare the overall winner.
Rock Paper Scissors Game in java

How the Game Works

Here’s a step-by-step breakdown of how the game works:

  1. Set Maximum Wins:
  • The user sets the number of wins required to declare the overall winner by entering a number in the text field.
  1. Select Choice:
  • The user selects one of the five choices (Rock, Paper, Scissors, Lizard, Spock) by clicking the corresponding button.
  • The selected button changes color to dark blue to indicate the choice.
  1. Play Round:
  • The user clicks the Play Round button to play the round.
  • The computer randomly selects a choice, and the winner is determined based on the game rules.
  1. View Result:
  • The result of the round is displayed prominently in the result panel.
  • The scores are updated, and the history panel is updated with the details of the round.
  1. Game History:
  • The history of all rounds is displayed in a scrollable panel, allowing the user to review the progress of the game.
  1. Reset Game:
  • The user can reset the game at any time by clicking the Reset Game button.
  • This clears the scores, history, and resets the game to its initial state.
  1. View Rules:
  • The user can view the game rules by clicking the Rules button.
  • The rules are displayed in a dialog box.
Rock Paper Scissors Game in java

Design and Implementation

1. Setting Up the GUI

The game GUI is built using Java’s Swing library. The main components include:

  • Top Panel: Displays the welcome message and the current score.
  • Choice Buttons: Buttons for Rock, Paper, Scissors, Lizard, and Spock.
  • Result Panel: Displays the result of each round.
  • History Panel: A scrollable text area that shows the history of all rounds.
  • Bottom Panel: Contains the Play Round, Reset Game, and Rules buttons, as well as a text field for setting the maximum number of wins.

The GUI is designed to be clean and modern, with a consistent color scheme and intuitive layout. The choice buttons are styled with hover effects, and the result panel provides clear feedback on the outcome of each round.

2. Handling User Input and Game Logic

The game logic is handled in the playRound() method. The user’s choice is compared with the computer’s random choice, and the winner is determined based on the game rules. The rules for determining the winner are as follows:

  • Rock crushes Scissors and Lizard.
  • Paper covers Rock and disproves Spock.
  • Scissors cut Paper and decapitate Lizard.
  • Lizard eats Paper and poisons Spock.
  • Spock vaporizes Rock and smashes Scissors.

The result of each round is displayed in the result panel, and the scores are updated accordingly. The history panel is also updated with the details of the round.

3. Game Rules

The game rules of are displayed in a dialog box when the user clicks the Rules button. The rules explain how each choice interacts with the others and how the winner is determined.

Rock Paper Scissors Game in java

4. Reset Functionality in Java

The Reset Game button allows the user to reset the game at any time. This clears the scores, history, and resets the game to its initial state. The choice buttons are also reset to their default colors.



Conclusion

This Rock Paper Scissors game in java is a fun and interactive way to explore Java’s Swing library and GUI development. The game features a modern and visually appealing interface, dynamic feedback, and a comprehensive history panel. Whether you’re a beginner or an experienced Java developer, this project is a great way to practice your skills and have fun at the same time.


Source Code of Rock Paper Scissors Game in java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class RPSLSGame extends JFrame {
    private int userScore = 0;
    private int computerScore = 0;
    private int rounds = 0;
    private int maxWins;

    private JLabel roundLabel, scoreLabel, messageLabel, resultLabel;
    private JButton rockButton, paperButton, scissorsButton, lizardButton, spockButton;
    private JButton playButton, resetButton, rulesButton;
    private JTextField maxWinsField;
    private JTextArea historyArea;
    private List<String> historyList;
    private int userChoice = -1; // Stores the user's choice
    private JButton lastSelectedButton = null; // Tracks the last selected choice button

    public RPSLSGame() {
        setTitle("Rock, Paper, Scissors, Lizard, Spock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 700);
        setLayout(new BorderLayout());
        getContentPane().setBackground(new Color(240, 240, 240)); // Light gray background

        // Initialize history list
        historyList = new ArrayList<>();

        // Top Panel
        JPanel topPanel = new JPanel(new GridLayout(2, 1));
        topPanel.setBackground(new Color(70, 130, 180)); // Steel blue background
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        roundLabel = new JLabel("Welcome! Set the number of wins to declare the overall winner.", JLabel.CENTER);
        roundLabel.setFont(new Font("Serif", Font.BOLD, 18));
        roundLabel.setForeground(Color.WHITE);
        topPanel.add(roundLabel);

        scoreLabel = new JLabel("Score: You 0 - 0 Computer", JLabel.CENTER);
        scoreLabel.setFont(new Font("Serif", Font.BOLD, 16));
        scoreLabel.setForeground(Color.WHITE);
        topPanel.add(scoreLabel);

        add(topPanel, BorderLayout.NORTH);

        // Center Panel
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setBackground(new Color(240, 240, 240)); // Light gray background
        centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // Choice Buttons Panel
        JPanel choicePanel = new JPanel(new GridLayout(1, 5, 10, 10));
        choicePanel.setBackground(new Color(240, 240, 240)); // Light gray background

        rockButton = createChoiceButton("Rock");
        paperButton = createChoiceButton("Paper");
        scissorsButton = createChoiceButton("Scissors");
        lizardButton = createChoiceButton("Lizard");
        spockButton = createChoiceButton("Spock");

        // Add action listeners to choice buttons
        rockButton.addActionListener(e -> selectChoice(1, rockButton));
        paperButton.addActionListener(e -> selectChoice(2, paperButton));
        scissorsButton.addActionListener(e -> selectChoice(3, scissorsButton));
        lizardButton.addActionListener(e -> selectChoice(4, lizardButton));
        spockButton.addActionListener(e -> selectChoice(5, spockButton));

        choicePanel.add(rockButton);
        choicePanel.add(paperButton);
        choicePanel.add(scissorsButton);
        choicePanel.add(lizardButton);
        choicePanel.add(spockButton);

        centerPanel.add(choicePanel, BorderLayout.NORTH);

        // Result Panel
        JPanel resultPanel = new JPanel();
        resultPanel.setBackground(new Color(240, 240, 240)); // Light gray background
        resultPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        resultLabel = new JLabel("", JLabel.CENTER);
        resultLabel.setFont(new Font("Serif", Font.BOLD, 20));
        resultLabel.setForeground(new Color(0, 0, 139)); // Dark blue text
        resultPanel.add(resultLabel);

        centerPanel.add(resultPanel, BorderLayout.CENTER);

        // History Panel
        historyArea = new JTextArea();
        historyArea.setEditable(false);
        historyArea.setFont(new Font("SansSerif", Font.PLAIN, 14));
        historyArea.setBackground(new Color(255, 255, 255)); // White background
        historyArea.setForeground(new Color(50, 50, 50)); // Dark gray text
        JScrollPane historyScrollPane = new JScrollPane(historyArea);
        historyScrollPane.setBorder(BorderFactory.createTitledBorder("Game History"));
        historyScrollPane.setPreferredSize(new Dimension(700, 150)); // Increased height for history area
        centerPanel.add(historyScrollPane, BorderLayout.SOUTH);

        add(centerPanel, BorderLayout.CENTER);

        // Bottom Panel
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(new Color(240, 240, 240)); // Light gray background
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        maxWinsField = new JTextField(5);
        maxWinsField.setFont(new Font("SansSerif", Font.PLAIN, 14));
        bottomPanel.add(new JLabel("Enter max wins: "));
        bottomPanel.add(maxWinsField);

        playButton = createStyledButton("Play Round");
        resetButton = createStyledButton("Reset Game");
        rulesButton = createStyledButton("Rules");

        bottomPanel.add(playButton);
        bottomPanel.add(resetButton);
        bottomPanel.add(rulesButton);

        add(bottomPanel, BorderLayout.SOUTH);

        // Message Label
        messageLabel = new JLabel("", JLabel.CENTER);
        messageLabel.setFont(new Font("Arial", Font.BOLD, 14));
        messageLabel.setForeground(new Color(70, 130, 180)); // Steel blue text
        add(messageLabel, BorderLayout.WEST);

        // Action Listeners
        playButton.addActionListener(e -> playRound());
        resetButton.addActionListener(e -> resetGame());
        rulesButton.addActionListener(e -> showRules());
    }

    private JButton createChoiceButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("SansSerif", Font.BOLD, 14));
        button.setBackground(new Color(70, 130, 180)); // Steel blue background
        button.setForeground(Color.WHITE); // White text
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // Hover effect
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button != lastSelectedButton) {
                    button.setBackground(new Color(100, 150, 200)); // Lighter blue on hover
                }
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button != lastSelectedButton) {
                    button.setBackground(new Color(70, 130, 180)); // Original color on exit
                }
            }
        });

        return button;
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("SansSerif", Font.BOLD, 14));
        button.setBackground(new Color(70, 130, 180)); // Steel blue background
        button.setForeground(Color.WHITE); // White text
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // Hover effect
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(100, 150, 200)); // Lighter blue on hover
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(70, 130, 180)); // Original color on exit
            }
        });

        return button;
    }

    private void selectChoice(int choice, JButton button) {
        // Reset the color of the previously selected button
        if (lastSelectedButton != null) {
            lastSelectedButton.setBackground(new Color(70, 130, 180)); // Reset to original color
        }

        // Set the new choice and change the button color
        userChoice = choice;
        button.setBackground(new Color(0, 0, 139)); // Dark blue color for selected button
        lastSelectedButton = button;
    }

    private String getChoiceName(int choice) {
        switch (choice) {
            case 1: return "Rock";
            case 2: return "Paper";
            case 3: return "Scissors";
            case 4: return "Lizard";
            case 5: return "Spock";
            default: return "Invalid";
        }
    }

    private int determineWinner(int userChoice, int computerChoice) {
        if (userChoice == computerChoice) {
            return 0; // Tie
        }
        switch (userChoice) {
            case 1: return (computerChoice == 3 || computerChoice == 4) ? 1 : -1; // Rock
            case 2: return (computerChoice == 1 || computerChoice == 5) ? 1 : -1; // Paper
            case 3: return (computerChoice == 2 || computerChoice == 4) ? 1 : -1; // Scissors
            case 4: return (computerChoice == 2 || computerChoice == 5) ? 1 : -1; // Lizard
            case 5: return (computerChoice == 1 || computerChoice == 3) ? 1 : -1; // Spock
        }
        return -1; // Computer wins
    }

    private void playRound() {
        if (maxWinsField.getText().isEmpty()) {
            messageLabel.setText("Please set the number of wins first.");
            return;
        }

        try {
            maxWins = Integer.parseInt(maxWinsField.getText());
        } catch (NumberFormatException ex) {
            messageLabel.setText("Invalid number of wins. Enter a valid integer.");
            return;
        }

        if (userChoice == -1) {
            messageLabel.setText("Please select a choice.");
            return;
        }

        int computerChoice = new Random().nextInt(5) + 1;

        String userChoiceName = getChoiceName(userChoice);
        String computerChoiceName = getChoiceName(computerChoice);

        int result = determineWinner(userChoice, computerChoice);
        rounds++;

        roundLabel.setText("Round " + rounds);

        if (result == 0) {
            resultLabel.setText("<html><center>It's a tie!<br>Both chose " + userChoiceName + ".</center></html>");
            resultLabel.setForeground(Color.ORANGE); // Orange for tie
        } else if (result == 1) {
            userScore++;
            resultLabel.setText("<html><center>You win this round!<br>" + userChoiceName + " beats " + computerChoiceName + ".</center></html>");
            resultLabel.setForeground(new Color(0, 0, 139)); // Dark blue for win
        } else {
            computerScore++;
            resultLabel.setText("<html><center>Computer wins this round!<br>" + computerChoiceName + " beats " + userChoiceName + ".</center></html>");
            resultLabel.setForeground(Color.RED); // Red for loss
        }

        scoreLabel.setText("Score: You " + userScore + " - " + computerScore + " Computer");

        // Update history
        String historyEntry = "Round " + rounds + ": You chose " + userChoiceName + ", Computer chose " + computerChoiceName + ". " + messageLabel.getText();
        historyList.add(historyEntry);
        historyArea.setText(String.join("\n", historyList));

        if (userScore >= maxWins || computerScore >= maxWins) {
            if (userScore > computerScore) {
                resultLabel.setText("<html><center>Congratulations!<br>You won the series!</center></html>");
                resultLabel.setForeground(new Color(0, 0, 139)); // Dark blue for win
            } else {
                resultLabel.setText("<html><center>Computer won the series.<br>Better luck next time!</center></html>");
                resultLabel.setForeground(Color.RED); // Red for loss
            }
            disableChoiceButtons();
        }

        // Reset user choice for the next round
        userChoice = -1;
        if (lastSelectedButton != null) {
            lastSelectedButton.setBackground(new Color(70, 130, 180)); // Reset to original color
            lastSelectedButton = null;
        }
    }

    private void disableChoiceButtons() {
        rockButton.setEnabled(false);
        paperButton.setEnabled(false);
        scissorsButton.setEnabled(false);
        lizardButton.setEnabled(false);
        spockButton.setEnabled(false);
    }

    private void resetGame() {
        userScore = 0;
        computerScore = 0;
        rounds = 0;
        maxWins = 0;
        maxWinsField.setText("");
        roundLabel.setText("Welcome! Set the number of wins to declare the overall winner.");
        scoreLabel.setText("Score: You 0 - 0 Computer");
        messageLabel.setText("");
        resultLabel.setText("");
        historyList.clear();
        historyArea.setText("");
        userChoice = -1;

        // Re-enable choice buttons
        rockButton.setEnabled(true);
        paperButton.setEnabled(true);
        scissorsButton.setEnabled(true);
        lizardButton.setEnabled(true);
        spockButton.setEnabled(true);

        // Reset button colors
        rockButton.setBackground(new Color(70, 130, 180));
        paperButton.setBackground(new Color(70, 130, 180));
        scissorsButton.setBackground(new Color(70, 130, 180));
        lizardButton.setBackground(new Color(70, 130, 180));
        spockButton.setBackground(new Color(70, 130, 180));
    }

    private void showRules() {
        String rules = "Rules of Rock, Paper, Scissors, Lizard, Spock:\n\n" +
                "1. Rock crushes Scissors and Lizard\n" +
                "2. Paper covers Rock and disproves Spock\n" +
                "3. Scissors cut Paper and decapitate Lizard\n" +
                "4. Lizard eats Paper and poisons Spock\n" +
                "5. Spock vaporizes Rock and smashes Scissors\n\n" +
                "First to reach the set number of wins wins the game!";
        JOptionPane.showMessageDialog(this, rules, "Game Rules", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            RPSLSGame game = new RPSLSGame();
            game.setVisible(true);
        });
    }
}

Leave a comment