Class: Knossos::Grid

Inherits:
Object
  • Object
show all
Defined in:
lib/knossos/grid.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#columnsObject (readonly)

Returns the value of attribute columns.



3
4
5
# File 'lib/knossos/grid.rb', line 3

def columns
  @columns
end

#rowsObject (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_countObject



38
39
40
# File 'lib/knossos/grid.rb', line 38

def cell_count
  grid.reduce(0) { |acc, e| acc += e.count }
end

#each_cellObject



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_rowObject



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_cellObject



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