Class: Knossos::Grid
- Inherits:
-
Object
- Object
- Knossos::Grid
- Defined in:
- lib/knossos/grid.rb
Instance Attribute Summary collapse
-
#columns ⇒ Object
readonly
Returns the value of attribute columns.
-
#rows ⇒ Object
readonly
Returns the value of attribute rows.
Instance Method Summary collapse
- #[](row, column) ⇒ Object
- #build_passage(cell, other) ⇒ Object
- #cell_count ⇒ Object
- #each_cell ⇒ Object
- #each_row ⇒ Object
- #east(cell) ⇒ Object
-
#initialize(args = {}) ⇒ Grid
constructor
A new instance of Grid.
- #neighborhood(cell) ⇒ Object
- #north(cell) ⇒ Object
- #random_cell ⇒ Object
- #south(cell) ⇒ Object
- #west(cell) ⇒ Object
Constructor Details
#initialize(args = {}) ⇒ Grid
Returns a new instance of Grid.
5 6 7 8 9 10 11 12 |
# File 'lib/knossos/grid.rb', line 5 def initialize(args = {}) args = defaults.merge(args) @rows = args[:rows] @columns = args[:columns] @grid = assemble_grid end |
Instance Attribute Details
#columns ⇒ Object (readonly)
Returns the value of attribute columns.
3 4 5 |
# File 'lib/knossos/grid.rb', line 3 def columns @columns end |
#rows ⇒ Object (readonly)
Returns the value of attribute rows.
3 4 5 |
# File 'lib/knossos/grid.rb', line 3 def rows @rows end |
Instance Method Details
#[](row, column) ⇒ Object
14 15 16 17 18 19 |
# File 'lib/knossos/grid.rb', line 14 def [](row, column) return nil unless row_is_valid?(row) return nil unless column_is_valid?(row, column) grid[row][column] end |
#build_passage(cell, other) ⇒ Object
62 63 64 65 |
# File 'lib/knossos/grid.rb', line 62 def build_passage(cell, other) cell.link_to(other) other.link_to(cell) end |
#cell_count ⇒ Object
38 39 40 |
# File 'lib/knossos/grid.rb', line 38 def cell_count grid.reduce(0) { |acc, e| acc += e.count } end |
#each_cell ⇒ Object
25 26 27 28 29 |
# File 'lib/knossos/grid.rb', line 25 def each_cell each_row do |cells, row| cells.each_with_index { |cell, column| yield(cell, row, column) } end end |
#each_row ⇒ Object
21 22 23 |
# File 'lib/knossos/grid.rb', line 21 def each_row grid.each_with_index { |cells, row| yield(cells, row) } end |
#east(cell) ⇒ Object
46 47 48 |
# File 'lib/knossos/grid.rb', line 46 def east(cell) self[cell.row, cell.column + 1] end |
#neighborhood(cell) ⇒ Object
58 59 60 |
# File 'lib/knossos/grid.rb', line 58 def neighborhood(cell) [:north, :east, :south, :west].map { |dir| self.send(dir, cell) }.compact end |
#north(cell) ⇒ Object
42 43 44 |
# File 'lib/knossos/grid.rb', line 42 def north(cell) self[cell.row - 1, cell.column] end |
#random_cell ⇒ Object
31 32 33 34 35 36 |
# File 'lib/knossos/grid.rb', line 31 def random_cell row = rand(rows) column = rand(columns_for(row)) self[row, column] end |
#south(cell) ⇒ Object
50 51 52 |
# File 'lib/knossos/grid.rb', line 50 def south(cell) self[cell.row + 1, cell.column] end |
#west(cell) ⇒ Object
54 55 56 |
# File 'lib/knossos/grid.rb', line 54 def west(cell) self[cell.row, cell.column - 1] end |