NOTE if the player enters an invalid choice, the computer wins by default.
NOTE To generate a random choice, this code uses the Random object as we have used in the previous labs. A value of 0 will be Plant, 1 will be Water and 2 will be Fire. Note that you MUST use these assignments of numbers to types for your submission to be able to pass the test cases!
NOTE You MUST only declare and instantiate one single Random object to be able to match the test cases. And this must be done outside of the main game loop and in the main method. Your methods should NOT create their own Random object. Note that this is typically how Random objects are used - you create them once and then use the same Random object for your entire program, rather than creating new ones every time you need a new random number.
NOTE You MUST only declare and instantiation on single Scanner object to be able to run the test cases. And this must be done outside of the main game loop and in the main method. Your methods should NOT create another Scanner object but instead should use the one passed in as a parameter. Note that this is also typically how Scanner objects get used - you create them once and then use the same Scanner object for your entire program.
Create a new project in your workspace and a new class named DragonTrainers. Then paste the code below into the class. Note that this "skeleton" of code includes a main method that has already been written for you. Read the main method and make sure you understand what it is doing and how it is calling the other methods in the program. Comments are included to help you understand what each piece of the code is supposed to be accomplishing. DO NOT CHANGE THE CODE IN THE MAIN METHOD TO GET YOUR SOLUTION TO WORK! Full credit for the assignment will only be earned if you can get the code to work without changing the main method provided.
/**
* YOUR DESCRIPTION OF THIS PROGRAM HERE
* @author YOUR NAME HERE
* @version DATE HERE
*/
import java.util.Random;
import java.util.Scanner;
public class DragonTrainers {
/**
* Constant array to hold the types of the dragon in order. 0 - Plant, 1 -
* Water, 2 - Fire. Make sure your code does not change these values!
*/
private static final String[] DRAGONS = { "Plant", "Water", "Fire" };
/**
* Prompts the user with the message: "How many matches will we play? " and
* takes in an integer as input. If the user enters a value that is 0 or
* negative, displays the error message: "ERROR - number of matches must
* be positive!" and asks again. Continues looping until the user enters a
* positive number.
*
* @param input
* - Scanner to read values from the keyboard
* @return - an integer value strictly larger than zero.
*/
public static int getNumberOfMatches(Scanner input) {
// TODO - complete this method
// TODO - the following line is only here to allow this program to
// compile. Replace it and remove this comment when you complete
// this method.
return 0;
}
/**
* Prompts the user with the message "Please select a dragon
* [Plant/Water/Fire]: " and waits for user input. If the user enters a
* blank line, prints the error message "ERROR - Dragon prompt cannot be
* empty" and asks the user again. Repeats until the user enters a non-blank
* line.
*
* @param input
* - Scanner to read values from the keyboard
* @return A non-empty String entered by the user
*/
public static String promptForDragon(Scanner input) {
// TODO - complete this method
// TODO - the following line is only here to allow this program to
// compile. Replace it and remove this comment when you complete
// this method.
return "";
}
/**
* Takes a single UPPERCASE character. If it is a 'W','P' or 'F' returns the
* appropriate numeric value given the dragon types in the array DRAGON
* (i.e. 0 for 'P', 1 for 'W', 2 for 'F'). If it is none of these returns a
* -1 to represent an invalid value.
*
* @param dragon
* - the UPPERCASE character to look up a value for.
* @return 0 if dragon is 'P', 1 if dragon is 'W', 2 if dragon is 'F', -1
* otherwise
*/
public static int dragonToNumber(char dragon) {
// TODO - complete this method
// TODO - the following line is only here to allow this program to
// compile. Replace it and remove this comment when you complete
// this method.
return 0;
}
/**
* Takes a number representing the player's choice and another representing
* the computer's choice. Returns a 0 if they tie, a 1 if the player wins,
* and a -1 if the player loses. Note that the values map to the indexes of
* the array DRAGONS above (0 is a Plant dragon, 1 is a Water dragon, 2 is a
* Fire Dragon).
*
* @param player
* - value 0-2 representing player dragon choice
* @param cpu
* - value 0-2 representing computer dragon choice
* @return 1 if the player wins, -1 if the computer wins, 0 if they tie
*/
public static int determineWinner(int player, int cpu) {
// TODO - complete this method
// TODO - the following line is only here to allow this program to
// compile. Replace it and remove this comment when you complete
// this method.
return 0;
}
/**
* Takes a number representing the player's choice and another number
* representing the computer's choice, and a third number that is positive
* if the player is the winner, negative if the computer is the winner, and
* 0 if they tied. Then displays the appropriate player defeats computer or
* computer defeats player or tie message as given in the project
* description.
*
* @param player
* index into the DRAGONS array representing the player choice
* @param cpu
* index into the DRAGONS array representing the computer's
* choice
* @param winner
* 0 for a tie, positive for a player win, negative for a
* computer win
*/
public static void displayMatchResult(int player, int cpu, int winner) {
// TODO - complete this method
}
/**
* Takes the number of wins, losses and ties and displays the final message
* and summary statistics as given in the project description.
*
* @param wins
* number of total wins for the player
* @param losses
* number of total losses for the player
* @param ties
* number of ties
*/
public static void displayFinalResult(int wins, int losses, int ties) {
// TODO - complete this method
}
/**
* NOTE: The main method has been completed for you. If you correctly
* complete the methods above, the main method will "just work" and produce
* the correct output.
*/
public static void main(String[] args) {
// Prompt for a random number seed
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a random seed: ");
int seed = Integer.parseInt(keyboard.nextLine());
// Create a Random instance with the seed
Random rnd = new Random(seed);
// Prompt for number of matches to play
int totalMatches = getNumberOfMatches(keyboard);
// Start with wins, losses and ties at 0.
// Repeat until all matches have been played (use the sum of the
// results so we don't need another variable)
int wins = 0, losses = 0, ties = 0;
while ((wins + losses + ties) < totalMatches) {
// Ask the user for a dragon to use
String input = promptForDragon(keyboard);
// Get the first character of the user's input as an uppercase
// value.
char dChar = input.toUpperCase().charAt(0);
// Convert the user's input to an index for the DRAGONS array
int playerDragon = dragonToNumber(dChar);
// Generate a choice between 0 and 2 for the computer
int cpuDragon = rnd.nextInt(3);
// Display the results
System.out.println("I chose: " + DRAGONS[cpuDragon] + " dragon.");
// If the player didn't enter a valid choice, print out an error
// message and increase the number of losses.
if (playerDragon == -1) {
System.out.println("You don't have the " + input + " dragon.");
System.out.println("So no dragon fights for you.");
System.out.println("I win by default!");
losses++;
} else {
// Print out the player's choice.
System.out.println("You chose: " + DRAGONS[playerDragon] + " dragon.");
// Determine who won the match.
int winner = determineWinner(playerDragon, cpuDragon);
// Display the result of the match.
displayMatchResult(playerDragon, cpuDragon, winner);
// Increase the count of wins, losses or ties according to
// who won the match.
if (winner > 0) {
wins++;
} else if (winner < 0) {
losses++;
} else {
ties++;
}
}
System.out.println();
}
// Display the final summary of the match to the screen.
displayFinalResult(wins, losses, ties);
// Don't forget to close the Scanner!
keyboard.close();
}
}
Here is one example of the game in action. Note that as always, user inputs are in BOLD:
Enter a random seed: 33 How many matches will we play? 3 Please select a dragon [Plant/Water/Fire]: F I chose: Plant dragon. You chose: Fire dragon. Fire defeats Plant - you win! Please select a dragon [Plant/Water/Fire]: W I chose: Plant dragon. You chose: Water dragon. Plant defeats Water - you lose! Please select a dragon [Plant/Water/Fire]: P I chose: Fire dragon. You chose: Plant dragon. Fire defeats Plant - you lose! The tournament is over! We tied 0 matches. I won 2 matches. You won 1 matches. I am the winner!
Here is another example of the game in action. Note that if the user enters an invalid response, the computer wins by default. But also note that only the first character of the input matters when determining whether or not the input is valid:
Enter a random seed: 24 How many matches will we play? 3 Please select a dragon [Plant/Water/Fire]: f I chose: Water dragon. You chose: Fire dragon. Water defeats Fire - you lose! Please select a dragon [Plant/Water/Fire]: alsdf I chose: Water dragon. You don't have the alsdf dragon. So no dragon fights for you. I win by default! Please select a dragon [Plant/Water/Fire]: pfjslkd I chose: Plant dragon. You chose: Plant dragon. A Tie! The tournament is over! We tied 1 matches. I won 2 matches. You won 0 matches. I am the winner!
If there is a tie, the final message should indicate that neither player is the winner as in the transcript below.
Enter a random seed: 33 How many matches will we play? 1 Please select a dragon [Plant/Water/Fire]: P I chose: Plant dragon. You chose: Plant dragon. A Tie! The tournament is over! We tied 1 matches. I won 0 matches. You won 0 matches. Neither of us can claim victory here!
Note that if the user enters a non-positive value for the number of matches, the program should reject it and make them enter a positive value, and if the user enters a blank line for the dragon the program should reject it and make them enter some non-empty value:
Enter a random seed: 33 How many matches will we play? 0 ERROR - number of matches must be positive! How many matches will we play? -1 ERROR - number of matches must be positive! How many matches will we play? 1 Please select a dragon [Plant/Water/Fire]: ERROR - Dragon prompt cannot be empty. Please select a dragon [Plant/Water/Fire]: P I chose: Plant dragon. You chose: Plant dragon. A Tie! The tournament is over! We tied 1 matches. I won 0 matches. You won 0 matches. Neither of us can claim victory here!
You MUST use the skeleton for your code. Your solution must include the implementation and use of all of the methods defined in this skeleton - think about what each method does and how it relates to the program overall. You MUST NOT make any changes to the main method - violating any of these requirements will cause a deduction in the points earned. Remember - a goal for this assignment is to practice writing methods that conform to a particular specification! The test cases for this program are written to let you test the individual methods as well as the final output. Test incrementally! Write one method at a time and then test it rather than waiting until you've written the whole program and testing it all at once! Taking an incremental approach will help you keep the whole assignment manageable by tackling it in pieces. Note also that you can complete the methods in any order
NOTE The template includes a private constant array named DRAGONS. The order of the Strings in the array DRAGONS matches the mapping of ints to dragon types required by this assignment. Since DRAGONS is declared at the class level - outside of any method - it is in scope for all of the methods in the class. You should use this array in your solutions, but do NOT change the values in this array when you run your solution.
NOTE 2: It is easy to write an overly complex determineWinner method if you think about it as checking every possible combination of choices for the player and the computer. If you think about the order required and given in the array in the code, you can see that it has been purposefully set up so that they are in a particular order. The dragon type at position 1 is beaten by the type at position 0, the type at position 2 is beaten the type at position 1, and the type at position 0 is beaten by the type at position 2. Notice that this is NOT strictly "the bigger index is beaten by the opponent", nor is it exactly "you beat your opponent if your index is exactly 1 smaller than their index", but there is a fairly elegant way to the comparisons without just "brute forcing" all of the possible combinations. Think about how to write a determineWinner method that makes use of this ordering instead of just brute forcing all of the possible combinations in a giant if-else-if-else statement. HINT One approach involves the fact that the winner of the pair is exactly one smaller than the loser in 2 of the 3 cases.
import java.util.Random;
import java.util.Scanner;
public class DragonTrainers {
/**
* Constant array to hold the types of the dragon in
order. 0 - Plant, 1 -
* Water, 2 - Fire. Make sure your code does not change
these values!
*/
private static final String[] DRAGONS = { "Plant",
"Water", "Fire" };
/**
* Prompts the user with the message: "How many matches
will we play? " and
* takes in an integer as input. If the user enters a
value that is 0 or
* negative, displays the error message: "ERROR -
number of matches must be
* positive!" and asks again. Continues looping until
the user enters a
* positive number.
*
* @param input
* - Scanner to read values from the keyboard
* @return - an integer value strictly larger than
zero.
*/
public static int getNumberOfMatches(Scanner input)
{
int totalMatches = 0;
do {
System.out.print("How many matches will we play? ");
// Check if
user enters a 0 or a negative number
if
((totalMatches = Integer.parseInt(input.nextLine())) <= 0)
System.out.print("ERROR - number of matches must
be positive!\n");
} while (totalMatches <= 0);
return totalMatches;
}
/**
* Prompts the user with the message "Please select a
dragon
* [Plant/Water/Fire]: " and waits for user input. If
the user enters a
* blank line, prints the error message "ERROR - Dragon
prompt cannot be
* empty" and asks the user again. Repeats until the
user enters a non-blank
* line.
*
* @param input
* - Scanner to read values from the keyboard
* @return A non-empty String entered by the user
*/
public static String promptForDragon(Scanner input)
{
String dragon = "";
do {
System.out.print("Please select a dragon [Plant/Water/Fire]:
");
// Check if
user enters a blank line
if ((dragon =
input.nextLine().trim()).isEmpty())
System.out.print("ERROR - Dragon prompt cannot
be empty\n");
} while (dragon.isEmpty());
return dragon;
}
/**
* Takes a single UPPERCASE character. If it is a
'W','P' or 'F' returns the
* appropriate numeric value given the dragon types in
the array DRAGON
* (i.e. 0 for 'P', 1 for 'W', 2 for 'F'). If it is
none of these returns a
* -1 to represent an invalid value.
*
* @param dragon
* - the UPPERCASE character to look up a value
for.
* @return 0 if dragon is 'P', 1 if dragon is 'W', 2 if
dragon is 'F', -1
* otherwise
*/
public static int dragonToNumber(char dragon) {
int dragonNum = -1;
switch (dragon) {
case 'P': // Plant
dragonNum =
0;
break;
case 'W': // Water
dragonNum =
1;
break;
case 'F': // Fire
dragonNum =
2;
}
return dragonNum;
}
/**
* Takes a number representing the player's choice and
another representing
* the computer's choice. Returns a 0 if they tie, a 1
if the player wins,
* and a -1 if the player loses. Note that the values
map to the indexes of
* the array DRAGONS above (0 is a Plant dragon, 1 is a
Water dragon, 2 is a
* Fire Dragon).
*
* @param player
* - value 0-2 representing player dragon choice
* @param cpu
* - value 0-2 representing computer dragon
choice
* @return 1 if the player wins, -1 if the computer
wins, 0 if they tie
*/
public static int determineWinner(int player, int cpu)
{
int result;
// Find the difference between
player and cpu
int diff = player - cpu;
// Find result
if ((diff == -1) || (diff == 2)) //
Player wins if diff is -1 or 2
result =
1;
else if ((diff == 1) || (diff ==
-2)) // CPU wins if diff is 1 or -2
result =
-1;
else // TIE
result = 0;
return result;
}
/**
* Takes a number representing the player's choice and
another number
* representing the computer's choice, and a third
number that is positive
* if the player is the winner, negative if the
computer is the winner, and
* 0 if they tied. Then displays the appropriate player
defeats computer or
* computer defeats player or tie message as given in
the project
* description.
*
* @param player
* index into the DRAGONS array representing the player
choice
* @param cpu
* index into the DRAGONS array representing the
computer's
* choice
* @param winner
* 0 for a tie, positive for a player win, negative for
a
* computer win
*/
public static void displayMatchResult(int player, int
cpu, int winner) {
// Print winner
if (winner == 1) // Player
wins
System.out.print(DRAGONS[player] + " defeats " + DRAGONS[cpu] + " -
you win!\n");
else if (winner == -1) // CPU
wins
System.out.print(DRAGONS[cpu] + " defeats " + DRAGONS[player] + " -
you lose!\n");
else // Tie
System.out.print("A Tie!\n");
}
/**
* Takes the number of wins, losses and ties and
displays the final message
* and summary statistics as given in the project
description.
*
* @param wins
* number of total wins for the player
* @param losses
* number of total losses for the player
* @param ties
* number of ties
*/
public static void displayFinalResult(int wins, int
losses, int ties) {
// Print statistics
System.out.print("The tournament is
over!\n");
System.out.print("We tied " + ties
+ " matches.\n");
System.out.print("I won " + losses
+ " matches.\n");
System.out.print("You won " + wins
+ " matches.\n");
// Print overall winner
if (wins > losses)
System.out.print("You are the winner!");
else if (wins < losses)
System.out.print("I am the winner!");
else
System.out.print("Neither of us can claim victory here!");
}
/**
* NOTE: The main method has been completed for you. If
you correctly
* complete the methods above, the main method will
"just work" and produce
* the correct output.
*/
public static void main(String[] args) {
// Prompt for a random number
seed
Scanner keyboard = new
Scanner(System.in);
System.out.print("Enter a random
seed: ");
int seed =
Integer.parseInt(keyboard.nextLine());
// Create a Random instance with
the seed
Random rnd = new Random(seed);
// Prompt for number of matches
to play
int totalMatches =
getNumberOfMatches(keyboard);
// Start with wins, losses and
ties at 0.
// Repeat until all matches have
been played (use the sum of the
// results so we don't need another
variable)
int wins = 0, losses = 0, ties =
0;
while ((wins + losses + ties) <
totalMatches) {
// Ask the user
for a dragon to use
String input =
promptForDragon(keyboard);
// Get the
first character of the user's input as an uppercase
// value.
char dChar =
input.toUpperCase().charAt(0);
// Convert
the user's input to an index for the DRAGONS array
int playerDragon
= dragonToNumber(dChar);
// Generate a
choice between 0 and 2 for the computer
int cpuDragon =
rnd.nextInt(3);
// Display
the results
System.out.println("I chose: " + DRAGONS[cpuDragon] + "
dragon.");
// If the
player didn't enter a valid choice, print out an error
// message and
increase the number of losses.
if (playerDragon
== -1) {
System.out.println("You don't have the " + input
+ " dragon.");
System.out.println("So no dragon fights for
you.");
System.out.println("I win by default!");
losses++;
} else {
// Print out the player's choice.
System.out.println("You chose: " +
DRAGONS[playerDragon] + " dragon.");
// Determine who won the match.
int winner = determineWinner(playerDragon,
cpuDragon);
// Display the result of the match.
displayMatchResult(playerDragon, cpuDragon,
winner);
// Increase the count of wins, losses or ties
according to
// who won the match.
if (winner > 0) {
wins++;
} else if (winner < 0) {
losses++;
} else {
ties++;
}
}
System.out.println();
}
// Display the final summary of the
match to the screen.
displayFinalResult(wins, losses,
ties);
// Don't forget to close the
Scanner!
keyboard.close();
}
}
SAMPLE OUTPUT:

RUN #2

NOTE if the player enters an invalid choice, the computer wins by default. NOTE To generate...
Reposting question with additional information. I am writing a java program that has the computer play a game of ConnectFour with the user, I am having trouble with the code that tells who wins the game. when I play the game after getting four in a row the program just continues to go on. I believe my FindLocalWinner method should be correct, so I need help with the findWinner method. /** * Check for a win starting at a given...
Java Program Note: no break statements or switch staements High, Low, Sevens For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------...
For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------ ------ High 1 x Wager Low 1 x Wager Sevens 4 x...
The following code skeleton contains a number of uncompleted methods. With a partner, work to complete the method implementations so that the main method runs correctly: /** * DESCRIPTION OF PROGRAM HERE * @author YOUR NAME HERE * @author PARTNER NAME HERE * @version DATE HERE * */ import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class ArrayExercises { /** * Given a random number generator and a length, create a new array of that * length and fill it from...
Modify your Rock Paper Scissor (Lizard/Spock) game from Week 5 to generate a random number for Player 2 and assign that as Player 2's choice. The rest of your program should stay the same. You can use your program with the nested if statements or the switch statement. The implementation should use the Random class to get your random number. The assignment is worth 10 points. Upload your submission to the assignment. code: import java.util.Scanner; public class RPSLSYourLastName { ...
JAVA Beginnings of a paper-rock-scissors game. Paper-rock-scissors is a game often used to make decisions. There are two players. Each player secretly chooses either, paper, rock or scissors. At the count of three, each player reveals what they have chosen. The winner of the game is determined this way: paper beats rock (because paper covers rock) rock beats scissors (because rock crushes scissors) scissors beat paper (because scissors cut paper) If the two players choose the same item, it is...
C++ Write a program that plays the rock, paper, scissors game. Rock beats scissors; scissors beats paper; paper beats rock. You must use these specific functions in your program. These are the prototypes: char generateP2toss(); int checkThrow(char, char); void printStatistics(int, int, int, int); void finalStatistics(int, int, int, int); void welcome(); Notes on these functions: generateP2toss() will generate the computer's toss (the computer is player2). It returns either an "r", "p", or "s/" checkThrow(char char) will check the throw by passing...
This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe { private char currentPlayer; private char[][] board; private char winner; /** * Default constructor * Initializes the board to be 3 by 3 and...
PLEASE INCLUDE SAW-PROMPTS FOR 2 PLAYERS NAMES(VALIDATE NAMES). SHOW MENU (PLAYER MUST SELECT FROM MENU B4 THE GAME STARTS 1=PLAY GAME, 2=SHOW GAME RULES, 3=SHOW PLAYER STATISTICS, AND 4=EXIT GAME WITH A GOODBYE MESSAGE.) PLAYERS NEED OPTION TO SHOW STATS(IN A DIFFERNT WINDOW-FOR OPTION 3)-GAME SHOULD BE rock, paper, scissor and SAW!! PLEASE USE A JAVA GRAPHICAL USER INTERFACE. MUST HAVE ROCK, PAPER, SCISSORS, AND SAW PLEASE This project requires students to create a design for a “Rock, Paper, Scissors,...
Please help with this, and leave comments explainging the code you wrote, thank you for your help Write a Lottery class that simulates a 6-number lottery (e.g. "Lotto"). The class should have an array of six integers named lotteryNumbers, and another array of six integers named userLotteryPicks. The class' constructor should use the Random class to generate a unique random number in the range of 1 to 60 for each of the 6 elements in the lotteryNumbers array. Thus, there...