# pnm library converts array to image in ruby
require "pnm"
class Universe
def initialize(row, column, percentFill)
@init_row = row
@init_column = column
@image = Array.new(row) { Array.new(column,0) }
@initialSeed = (percentFill*@init_row*@init_column/100).to_i
@initialSeed.times do |i|
rand_row = rand(0..@init_row-1)
rand_column = rand(0..@init_column-1)
@image[rand_row][rand_column]=1
end
@options = {:type => "pbm"}
end
def printme(input)
image2 = PNM.create(@image)
str = input.to_s.rjust(4, "0")
image2.write_with_extension(str)
end
def generate_next_frame
newframe = Marshal.load(Marshal.dump(@image))
@image.each_with_index do |x, xi|
x.each_with_index do |y, yi|
neighbors = check_live_neighbors(xi,yi)
if @image[xi][yi] == 1
if neighbors < 2 || neighbors > 3
newframe[xi][yi] = 0
end
else
if neighbors == 3
newframe[xi][yi] = 1
end
end
end
end
@image = Marshal.load(Marshal.dump(newframe))
end
def check_live_neighbors(row,column)
neighbors = {:n => 0, :e=>0,:w=>0, :s=>0, :ne=>0, :nw=>0, :se=>0, :sw=>0}
if row>0
neighbors[:n] = @image[row-1][column]
end
if row<@init_row-1
neighbors[:s] = @image[row+1][column]
end
if column<@init_column-1
neighbors[:e] = @image[row][column+1]
end
if column>0
neighbors[:w] = @image[row][column-1]
end
if row>0 && column<@init_column-1
neighbors[:ne]= @image[row-1][column+1]
end
if row>0 && column>0
neighbors[:nw]= @image[row-1][column-1]
end
if row<@init_row-1 && column<@init_column-1
neighbors[:se]= @image[row+1][column+1]
end
if row<@init_row-1 && column>0
neighbors[:sw]= @image[row+1][column-1]
end
neighbors.values.inject(:+)
end
end
# execution
u = Universe.new(200,200,20)
i = 0
while (i <200) do
u.generate_next_frame
u.printme(i)
i +=1
end