Class: AIPlayer

Inherits:
GenericPlayer show all
Defined in:
lib/fiveinarow/ai_player.rb

Instance Attribute Summary

Attributes inherited from GenericPlayer

#sym

Instance Method Summary collapse

Methods inherited from GenericPlayer

#initialize

Constructor Details

This class inherits a constructor from GenericPlayer

Instance Method Details

#ai(board) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/fiveinarow/ai_player.rb', line 21

def ai(board)
  if self.sym == Cell::PLAYER_A
    opsym = Cell::PLAYER_B
  else
    opsym = Cell::PLAYER_A
  end

  # 0 is EMPTY_CELL
  # 1 is AI (this one)
  # 2 is opponent
  # -1 is end of pattern

  [
      # my four, go for win
      [0, [0, 1, 1, 1, 1]],
      [1, [1, 0, 1, 1, 1]],
      [2, [1, 1, 0, 1, 1]],

      # his four, need to block
      [0, [0, 2, 2, 2, 2]],
      [1, [2, 0, 2, 2, 2]],
      [2, [2, 2, 0, 2, 2]],

      # my three, go for four
      [0, [0, 1, 1, 1, 0]],
      [2, [0, 1, 0, 1, 1]],
      [1, [1, 0, 1, 1, 0]],
      [1, [0, 0, 1, 1, 1]],

      # his three, need to block
      [0, [0, 2, 2, 2, 0]],
      [1, [2, 0, 2, 2, 0]],
      [1, [0, 2, 0, 2, 2]],

      # my two, let's make three
      [2, [0, 1, 0, 1, 0]],
      [1, [0, 0, 1, 1, 0]],
      [1, [0, 0, 1, 1, 0, 0]],

      # really nothing to do, lets make mark next to another
      [1, [0, 0, 1, 0, 0]],
      [1, [0, 0, 1, 0]],
      [0, [0, 1, 0]],

      # okay... so, just block something
      [1, [0, 0, 2, 0]],
      [0, [0, 2, 0]]

  ].each do |pattern|
    puts "pattern = #{pattern}"
    (0..board.size - 1).each do |row|
      (0..board.size - 1).each do |col|
        [[1, 1], [1, 0], [-1, 1], [0, 1], [-1, -1], [-1, 0], [1, -1], [0, -1]].each do |k|
          rd = k[0]
          cd = k[1]
          s = 0
          pattern[1].each_with_index.map do |pval, pind|
            if pval == 0
              break if board.on(row + rd*pind, col + cd*pind) != 0
            elsif pval == 1
              break if board.on(row + rd*pind, col + cd*pind) != self.sym
            elsif pval == 2
              break if board.on(row + rd*pind, col + cd*pind) != opsym
            end
            s += 1
          end
          if s == pattern[1].length
            board.mark_cell(row + rd*pattern[0], col+ cd*pattern[0], self.sym)
            return true
          end
        end
      end
    end
  end

  puts "oh shit"
  return false
end

#make_move(board) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/fiveinarow/ai_player.rb', line 5

def make_move(board)
  ai(board)
  "prng = Random.new

  loop do
    row = prng.rand(0..board.size - 1)
    col = prng.rand(0..board.size - 1)

    if board.grid[row][col].e?
      board.grid[row][col].set(@sym)
      break
    end
  end"
end