-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClac.java
83 lines (75 loc) · 2.32 KB
/
Clac.java
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
import java.util.Random;
import java.util.Scanner;
public class Clac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
String userChoice = inputHandler(input, "Enter your choice (rock, paper, scissors) or 'exit' to quit:\t");
if (userChoice.equals("exit")) {
System.out.println("Game exited. Cya!");
break;
}
String result = playGame(userChoice);
System.out.println(result);
System.out.print("Do you want to play again? (yes/no)\t");
String playAgain = input.nextLine().toLowerCase();
if (!playAgain.equals("yes")) {
System.out.println("Game exited. Cya!");
break;
}
}
input.close();
}
public static String playGame(String userChoice) {
Random random = new Random();
int computerRandom = random.nextInt(3);
String computerChoice = computerRandGen(computerRandom);
return winner(userChoice, computerChoice);
}
public static String inputHandler(Scanner input, String prompt) {
String userChoice;
while(true) {
System.out.print(prompt);
userChoice = input.nextLine().toLowerCase();
if (userChoice.equals("exit")) {
return userChoice;
}
if (!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Invalid choice. Please try again.");
continue;
}
break;
}
return userChoice;
}
public static String computerRandGen(int randNum) {
String computerChoice = "";
if (randNum == 0) {
computerChoice = "rock";
} else if (randNum == 1) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
System.out.print("Computer chose: " + computerChoice + ". ");
return computerChoice;
}
public static String winner(String userChoice, String computerChoice) {
int userScore = 0;
int computerScore = 0;
boolean userWinChk = (
(userChoice.equals("rock") && computerChoice.equals("scissors")) ||
(userChoice.equals("paper") && computerChoice.equals("rock")) ||
(userChoice.equals("scissors") && computerChoice.equals("paper"))
);
if (userChoice.equals(computerChoice)) {
return "It's a tie!";
} else if (userWinChk == true) {
userScore++;
return "YOU WIN!";
} else {
computerScore++;
return "COMPUTER WINS!";
}
}
}