I'm trying to use the minmax algorithm for a game of tic-tac-toe.
This is the code I'm working with for getting the best AI move in the game.
def get_best_move(board, next_player, depth = 0, best_score = {})
return 0 if tie(board)
return -1 if game_is_over(board)
available_spaces = []
best_move = nil
board.each do |s|
if s != "X" && s != "O"
available_spaces << s
end
end
available_spaces.each do |as|
board[as.to_i] = @com
if game_is_over(board)
best_score[as.to_i] = -1 * get_best_move(board, @com, depth + 1, {})
board[as.to_i] = as
return best_score
else
board[as.to_i] = @hum
if game_is_over(board)
best_score[as.to_i] = -1 * get_best_move(board, @com, depth + 1, {})
board[as.to_i] = as
return best_score
else
board[as.to_i] = as
end
end
end
best_move = best_score.max_by { |key, value| value }[0]
highest_minimax_score = best_score.max_by { |key, value| value }[1]
if depth == 0
return best_move
elsif depth > 0
return highest_minimax_score
end
end
I get this error when I run the game in the terminal, and I would like to know how to fix it.
rb:332:in get_best_move': undefined method `[]' for nil:NilClass (NoMethodError)
rb:332 is referring to these 2 lines in the example below
best_move = best_score.max_by { |key, value| value }[0]
highest_minimax_score = best_score.max_by { |key, value| value }[1]