Class: Board

Inherits:
Object
  • Object
show all
Defined in:
lib/connect-four.rb

Constant Summary collapse

COLS =
7
ROWS =
6

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBoard

Returns a new instance of Board.



9
10
11
# File 'lib/connect-four.rb', line 9

def initialize
  @pieces = ([nil] * COLS).map { [nil] * ROWS }
end

Instance Attribute Details

#piecesObject

Returns the value of attribute pieces.



4
5
6
# File 'lib/connect-four.rb', line 4

def pieces
  @pieces
end

Instance Method Details

#column(id) ⇒ Object



78
79
80
# File 'lib/connect-four.rb', line 78

def column(id)
  pieces[id]
end

#current_colorObject



56
57
58
# File 'lib/connect-four.rb', line 56

def current_color
  red? ? :red : :yellow
end

#current_playerObject



60
61
62
# File 'lib/connect-four.rb', line 60

def current_player
  current_color.to_s.colorize(current_color)
end

#drawObject



13
14
15
16
17
18
19
20
# File 'lib/connect-four.rb', line 13

def draw
  ROWS.times do |i|
    row(ROWS - 1 - i).each do |char|
      print "\u25A0 ".colorize(char || :light_black)
    end
    print "\n"
  end
end

#movesObject



22
23
24
# File 'lib/connect-four.rb', line 22

def moves
  pieces.flatten.compact.length
end

#place(col) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/connect-four.rb', line 64

def place(col)
  if col.match(/\A[^\d]/)
    false
  else
    col = col.to_i
    id = column(col).each_with_index.find { |el, i| el.nil? }[1]
    column(col)[id] = current_color
  end
end

#point_won?(row, column) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
# File 'lib/connect-four.rb', line 34

def point_won?(row, column)
  possible_wins(row, column).find do |items|
    items.compact.size == 4 and items.uniq.length == 1
  end
end

#possible_wins(row, column) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/connect-four.rb', line 40

def possible_wins(row, column)
  directions = {n: [-1, 0], w: [0, -1], nw: [-1, -1], ne: [-1, 1]}
  directions.keys.map do |direction|
    relative_direction = directions[direction]
    (0..3).map do |i|
      x = row + (relative_direction[0] * i)
      y = column + (relative_direction[1] * i)
      pieces[x][y] if x >= 0 and y >= 0
    end
  end
end

#red?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/connect-four.rb', line 52

def red?
  moves % 2 == 0
end

#row(id) ⇒ Object



74
75
76
# File 'lib/connect-four.rb', line 74

def row(id)
  pieces.collect { |el| el[id] }
end

#won?Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
# File 'lib/connect-four.rb', line 26

def won?
  ROWS.times.find do |r|
    COLS.times.find do |c|
      point_won?(r, c)
    end
  end
end