forked from Kartikey0205/Program1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPC.java
More file actions
75 lines (69 loc) · 1.99 KB
/
RPC.java
File metadata and controls
75 lines (69 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS, /*LIZARD, SPOCK*/;
public List<Item> losesToList;
public boolean losesTo(Item other) {
return losesToList.contains(other);
}
static {
SCISSORS.losesToList = Arrays.asList(ROCK/*, SPOCK*/);
ROCK.losesToList = Arrays.asList(PAPER/*, SPOCK*/);
PAPER.losesToList = Arrays.asList(SCISSORS/*, LIZARD*/);
/*
SPOCK.losesToList = Arrays.asList(PAPER, LIZARD);
LIZARD.losesToList = Arrays.asList(SCISSORS, ROCK);
*/
}
}
//EnumMap uses a simple array under the hood
public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
for(Item item:Item.values())
put(item, 1);
}};
private int totalThrows = Item.values().length;
public static void main(String[] args){
RPS rps = new RPS();
rps.run();
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Make your choice: ");
while(in.hasNextLine()){
Item aiChoice = getAIChoice();
String input = in.nextLine();
Item choice;
try{
choice = Item.valueOf(input.toUpperCase());
}catch (IllegalArgumentException ex){
System.out.println("Invalid choice");
continue;
}
counts.put(choice, counts.get(choice) + 1);
totalThrows++;
System.out.println("Computer chose: " + aiChoice);
if(aiChoice == choice){
System.out.println("Tie!");
}else if(aiChoice.losesTo(choice)){
System.out.println("You chose...wisely. You win!\n");
}else{
System.out.println("You chose...poorly. You losen");
}
System.out.print("Make your choice: ");
}
}
private static final Random rng = new Random();
private Item getAIChoice() {
int rand = rng.nextInt(totalThrows);
for(Map.Entry<Item, Integer> entry:counts.entrySet()){
Item item = entry.getKey();
int count = entry.getValue();
if(rand < count){
List<Item> losesTo = item.losesToList;
return losesTo.get(rng.nextInt(losesTo.size()));
}
rand -= count;
}
return null;
}
}