class Vida::Grid

Attributes

columns[R]
elements[R]
rows[R]

Public Class Methods

new(args = {}) click to toggle source
# File lib/vida/grid.rb, line 4
def initialize(args = {})
  @rows       = args.fetch(:rows, 50)
  @columns    = args.fetch(:columns, 50)
  @elements   = Array.new(rows) do |row|
    Array.new(columns) do |column|
      Vida::Cell.new(x: column, y: row, alive: random_status)
    end
  end
  @generation_number = 0
end

Public Instance Methods

live_cells_around(cell) click to toggle source
# File lib/vida/grid.rb, line 15
def live_cells_around(cell)
  cells = []
  cells << [
    north(cell),
    south(cell),
    west(cell),
    east(cell),
    ul_corner(cell),
    ur_corner(cell),
    dl_corner(cell),
    dr_corner(cell)
  ]
  cells.flatten!.count { |c| !c.nil? && c.alive == true }
end
update_cells() click to toggle source
# File lib/vida/grid.rb, line 30
def update_cells
  elements.each do |column|
    column.each do |element|
      element.update_status(live_cells_around(element))
    end
  end
  @generation_number += 1
end

Private Instance Methods

dl_corner(cell) click to toggle source
# File lib/vida/grid.rb, line 87
def dl_corner(cell)
  if cell.x > 0 && cell.y < (rows - 1)
    elements[cell.x - 1][cell.y + 1]
  end
end
dr_corner(cell) click to toggle source
# File lib/vida/grid.rb, line 93
def dr_corner(cell)
  if cell.x < (columns - 1) && cell.y < (rows - 1)
    elements[cell.x + 1][cell.y + 1]
  end
end
east(cell) click to toggle source
# File lib/vida/grid.rb, line 69
def east(cell)
  if cell.x < (columns - 1)
    elements[cell.x + 1][cell.y]
  end
end
north(cell) click to toggle source
# File lib/vida/grid.rb, line 51
def north(cell)
  if cell.y > 0
    elements[cell.x][cell.y - 1]
  end
end
random_status() click to toggle source
# File lib/vida/grid.rb, line 99
def random_status
  [true, false].sample
end
south(cell) click to toggle source
# File lib/vida/grid.rb, line 57
def south(cell)
  if cell.y < (rows - 1)
    elements[cell.x][cell.y + 1]
  end
end
to_s() click to toggle source
# File lib/vida/grid.rb, line 41
def to_s
  elements.each do |c|
    c.each do |r|
      print r
    end
    print "\n"
  end
  puts "Generation: #{@generation_number}"
end
ul_corner(cell) click to toggle source
# File lib/vida/grid.rb, line 75
def ul_corner(cell)
  if cell.x > 0 && cell.y > 0
    elements[cell.x - 1][cell.y - 1]
  end
end
ur_corner(cell) click to toggle source
# File lib/vida/grid.rb, line 81
def ur_corner(cell)
  if cell.x < (columns - 1) && cell.y > 0
    elements[cell.x + 1][cell.y - 1]
  end
end
west(cell) click to toggle source
# File lib/vida/grid.rb, line 63
def west(cell)
  if cell.x > 0
    elements[cell.x - 1][cell.y]
  end
end