HT Games
Home  >> Games

Python Matchstick Game: Computer Always Wins with Perfect Strategy

import random

def matchstick_game():
    """ 
    Plays the matchstick game where the computer always wins.
    Rules: 21 sticks. Players take 1-3 sticks per turn.
    Player forced to take last stick loses (misère) or wins (normal).
    This implementation uses normal play: taking last stick wins.
    Computer strategy: leave a multiple of 4 after its turn.
    """
    sticks = 21
    turn = 1  # 1 = user, 2 = computer
    
    print("Matchstick Game - 21 sticks. Take 1, 2, or 3. Take the last to win.")
    print("Computer plays optimally and will always win with perfect play.\n")
    
    while sticks > 0:
        print(f"Sticks remaining: {sticks}")
        
        if turn == 1:  # User's turn
            while True:
                try:
                    take = int(input("Your turn (1-3): "))
                    if 1 <= take <= 3 and take <= sticks:
                        break
                    print("Invalid. Enter 1, 2, or 3 (and not more than remaining).")
                except ValueError:
                    print("Please enter a number.")
            sticks -= take
            print(f"You took {take}.")
            turn = 2
        else:  # Computer's turn - winning strategy
            if sticks % 4 == 0:
                take = 1
            else:
                take = 4 - (sticks % 4)
            # Ensure we don't take more than available (endgame)
            take = min(take, sticks)
            print(f"Computer takes {take}.")
            sticks -= take
            turn = 1
    
    # Game over
    if turn == 1:  # Computer took last stick
        print("\nComputer wins! Better luck next time.")
    else:
        print("\nYou win! ...Wait, that shouldn't happen with perfect play.")

if __name__ == "__main__":
    matchstick_game()

How the Strategy Works

  • Target multiples of 4: 21 → computer wants to leave 20, 16, 12, 8, 4
  • User takes n (1–3): Computer takes 4-n, sum = 4 each round
  • Endgame: At 4 sticks, user takes 1–3, computer takes remainder and wins

Variations

  • Misère (last stick loses): Start with 21, target multiples of 4 plus 1 (i.e., leave 5, 9, 13, 17, 21). Adjust first move accordingly.
  • Different starting counts: Any non-multiple-of-4 start is a first-player win with perfect play.

Run the script, try to beat it—you can't if the computer plays perfectly!


https://www.htfbw.com © HT Games