# Python设计和实现聪明的尼姆游戏

Python设计和实现聪明的尼姆游戏

``````import random

# 玩家拿走物品
def play(num):
while True:
try:
if num == 1:
print('请输入要拿走物品的数量(1)')
take_num = int(input())
assert take_num == 1
else:
print('请输入要拿走物品的数量(1-%d)' % (num / 2))
take_num = int(input())
assert 1 <= take_num <= num // 2
except(ValueError, AssertionError):
print('请正确输入数量！')
else:
break
num -= take_num
print('玩家拿走了', take_num, '个，还剩', num, '个')
return num

# 电脑拿走物品
def computer(num):
take_max = num // 2
lst = []
for i in range(1, num):
temp = 2 ** i - 1
if temp <= num - 1:
lst.append(temp)
else:
break
lst = list(filter(lambda y: num - y <= num // 2, lst))
if lst:
temp_lst = []
for i in lst:
x = num - i
temp_lst.append(x)
take_num = random.choice(temp_lst)
num -= take_num
print('电脑拿走了', take_num, '个，还剩', num, '个')
return num
else:
take_num = random.randint(1, take_max)
num -= take_num
print('电脑拿走了', take_num, '个，还剩', num, '个')
return num

while True:
try:
initial_value = int(input('请输入起始数量堆的大小：'))
except(ValueError, AssertionError):
print('请正确输入数量！')
else:
break
player = 1
computer_player = 1
# 依次循环玩家和电脑那走物品，若玩家先拿完则提前跳出循环，若电脑先拿完则正常退出循环
while computer_player and player:
initial_value = play(initial_value)
player = initial_value
if player == 0 or player == 1:
break
initial_value = computer(initial_value)
computer_player = initial_value
if player == 0:
print('n电脑胜利！')
else:
print('电脑拿走了 1 个，还剩 0 个')
print('n玩家胜利！')

``````

THE END

)">