-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathE5.java
62 lines (59 loc) · 1.77 KB
/
E5.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
/**
* E5.java
* Lesson 8 - OOP
* Exercise 5 - Nim2
*/
public class E5 extends Problem {
// Constructor to initialize fields in parent class
public E5() {
super(5, "Nim2", "Emulates a name of Nim2");
}
/**
* Main function run from outside
*/
@Override
public void run() {
// Creates a new Nim2 game object
Nim2 nimGame = new Nim2();
// Initialize the result variable, if the result is negative, the game has ended
int result;
do {
// Prompt user for input
System.out.printf(
"There are currently %d stones\n" +
"How many would you like to take? ",
nimGame.getStoneCount()
);
result = nimGame.playerPlay(super.inputReader.nextInt());
super.inputReader.nextLine();
// If the input is invalid, keep prompting until valid
while (result == 1) {
System.out.print("That is not a valid amount, please try again.\n > ");
result = nimGame.playerPlay(super.inputReader.nextInt());
super.inputReader.nextLine();
}
// Computer plays the game
result = nimGame.computerPlay();
// The function returns 0 if the player wins
if (result == 0) {
// Inform the user of their victory
System.out.println("The player wins!");
// The function returns the number of stones it takes if the computer wins, but negative
} else if (result < 0) {
// Inform the user of the computer vitory
System.out.printf(
"The computer takes %d stone%s\n",
-result, (-result == 1 ? "" : "s")
);
System.out.println("The computer wins!");
// The function returns the number of stones it takes otherwise
} else {
// Inform the user of the number of stones the computer takes
System.out.printf(
"The computer takes %d stone%s\n",
result, (result == 1 ? "" : "s")
);
}
} while (result > 0);
}
}