Write a game that plays many rounds of Rock Paper Scissor. The user and computer
ID: 3762145 • Letter: W
Question
Write a game that plays many rounds of Rock Paper Scissor. The user and computer will each choose between three items: rock (defeats scissor, but loses to paper), paper (defeats rock, but loses to scissors), and scissors (defeats paper, but loses to rock). If the player and computer choose the same item, the game is a tie. Extend this program to include different algorithmic strategies for choosing the best item. Should the computer pick randomly? Should the computer always pick a particular item or a repeating pattern of items? Should it count the number of times the opponent chooses various items and base its strategy on this history? Be creative here. Each strategy should be in its own method, and at the start of a round of games the user should be able to choose which strategy to play against. Include at least two strategies.
(java)
Explanation / Answer
public class RockPaperScissors { static int cScore, pScore, tie, rounds; enum RPS { R("Rock", "S"), P("Paper", "R"), S("Scissors", "P"); private final String beats, name; RPS(String name, String beats) { this.beats = beats; this.name = name; } int compare(RPS other) { return other == this? 0 : other == valueOf(beats)? 1 : -1; } String fullName() { return name; } } public static void main (String[] args) { final Scanner input = new Scanner(System.in); final Random rgen = new Random(); System.out.println("Hello, for this exercise we're going to be playing everyone's favourite game, Rock-Paper-Scissors!"); while (true) { final RPS playerChoice, compChoice = RPS.values()[rgen.nextInt(3)]; System.out.println("Please make your selection: R - Rock. P - Paper. S - Scissors"); try { playerChoice = RPS.valueOf(input.nextLine().toUpperCase()); } catch (Exception e) { System.out.println( "Sorry, you didn't pick Rock, Paper, or Scissors. The game will end now. " + "Here are the final scores after " + rounds +" rounds: You Computer Ties " + " "+ pScore +" " + cScore + " " + tie); return; } System.out.println(" Computer picked " + compChoice.fullName() + "!"); switch (playerChoice.compare(compChoice)) { case 0: System.out.println("Tie Game! "); tie++; break; case -1: System.out.println(compChoice.fullName() + " beats " + playerChoice.fullName() + "!"); System.out.println("**Computer Wins!** "); cScore++; break; case 1: System.out.println(playerChoice.fullName() + " beats " + compChoice.fullName() + "!"); System.out.println("**Player Wins!** "); pScore++; } rounds++; } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.