Here’s how to create a simple Rock-Paper-Scissors game in Java using the Swing library.
In this game, the user can choose Rock, Paper, or Scissors, and the computer randomly chooses one of the three.
Based on the standard rules of Rock-Paper-Scissors, the program then displays the choices and the result (Win, Lose, or Draw).
Code
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class RockPaperScissorsGame extends JFrame { private JLabel promptLabel, resultLabel, computerChoiceLabel, userChoiceLabel; private JButton rockButton, paperButton, scissorsButton; private String[] choices = {"Rock", "Paper", "Scissors"}; private Random random = new Random(); public RockPaperScissorsGame() { // Set up the JFrame setTitle("Rock Paper Scissors"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); // Prompt label promptLabel = new JLabel("Choose Rock, Paper, or Scissors:"); add(promptLabel); // Buttons for user choice rockButton = new JButton("Rock"); paperButton = new JButton("Paper"); scissorsButton = new JButton("Scissors"); add(rockButton); add(paperButton); add(scissorsButton); // Labels to display the choices and result userChoiceLabel = new JLabel("You chose: "); computerChoiceLabel = new JLabel("Computer chose: "); resultLabel = new JLabel("Result: "); add(userChoiceLabel); add(computerChoiceLabel); add(resultLabel); // Add action listeners to buttons rockButton.addActionListener(new ButtonClickListener("Rock")); paperButton.addActionListener(new ButtonClickListener("Paper")); scissorsButton.addActionListener(new ButtonClickListener("Scissors")); } private class ButtonClickListener implements ActionListener { private String playerChoice; public ButtonClickListener(String playerChoice) { this.playerChoice = playerChoice; } @Override public void actionPerformed(ActionEvent e) { String computerChoice = choices[random.nextInt(3)]; // Random choice for computer userChoiceLabel.setText("You chose: " + playerChoice); computerChoiceLabel.setText("Computer chose: " + computerChoice); resultLabel.setText("Result: " + determineWinner(playerChoice, computerChoice)); } } private String determineWinner(String playerChoice, String computerChoice) { if (playerChoice.equals(computerChoice)) { return "It's a tie!"; } else if ((playerChoice.equals("Rock") && computerChoice.equals("Scissors")) || (playerChoice.equals("Paper") && computerChoice.equals("Rock")) || (playerChoice.equals("Scissors") && computerChoice.equals("Paper"))) { return "You win!"; } else { return "Computer wins!"; } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { RockPaperScissorsGame game = new RockPaperScissorsGame(); game.setVisible(true); }); } }
Explanation
- Import Required Libraries:
- javax.swing.*: For creating the GUI components (JFrame, JButton, JLabel).
- java.awt.*: For layouts and styling.
- java.awt.event.*: For handling button click events.
- java.util.Random: For generating a random choice for the computer.
- Class Definition:
- RockPaperScissorsGame extends JFrame: Our main game class inherits from JFrame, making it a GUI application window.
- Define Labels and Buttons:
- Labels:
- promptLabel displays the prompt for the player to choose Rock, Paper, or Scissors.
- userChoiceLabel shows what the user chose.
- computerChoiceLabel shows what the computer chose.
- resultLabel shows the result of the game (Win, Lose, or Tie).
- Buttons:
- rockButton, paperButton, scissorsButton: These buttons allow the user to choose Rock, Paper, or Scissors.
- Labels:
- Constructor for Setting Up the JFrame:
- setTitle(“Rock Paper Scissors”) sets the title of the window.
- setSize(400, 300) sets the window size.
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the application when the window is closed.
- setLayout(new FlowLayout()) sets a simple layout manager to arrange components in a single row or column.
- Add Components to the JFrame:
- promptLabel is added to display instructions to the user.
- Buttons (rockButton, paperButton, scissorsButton) are added for the user to make a choice.
- Labels (userChoiceLabel, computerChoiceLabel, resultLabel) are added to display the game status and result.
- Add Action Listeners for Buttons:
- Each button has an ActionListener assigned through an instance of the inner class ButtonClickListener.
- new ButtonClickListener(“Rock”) sets the player’s choice to “Rock” when the Rock button is clicked.
- Similarly, “Paper” and “Scissors” are set for the respective buttons.
- ButtonClickListener Inner Class:
- This inner class implements ActionListener to handle button clicks.
- Constructor:
- The constructor ButtonClickListener(String playerChoice) takes the player’s choice as an argument (Rock, Paper, or Scissors) and assigns it to playerChoice.
- actionPerformed Method:
- This method is triggered when a button is clicked.
- String computerChoice = choices[random.nextInt(3)] randomly selects Rock, Paper, or Scissors for the computer.
- userChoiceLabel.setText(…) updates the user’s choice display.
- computerChoiceLabel.setText(…) updates the computer’s choice display.
- resultLabel.setText(…) updates the result display by calling determineWinner().
- determineWinner Method:
- This method determines the winner based on the player’s and computer’s choices.
- Game Logic:
- If the player’s choice and computer’s choice are the same, it’s a tie.
- If the player’s choice wins against the computer’s choice (e.g., Rock beats Scissors), the player wins.
- Otherwise, the computer wins.
- Main Method to Run the Game:
- SwingUtilities.invokeLater(…): Runs the game on the Event Dispatch Thread.
- Creates an instance of RockPaperScissorsGame and sets it visible to display the GUI.
Summary of Gameplay
- Starting the Game:
- The player sees a window with options to choose Rock, Paper, or Scissors.
- Making a Choice:
- When the player clicks a button, the computer makes a random choice.
- The player’s choice, computer’s choice, and result are displayed.
- Determining the Winner:
- The game logic in determineWinner() compares choices to decide if the player wins, loses, or ties.
Sample GUI Layout
- Prompt: “Choose Rock, Paper, or Scissors”
- Buttons: Rock | Paper | Scissors
- Results Display:
- You chose: Rock
- Computer chose: Scissors
- Result: You win!
This code demonstrates how to use Swing to create a simple interactive game with GUI components, making use of ActionListener for button interaction, JLabel for displaying text, and Random for generating random choices.
This game is a fun way to practice GUI design and event handling in Java.