给出代码实现Nim游戏
时间: 2023-12-05 12:29:29 浏览: 52
下面是一个简单的 Nim 游戏的 Python 代码实现:
```python
def nim_game():
print("Welcome to Nim Game!")
piles = [3, 4, 5] # 初始化三堆棋子的数量
player = 1 # 初始化玩家为1
while True:
print("Current piles: ", piles)
if sum(piles) == 0:
print("Player", player, "wins!")
break
print("Player", player, "turn.")
pile_choice = int(input("Which pile do you choose? ")) - 1
while pile_choice < 0 or pile_choice > 2 or piles[pile_choice] == 0:
pile_choice = int(input("Invalid choice! Choose again: ")) - 1
amount_choice = int(input("How many do you want to take? "))
while amount_choice < 1 or amount_choice > piles[pile_choice]:
amount_choice = int(input("Invalid amount! Choose again: "))
piles[pile_choice] -= amount_choice
if player == 1:
player = 2
else:
player = 1
```
这个代码实现了一个简单的 3 堆 Nim 游戏,玩家每次可以选择一堆棋子和取走其中的若干个棋子。当所有的棋子都被取走时,游戏结束。你可以根据需要修改代码,增加更多的功能或者变化。