Skip to content

Commit d8b409d

Browse files
committed
Add RockPaperScissors game implementation (Jokenpo)
1 parent 21eff8a commit d8b409d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.thealgorithms.puzzlesandgames;
2+
3+
import java.util.Random;
4+
import java.util.Scanner;
5+
6+
/**
7+
* RockPaperScissors (Jokenpô)
8+
* Simple terminal game where the user plays Rock, Paper, Scissors against the computer.
9+
* Rules:
10+
* - Rock beats Scissors
11+
* - Scissors beats Paper
12+
* - Paper beats Rock
13+
* Example:
14+
* User: rock
15+
* Computer: scissors
16+
* Result: You win!
17+
* Author: Lígia Alves (Hacktoberfest 2025)
18+
*/
19+
public class RockPaperScissors {
20+
21+
public static void main(String[] args) {
22+
Scanner scanner = new Scanner(System.in);
23+
Random random = new Random();
24+
25+
String[] options = {"rock", "paper", "scissors"};
26+
27+
System.out.println("=== Rock Paper Scissors Game ===");
28+
System.out.println("Type 'rock', 'paper', or 'scissors'. Type 'exit' to quit.");
29+
30+
while (true) {
31+
System.out.print("\nYour choice: ");
32+
String userChoice = scanner.nextLine().trim().toLowerCase();
33+
34+
if (userChoice.equals("exit")) {
35+
System.out.println("Thanks for playing! ");
36+
break;
37+
}
38+
39+
// Validate input
40+
if (!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
41+
System.out.println("Invalid choice! Try again.");
42+
continue;
43+
}
44+
45+
// Computer chooses randomly
46+
String computerChoice = options[random.nextInt(3)];
47+
System.out.println("Computer chose: " + computerChoice);
48+
49+
// Determine result
50+
String result = getResult(userChoice, computerChoice);
51+
System.out.println(result);
52+
}
53+
54+
scanner.close();
55+
}
56+
57+
private static String getResult(String userChoice, String computerChoice) {
58+
if (userChoice.equals(computerChoice)) {
59+
return "It's a tie!";
60+
} else if (
61+
(userChoice.equals("rock") && computerChoice.equals("scissors")) ||
62+
(userChoice.equals("scissors") && computerChoice.equals("paper")) ||
63+
(userChoice.equals("paper") && computerChoice.equals("rock"))
64+
) {
65+
return "You win! :D ";
66+
} else {
67+
return "You lose! :( ";
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)