import random
def print_sticks(sticks):
"""打印当前的棍子状态"""
print("当前棍子状态:", ' '.join(str(i) for i in range(1, sticks + 1)))
def player_turn(sticks):
"""处理玩家的回合"""
while True:
try:
count = int(input(f"选择 1 到 {sticks} 根棍子:"))
if 1 <= count <= sticks:
return count
else:
print(f"请输入一个有效的数字,范围是 1 到 {sticks}")
except ValueError:
print("请输入一个有效的数字")
def main():
"""主游戏函数"""
sticks = random.randint(10, 20) # 随机设置初始棍子数量
print("挑棍游戏开始!")
print_sticks(sticks)
while sticks > 0:
# 玩家回合
print(f"\n当前剩余棍子数: {sticks}")
taken = player_turn(sticks)
sticks -= taken
print(f"你选择了 {taken} 根棍子")
# 检查游戏是否结束
if sticks == 0:
print("你赢了!没有棍子剩下")
break
# 计算机回合
computer_take = random.randint(1, min(sticks, 3)) # 计算机随机选择 1 到 3 根棍子
sticks -= computer_take
print(f"计算机选择了 {computer_take} 根棍子")
# 检查游戏是否结束
if sticks == 0:
print("计算机赢了!没有棍子剩下")
break
print_sticks(sticks)
if __name__ == "__main__":
main()