This is a two-player game with n matchboxes.
On each turn, a player can take between 1 and k matchboxes.
The player who takes the last matchbox loses.
The program alternates turns between Player 1 and Player 2 and announces the loser at the end.
def matchbox_game(n: int, k: int):
turn = 0 # 0: Player 1, 1: Player 2
while n > 0:
print(f"\nRemaining matchboxes: {n}")
move = int(input(f"Player {turn + 1}, pick 1 to {min(k, n)} matchboxes: "))
if move < 1 or move > min(k, n):
print("Invalid move. Try again.")
continue
n -= move
if n == 0:
print(f"\nPlayer {turn + 1} took the last matchbox and loses!")
break
turn = 1 - turn
# Read inputs from user
n = int(input("Enter total number of matchboxes: "))
k = int(input("Enter maximum number allowed per turn: "))
matchbox_game(n, k)
Total matchboxes: 10
Maximum per turn: 3
Remaining matchboxes: 10
Player 1, pick 1 to 3 matchboxes: 2
Remaining matchboxes: 8
Player 2, pick 1 to 3 matchboxes: 3
Remaining matchboxes: 5
Player 1, pick 1 to 3 matchboxes: 2
Remaining matchboxes: 3
Player 2, pick 1 to 3 matchboxes: 3
Player 2 took the last matchbox and loses!
- The game starts with n matchboxes
- Players alternate turns, each picking between 1 and k matchboxes
- If a player takes the last matchbox, they lose