2

I am writing unbeatable tic tac toe game using minimax algorithm. For some reason my scores hash lose its value as it comes out for the loop. If it is happening then I must be doing something wrong that I am unable to catch. I am new to coding. Need help!!!

mark is the mark for current player

mark1 and mark2 are the two marks for player1 and player2 respectively

spots is the empty spots on the board

require_relative 'board'

class ComputerPlayer
  attr_reader :board

  def initialize
    @board = Board.new
    @optimal_moves = [0, 2, 4, 6, 8]
  end

  def get_position(name, spots, mark, mark1, mark2)
    position = nil
    other_mark = nil
    mark == mark1 ? other_mark = mark2 : other_mark = mark1
    if spots.length == 9
      position = @optimal_moves.sample.to_i
    else
      position = best_move(spots, mark, other_mark)
    end
    print "Enter your move #{name}: #{position}\n"
    position
  end

  def best_move(spots, mark, other_mark, depth = 0, scores = {})
    return 1 if board.winner == mark
    return 0 if board.draw?
    return -1 if board.winner == other_mark

    spots.each do |move|
      board.place_mark(move, mark)
      scores[move] = best_move(spots[1..-1], mark, other_mark, depth += 1, {})
      board.reset_position(move)
    end

    # it does not keep the value of scores. scores here is {}
    return scores.max_by { |key, value| value }[0] if depth == 0
    return scores.max_by { |key, value| value }[1] if depth > 0
    return scores.min_by { |key, value| value }[1] if depth < 0
  end
end
gkaur
  • 21
  • 2

1 Answers1

0

It looks like you are passing an empty hash back into best_move every time. What you're probably wanting to do is pass scores in on each recurrence to build up an object with moves and scores.

scores[move] = best_move(spots[1..-1], mark, other_mark, depth += 1, scores)

crice1988
  • 81
  • 1
  • 10