Class: CellularAutomata::Board

Inherits:
Object
  • Object
show all
Defined in:
lib/cellular_automata/board.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rule: 'B3S2', width: 80, height: 20, max_history: 2) ⇒ Board

Returns a new instance of Board.



3
4
5
6
7
8
9
10
11
12
# 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

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



2
3
4
# File 'lib/cellular_automata/board.rb', line 2

def height
  @height
end

#historyObject (readonly)

Returns the value of attribute history.



2
3
4
# File 'lib/cellular_automata/board.rb', line 2

def history
  @history
end

#ruleObject (readonly)

Returns the value of attribute rule.



2
3
4
# File 'lib/cellular_automata/board.rb', line 2

def rule
  @rule
end

#stateObject (readonly)

Returns the value of attribute state.



2
3
4
# File 'lib/cellular_automata/board.rb', line 2

def state
  @state
end

#widthObject (readonly)

Returns the value of attribute width.



2
3
4
# File 'lib/cellular_automata/board.rb', line 2

def width
  @width
end

Instance Method Details

#each_cellObject



42
43
44
45
46
47
48
# 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:) ⇒ Object



34
35
36
# File 'lib/cellular_automata/board.rb', line 34

def kill(array: , x: , y: )
  array[y][x] = 0
end

#live(array:, x:, y:) ⇒ Object



38
39
40
# File 'lib/cellular_automata/board.rb', line 38

def live(array: , x: , y: )
  array[y][x] = 1
end

#tick!Object



27
28
29
30
31
32
# 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_sObject



14
15
16
17
18
19
20
21
22
23
24
25
# 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