Question

I am making a game like Rock Paper Scissors called fire water stick where the rules...

I am making a game like Rock Paper Scissors called fire water stick where the rules are

  1. Stick beats Water by floating on top of it

  2. Water beats Fire by putting it out

  3. Fire beats Stick by burning it

The TODOS are as follows:

TODO 1: Declare the instance variables of the class. Instance variables are private variables that keep the state of the game. The recommended instance variables are:

1.

2. 3. 4. 5. 6.

A variable, “rand” that is the instance of the Random class. It will be initialized in a constructor (either seeded or unseeded) and will be used by the getRandomChoice() method.
A variable to keep the player’s cumulative score. This is the count of the number of times the player (the user) has won a round. Initial value: 0.

A variable to keep the computer’s cumulative score. This is the count of the number of times the computer has won a round. Initial value: 0.

A variable to keep the count of the number of rounds that have been played. Initial value: 0.

A variable to keep track of if the player has won the current round (round-specific): true or false. This would be determined by the playRound method. Initial value: false.

A variable to keep track of if the player and computer have tied in the current round (round-specific): true or false. This would be determined by the playRound method. Initial value: false.

The list above contains the minimum variables to make a working program. You may declare more instance variables as you wish.

TODOs 2 and 3: Implement the constructors. The constructors assign the instance variables to their initial values. In the case of the Random class instance variable, it is initialized to a new instance of the Random class in the constructors. If a constructor has a seed parameter, the seed is passed to the Random constructor. If the constructor does not have a seed parameter, the default (no parameter) Random constructor is called.

TODO 4: This method returns true if the inputStr passed in is one of the following: "S", "s", "W", "w", "F", "f", false otherwise. Note that the input can be upper or lower case.

TODOs 5, 6, 7, 8, 9, 10 These methods just return the values of their respective instance variables.

TODO 11: This is a private method that is called by the playRound method. It uses the instance variable of the Random class to generate an integer that can be “mapped” to one of the three Strings: "S", "W", "F", and then returns that String, which represents the computer’s choice.

TODO 12: The playRound method carries out a single round of play of the SWF game. This is the major, “high-level” method in the class. This method does many tasks including the following steps:

Here is my code that is not giving the correct output:

1 import java.util.Random;
2
3 public class StickWaterFireGame {
4
5 private int playerScore;
6 private int computerScore;
7 private int rounds;
8 private boolean playerWins;
9 private boolean isTie;
10 private Random rand;
11 private String playerChoice;
12 private String computerChoice;
13
14
15 public StickWaterFireGame() {
16
17 rand = new Random();
18 playerScore = 0;
19 computerScore = 0;
20 rounds = 0;
21 playerWins = false;
22 isTie = false;
23 playerChoice = "";
24 computerChoice = "";
25
26 }
27
28
29 public StickWaterFireGame(int seed) {
30
31 rand = new Random(seed);
32 playerScore = 0;
33 computerScore = 0;
34 rounds = 0;
35 playerWins = false;
36 isTie = false;
37 playerChoice = "";
38 computerChoice = "";
39
40 }
41
42 public boolean isValidInput(String inputStr) {
43
44 if (inputStr.equalsIgnoreCase("s")) {
45
46 return true;
47
48 }
49
50 else if (inputStr.equalsIgnoreCase("w")) {
51
52 return true;
53
54 }
55
56 else if (inputStr.equalsIgnoreCase("f")) {
57
58 return true;
59
60 }
61
62 else {
63
64 return false;
65
66 }
67
68 }
69
70
71
72 public String getComputerChoice(){
73
74 computerChoice = getRandomChoice();
75 return computerChoice;
76 }
77
78 public boolean playerWins(){
79
80 if ((playerChoice.equals("S")) && (computerChoice.equals("W"))) {
81
82 return true;
83
84 }
85
86 else if ((playerChoice.equals("W")) && (computerChoice.equals("F"))) {
87
88 return true;
89
90 }
91
92 else if ((playerChoice.equals("F")) && (computerChoice.equals("S"))) {
93
94 return true;
95
96 }
97
98 else {
99
100 return false;
101
102 }
103
104 }
105
106
107 public int getPlayerScore(){
108
109 return playerScore;
110
111 }
112
113
114 public int getComputerScore(){
115
116 return computerScore;
117
118 }
119
120
121 public int getNumRounds(){
122
123 return rounds;
124
125 }
126
127
128 public boolean isTie(){
129
130 if (playerChoice.equals(computerChoice)){
131
132 return true;
133
134 }
135
136 else{
137
138 return false;
139
140 }
141
142 }
143
144
145 private String getRandomChoice() {
146
147 int num;
148 Random rand = new Random();
149 num = rand.nextInt(3);
150 String computerChoice = "";
151
152 if (num == 0){
153
154 computerChoice = "S";
155
156 }
157
158 else if (num == 1){
159
160 computerChoice = "W";
161
162 }
163
164 else if (num == 2){
165
166 computerChoice = "F";
167
168 }
169
170 return computerChoice;
171
172 }
173
174
175
176 public void playRound(String playerChoice) {
177
178 if (isValidInput(playerChoice)){
179
180 this.playerChoice = playerChoice.toUpperCase();
181 rounds++;
182 this.computerChoice = getRandomChoice();
183
184 if(playerWins() == true) {
185
186 playerScore++;
187 playerWins = true;
188
189 }
190
191 else if (isTie() == true){
192
193 isTie = true;
194 playerWins = false;
195
196 }
197
198 else{
199
200 computerScore++;
201 playerWins = false;
202
203 }
204
205 }
206
207 else{
208
209 rounds++ ;
210 computerScore++ ;
211 }
212
213 playerWins = false;
214 isTie = false;
215
216 }
217 }

Homework Answers

Answer #1

modified code is as below(marked as bold are the changes) :

import java.util.Random;

public class StickWaterFireGame {
   private int playerScore;
   private int computerScore;
   private int rounds;
   private boolean playerWins;
   private boolean isTie;
   private Random rand;
   private String playerChoice;
   private String computerChoice;

   public StickWaterFireGame() {
       rand = new Random();
       playerScore = 0;
       computerScore = 0;
       rounds = 0;
       playerWins = false;
       isTie = false;
       playerChoice = "";
       computerChoice = "";
   }

   public StickWaterFireGame(int seed) {
       rand = new Random(seed);
       playerScore = 0;
       computerScore = 0;
       rounds = 0;
       playerWins = false;
       isTie = false;
       playerChoice = "";
       computerChoice = "";
   }

   public boolean isValidInput(String inputStr) {
       if (inputStr.equalsIgnoreCase("s")) {
           return true;
       } else if (inputStr.equalsIgnoreCase("w")) {
           return true;
       } else if (inputStr.equalsIgnoreCase("f")) {
           return true;
       } else {
           return false;
       }
   }

   public String getComputerChoice() {
       //computerChoice = getRandomChoice();//remove this line of code
       return computerChoice;
   }

   public boolean playerWins() {
       if ((playerChoice.equals("S")) && (computerChoice.equals("W"))) {
           return true;
       } else if ((playerChoice.equals("W")) && (computerChoice.equals("F"))) {
           return true;
       } else if ((playerChoice.equals("F")) && (computerChoice.equals("S"))) {
           return true;
       } else {
           return false;
       }
   }

   public int getPlayerScore() {
       return playerScore;
   }

   public int getComputerScore() {
       return computerScore;
   }

   public int getNumRounds() {
       return rounds;
   }

   public boolean isTie() {
       if (playerChoice.equals(computerChoice)) {
           return true;
       } else {
           return false;
       }
   }

   private String getRandomChoice() {
       int num;
       // Random rand = new Random();
       num = rand.nextInt(3);// here we can directly use rand(instance variable)
       String computerChoice = "";
       if (num == 0) {
           computerChoice = "S";
       } else if (num == 1) {
           computerChoice = "W";
       } else if (num == 2) {
           computerChoice = "F";
       }
       return computerChoice;
   }

   public void playRound(String playerChoice) {
       if (isValidInput(playerChoice)) {
           this.playerChoice = playerChoice.toUpperCase();
           rounds++;
           this.computerChoice = getRandomChoice();
           if (playerWins() == true) {
               playerScore++;
               playerWins = true;
           } else if (isTie() == true) {
               isTie = true;
               playerWins = false;
           } else {
               computerScore++;
               playerWins = false;
           }
       } else {
           rounds++;
           computerScore++;
           playerWins = false;
           isTie = false;

       }
       /*
       * i don't see why you are making these variables as false when a round is over,
       * as they represent stauts of current round, instead you should make them as
       * false for an invalid user choice, that's why i have commented it and pasted
       * in else above
       */
       // playerWins = false;
       // isTie = false;

   }
}

Main provided by you (unchanged):

public class StickWaterFireMain {

   public static void main(String[] args) {
       // StickWaterFireGame game = new StickWaterFireGame();
       StickWaterFireGame game = new StickWaterFireGame(1234);
       Scanner scan = new Scanner(System.in);
       boolean keepGoing = true;
       String playerChoice = "";

       // Greet the user and state the rules:
       System.out.println("Welcome to Stick-Water-Fire!\n");
       System.out.println("Rules:");
       System.out.println("\tYou will play against the computer for the specified number of rounds.");
       System.out.println("\tYou will make a choice: 'S', 'W', or 'F' to represent 'Stick', 'Water', or 'Fire'.");
       System.out.println("\tThe computer will also make a choice, and the winner is chosen as follows:");
       System.out.println("\t\t Stick beats Water (it floats on top)");
       System.out.println("\t\t Water beats Fire (extinguishes the fire)");
       System.out.println("\t\t Fire beats Stick (burns the stick)");
       System.out.println("\tIn the event of a tie, there is no winner.");
       System.out.println("\tEach round, the winner will have their score incremented.");
       System.out.println("\tA report of scores and number of rounds will be displayed at the end of each round.");
       System.out.println("\tEnter X to quit.");
       System.out.println("\tGood luck!");

       // begin the game loop.
       while (keepGoing) {
           System.out.println("Enter 'S' for Stick, 'W' for Water, 'F' for Fire, or X to quit:");
           playerChoice = scan.nextLine();
           if (playerChoice.equalsIgnoreCase("X")) {
               keepGoing = false;
           }
           else { // Handle round of play
               // validate input
               if (!game.isValidInput(playerChoice)) {
                   System.out.println("\tInvalid input entered: " + playerChoice + "\n");
               }
               else {
                   game.playRound(playerChoice);
                   String computerChoice = game.getComputerChoice();
                   System.out.println("You chose " + playerChoice + " and the computer chose " + computerChoice);
                   // report winner
                   if (game.isTie()) {
                       System.out.println("You tied!");
                   } else if (game.playerWins()) {
                       System.out.println("You won! Nice job!\n");
                   } else { // Computer won
                       System.out.println("You lost. Better luck next time!\n");
                   }
                   // Print report
                   System.out.println("Game summary:");
                   System.out.println(getScoreReportStr(game));
                   System.out.println(" ");
               }
           } // end of round
       } // end loop
       System.out.println("Thanks for playing!");
   } // end main

   public static String getScoreReportStr(StickWaterFireGame game) {
       return "Total plays: " + game.getNumRounds() + "\nYour total score: " + game.getPlayerScore()
               + ", computer total score: " + game.getComputerScore();
   }

}

output when you run above class will be as below:

its working as required, please test it rigorously by yourself and let me know.

In case of a tie scores are not increased( highlighted in the output screenshot)

please comment if you need any help or suggestions to improve..

to format the code : Ctrl+a then Ctrl+Shift+f

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
This is my course class. Can someone please explain what the equals method is for and...
This is my course class. Can someone please explain what the equals method is for and also the compareTo method is for in general and then explain what the methods are doing in this class. public class Course {    private boolean isGraduateCourse;    private int courseNum;    private String courseDept;    private int numCredits;       public Course(boolean isGraduateCourse, int courseNum, String courseDept, int numCredits) {        this.isGraduateCourse=isGraduateCourse;        this.courseNum=courseNum;        this.courseDept=courseDept;        this.numCredits=numCredits;   ...
Modify the Employee9C superclass so that is an abstract superclass with a constructor to set its...
Modify the Employee9C superclass so that is an abstract superclass with a constructor to set its variables (firstName and lastName). It should contain an abstract method called payPrint. Below is the source code for the Employee9C superclass: public class Employee9C {    //declaring instance variables private String firstName; private String lastName; //declaring & initializing static int variable to keep running total of the number of paychecks calculated static int counter = 0;    //constructor to set instance variables public Employee9C(String...
import java.util.Scanner; public class InRange { private int min; private int max; public InRange(int initialMin, int...
import java.util.Scanner; public class InRange { private int min; private int max; public InRange(int initialMin, int initialMax) { min = initialMin; max = initialMax; } // You need to write two instance methods: // 1.) A method named inRange, which takes an int. // This returns true if the int is within the given range // (inclusive), else false. // // 2.) A method named outOfRange which takes an int. // This returns false if the int is within the...
1. Suppose that the integer variables n and m have been initialized. Check all the correct...
1. Suppose that the integer variables n and m have been initialized. Check all the correct statements about the following code fragment. String s2 = (n>=m) ? "one" : ( (m<=2*n) ? "two": "three" ); Question 5 options: If m is strictly greater than 2n then the value of s2 is "two" If n is equal to m then the value of s2 is "two" If m is strictly greater than 2n then the value of s2 is "three" If...
In java create a dice game called sequences also known as straight shooter. Each player in...
In java create a dice game called sequences also known as straight shooter. Each player in turn rolls SIX dice and scores points for any sequence of CONSECUTIVE numbers thrown beginning with 1. In the event of two or more of the same number being rolled only one counts. However, a throw that contains three 1's cancels out player's score and they mst start from 0. A total of scores is kept and the first player to reach 100 points,...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with the default values denoted by dataType name : defaultValue - String animal : empty string - int lapsRan : 0 - boolean resting : false - boolean eating : false - double energy : 100.00 For the animal property implement both getter/setter methods. For all other properties implement ONLY a getter method Now implement the following constructors: 1. Constructor 1 – accepts a String...
Here is a basic Counter class. class Counter { private int num = 0; // Not...
Here is a basic Counter class. class Counter { private int num = 0; // Not needed for this question public void increment() { num++; } public boolean equals(Counter other) { return this.num == other.num; } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Counter[] counters, int numCounters, Counter counter) The goal of the method is to...
Write a class called Item that has a string field called name and a double field...
Write a class called Item that has a string field called name and a double field called price and an integer field called quantity. In main, create a bag of type Item and place several item objects in the bag. Then in main calculate the total price of items purchased. You may remove each item and add the price to a total variable in a loop. The loop should end when the bag is empty. Using bag algorithms public final...
Here is my java code, I keep getting this error and I do not know how...
Here is my java code, I keep getting this error and I do not know how to fix it: PigLatin.java:3: error: class Main is public, should be declared in a file named Main.java public class Main { ^ import java.io.*; public class Main { private static BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String english = getString(); String translated = translate(english); System.out.println(translated); } private static String translate(String s) { String latin =...
Compile and execute the application. You will discover that is has a bug in it -...
Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn. Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code. Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the...