Class: Minimax
- Inherits:
-
Object
- Object
- Minimax
- Defined in:
- lib/minimax.rb
Instance Attribute Summary collapse
-
#board ⇒ Object
Returns the value of attribute board.
-
#current_token ⇒ Object
Returns the value of attribute current_token.
-
#last_move ⇒ Object
Returns the value of attribute last_move.
-
#root_token ⇒ Object
Returns the value of attribute root_token.
-
#score ⇒ Object
Returns the value of attribute score.
Instance Method Summary collapse
- #build_tree ⇒ Object
- #game_ended ⇒ Object
- #get_next_move ⇒ Object
-
#initialize(board, last_move, current_token, root_token) ⇒ Minimax
constructor
A new instance of Minimax.
Constructor Details
#initialize(board, last_move, current_token, root_token) ⇒ Minimax
Returns a new instance of Minimax.
4 5 6 7 8 9 10 |
# File 'lib/minimax.rb', line 4 def initialize(board, last_move, current_token, root_token) @board = board @last_move = last_move @current_token = current_token @root_token = root_token @children = [] end |
Instance Attribute Details
#board ⇒ Object
Returns the value of attribute board.
2 3 4 |
# File 'lib/minimax.rb', line 2 def board @board end |
#current_token ⇒ Object
Returns the value of attribute current_token.
2 3 4 |
# File 'lib/minimax.rb', line 2 def current_token @current_token end |
#last_move ⇒ Object
Returns the value of attribute last_move.
2 3 4 |
# File 'lib/minimax.rb', line 2 def last_move @last_move end |
#root_token ⇒ Object
Returns the value of attribute root_token.
2 3 4 |
# File 'lib/minimax.rb', line 2 def root_token @root_token end |
#score ⇒ Object
Returns the value of attribute score.
2 3 4 |
# File 'lib/minimax.rb', line 2 def score @score end |
Instance Method Details
#build_tree ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/minimax.rb', line 12 def build_tree if game_ended @score = game_ended return end moves = @board.available_spaces moves.each do |move| next_board = @board.clone next_board.add_piece(@current_token, move) @children << Minimax.new(next_board, move, switch_token(@current_token), @root_token) end score_list = [] @children.each do |child| child.build_tree score_list << child.score end # calculate score for non-leaf nodes if @current_token == @root_token @score = score_list.max else @score = score_list.min end end |
#game_ended ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/minimax.rb', line 42 def game_ended if diagonal_win diagonal_win == @root_token ? 1 : -1 elsif horizontal_win horizontal_win == @root_token ? 1 : -1 elsif vertical_win vertical_win == @root_token ? 1 : -1 elsif cat_game? # cat game 0 end end |
#get_next_move ⇒ Object
57 58 59 60 61 62 63 64 65 66 |
# File 'lib/minimax.rb', line 57 def get_next_move move_list = [] @children.each do |child| move_list << [child.last_move, child.score] end move = move_list.max_by {|move| move.last} return move.first end |