// CS7 - Solution to RPS // Spring 2004 // // This program plays Rock, Paper, Scissors with the user. It asks how // long of a match is desired, and then plays until a majority of those // games are won. For example, a 5 game match is over when either player // (the person or the computer) reaches 3 wins. The user's win/loss record // is displayed after each game. // // Game choices are represented by integers, but constants are available // to make the code more readable. The computer's choice is determined // randomly. import tio.*; // using JBD's input package class rps1 { // Constants for all to use static final int ROCK = 1; static final int PAPER = 2; static final int SCISSORS = 3; // the main steps of the algorithm are in main(), with methods handling // most of the details public static void main(String [] args) { int userChoice, compChoice; // the "hands" of each player // get the two picks and display them userChoice = getUserChoice(); compChoice = getCompChoice(); System.out.print("Your choice: "); printGameChoice(userChoice); System.out.print("Compuer choice: "); printGameChoice(compChoice); } // ask the user for a game choice static int getUserChoice() { System.out.print("Enter (1) for Rock, (2) for Paper, or (3) for Scissors: "); int choice = Console.in.readInt(); while (choice < 1 || choice > 3) { System.out.println("Try again: "); choice = Console.in.readInt(); } return choice; } // returns a random number between 1 and 3 for the three possible choices static int getCompChoice() { return (int)(Math.random() * 3) + 1; } // prints a choice on the screen (as a string) static void printGameChoice(int c) { switch (c) { case ROCK: System.out.println("Rock"); break; case PAPER: System.out.println("Paper"); break; case SCISSORS: System.out.println("Scissors"); break; default: System.out.println("!!"); } } }