How to Code "Nim" for Python
The "Nim" puzzle game is an ancient game that supposedly originated in China, with various incarnations appearing throughout history. One variation challenges two players to choose "sticks" until only one stick is left. The player who takes the last stick loses. Coding a simple version of this game in Python only requires some basic conditional statements and input from the players.
Instructions
-
-
1
Set up your Python script with appropriate variables. The following code allows players to pick up to four sticks:
>>>sticks = 13
>>>max_picks = 4 -
2
Set up the main loop and the user input interface. The dots shown below are for formatting purposes only and should not be typed into your code.
>>>while (sticks != 0):
. . . pick1, pick 2 = 0
. . . pick1 = raw_input('Player 1 pick :')
. . . while pick1 >= int(max_picks):
. . . . . pick1 = raw_input('Player 1 pick :')
. . . . . sticks -= pick1
. . . pick2 = raw_input('Player 2 pick :')
. . . while pick2 >= int(max_picks):
. . . . . pick2 = raw_input('Player 2 pick :')
. . . . . sticks -= pick2 -
-
3
Set up the winning conditions in the loop:
>>>while (sticks != 0):
. . . pick1, pick 2 = 0
. . . pick1 = raw_input('Player 1 pick :')
. . . while pick1 >= int(max_picks):
. . . . .pick1 = raw_input('Player 1 pick :')
. . . . .sticks -= pick1
. . . if sticks == 1:
. . . . . print 'Player 1 Wins!'
. . . . . return
. . . pick2 = raw_input('Player 2 pick :')
. . . while pick2 >= int(max_picks):
. . . . . pick2 = raw_input('Player 2 pick :')
. . . . . sticks -= pick2
. . . if sticks == 1:
. . . . . print 'Player 2 Wins!'
. . . . . return
-
1