Example Program 5 (Part 1)

NIM GameThis example program is based upon the game of NIM. Before we look at the code we will have a quick look at the game and what is required to win.

The game starts will a number of objects, such as matches or coins. This must be an integer value. The object of the game is for two players to take turns removing either 1 or 2 items from the total until there are no items left. The winner is the player who removes the final items.

The picture shown below illustrates a game of Nim that has a starting value of 9 items/

Turn 1 – Player 1 (Red) removes 2 items leaving 4 remaining.
Turn 2 – Player 2 (Green) removes 2 items leaving 2 remaining.
Turn 3 – Player 1 (Red) removes 1 item leaving 1 remaining.
Turn 4 – Player 2 (Green) removes the last item leaving 0 which means that player 2 is the winner.

In the example game, Player 1 makes a mistake during Turn 3 by not removing two items and therefore winning. When you are playing the computer as your opponent do not expect to computer to make any mistakes during its turns. There is a strategy to win at Nim but this is best discovered during play and because of this I will not reveal it here.

Next: Example Program 5 (Part 2)