class NLife::Game

encapsulates game logic

Attributes

density[R]
state[R]

Public Class Methods

new(rows, cols, surround = nil, rule = nil) click to toggle source
# File lib/nlife/game.rb, line 13
def initialize(rows, cols, surround = nil, rule = nil)
  @state = NArray.float(cols, rows)
  @density = NArray.float(cols, rows)
  surround ||= default_surround(rows, cols)
  @fft_surround = FFTW3.fft(surround.to_f, -1) / surround.size
  @rule = rule || default_rule
end

Public Instance Methods

calc_density() click to toggle source
# File lib/nlife/game.rb, line 54
def calc_density
  t_state = FFTW3.fft(@state, -1)
  t_density = t_state * @fft_surround
  @density = FFTW3.fft(t_density, 1).real.round
end
calc_next_state() click to toggle source
# File lib/nlife/game.rb, line 60
def calc_next_state
  @state.shape[1].times do |row|
    @state.shape[0].times do |col|
      @state[col, row] = @rule.call(@state[col, row], @density[col, row])
    end
  end
end
cols() click to toggle source
# File lib/nlife/game.rb, line 90
def cols
  @state.shape[0]
end
default_rule() click to toggle source
# File lib/nlife/game.rb, line 27
def default_rule
  Helper.rule_from_golly('B3/S23')
end
default_surround(rows, cols) click to toggle source
# File lib/nlife/game.rb, line 21
def default_surround(rows, cols)
  Helper.surround_from_block(rows, cols) do |row, col|
    [row.abs, col.abs].max == 1 ? 1 : 0
  end
end
print() click to toggle source

use for debug only

print_row(row) click to toggle source

use for debug only

reset() click to toggle source
# File lib/nlife/game.rb, line 31
def reset
  @state.shape[1].times do |row|
    @state.shape[0].times do |col|
      @state[col, row] = 0.0
    end
  end
end
rows() click to toggle source
# File lib/nlife/game.rb, line 86
def rows
  @state.shape[1]
end
seed() click to toggle source
# File lib/nlife/game.rb, line 39
def seed
  @state.shape[1].times do |row|
    @state.shape[0].times do |col|
      @state[col, row] = rand.round
    end
  end
end
step(count = 1) click to toggle source
# File lib/nlife/game.rb, line 47
def step(count = 1)
  count.times do
    calc_density
    calc_next_state
  end
end
surround() click to toggle source
# File lib/nlife/game.rb, line 82
def surround
  FFTW3.fft(@fft_surround, 1).real
end