Created
November 29, 2012 20:11
-
-
Save rewinfrey/4171586 to your computer and use it in GitHub Desktop.
Minimax recursive alpha/beta refactored as hash
This file contains hidden or 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 minimax_with_alpha(max_player = true, ply = 0, alpha = -9999, beta = 9999) | |
| if board.winner? | |
| return winning_score(max_player, ply) | |
| elsif board.draw_game? | |
| return 0 | |
| end | |
| current_round = gen_score_game_tree(max_player: max_player, | |
| alpha: alpha, | |
| beta: beta, | |
| ply: ply) | |
| return (ply == 0 ? current_round[:best_move] : (current_round[:max_player] ? current_round[:alpha] : current_round[:beta])) | |
| end | |
| def winning_score(max_player, ply) | |
| max_player ? (-9999 + ply) : (9999 - ply) | |
| end | |
| def gen_score_game_tree(state) | |
| state[:best_move] = 0 | |
| available_moves.each do |index| | |
| board[][index] = mark_with_current_player_side(state) | |
| state[:score] = minimax_with_alpha(!state[:max_player], state[:ply] + 1, state[:alpha], state[:beta]) | |
| undo_move(index) | |
| state[:index] = index | |
| state = eval_score(state) | |
| break if alpha_beta_swapped?(state) | |
| end | |
| state | |
| end | |
| def available_moves | |
| avail_moves = Array.new | |
| board[].each_index do |index| | |
| if board[][index] == " " | |
| avail_moves << index | |
| end | |
| end | |
| avail_moves.empty? ? nil : avail_moves | |
| end | |
| def eval_score(state) | |
| if state[:max_player] && state[:score] > state[:alpha] | |
| state[:alpha] = state[:score] | |
| state[:best_move] = state[:index] | |
| elsif !state[:max_player] && state[:score] < state[:beta] | |
| state[:beta] = state[:score] | |
| end | |
| state | |
| end | |
| def alpha_beta_swapped?(state) | |
| state[:alpha] >= state[:beta] | |
| end | |
| def mark_with_current_player_side(state) | |
| state[:max_player] ? side : opposite_side(side) | |
| end | |
| def undo_move(index) | |
| board[][index] = " " | |
| end | |
| def opposite_side(side) | |
| side == "x" ? "o" : "x" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment