Sunday, June 30, 2013

Java: Rock, Paper, Scissor Game Source Code

This is the source code for how to implement a rock, paper, scissor game in JAVA. It has a swing GUI interface (using JOptionPane) that prompt the user for input.

// A game that plays rock paper scissor with user

import javax.swing.JOptionPane;

public class GameRockPaperScissor {
 public static void main(String[] args) {
  // Prompt the user to input the option they choose
  String humanInput = JOptionPane.showInputDialog(
    "Enter rock, paper, or scissor:");
  // Convert to lower case
  humanInput = humanInput.toLowerCase();
  // Generate a random number
  // Scissor (0),  rock (1), paper (2)
  int random = (int)(Math.random() * 3);
  String computerInput; // Computer's choice
  if (random == 0) 
   computerInput = "rock";
  else if (random == 1)
   computerInput = "paper";
   computerInput = "scissor";
  String message = "The computer is " + computerInput + ". You are "
    + humanInput;
  // Determine who win
  boolean isTie = computerInput.equals(humanInput);
  boolean isWin = 
   ((computerInput.equals("rock") && humanInput.equals("scissor")) ||
   (computerInput.equals("paper") && humanInput.equals("rock")) ||
   (computerInput.equals("scissor") && humanInput.equals("paper")));
  // Prepare the message
  if (isWin)
   message += ". Computer Won.";
  else if (isTie)
   message += " too. It is Tie";
  // There are 3 options, computer win, tie, or you win
  // So we don't have to test here, if the code reach here, human win.
   message += ". You Won";
  // Display the result on the screen
  JOptionPane.showMessageDialog(null, message);


  1. hi.can i ask something..i just want to know if this code is useable to create a java applet game with a gui.and how to have a gui like this

  2. @vjdionio Yes it is, I use NetBeans IDE 6.4, you can create gui, but it is going to be a bit harder.