Question

In: Computer Science

The programming language that is being used here is JAVA, below I have my code that...

The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly.

OverView:

For this project, you will develop a game program called Stick, Water. Fire- a version of the game Rock, Paper, Scissors. The user plays against the computer. You will use conditional expressions in several ways in this project. Primarily, you will write code to implement the game rules using conditional statements. You will also utilize Java’s ​Random​ class to generate random outcomes used in the game for the computer’s choice. The ​Random ​class can be seeded so that development and testing can be more easily done. Another aspect of this project is the use of a private method in a class. Private methods are used only within a class to help other methods with their calculations.

Program Interaction:

Our goal is to make a fun and interactive game for users. The user will be able to enter their choice of Stick, Water, or Fire. The computer will also make a choice, and the winner will be chosen based on the following three rules:

  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 user is prompted to enter S, W or F (Note that the input can be upper or lower case). The computer then makes its choice (randomly generated) and the program applies the game rules to the user and computer’s choices.
The user and computer’s scores are recorded as well as the number of rounds played.

Ties result in no increase in either user or computer scores, but the round is counted.

A sample of the program’s behavior is given below. This is how the program should function when you have it working:

======Code===============

import java.util.Random;

/* This class ecapsulates the state and logic required to play the
Stick, Water, Fire game. The game is played between a user and the computer.
A user enters their choice, either S for stick, F for fire, W for water, and
the computer generates one of these choices at random- all equally likely.
The two choices are evaluated according to the rules of the game and the winner
is declared.

Rules of the game:
S beats W
W beats F
F beats S
no winner on a tie.

Each round is executed by the playRound method. In addition to generating the computer
choice and evaluating the two choices, this class also keeps track of the user and computer
scores, the number of wins, and the total number of rounds that have been played. In the case
of a tie, neither score is updated, but the number of rounds is incremented.

NOTE: Do not modify any of the code that is provided in the starter project. Additional instance variables and methods
are not required to make the program work correctly, but you may add them if you wish as long as
you fulfill the project requirements.

*/
public class StickWaterFireGame {

// TODO 1: Declare private instance variables here:
private static Random rand;
public static int computerScore;
public static int rounds;
public static int playerScore;
private static boolean playerWins;
private static boolean isTie;
private static String computerChoice = "";
private static String playerChoice = "";


  
/* This constructor assigns the member Random variable, rand, to
* a new, unseeded Random object.
* It also initializes the instance variables to their default values:
* rounds, player and computer scores will be 0, the playerWins and isTie
* variables should be set to false.
*/
public StickWaterFireGame() {
// TODO 2: Implement this method.
rand = new Random();
playerScore = 0;
computerScore = 0;
rounds = 0;
playerWins = false;
isTie = false;
}

/* This constructor assigns the member Random variable, rand, to
* a new Random object using the seed passed in.
* It also initializes the instance variables to their default values:
* rounds, player and computer scores will be 0, the playerWins and isTie
* variables should be set to false.
*/
public StickWaterFireGame(int seed) {
// TODO 3: Implement this method.
rand = new Random(seed);
playerScore = 0;
computerScore = 0;
rounds = 0;
playerWins = false;
isTie = false;

}   

/* This method returns true if the inputStr passed in is
* either "S", "W", or "F", false otherwise.
* Note that the input can be upper or lower case.
*/
public boolean isValidInput(String inputStr) {
// TODO 4: Implement this method.
if (inputStr.equalsIgnoreCase("S") || inputStr.equalsIgnoreCase("W") || inputStr.equalsIgnoreCase("F")) {
return true;
}
return false;
}
  
/* This method carries out a single round of play of the SWF game.
* It calls the isValidInput method and the getRandomChoice method.
* It implements the rules of the game and updates the instance variables
* according to those rules.
*/
  
// Returns the choice of the computer for the most recent round of play
public String getComputerChoice(){
// TODO 5: Implement this method.
return computerChoice;
}

// Returns true if the player has won the last round, false otherwise.
public boolean playerWins(){
// TODO 6: Implement this method.
if ((playerChoice.equalsIgnoreCase("s"))&&(computerChoice.equalsIgnoreCase("w"))){
return true;
}
else if ((playerChoice.equalsIgnoreCase("f"))&&(computerChoice.equalsIgnoreCase("w"))){
return true;
}
else if ((playerChoice.equalsIgnoreCase("s"))&&(computerChoice.equalsIgnoreCase("f"))){
return true;
}
else {
return false;
}
}



// Returns the player's cumulative score.
public int getPlayerScore(){
// TODO 7: Implement this method.
return playerScore;
}

// Returns the computer's cumulative score.   
public int getComputerScore(){
// TODO 8: Implement this method.
return computerScore;
}

// Returns the total nuber of rounds played.   
public int getNumRounds(){
// TODO 9: Implement this method.
return rounds;
}

// Returns true if the player and computer have the same score on the last round, false otherwise.
public boolean isTie(){
// TODO 10: Implement this method.
if (playerChoice.equals(computerChoice)) {
return true;
}
return false;
}

/* This "helper" method uses the instance variable of Random to generate an integer
* which it then maps to a String: "S", "W", "F", which is returned.
* This method is called by the playRound method.
*/
private String getRandomChoice() {
// TODO 11: Implement this method.
    int number = rand.nextInt(3)+1;
String choice = null;
if(number == 1) {
choice = "S";
}
else if (number == 2) {
choice = "W";
}
else if (number == 3) {
choice = "F";
}
return choice;
}

public void playRound(String playerChoice) {
// TODO 12: Implement this method.
if(isValidInput(playerChoice)) {
this.playerChoice = playerChoice.toLowerCase();
rounds++;
this.computerChoice = getRandomChoice();
if(playerWins()) {
playerScore++;
playerWins=true;
}
else if(isTie())
isTie=true;
else
computerScore++;
}

}
}

Tests that failed

Test 11: computer score is updated if user enters an invalid input. (0.0/5.0)

Test Failed!
Test computer score is updated if user enters an invalid input. expected:<1> but was:<0>
    at StickWaterFireGameTest.computerScoreUpdateInvalidPlayerInputTest:241 (StickWaterFireGameTest.java)

Test 8: playRound updates scores correctly on many rounds with unseeded generator. (0.0/5.0)

Test Failed!
playRound updates player scores correctly using unseeded generator. expected: but was:
    at StickWaterFireGameTest.playManyRoundsTestUnseeded:170 (StickWaterFireGameTest.java)

Test 7: playRound updates scores correctly on many rounds. (0.0/5.0)

Test Failed!
playRound updates player scores correctly using seeded generator. expected: but was:
    at StickWaterFireGameTest.playManyRoundsTestSeeded:142 (StickWaterFireGameTest.java)

========Main.Java code============

import java.util.*;

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();
   }
}// end class

Solutions

Expert Solution

I have found the following issues witho your code

  • Test case one states thet the computer score should increase if player has made an invalid selection
    • which means we need to increment player score befroe returning false inside the method isValidInput()
  • In the class StickWaterFireGame.java, inside the method playerWins() the logic implemented is incorrect.
    • According to the question w beats f and f beats s but you have implemented it otherwise
    • This is possibly failing test case 2 and 3

Please find below code with both of the above mistakes corrected.

StickWaterFireGame.java (code to copy)

import java.util.Random;

/* This class ecapsulates the state and logic required to play the
Stick, Water, Fire game. The game is played between a user and the computer.
A user enters their choice, either S for stick, F for fire, W for water, and
the computer generates one of these choices at random- all equally likely.
The two choices are evaluated according to the rules of the game and the winner
is declared.

Rules of the game:
S beats W
W beats F
F beats S
no winner on a tie.

Each round is executed by the playRound method. In addition to generating the computer
choice and evaluating the two choices, this class also keeps track of the user and computer
scores, the number of wins, and the total number of rounds that have been played. In the case
of a tie, neither score is updated, but the number of rounds is incremented.

NOTE: Do not modify any of the code that is provided in the starter project. Additional instance variables and methods
are not required to make the program work correctly, but you may add them if you wish as long as
you fulfill the project requirements.

*/
public class StickWaterFireGame {

    // TODO 1: Declare private instance variables here:
    private static Random rand;
    public static int computerScore;
    public static int rounds;
    public static int playerScore;
    private static boolean playerWins;
    private static boolean isTie;
    private static String computerChoice = "";
    private static String playerChoice = "";


  
    /* This constructor assigns the member Random variable, rand, to
    * a new, unseeded Random object.
    * It also initializes the instance variables to their default values:
    * rounds, player and computer scores will be 0, the playerWins and isTie
    * variables should be set to false.
    */
    public StickWaterFireGame() {
    // TODO 2: Implement this method.
    rand = new Random();
    playerScore = 0;
    computerScore = 0;
    rounds = 0;
    playerWins = false;
    isTie = false;
    }

    /* This constructor assigns the member Random variable, rand, to
    * a new Random object using the seed passed in.
    * It also initializes the instance variables to their default values:
    * rounds, player and computer scores will be 0, the playerWins and isTie
    * variables should be set to false.
    */
    public StickWaterFireGame(int seed) {
    // TODO 3: Implement this method.
    rand = new Random(seed);
    playerScore = 0;
    computerScore = 0;
    rounds = 0;
    playerWins = false;
    isTie = false;

    }   

    /* This method returns true if the inputStr passed in is
    * either "S", "W", or "F", false otherwise.
    * Note that the input can be upper or lower case.
    */
    public boolean isValidInput(String inputStr) {
    // TODO 4: Implement this method.
    if (inputStr.equalsIgnoreCase("S") || inputStr.equalsIgnoreCase("W") || inputStr.equalsIgnoreCase("F")) {
    return true;
    }
    computerScore++;
    return false;
    }
  
    /* This method carries out a single round of play of the SWF game.
    * It calls the isValidInput method and the getRandomChoice method.
    * It implements the rules of the game and updates the instance variables
    * according to those rules.
    */
    
    // Returns the choice of the computer for the most recent round of play
    public String getComputerChoice(){
    // TODO 5: Implement this method.
    return computerChoice;
    }

    // Returns true if the player has won the last round, false otherwise.
    public boolean playerWins(){
    // TODO 6: Implement this method.
    if ((playerChoice.equalsIgnoreCase("s"))&&(computerChoice.equalsIgnoreCase("w"))){
    return true;
    }
    else if ((playerChoice.equalsIgnoreCase("w"))&&(computerChoice.equalsIgnoreCase("f"))){
    return true;
    }
    else if ((playerChoice.equalsIgnoreCase("f"))&&(computerChoice.equalsIgnoreCase("s"))){
    return true;
    }
    else {
    return false;
    }
    }



    // Returns the player's cumulative score.
    public int getPlayerScore(){
    // TODO 7: Implement this method.
    return playerScore;
}

// Returns the computer's cumulative score.   
public int getComputerScore(){
// TODO 8: Implement this method.
return computerScore;
}

// Returns the total nuber of rounds played.   
public int getNumRounds(){
// TODO 9: Implement this method.
return rounds;
}

// Returns true if the player and computer have the same score on the last round, false otherwise.
public boolean isTie(){
// TODO 10: Implement this method.
if (playerChoice.equals(computerChoice)) {
return true;
}
return false;
}

/* This "helper" method uses the instance variable of Random to generate an integer
* which it then maps to a String: "S", "W", "F", which is returned.
* This method is called by the playRound method.
*/
private String getRandomChoice() {
// TODO 11: Implement this method.
    int number = rand.nextInt(3)+1;
String choice = null;
if(number == 1) {
choice = "S";
}
else if (number == 2) {
choice = "W";
}
else if (number == 3) {
choice = "F";
}
return choice;
}

public void playRound(String playerChoice) {
// TODO 12: Implement this method.
if(isValidInput(playerChoice)) {
this.playerChoice = playerChoice.toLowerCase();
rounds++;
this.computerChoice = getRandomChoice();
if(playerWins()) {
playerScore++;
playerWins=true;
}
else if(isTie())
isTie=true;
else
computerScore++;
}

}
}

StickWaterFireGame.java (code screenshot)

Sample output screenshot


Related Solutions

Here is my java code. It works and has the correct output, but I need to...
Here is my java code. It works and has the correct output, but I need to add a file and I am not sure how. I cannot use the FileNotFoundException. Please help! import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,0,0}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: "...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that the following test cases work. Note: I have removed all the unnecessary inherited List implementations. I have them to: throw new UnsupportedException(); For compilation, you could also add //TODO. Test (Main) List list = new SparseList<>(); list.add("0"); list.add("1"); list.add(4, "4"); will result in the following list of size 5: [0, 1, null, null, 4]. list.add(3, "Three"); will result in the following list of size...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code Classwork A zoo is developing an educational safari game with various animals. You will write classes representing Elephants, Camels, and Moose. Part A Think through common characteristics of animals, and write a class ZooAnimal. ☑ ZooAnimal should have at least two instance variables of different types (protected), representing characteristics that all animals have values for. ☑ It should also have at least two methods...
This is my C language code. I have some problems with the linked list. I can't...
This is my C language code. I have some problems with the linked list. I can't store the current. After current = temp, I don't know how to move to the next node. current = current-> next keeps making current into NULL. #include #include #include #include struct node{int data; struct node *next;}; int main() {     struct node *head, *current, *temp, *trash;     srand(time(0));     int randNumber = rand()%51;     if(randNumber != 49)     {         temp = (struct node*)malloc(sizeof(struct node));         current = (struct node*)malloc(sizeof(struct node));...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
PHP Language I have XAMPP and I don't know how to display my PHP code. For...
PHP Language I have XAMPP and I don't know how to display my PHP code. For instance, when I create a basic HTML webpage I just open the code into a web browser and it shows me a basic web page. When I try to show a PHP calculation it doesn't show. What are the steps in displaying my PHP doc?
Language: Java I have written this code but not all methods are running. First method is...
Language: Java I have written this code but not all methods are running. First method is running fine but when I enter the file path, it is not reading it. Directions The input file must be read into an input array and data validated from the array. Input file format (500 records maximum per file): comma delimited text, should contain 6 fields: any row containing exactly 6 fields is considered to be invalid Purpose of this code is to :...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT