0

至少我已经为此工作了几天。测试似乎显示正在返回正确的值。我的问题是能够获取best_move价值并将其打印出来。我设置了suggested_move方法并尝试使用return suggested_move(best_move),但它会触发每个级别备份树的方法。它还返回错误的值,我猜这是因为它在深度回到 0 之前就停止了。

在我的 minimax 中,我有一个类似的设置,不同之处在于深度在连续调用时增加(而不是减少)。重点是我可以说if depth == 0 p best_move。所以我摸不着头脑,因为使用相同的条件我在这段代码中得到一个 nil 类错误。

 @board = ["X","O","O","X","X","","","O",""]

def available_spaces
   @board.map.with_index {|a, i| a == "" ? i+1 : nil}.compact
end

def suggested_move(move)
  p "Suggested move: #{move}"
end

def full?
  @board.all?{|token| token == "X" || token == "O"}
end

def suggested_move(move)
  p "Move: #{move}"
end

def bestmove(board, depth=0, best_score = {})
return 0 if full?
return 1 if won?

best = -Float::INFINITY

  available_spaces.each do |space|
  @board[space-1] = current_player
  best_score[space] = -bestmove(@board, depth-1, {})
  @board[space-1] = ""  
end
 p best_score
  if best_score.max_by {|key,value| value }[1] > best
    best = best_score.max_by {|key,value| value }[1]
    best_move = best_score.max_by {|key,value| value }[0]
  end
  return best_move
end 

bestmove(@board)
4

0 回答 0