Simple Python project for intermediates
Nim Game with Python
Nim is a game of logic and strategy. The winner of Nim is the player who removes the last of 12 matchsticks. The goal of this simple Python project for intermediates is to write a program to play a version of the game where the second player (the computer) always wins by following a specific winning strategy.
The game has 3 rules:
- Start with 12 matchsticks
- Each player can take 1, 2, or 3 matchsticks, in turn the player who takes the last token wins.
The trick to always win is to subtract 4 to the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1.
Coding Steps
- Inside the function, we initiate the game with 12 matchsticks and then enter a game loop where the user and computer take turns.
- The user goes first and inputs the number of matchsticks he wants to take, and the computer calculates its move based on the user’s choice to ensure it always wins.
- The game continues until all the matchsticks are taken, and the program prints the winner.
Expected output
Take 1, 2, or 3 matchstick: 2 matchstick left: 10 Computer takes 2 matchstick. matchstick left: 8 Take 1, 2, or 3 matchstick: 3 matchstick left: 5 Computer takes 1 matchstick. matchstick left: 4 Take 1, 2, or 3 matchstick: 3 matchstick left: 1 Computer takes 1 matchstick. matchstick left: 0 Computer took the last token. Computer wins!
Source code
# Function to apply game rules
def nim_game():
matchstick = 12
# Game loop
while matchstick > 0:
# User's turn
user_choice = int(input("Take 1, 2, or 3 matchstick: "))
if user_choice < 1 or user_choice > 3 or user_choice > matchstick:
print("Invalid choice. Please try again.")
continue
matchstick -= user_choice
print(f"matchstick left: {matchstick}")
if matchstick == 0:
print("You took the last token. You win!")
break
# Computer's turn
computer_choice = 4 - user_choice
print(f"Computer takes {computer_choice} matchstick.")
matchstick -= computer_choice
print(f"matchstick left: {matchstick}")
if matchstick == 0:
print("Computer took the last token. Computer wins!")
# Start the game
nim_game()