Class: Tictactoe::Ai::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/tictactoe/ai/tree.rb

Constant Summary collapse

MAXIMUM_SCORE =
2
MINIMUM_SCORE =
-2
NEUTRAL_SCORE =
0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(state, mark, current_mark = mark, move_to_arrive_here = nil) ⇒ Tree

Returns a new instance of Tree.



8
9
10
11
12
13
# File 'lib/tictactoe/ai/tree.rb', line 8

def initialize(state, mark, current_mark = mark, move_to_arrive_here=nil)
  @state = state
  @mark = mark
  @current_mark = current_mark
  @move = move_to_arrive_here
end

Instance Attribute Details

#current_markObject (readonly)

Returns the value of attribute current_mark.



14
15
16
# File 'lib/tictactoe/ai/tree.rb', line 14

def current_mark
  @current_mark
end

#markObject (readonly)

Returns the value of attribute mark.



14
15
16
# File 'lib/tictactoe/ai/tree.rb', line 14

def mark
  @mark
end

#moveObject (readonly)

Returns the value of attribute move.



14
15
16
# File 'lib/tictactoe/ai/tree.rb', line 14

def move
  @move
end

#stateObject (readonly)

Returns the value of attribute state.



14
15
16
# File 'lib/tictactoe/ai/tree.rb', line 14

def state
  @state
end

Instance Method Details

#base_scoreObject



32
33
34
35
36
37
38
39
40
41
# File 'lib/tictactoe/ai/tree.rb', line 32

def base_score
  case state.winner
  when mark.value
    MAXIMUM_SCORE
  when nil
    NEUTRAL_SCORE
  else
    MINIMUM_SCORE
  end
end

#childrenObject



20
21
22
23
24
25
# File 'lib/tictactoe/ai/tree.rb', line 20

def children
  state.available_moves.map do |move|
    next_state = state.make_move(move, current_mark.value)
    Tree.new(next_state, mark, current_mark.next, move)
  end
end

#is_final?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/tictactoe/ai/tree.rb', line 16

def is_final?
  state.is_finished?
end

#scoreObject



27
28
29
30
# File 'lib/tictactoe/ai/tree.rb', line 27

def score 
  height = state.available_moves.length + 1
  base_score * height
end