The winning strategy would be to leave the opponent with 1 or 5 or 9 or 13 ... sticks. A NimPlayer
class that plays the optimal OneRowNim
game would be identical to the NimPlayerBad
class except the move():int
method would be replaced with the following implementation:
public int move() {
int sticksLeft = game.getSticks();
if (sticksLeft % (game.MAX_PICKUP + 1) != 1)
return (sticksLeft - 1) % (game.MAX_PICKUP +1);
else {
int maxPickup = Math.min(game.MAX_PICKUP, sticksLeft);
return 1 + (int)(Math.random() * maxPickup);
}
}
You might also want to modify main()
to give the user the choice of which player to use as the computer:
public static void main(String args[]) {
KeyboardReader kb = new KeyboardReader();
OneRowNim game = new OneRowNim();
kb.prompt("How many computers are playing, 0, 1, or 2? ");
int m = kb.getKeyboardInteger();
for (int k = 0; k < m; k++) {
kb.prompt("What type of player, " +
"NimPlayerBad = 1, or NimPlayer = 2 ? ");
int choice = kb.getKeyboardInteger();
if (choice == 1) {
IPlayer computer = new NimPlayerBad(game);
game.addComputerPlayer(computer);
} else {
IPlayer computer = new NimPlayer(game);
game.addComputerPlayer(computer);
}
}
game.play(kb);
} // main()