Class: NLife::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/nlife/game.rb

Overview

encapsulates game logic

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rows, cols, surround = nil, rule = nil) ⇒ Game

Returns a new instance of Game.



13
14
15
16
17
18
19
# 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

Instance Attribute Details

#densityObject (readonly)

Returns the value of attribute density.



11
12
13
# File 'lib/nlife/game.rb', line 11

def density
  @density
end

#stateObject (readonly)

Returns the value of attribute state.



10
11
12
# File 'lib/nlife/game.rb', line 10

def state
  @state
end

Instance Method Details

#calc_densityObject



46
47
48
49
50
# File 'lib/nlife/game.rb', line 46

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_stateObject



52
53
54
55
56
57
58
# File 'lib/nlife/game.rb', line 52

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

#colsObject



82
83
84
# File 'lib/nlife/game.rb', line 82

def cols
  @state.shape[0]
end

#default_ruleObject



27
28
29
# File 'lib/nlife/game.rb', line 27

def default_rule
  Helper.rule_from_golly('B3/S23')
end

#default_surround(rows, cols) ⇒ Object



21
22
23
24
25
# 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

use for debug only



61
62
63
64
65
66
67
# File 'lib/nlife/game.rb', line 61

def print
  puts '#' * (@state.shape[0] + 2)
  @state.shape[1].times do |i|
    print_row(i)
  end
  puts '#' * (@state.shape[0] + 2)
end

use for debug only



70
71
72
# File 'lib/nlife/game.rb', line 70

def print_row(row)
  puts '#' + @state[true, row].each.map { |e| e > 0 ? '*' : ' ' }.join + '#'
end

#rowsObject



78
79
80
# File 'lib/nlife/game.rb', line 78

def rows
  @state.shape[1]
end

#seedObject



31
32
33
34
35
36
37
# File 'lib/nlife/game.rb', line 31

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) ⇒ Object



39
40
41
42
43
44
# File 'lib/nlife/game.rb', line 39

def step(count = 1)
  count.times do
    calc_density
    calc_next_state
  end
end

#surroundObject



74
75
76
# File 'lib/nlife/game.rb', line 74

def surround
  FFTW3.fft(@fft_surround, 1).real
end