class CellularAutomata::Board

Attributes

height[R]
history[R]
rule[R]
state[R]
width[R]

Public Class Methods

new(rule: 'B3S2', width: 80, height: 20, max_history: 2) click to toggle source
# File lib/cellular_automata/board.rb, line 3
def initialize(rule: 'B3S2', width: 80, height: 20, max_history: 2)
  @height = height
  @width  = width
  @state  = build_array
  @rule   = CellularAutomata::Rule.new(rule)
  @history = []
  @max_history = max_history
  max_history.times { history.push build_array }
  seed!
end

Public Instance Methods

each_cell() { |x, y| ... } click to toggle source
# File lib/cellular_automata/board.rb, line 42
def each_cell
  (0..height-1).each do |y|
    (0..width-1).each do |x|
      yield(x, y)
    end
  end
end
kill(array: , x: , y: ) click to toggle source
# File lib/cellular_automata/board.rb, line 34
def kill(array: , x: , y: )
  array[y][x] = 0
end
live(array: , x: , y: ) click to toggle source
# File lib/cellular_automata/board.rb, line 38
def live(array: , x: , y: )
  array[y][x] = 1
end
tick!() click to toggle source
# File lib/cellular_automata/board.rb, line 27
def tick!
  next_state = CellularC.next_state(@state, rule)
  history.unshift CellularC.dup_state(@state)
  history.pop if history.length > @max_history
  @state = next_state
end
to_s() click to toggle source
# File lib/cellular_automata/board.rb, line 14
def to_s
  line = '+' << ('-' * width) << "+\n"
  ret = '' << line
  @state.each do |row|
    ret << "|"
    row.each do |cell|
      ret << (cell == 0 ? ' ' : '*' )
    end
    ret << "|\n"
  end
  ret << line
end

Private Instance Methods

build_array() click to toggle source
# File lib/cellular_automata/board.rb, line 56
def build_array
  arr = []
  (0..height-1).each do |y|
    arr[y] = []
    (0..width-1).each do |x|
      arr[y][x] = 0
    end
  end
  return arr
end
neighbor_population_of(x: , y: ) click to toggle source
# File lib/cellular_automata/board.rb, line 67
def neighbor_population_of(x: , y: )
  ret = 0
  min_x = x > 1 ? x - 1 : 0
  max_x = x < width - 2 ? x + 1 : width - 1
  min_y = y > 1 ? y - 1 : 0
  max_y = y < height - 2 ? y + 1 : height - 1
  (min_y..max_y).each do |row|
    (min_x..max_x).each do |col|
      ret += 1 unless ((x == col && y == row) || @state[row][col] == 0)
    end
  end
  ret
end
seed!() click to toggle source
# File lib/cellular_automata/board.rb, line 52
def seed!
  each_cell { |x, y| @state[y][x] = 1 if rand < 0.1 }
end