I am trying to write the code for minimax algorithm for tic tac toe in python all by myself, I have wrote the code but whenever the function is getting called it is showing a "maximum recursion depth in comparison" error. I am stuck in this part. When I am trying to debug it it is also not helping out.
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()
In this code the user input part is working fine but the computer input or the minimax algorithm part is not working, and showing the recursion error