In Chapter 7 you improved a Rock Paper Scissors game played between a user and t
ID: 3669315 • Letter: I
Question
In Chapter 7 you improved a Rock Paper Scissors game played between a user and the computer. Add an enumeration that holds three values that represent ROCK, PAPER, and SCISSORS, and use it for all comparisons in the program. Save the file as RockPaperScissors3.java.
Here's the game:
Test.java
import java.util.*;
import java.util.Random;
public class Test
{
static int computerWins = 0;
static int playerWins = 0;
static int numDraws = 0;
static final int ROCK = 1;
static final int PAPER = 2;
static final int SCISSORS = 3;
public static void main(String[] args) {
System.out.print("Enter your name and press return: ");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Welcome " +name+ " to a game of Rock-Paper-Scissors!");
System.out.print("Enter the number of rounds you want to play and press return: ");
int numGames = input.nextInt();
playGame(name,numGames,input);
}
public static void playGame(String name, int numGames, Scanner input) // Initializing the game
{
int count = 0;
boolean play = true;
String yourChoice = "";
String computerChoice = "";
while(play == true) // The while loop escapes when our play flag is false
{
count++;
if(numGames <= count )
{
play = false;
}
System.out.println("Round " + count);
System.out.print(name + ", make your move [ 1 = Rock, 2 = Paper, 3 = Scissors ]: ");
int choice = input.nextInt();
Random rand = new Random();
int compChoice = rand.nextInt(3) +1;
yourChoice = "";
computerChoice = "";
if(choice == ROCK)
{
yourChoice+=name+" plays Rock ...";
}
else if(choice == PAPER)
{
yourChoice+=name+" plays Paper ...";
}
else if(choice == SCISSORS)
{
yourChoice+=name+" plays Scissors ...";
}
if(compChoice == 1)
{
computerChoice+="Computer plays Rock -- ";
}
else if(compChoice == 2)
{
computerChoice+="Computer plays Paper -- ";
}
else if(compChoice == 3)
{
computerChoice+="Computer plays Scissors -- ";
}
System.out.print(computerChoice + yourChoice );
System.out.println();
checkOutcome(choice, compChoice, computerChoice, yourChoice, name, play);
}
System.out.println("You played " +count +" games of Rock Paper Scissors.");
System.out.println("The Computer won "+computerWins+" times.");
System.out.println(name+ " won "+playerWins+" times.");
System.out.println("There were "+numDraws+" draws.");
if(playerWins > computerWins)
{
System.out.println("You are the winner of Rock Paper Scissors!");
}
else if(computerWins > playerWins)
{
System.out.println("The Computer is the winner of Rock Paper Scissors!");
}
else if(playerWins == computerWins)
{
System.out.println("It is a tie. Everyone is a winner of Rock Paper Scissors!");
}
}
// Checks the player's choice against the Computer's choice
public static void checkOutcome(int choice, int compChoice, String computerChoice, String yourChoice, String name, boolean play)
{
if(choice == 1 && compChoice == 1 || choice == 2 && compChoice == 2 || choice == 3 && compChoice==3)
{
tieGame(play);
numDraws++;
}
if(choice == 1 && compChoice == 2 || choice == 2 && compChoice == 3 || choice == 3 && compChoice == 1)
{
youLose(computerChoice, play);
computerWins++;
}
if(choice == 1 && compChoice == 3 || choice == 2 && compChoice == 1 || choice == 3 && compChoice == 2 )
{
youWin(yourChoice, name, play);
playerWins++;
}
}
// The three outcome methods deciding the fate of the player's choice
public static void youLose(String computerChoice, boolean play)
{
if(play == true)
{
if(computerChoice.equals("Computer chooses Rock, "))
{
System.out.println("Rock breaks Scissors, Computer wins.");
System.out.println();
}
else if(computerChoice.equals("Computer chooses Paper, "))
{
System.out.println("Paper covers Rock, Computer wins.");
System.out.println();
}
else if(computerChoice.equals("Computer chooses Scissors, "))
{
System.out.println("Scissors cuts Paper, Computer wins.");
System.out.println();
}
}
}
public static void youWin(String yourChoice, String name, boolean play)
{
if(play == true)
{
if(yourChoice.equals(name+" chose Rock"))
{
System.out.println("Rock breaks Scissors - YOU WIN!");
System.out.println();
}
else if(yourChoice.equals(name+" chose Paper"))
{
System.out.println("Paper covers Rock - YOU WIN!");
System.out.println();
}
else if(yourChoice.equals(name+" chose Scissors"))
{
System.out.println("Scissors cuts Paper - YOU WIN!");
System.out.println();
}
}
}
public static void tieGame(boolean play)
{
if(play == true)
{
System.out.println("This round is a draw");
System.out.println();
}
}
}
Explanation / Answer
import java.util.InputMismatchException;
import java.util.Scanner;
public class HelloWorld {
public static Difficulty gamemode = Difficulty.IMPOSSIBLE; // normal,
// harder,
// brutal, or
// impossible
/*
* Difficulties: This game is programmed with four unique levels of 'difficulty' The
* levels are normal, harder, brutal, and impossible. You may notice there is no 'easy'
* mode. Life is hard. Get over it.
*
* NORMAL: A 'standard' game of Rock Paper Scissors. The computer will indiscriminately
* choose a random weapon. Very boring.
*
* HARDER: The computer will track your history in a game, meaning that continuously
* selecting a single weapon "just to get through it" will always result in a loss.
* Your only hope is to keep your choices as varied as possible
*
* BRUTAL: The computer can see your choice before it makes its own. In any given turn,
* the computer has a 65% chance to cheat outright, and automatically select the weapon
* that will defeat you. In the other 35% of cases, the computer will select a weapon
* based on normal rules. Here, victory is still very possible, but the odds are most
* definitely against you.
*
* IMPOSSIBLE: The computer can see your choice before it makes its own. The computer
* will cheat. There is no avoiding it. You will lose every single game. You brought
* this upon yourself.
*/
public static Scanner console = new Scanner(System.in);
public static int[] userInputs = new int[3]; // times the user has selected
// {rock, paper scissors}
public static void main(String[] args) {
HelloWorld.printIntro();
int games = HelloWorld.getNumGames();
int[] stats = HelloWorld.playAllGames(games);
HelloWorld.printStats(stats);
}
// print an intro to the program
public static void printIntro() {
System.out.println("This program plays games of Rock-Paper-Scissors "
+ "against the computer. You'll type in your guess "
+ "of (R)ock, (P)aper, or (S)cissors and try to "
+ "beat the computer as many times as you can. ");
}
// ask the user how many games they want to play
public static int getNumGames() {
int num = 0;
boolean success = false;
do {
try {
do {
System.out.print("Best out of how many games (must be odd)? ");
num = HelloWorld.console.nextInt();
if (num % 2 == 0 || num < 0) {
System.out.println("Invalid number of games. Type a positive odd number!");
}
} while (num % 2 == 0 || num < 0);
success = true; // we're done here
} catch (InputMismatchException e) {
System.out.println("Invalid input; must be an integer");
HelloWorld.console.nextLine(); // ignore the non-integer, and
// remove it
// from the heap
}
} while ( !success);
return num;
}
// manage the games occuring, and prompt to quit after each match
public static int[] playAllGames(int games) {
String[] winMessages = {"Tie!", "You win!", "You lose!"};
int[] stats = new int[3]; // times the user has {tied, won, lost}
do {
System.out.println();
for (int i = 1; i <= games; i++) {
int winner = HelloWorld.playGame(i);
stats[winner]++; // get the winner of the game and increment
// that statistic
System.out.println(winMessages[winner]);
}
} while (HelloWorld.promptContinue());
return stats;
}
// code to play a single game; returns int representing winner
public static int playGame(int gameNum) {
System.out.println("Game " + gameNum + ":");
HelloWorld.console.nextLine();
String userWeapon = HelloWorld.getUserWeapon();
String computerWeapon = HelloWorld.getComputerWeapon(userWeapon);
HelloWorld.storeUserWeapon(userWeapon);
System.out.println("I chose the weapon: " + computerWeapon.toUpperCase());
return HelloWorld.winner(userWeapon, computerWeapon);
}
// ask the user to either continue or to quit playing
public static boolean promptContinue() {
System.out.print("Do you want to play again? ");
return HelloWorld.console.next().toLowerCase().startsWith("y");
}
// print final statistics about the session
public static void printStats(int[] stats) {
System.out.println();
System.out.println();
int totalGames = 0;
for (int i : stats) {
totalGames += i;
}
System.out.println("Overall results:" + " total games = " + totalGames + " wins = "
+ stats[1] + " losses = " + stats[2] + " ties = " + stats[0]
+ " win % = " + String.format("%.2f", (100 * (double) stats[1] / totalGames)));
}
// during a game, ask the user for their choice of weapon
public static String getUserWeapon() {
String weapon;
boolean isValid;
do {
System.out.print("Choose your weapon? ");
weapon = HelloWorld.console.next().toLowerCase();
isValid = weapon.startsWith("r") || weapon.startsWith("p") || weapon.startsWith("s");
if ( !isValid) {
System.out.println("Weapon must be rock, paper, or scissors. "" + weapon
+ "" is not valid.");
}
} while ( !isValid);
return weapon.substring(0, 1);
}
// during a game, generate a computer weapon, possibly based on the user's
// choice
public static String getComputerWeapon(String userInput) {
String[] weapons = {"r", "p", "s"};
if (HelloWorld.gamemode == Difficulty.NORMAL) {
return weapons[(int) (3 * Math.random())];
} else if (HelloWorld.gamemode == Difficulty.HARDER) {
if (HelloWorld.userInputs[0] >= HelloWorld.userInputs[1]
&& HelloWorld.userInputs[0] >= HelloWorld.userInputs[2]) {
return "p";
}
if (HelloWorld.userInputs[1] >= HelloWorld.userInputs[0]
&& HelloWorld.userInputs[1] >= HelloWorld.userInputs[2]) {
return "s";
}
if (HelloWorld.userInputs[2] >= HelloWorld.userInputs[0]
&& HelloWorld.userInputs[2] >= HelloWorld.userInputs[1]) {
return "r";
}
} else if (HelloWorld.gamemode == Difficulty.BRUTAL) {
if (Math.random() > 0.35) {
return HelloWorld.cheatResponse(userInput);
} else {
return weapons[(int) (3 * Math.random())]; // play legitimately
}
} else { // gamemode == IMPOSSIBLE
return HelloWorld.cheatResponse(userInput);
}
return "r"; // Dead code, but required to compile. Might as well return
// something useful
}
// given an input, return whatever would win against it
public static String cheatResponse(String weapon) {
if (weapon.equals("r")) {
return "p";
}
if (weapon.equals("p")) {
return "s";
}
if (weapon.equals("s")) {
return "r";
}
return ""; // error
}
// log the user's weapon choice for later accessing
public static void storeUserWeapon(String weapon) {
if (weapon.equals("r")) {
HelloWorld.userInputs[0]++;
}
if (weapon.equals("p")) {
HelloWorld.userInputs[1]++;
}
if (weapon.equals("s")) {
HelloWorld.userInputs[2]++;
}
}
@Deprecated
public static boolean isValidWeapon(String weapon) {
if (weapon.length() == 0) {
return false;
}
weapon = weapon.toLowerCase();
return weapon.startsWith("r") || weapon.startsWith("p") || weapon.startsWith("s");
}
// returns 1 or 2 if a string 'wins', 0 if they're the same, and -1 for
// error
static int winner(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// easier than using equalsIgnoreCase() on every comparison
if (a.equals(b)) {
return 0;
} else if (a.equals("r")) {
if (b.equals("s")) {
return 1;
} else {
return 2;
}
} else if (a.equals("s")) {
if (b.equals("p")) {
return 1;
} else {
return 2;
}
} else if (a.equals("p")) {
if (b.equals("r")) {
return 1;
} else {
return 2;
}
} else {
// unexpected
return -1;
}
}
}
enum Difficulty {
NORMAL,
HARDER,
BRUTAL,
IMPOSSIBLE
}
output
This program plays games of Rock-Paper-Scissors
against the computer. You'll type in your guess
of (R)ock, (P)aper, or (S)cissors and try to
beat the computer as many times as you can.
Best out of how many games (must be odd)? 3
Game 1:
Choose your weapon? r
I chose the weapon: P
You lose!
Game 2:
Choose your weapon? p
I chose the weapon: S
I chose the weapon: S
You lose!
Game 3:
Choose your weapon? s
I chose the weapon: R
You lose!
Do you want to play again? n
Overall results:
total games = 3
wins = 0
losses = 3
ties = 0
win % = 0.00
sh-4.3$