Class: Reversi::Player::NegaMaxAI

Inherits:
BasePlayer show all
Defined in:
lib/reversi/player/nega_max_ai.rb

Instance Attribute Summary

Attributes inherited from BasePlayer

#board, #my_color, #opponent_color

Instance Method Summary collapse

Methods inherited from BasePlayer

#count_disks, #next_moves, #put_disk, #status

Constructor Details

#initialize(_color, _board) ⇒ NegaMaxAI

Returns a new instance of NegaMaxAI.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/reversi/player/nega_max_ai.rb', line 4

def initialize(_color, _board)
  super

  points = [
    100, -10,  0, -1, -1,  0, -10, 100,
    -10, -30, -5, -5, -5, -5, -30, -10,
      0,  -5,  0, -1, -1,  0,  -5,   0,
     -1,  -5, -1, -1, -1, -1,  -5,  -1,
     -1,  -5, -1, -1, -1, -1,  -5,  -1,
      0,  -5,  0, -1, -1,  0,  -5,   0,
    -10, -30, -5, -5, -5, -5, -30, -10,
    100, -10,  0, -1, -1,  0, -10, 100
  ]
  @evaluation_value = 
    Hash[(1..8).map{ |x| (1..8).map{ |y| [[x, y], points.shift] } }.flatten(1) ]
end

Instance Method Details

#evaluate(move, board, depth, color) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/reversi/player/nega_max_ai.rb', line 30

def evaluate(move, board, depth, color)
  put_disk(*move, color)
  moves = next_moves(!color)

  if depth == 1
    status[:mine].inject(0){ |sum, xy| sum + @evaluation_value[xy] }
  elsif moves.empty?
    -100
  else
    -( moves.map{ |move| evaluate(move, board, depth - 1, !color) }.max )
  end

ensure
  board.undo!
end

#move(board) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/reversi/player/nega_max_ai.rb', line 21

def move(board)
  moves = next_moves
  return if moves.empty?
  next_move = moves.map do |move|
    { :move => move, :point => evaluate(move, board, 3, true) }
  end.max_by{ |v| v[:point] }[:move]
  put_disk(*next_move)
end