class MinimaxComputer
Public Class Methods
new(board, observer)
click to toggle source
# File lib/minimax_computer.rb, line 3 def initialize(board, observer) @game_board, @observer = board, observer @my_player_value = @game_board.player_value end
Public Instance Methods
move(iteration = 0)
click to toggle source
# File lib/minimax_computer.rb, line 8 def move(iteration = 0) if first_move? make_first_move else perform_mini_max(iteration) end end
Private Instance Methods
calculate_path_score(row, column, iteration)
click to toggle source
# File lib/minimax_computer.rb, line 61 def calculate_path_score(row, column, iteration) @game_board.move(row, column) score = calculate_score(iteration) @game_board.undo_move return score end
calculate_score(iteration)
click to toggle source
# File lib/minimax_computer.rb, line 68 def calculate_score(iteration) if immediate_win_or_loss?(iteration) return infinity else return perform_mini_max(iteration + 1) end end
first_move?()
click to toggle source
# File lib/minimax_computer.rb, line 18 def first_move? @game_board.number_of_moves_made < 2 end
for_each_cell() { |row, column| ... }
click to toggle source
# File lib/minimax_computer.rb, line 50 def for_each_cell (1..@game_board.dimension).each do |row| (1..@game_board.dimension).each { |column| yield(row, column) } end end
immediate_win_or_loss?(iteration)
click to toggle source
# File lib/minimax_computer.rb, line 76 def immediate_win_or_loss?(iteration) iteration<2 && @observer.has_winner? end
infinity()
click to toggle source
# File lib/minimax_computer.rb, line 80 def infinity -@game_board.player_value * 1.0/0.0 end
make_first_move()
click to toggle source
# File lib/minimax_computer.rb, line 22 def make_first_move move = select_first_move @game_board.move(move.row, move.column) end
middle_move()
click to toggle source
# File lib/minimax_computer.rb, line 45 def middle_move middle = @game_board.dimension/2 + 1 return move = Move.new(middle, middle) end
path_score()
click to toggle source
# File lib/minimax_computer.rb, line 56 def path_score return -@game_board.player_value if @observer.has_winner? return 0 end
perform_mini_max(iteration)
click to toggle source
# File lib/minimax_computer.rb, line 27 def perform_mini_max(iteration) return path_score if @observer.game_over? best_moves = BestMove.new(@game_board, @my_player_value) for_each_cell { |row, column| best_moves.add_better_move(calculate_path_score(row, column,iteration), Move.new(row, column)) if @game_board.is_empty_at?(row, column) } return best_moves.value if !iteration.zero? move = best_moves.get_random_move @game_board.move(move.row, move.column) end
select_first_move()
click to toggle source
# File lib/minimax_computer.rb, line 37 def select_first_move if @game_board.number_of_moves_made.zero? || @game_board.game_history[0] == middle_move return @game_board.random_corner_cell else return middle_move end end