【发布时间】:2019-03-27 04:22:50
【问题描述】:
我正在使用 minimax 算法编写无与伦比的井字游戏。由于某种原因,我的分数散列在循环出现时失去了它的价值。如果它正在发生,那么我一定做错了我无法抓住的事情。我是编码新手。需要帮助!!!
mark 是当前玩家的标记
mark1和mark2分别是player1和player2的两个mark
spots 是棋盘上的空白点
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
【问题讨论】:
-
你指的是什么循环?
spots.each,也许? -
是的,没错。一旦出局。每个分数都是空的。
-
发生这种情况的唯一可能是
spots那里是空的,并且根本没有进入循环。检查spots。 -
呃。以我的经验,调试递归函数可能会非常令人费解......
标签: ruby loops hash tic-tac-toe minimax