This Python program reads the initial number of matchsticks and simulates a turn-based game.
At each step, it displays how many matchsticks remain after a player removes some.
The game continues until all matchsticks are taken.
def matchstick_tracker(n: int, k: int):
turn = 0 # 0: Player 1, 1: Player 2
while n > 0:
print(f"\nRemaining matchsticks: {n}")
move = int(input(f"Player {turn + 1}, pick 1 to {min(k, n)} matchsticks: "))
if move < 1 or move > min(k, n):
print("Invalid move. Try again.")
continue
n -= move
turn = 1 - turn
print(f"\nPlayer {turn + 1} took the last matchstick and loses!")
# Read inputs
n = int(input("Enter initial number of matchsticks: "))
k = int(input("Enter maximum allowed per turn: "))
matchstick_tracker(n, k)
Initial matchsticks: 7
Max per turn: 3
Remaining matchsticks: 7
Player 1, pick 1 to 3 matchsticks: 2
Remaining matchsticks: 5
Player 2, pick 1 to 3 matchsticks: 3
Remaining matchsticks: 2
Player 1, pick 1 to 2 matchsticks: 2
Player 1 took the last matchstick and loses!
- The game starts with n matchsticks
- Players alternate turns, each removing 1 to k matchsticks
- After each move, the program displays the remaining count
- The player who takes the last matchstick loses