Class: Board
- Inherits:
-
Object
- Object
- Board
- Defined in:
- lib/connect-four.rb
Constant Summary collapse
- COLS =
7
- ROWS =
6
Instance Attribute Summary collapse
-
#pieces ⇒ Object
Returns the value of attribute pieces.
Instance Method Summary collapse
- #column(id) ⇒ Object
- #current_color ⇒ Object
- #current_player ⇒ Object
- #draw ⇒ Object
-
#initialize ⇒ Board
constructor
A new instance of Board.
- #moves ⇒ Object
- #place(col) ⇒ Object
- #point_won?(row, column) ⇒ Boolean
- #possible_wins(row, column) ⇒ Object
- #red? ⇒ Boolean
- #row(id) ⇒ Object
- #won? ⇒ Boolean
Constructor Details
Instance Attribute Details
#pieces ⇒ Object
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_color ⇒ Object
56 57 58 |
# File 'lib/connect-four.rb', line 56 def current_color red? ? :red : :yellow end |
#current_player ⇒ Object
60 61 62 |
# File 'lib/connect-four.rb', line 60 def current_player current_color.to_s.colorize(current_color) end |
#draw ⇒ Object
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 |
#moves ⇒ Object
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
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
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 |