• Please make sure to complete your profile by filling in any details pertaining to your company, name, photo, socials and contact information for any updates.
  • Need a hand with one of our platforms? post it under the support forum!
  • Reach out to us by emailing devsupport@redtorrentmedia.app if you don't see a response in 24/48 hours. - Please forward your thread!

Why doesn't Tic Tac Toe mini max work properly

xandercage43

New member
I made this tictactoe a long time ago and decided to add an AI option today. However, for no obvious to my reason, it just doesn't work even though I converted it from working javascript code.

Removed some irrelevant to the problem functions

Code:
    def minimax(self, is_max):
        if self.won():
            return 1 if self.winner() == 'O' else -1

        if self.draw():
            return 0

        if is_max:
            best_score = float('-inf')
            for i in range(9):
                if self.valid_move(i):
                    self.board[i] = 'O'
                    score = self.minimax(False)
                    self.board[i] = ' '
                    best_score = max(best_score, score)
            return best_score
        else:
            best_score = float('inf')
            for i in range(9):
                if self.valid_move(i):
                    self.board[i] = 'X'
                    score = self.minimax(True)
                    self.board[i] = ' '
                    best_score = min(best_score, score)
            return best_score

    def best_move(self):
        best_score = float('-inf')
        move = 0
        for i in range(9):
            if self.valid_move(i):
                self.board[i] = 'O'
                score = self.minimax(False)
                self.board[i] = ' '

                if score > best_score:
                    best_score = score
                    move = i

        return move

    def move_ai(self):
        self.board[self.best_move()] = self.current_player()
        self.current_move += 1
        self.show_board()

Please help me with that.


___________________
Pursuing Artificial intelligence coaching in Chennai.
 
Top