-1

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]
sawa
  • 165,429
  • 45
  • 277
  • 381
Mahler7
  • 27
  • 5

1 Answers1

2

The error message says pretty clearly what the problem is: you are attempting to call [] on nil, but nil doesn't respond to []. The only place where you call [] is on the result of max_by. max_by returns nil when called on an empty Enumerable. Ergo, best_score must be empty. And indeed: you always pass an empty Hash as the argument to best_score, and you never modify best_score, so it is and always will be empty.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653