/** * -------------------------------------------------------------------| * Rock, paper, scissors game class. * * @author (Dustin Baker) * @version (10/31/07) */ import java.util.Scanner; class Game { private String response; private Scanner scanIn; private Player player0; private Player player1; public Game() { this.response = ""; } public void go() { Player player0 = new Player(); Player player1 = new Player(); Scanner scanIn = new Scanner (System.in); int validInput = 0; System.out.println("Would you like to play a game of " + "rock, paper, scissors?"); while (validInput == 0) { String response = scanIn.nextLine(); if (response.toLowerCase().equals("yes")) { playGame(); System.out.println(""); System.out.println("Would you like to play a game " + "of rock, paper, scissors?"); } else if (response.toLowerCase().equals("no")) { quit(); validInput = 1; } else { System.out.println("Please enter yes or no only."); } } } private void playGame() { player0.choose(); player1.choose(); System.out.println(this.toString()); if (player0.ties(player1) == true) { System.out.println("Result: tie"); } else if (player0.beats(player1) == true) { System.out.println("Result: player0 won"); } else { System.out.println("Result: player1 won"); } } public String toString() { return "(player0 choice: " + player0.toString() + ", player1 choice: " + player1.toString() + ")"; } private void quit() { System.out.println("Thanks for playing."); } } /** * -------------------------------------------------------------------| * Rock, paper, scissors player class. */ class Player { private String choice; public Player() { this.choice = ""; } public void choose() { String choice; final int NUM_RANGE = 3; int choiceNum = (int) (NUM_RANGE * Math.random()); if (choiceNum == 0) { this.choice = "rock"; } else if (choiceNum == 1) { this.choice = "paper"; } else { this.choice = "scissors"; } } public boolean beats(Player p2) { if (this.equals("rock") && p2.equals("scissors")) { return true; } else if (this.equals("paper") && p2.equals("rock")) { return true; } else if (this.equals("scissors") && p2.equals("paper")) { return true; } else { return false; } } public boolean ties(Player p2) { if (this.equals(p2)) { return true; } else { return true; } } public String toString() { if (this.choice.equals("")) { return "none"; } else { return this.choice; } } } /** * -------------------------------------------------------------------| * Rock, paper, scissors driver. */ public class Driver { public static void main(String[] args) { Game newGame = new Game(); newGame.go(); } }