Class: Minimax

Inherits:
Object
  • Object
show all
Defined in:
lib/minimax.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#boardObject

Returns the value of attribute board.



2
3
4
# File 'lib/minimax.rb', line 2

def board
  @board
end

#current_tokenObject

Returns the value of attribute current_token.



2
3
4
# File 'lib/minimax.rb', line 2

def current_token
  @current_token
end

#last_moveObject

Returns the value of attribute last_move.



2
3
4
# File 'lib/minimax.rb', line 2

def last_move
  @last_move
end

#root_tokenObject

Returns the value of attribute root_token.



2
3
4
# File 'lib/minimax.rb', line 2

def root_token
  @root_token
end

#scoreObject

Returns the value of attribute score.



2
3
4
# File 'lib/minimax.rb', line 2

def score
  @score
end

Instance Method Details

#build_treeObject



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_endedObject



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_moveObject



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