I am trying to get the minmax algorithm (computer AI) to work in my tic-tac-toe game. I got stuck on this for a few days. In fact, I don’t understand why computer AI simply places its marker ( "O") in sequential order from the boards of the board 0-8.
For example, as human-human, if I choose 1, then the computer will choose 0:
O| X| 2
--+---+--
3| 4| 5
--+---+--
6| 7| 8
Next, if I choose 4, then the computer will select 2:
O| X| O
--+---+--
3| X| 5
--+---+--
6| 7| 8
Etc:
O| X| O
--+---+--
O| X| O
--+---+--
X| 7| X
I debugged the minmax algorithm as much as possible, but it is very difficult for me to keep track of what is happening.
ComputerPlayer ( ). minmax , . ( 100% worst_score .)
class ComputerPlayer < Player
def move(game_board)
minmax(game_board)
game_board.place_piece(@best_move, marker)
end
def minmax(board, player_tracker = 0)
if board.game_over?
return score(board)
else
worst_score = (1.0/0.0)
best_score = -(1.0/0.0)
@best_move = board.get_available_positions.first
new_marker = player_tracker.even? ? 'O' : 'X'
player_tracker += 1
board.get_available_positions.each do |move|
new_board = board.place_piece(move, new_marker)
current_score = minmax(new_board, player_tracker)
if new_marker == marker
if current_score > best_score
@best_move = move
best_score = current_score
end
else
if current_score < worst_score
worst_score = current_score
end
end
end
end
return best_score
end
def score(board)
if board.winner == "O"
10
elsif board.winner == "X"
-10
elsif board.winner == nil
0
end
end
end