-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPSLS.java
More file actions
100 lines (97 loc) · 2.75 KB
/
Copy pathRPSLS.java
File metadata and controls
100 lines (97 loc) · 2.75 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.Scanner;
public class RPSLS{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
// We ask the player to choose his play
System.out.print("Enter your play: R, P, S, L, O: ");
String humanPlay = in.next();
String computerPlay; String winner;
// We call the "computer" method to know the play of the computer
computerPlay = computer();
System.out.println("Computer play is " + computerPlay);
// We call the "compare" method to determine who the winner is and print it
winner = compare(humanPlay,computerPlay);
if (winner != "none"){
System.out.println(winner + " win !");
}
}
public static String computer(){
// generate a random number between 0 and 1, so we can give equal chances to each possiblility
double random = Math.random();
String computerPlay = "none";
if (random < 0.2) {
computerPlay = "R";
} else if (random < 0.4){
computerPlay = "P";
} else if (random < 0.6){
computerPlay = "S";
} else if (random < 0.8){
computerPlay = "L";
} else if (random < 1){
computerPlay = "O";
}
return computerPlay;
}
public static String compare(String str1, String str2){
String winner = "none";
str1 = str1.toUpperCase();
if (str1.equals(str2)){
// In case of a draw, we call the main method so the player can play again
System.out.println(" Draw. Play again !");
main(null);
// We design the conditionals that decide the winner
} else if (str1.equals("R")){
if (str2 == "P"){
winner = "computer";
} else if (str2 == "S"){
winner = "player";
} else if (str2 == "L"){
winner = "player";
} else if (str2 == "O"){
winner = "computer";
}
} else if (str1.equals("P")){
if (str2 == "R"){
winner = "player";
} else if (str2 == "S"){
winner = "computer";
} else if (str2 == "L"){
winner = "computer";
} else if (str2 == "O"){
winner = "player";
}
} else if (str1.equals("S")){
if (str2 == "R"){
winner = "computer";
} else if (str2 == "P"){
winner = "player";
} else if (str2 == "L"){
winner = "player";
} else if (str2 == "O"){
winner = "computer";
}
} else if (str1.equals("L")){
if (str2 == "R"){
winner = "computer";
} else if (str2 == "S"){
winner = "computer";
} else if (str2 == "P"){
winner = "player";
} else if (str2 == "O"){
winner = "player";
}
} else if (str1.equals("O")){
if (str2 == "R"){
winner = "player";
} else if (str2 == "S"){
winner = "player";
} else if (str2 == "L"){
winner = "computer";
} else if (str2 == "O"){
winner = "computer";
}
}
// return the winner (computer or player)
return winner;
}
}