Skip to content

Instantly share code, notes, and snippets.

@xunker
Last active January 4, 2016 18:39
Show Gist options
  • Save xunker/8662291 to your computer and use it in GitHub Desktop.
Save xunker/8662291 to your computer and use it in GitHub Desktop.
Bad life
require './drawer'
class Life
def initialize(window_x: 640, window_y: 480)
@window_x = window_x
@window_y = window_y
@cellsize = 8
calcuate_bounds
@cells = []
if ARGV[0]
load_seed(ARGV[0])
else
randomize_cells
end
@drawer = Drawer.new(self, max_x: window_x, max_y: window_y, cellsize: @cellsize)
@drawer.show
end
def calcuate_bounds
@cells_x = (@window_x/@cellsize).to_i-1
@cells_y = (@window_y/@cellsize).to_i-1
end
def initialize_cells
@cells_x.times do |x|
@cells[x] = []
@cells_y.times do |y|
@cells[x] << 0
end
end
end
def load_seed(file_path)
initialize_cells
File.open(file_path) do |file|
while (line = file.readline) && (!file.eof?)
next if line.size < 3
(x, y) = line.split(',')
puts "line: #{line} x: #{x} y: #{y}"
@cells[y.to_i][x.to_i] = 1
end
end
# print_cells
end
def print_cells
@cells.each do |cx|
puts cx.map{|v|v==1 ? 'X' : '_'}.join
end
end
def randomize_cells
@cells_x.times do |x|
@cells[x] = []
@cells_y.times do |y|
rand(10) > 8 ? @cells[x] << 1 : @cells[x] << 0
end
end
end
def get_neighbors(x,y)
n=0
[
[x-1,y-1], [x,y-1], [x+1, y-1],
[x-1,y], [x+1, y],
[x-1,y+1], [x,y+1], [x+1, y+1],
].each do |xx,yy|
if @cells[xx] && @cells[xx][yy] && (xx >= 0) && (yy >= 0) && (yy <= @cells[xx].size) && (xx <= @cells.size)
n+=1 if @cells[xx][yy]==1
end
end
n
end
def update
# return
@cells.each_with_index do |cy, y|
cy.each_with_index do |cx, x|
neighbors = get_neighbors(x,y)
if (neighbors < 2) || (neighbors > 3) && @cells[x][y]==1
@cells[x][y]=0
elsif neighbors == 3 && @cells[x][y]==0
@cells[x][y]=1
end
end
end
end
def draw
@cells.each_with_index do |cy, y|
cy.each_with_index do |cx, x|
if cx == 1
@drawer.draw_point(y,x)
end
end
end
end
end
Life.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment