从我的negmax方法

时间:2017-09-07 20:19:00

标签: ruby tic-tac-toe negamax

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

在我的极小动画中,我有一个类似的设置,不同之处在于连续调用时深度增加(不减少)。我能够说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)

0 个答案:

没有答案