Skip to content

Instantly share code, notes, and snippets.

@rewinfrey
Created December 10, 2012 16:04
Show Gist options
  • Save rewinfrey/4251485 to your computer and use it in GitHub Desktop.
Save rewinfrey/4251485 to your computer and use it in GitHub Desktop.
Minimax recursive with max/min values
def minimax_back(max_player = true, ply = 0, min_score = 1000, max_score = -1000)
if board.winner?
return(max_player ? (-1000 + ply) : (1000 - ply))
elsif board.draw_game?
return 0
end
if ply >= max_ply
return(max_player ? max_score : min_score)
end
best_move = 0
score = 0
available_moves.each do |index|
board[][index] = ( max_player ? side : opposite_side(side) )
score = minimax(!max_player, ply + 1, min_score, max_score)
undo_move(index)
if max_player && score > max_score
max_score = score
best_move = index
elsif !max_player && score < min_score && min_score.abs > max_score
min_score = score
end
break if max_min_swapped?(max_score, min_score)
end
return( ply == 0 ? best_move : ( max_player ? max_score : min_score ) )
end
def set_max_ply(moves)
5
end
def max_min_swapped?(max, min)
max >= min
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment