【发布时间】:2019-12-29 19:10:01
【问题描述】:
我正在尝试自己在 python 中为井字游戏编写 minimax 算法的代码,我已经编写了代码,但是每当调用该函数时,它都会显示“比较的最大递归深度”错误。我被困在这部分。当我尝试调试它时,它也无济于事。
import sys
marked=['','','','','','','','','']
markingSignal=[False,False,False,False,False,False,False,False,False]
def printTable():
print("\t%s|\t%s|\t%s\n------------------------\n\t%s|\t%s|\t%s\n------------------------\n\t%s|\t%s|\t%s\n"%(marked[0],marked[1],marked[2],marked[3],marked[4],marked[5],marked[6],marked[7],marked[8]))
def winning(m,player):
i=0
x=0
while x<3:
if m[i]==player and m[i+1]==player and m[i+2]==player:
return True
x=x+1
i=i+3
x=0
i=0
while x<3:
if m[2]==player and m[4]==player and m[6]==player:
return True
x=x+1
i=i+3
x=0
i=0
if m[0]==player and m[4]==player and m[8]==player:
return True
if m[2]==player and m[4]==player and m[6]==player:
return True
return False
def minimax(table,marktab,points,pos=0):
copyTab=table
copymark=marktab
remaining=0
for x in table:
if x==False:
remaining=remaining+1
if remaining==0:
return points,pos
scores=[None]*remaining
positions=[None]*remaining
z=0
maximum=0
bestpos=0
previous=88
x=0
while x<9:
if table[x]==False:
if points%2==0:
copyTab[x]==True
copymark[x]=='O'
result=winning(copymark,'O')
previous=x
if result:
return points ,x
else:
copyTab[x]==True
copymark[x]=='X'
scores[z],positions[z]=minimax(copyTab,copymark,points+1,previous)
z=z+1
copyTab[x]==False
copymark[x]==''
x=x+1
for x in range(0,len(scores)):
if x==0:
maximum=scores[x]
bestpos=positions[x]
if scores[x]<maximum:
maximum=scores[x]
bestpos=positions[x]
return maximum, bestpos
def takeInput(player):
filled=False
while filled==False:
print("Enter Your Choice 1-9")
x=int(input())
if x>9:
print("Invalid Choice")
continue
if markingSignal[x-1]:
print("This slot is already filled")
continue
filled=True
marked[x-1]=player
markingSignal[x-1]=True
def main():
sys.setrecursionlimit(5000)
print(sys.getrecursionlimit())
printTable()
count=0
player='X'
while count<9:
if count%2==0:
player='X'
takeInput(player)
else:
player='O'
p,choice=minimax(markingSignal,marked,0)
marked[choice]=player
markingSignal[choice]=True
printTable()
result=winning(marked,player)
if result:
print("\n%s WON !!!\n"%(player))
break
count=count+1
main()
在此代码中,用户输入部分工作正常,但计算机输入或极大极小算法部分不工作,并显示递归错误
【问题讨论】:
-
minimax的目的是什么? -
乍一看,我猜
copyTab=table和copymark=marktab可能是问题所在——它们通过引用而不是复制来传递相同的列表。要制作副本,请改为使用copyTab = table[:]。 -
stackoverflow.com/a/9697367/567595 以及那里的链接和其他答案可能有助于在 Python 中分配变量。
-
我看了你的代码有一段时间了,错误太多了,无法总结。记住 Stuart 的评论,但抄袭、双人桌……这毫无意义。你为什么不去 Wikipedia 看看 minimax 是如何实现的?这比调试代码中的许多误解要好。
-
两个月前我才开始学习python。我花了几个小时写这篇文章,现在从互联网上复制算法对我来说会令人心碎
标签: python algorithm tic-tac-toe minimax