#尼姆游戏模拟电脑与玩家之间的对战
import random
def smartNimuGame(n): #n是总共物品的数量
while n>1:
# 人类玩家先走
print("玩家走,现在有{}个棋子剩下。".format(n))
# 人类玩家取走的棋子要合法
while True:
try:
num = int(eval(input("你要取走多少个棋子:")))
assert 1 <= num <= n // 2 # assert断言:可以理解为“这里一定是成立的”,如果表达式不成立(False),则抛出异常。
break
except:
print("你输入的数字有误,请再次输入")
# 剩下的棋子
n = n - num
if n==1:
return print("人类赢")
a=computerGet(n)
n = n - a
print("计算机取走了多少{}".format(a))
if n==1:
return print("计算机赢")
def computerGet(n):#还剩下多少让计算机取
half=n//2
m=1
possible=[]
while True:
rest=pow(2,m)-1 #剩下的要合法 n>rest>=half
if rest>=n:
break
if rest>=half:
possible.append(n-rest) #(n-rest)就是计算机要取走的
m=m+1
#如果至少存在一种办法使剩下的为2^n-1
if possible:
return random.choice(possible)
#如果不存在随机取走一些
return random.randint[1,half]
smartNimuGame(100)
2018.6.17 学习日志 -----尼姆游戏模拟电脑与玩家之间的对战
猜你喜欢
转载自blog.csdn.net/Yk_0311/article/details/80725456
今日推荐
周排行