Created
October 1, 2012 00:41
-
-
Save mikeebert/3808840 to your computer and use it in GitHub Desktop.
Minimax Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_minimax_move(board,max_symbol,min_symbol) | |
set_min_and_max_players(max_symbol, min_symbol) | |
best_score_for_max = @max.starting_score | |
alpha = -100 | |
beta = 100 | |
depth = 0 | |
board.available_spaces.each do |space| | |
test_board = copy(board) | |
test_board.place_move(@max.symbol, space) | |
new_score = minimax_score(test_board, opponent_of(@max), alpha, beta, depth + 1) | |
if new_score > best_score_for_max | |
best_score_for_max = new_score | |
@possible_moves = [] | |
@possible_moves << space | |
elsif new_score == best_score_for_max | |
@possible_moves << space | |
end | |
end | |
return chosen_move | |
end | |
def minimax_score(board, player, alpha, beta, depth) | |
score = game_value(board, depth) | |
return score unless score == -1 | |
best_score = player.starting_score | |
board.available_spaces.each do |space| | |
test_board = copy(board) | |
test_board.place_move(player.symbol, space) | |
new_score = minimax_score(test_board, opponent_of(player), alpha, beta, depth + 1) | |
best_score = player.compare(best_score, new_score) | |
is_max?(player) ? alpha = best_score : beta = best_score | |
break if alpha >= beta | |
end | |
return best_score | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment