-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEasyNim.java
95 lines (79 loc) · 2.95 KB
/
EasyNim.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
84
85
86
87
88
89
90
91
92
93
94
95
import java.util.Scanner;
import java.util.Stack;
public class EasyNim {
public static void main(String[] args) {
System.out.println("\nWelcome to Easy Mode Nim!");
Scanner scanner = new Scanner(System.in);
Stack<Integer>[] piles = new Stack[4];
piles[1] = new Stack<>();
piles[2] = new Stack<>();
piles[3] = new Stack<>();
for (int i = 1; i <= 3; i++) {
for (int j = 0; j < 3 + 2 * (i - 1); j++) {
piles[i].push(1); // Each object represented by '1'
}
}
// Game loop
while (!isGameOver(piles)) {
// Display current state of the piles
displayPiles(piles);
// Player 1's turn
playerTurn(1, piles, scanner);
// Check if the game is over
if (isGameOver(piles)) {
System.out.println("Congratulations, Player 1 won!");
break;
}
// Display current state of the piles
displayPiles(piles);
// Player 2's turn
playerTurn(2, piles, scanner);
// Check if the game is over
if (isGameOver(piles)) {
System.out.println("Congratulations, Player 2 won!");
break;
}
}
scanner.close();
}
// Method to display current state of the piles
private static void displayPiles(Stack<Integer>[] piles) {
System.out.println("Current piles: ");
for (int i = 1; i <= 3; i++) { // Start from 1
System.out.println("Pile " + i + ": " + piles[i].size() + " ");
}
System.out.println();
}
// Method for player's turn
private static void playerTurn(int player, Stack<Integer>[] piles, Scanner scanner) {
System.out.println("Player " + player + "'s turn:");
while (true) {
System.out.print("Choose a pile to remove objects (1, 2, or 3): ");
int pileIndex = scanner.nextInt();
if (pileIndex < 1 || pileIndex > 3 || piles[pileIndex].isEmpty()) { // Adjust bounds
System.out.println("Invalid pile. Try again.");
continue;
}
System.out.print("Choose the number of objects to remove (1 or 2): ");
int numToRemove = scanner.nextInt();
if (numToRemove != 1 && numToRemove != 2) {
System.out.println("Invalid number of objects. Try again.");
continue;
}
// Remove objects from the pile
for (int i = 0; i < numToRemove; i++) {
piles[pileIndex].pop();
}
break;
}
}
// Method to check if the game is over
private static boolean isGameOver(Stack<Integer>[] piles) {
for (int i = 1; i <= 3; i++) { // Start from 1
if (!piles[i].isEmpty()) {
return false;
}
}
return true;
}
}