package INF101.lab1.rockPaperScissors; import java.util.List; import java.util.Random; import java.util.Arrays; import java.util.Scanner; public class RockPaperScissors { public static void main(String[] args) { /* * The code here does two things: * It first creates a new RockPaperScissors -object with the * code `new RockPaperScissors()`. Then it calls the `run()` * method on the newly created object. */ new RockPaperScissors().run(); } Scanner sc = new Scanner(System.in); int roundCounter = 1; int humanScore = 0; int computerScore = 0; List<String> rpsChoices = Arrays.asList("rock", "paper", "scissors"); Random random = new Random(); public void run() { while (true) { System.out.println("Let's play round " + roundCounter); String myChoice = humanChoice(); String compChoice = computerChoice(); String matchSummary = String.format("Human chose %s, computer chose %s. ", myChoice, compChoice); if (myChoice.equals(weaknessOf(compChoice))) { matchSummary += "Human wins!"; humanScore++; } else if (compChoice.equals(weaknessOf(myChoice))) { matchSummary += "Computer wins!"; computerScore++; } else { matchSummary += "It's a tie!"; } System.out.println(matchSummary); System.out.printf("Score: human %s, computer %s\n", humanScore, computerScore); if (!wantsToPlayAgain()) { System.out.println("Bye bye :)"); break; } roundCounter++; } } /** * Reads input from console with given prompt * @param prompt * @return string input answer from user */ public String readInput(String prompt) { System.out.println(prompt); String userInput = sc.next(); return userInput; } /* * Weapon selection */ public String humanChoice() { String userAnswer; while (true) { userAnswer = readInput("Your choice (Rock/Paper/Scissors)?").toLowerCase(); if (rpsChoices.contains(userAnswer)) return userAnswer; else System.out.printf("I do not understand %s. Could you try again?\n", userAnswer); } } public String computerChoice() { int randomNumber = random.nextInt(rpsChoices.size()); return rpsChoices.get(randomNumber); } public boolean wantsToPlayAgain() { String continuePlayingAnswer; while (true) { continuePlayingAnswer = readInput("Do you wish to continue playing? (y/n)?").toLowerCase(); if (continuePlayingAnswer.equals("n")) return false; else if (continuePlayingAnswer.equals("y")) return true; else System.out.println("I do not understand " + continuePlayingAnswer + ". Could you try again?"); } } public String weaknessOf(String string) { if (string.equals("rock")) { return "paper"; } else if (string.equals("scissors")) { return "rock"; } else { return "scissors"; } } }