我正在使用minimax算法编写无与伦比的井字游戏。由于某种原因,我的分数哈希值在循环中丢失了它的值。如果发生这种情况,那么我必须做错了我无法发现的错误。我是编码新手。需要帮助!
标记是当前玩家的标记
mark1和mark2分别是玩家1和玩家2的两个标记
斑点是板上的空白点
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
答案 0 :(得分:0)
似乎您每次都将一个空哈希传递回best_move。您可能想要做的是在每次重复中传递分数,以建立具有移动和分数的对象。
scores[move] = best_move(spots[1..-1], mark, other_mark, depth += 1, scores)