Class: Ai

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mark, manager) ⇒ Ai

Returns a new instance of Ai.



7
8
9
10
11
# File 'lib/ai.rb', line 7

def initialize(mark, manager)
  @mark = mark
  @state = State.new(manager)
  @manager = manager
end

Instance Attribute Details

#choiceObject (readonly)

Returns the value of attribute choice.



5
6
7
# File 'lib/ai.rb', line 5

def choice
  @choice
end

#markObject (readonly)

Returns the value of attribute mark.



5
6
7
# File 'lib/ai.rb', line 5

def mark
  @mark
end

Instance Method Details

#score(board, mark) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/ai.rb', line 13

def score(board, mark)
  if @state.winner?(board, mark) || @state.winner?(board, @manager.other_mark(mark))
    -10
  else
    0
  end  
end

#score_moves(board, mark, depth, scores) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/ai.rb', line 21

def score_moves(board, mark, depth, scores)
  return score(board, mark) if @state.terminal?(board) || (board.size == 16 && depth == 2)
  @state.empty_indices(board).each do |move|
    board[move] = mark
    scores[move] = -1 * score_moves(board, @manager.other_mark(mark), depth + 1, Hash.new)
    board[move] = "-"
  end
  best_score = scores.values.max
  depth == 0 ? scores : best_score
end

#smart_move(board) ⇒ Object



32
33
34
# File 'lib/ai.rb', line 32

def smart_move(board)
  @choice = score_moves(board, @mark, 0, Hash.new).max_by{ |k, v| v }[0]
end