// 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 rps2 { // 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 int outcome; // holds the result of the game // 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); // find out the result (two game choices are input) - this method // returns a -1 if the user lost, 0 on a tie, and 1 is the user wins. outcome = determineWinner(userChoice, compChoice); // print result and update counters if (outcome < 0) { // user loses System.out.println("The Computer wins."); } else if (outcome > 0) { // user wins System.out.println("You win!"); } else System.out.println("The game is a tie."); } // 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("!!"); } } // determineWinner() accepts two RPS game choices and returns the result // of the game. A game can end with a player win (1), a tie (0), or a // player loss (-1). The first argument should be the player's choice. static int determineWinner(int uc, int cc) { // when the choices are the same, the result is a tie. if (uc == cc) return 0; // there are 3 ways the user can win else if ( (uc == ROCK && cc == SCISSORS) || (uc == SCISSORS && cc == PAPER) || (uc == PAPER && cc == ROCK) ) return 1; // the only other possibility is a user loss return -1; } }