Passing the return value from my negmax method

46 views Asked by At

I've been working on this for a few days, at least. Testing seems to show the correct value is being returned. My problem is being able to grab the best_move value and have it print out. I set up the suggested_move method and try to use return suggested_move(best_move) but it triggers the method for every level back up the tree. Also it returns the wrong value, which I'm guessing is because it's stopping before depth is back to 0.

In my minimax I had a similar setup the difference being the depth was incremented (not decremented) on successive calls. Point being I was able to say if depth == 0 p best_move. So I'm scratching my head because using that same conditional I get a nil class error in this code.

 @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

There are 0 answers