I am currently working on creating an AI player for tic tac toe. After researching, I discovered that the minimax algorithm would be perfect for the job.
I am pretty confident in my understanding of the algorithm and how it works, but coding it has proven a little bit of a challenge. I will admit, recursion is one of my weak areas . The following code is my AI class. It currently runs, but it makes poor decisions. Could someone please point out where I went wrong? Thank You!
import tictactoe as tic # interface to tictactoe game logic like check_victory
class AI:
def __init__(self, mark):
self.mark = mark
def minimax(self, state, player):
#end condition - final state
if tic.check_victory(state):
if player == self.mark:
return 1
else:
return -1
if tic.check_cat(state):
return 0
nextturn = tic.O if player == tic.X else tic.X
#generate possible moves
mvs = []
for i, mark in enumerate(state):
if mark == tic.EMPTY:
mvs.append(i)
#generate child states of parent state
scores = []
for mv in mvs:
leaf = state[:]
leaf[mv] = player
result = self.minimax(leaf, nextturn)
scores.append(result)
if player == self.mark:
maxelle = max(scores)
return mvs[scores.index(maxelle)]
else:
minele = min(scores)
return mvs[scores.index(minele)]
def make_move(self, board, player):
place = self.minimax(board, player)
return place