我试图独自用python为tic tac toe编写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算法部分不工作,并显示了递归错误
scores[z],positions[z]=minimax(copyTab,copymark,points+1,previous)
这正在进入永无止境的冰柱。它不断重复...前一个值始终在88到0之间。该递归函数必须在某个点返回(您只有在调用该递归函数所在的获胜位置之前才有返回值。不能有赢家,因此递归永远不会结束。考虑到在minimax函数中,您不复制值,仅通过引用传递:
copyTab=table.copy() copymark=marktab.copy()
而且,您不会增加X值(仅在调用递归函数之后),因此不会在算法的表中进行任何更改,这就是得到该错误的原因。不是您需要分配值:copyTab [x] = Truecopymark [x] ='O'并且不使用双等于
==