Untitled
unknown
plain_text
4 years ago
2.6 kB
8
Indexable
import java.util.Scanner;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
public class Main {
static Scanner scanner = new Scanner(System.in);
static Map<String, Integer> log = new HashMap<>();
final static String VALUE_ROCK = "ROCK";
final static String VALUE_PAPER = "PAPER";
final static String VALUE_SCISSORS = "SCISSORS";
final static String PLAYER_WON = "PLAYER";
final static String COMPUTER_WON = "COMPUTER";
final static String VALUE_DRAW = "DRAW";
public static void main(String[] args) {
while (true) {
startGame();
}
}
public static String getComputerChoice() {
var random = new Random();
var number = random.nextInt((3 - 1) + 1) + 1;
switch (number) {
case 1:
return VALUE_PAPER;
case 2:
return VALUE_SCISSORS;
default:
return VALUE_ROCK;
}
}
public static String getUserChoice() {
System.out.print(VALUE_ROCK + ", " + VALUE_PAPER + ", " + VALUE_SCISSORS + "?: ");
var input = scanner.nextLine().toUpperCase().trim();
switch (input) {
case VALUE_ROCK:
return VALUE_ROCK;
case VALUE_PAPER:
return VALUE_PAPER;
case VALUE_SCISSORS:
return VALUE_SCISSORS;
default:
System.out.println("Your input is invalid. Choosing " + VALUE_ROCK + " instead.");
return VALUE_ROCK;
}
}
public static String determineWinner(String computerChoice, String userChoice) {
if (userChoice.equals(computerChoice)) {
return VALUE_DRAW;
} else if (userChoice.equals(VALUE_ROCK) && computerChoice.equals(VALUE_SCISSORS) ||
userChoice.equals(VALUE_SCISSORS) && computerChoice.equals(VALUE_PAPER) ||
userChoice.equals(VALUE_PAPER) && computerChoice.equals(VALUE_ROCK)
) {
return PLAYER_WON;
}
return COMPUTER_WON;
}
public static void startGame() {
String computerChoice = getComputerChoice();
String userChoice = getUserChoice();
String winner = determineWinner(computerChoice, userChoice);
System.out.println("Computer choice: " + computerChoice);
System.out.println("User choice: " + userChoice);
if (winner.equals(VALUE_DRAW)) {
System.out.println("\nIt's a " + VALUE_DRAW + "!");
} else {
System.out.println("\nWinner is: " + winner);
}
writeToLog(winner, 0);
printLog();
}
public static void writeToLog(String winner, int count) {
log.putIfAbsent(winner, count);
if (log.containsKey(winner)) {
log.put(winner, (log.get(winner) + 1));
}
}
public static void printLog() {
System.out.println("\n----\nLog:\n----\n");
for (String value : log.keySet()) {
System.out.println(value + ": " + log.get(value));
}
}
}Editor is loading...