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()
Run the script, try to beat it—you can't if the computer plays perfectly!