Created
February 24, 2011 02:10
-
-
Save kognate/841618 to your computer and use it in GitHub Desktop.
I worked on this for another twenty minutes or so. found the bug. Run it in a terminal and you can see it run.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Conway | |
attr_reader :displayrange | |
attr_accessor :board | |
# Any live cell with fewer than two live neighbours dies, as if caused by under-population. | |
# Any live cell with two or three live neighbours lives on to the next generation. | |
# Any live cell with more than three live neighbours dies, as if by overcrowding. | |
# Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. | |
def initialize disprange = nil | |
@board = { 1 => { 2 => 1}, 2 => { 2 => 1}, 3 => { 2 => 1} } | |
@displayrange = disprange.nil? ? (0..10) : disprange | |
end | |
def randomize n=30 | |
@board = {} | |
(0..n).each { | |
_x = srand % @displayrange.max | |
_y = srand % @displayrange.max | |
@board[_x].nil? ? @board[_x] = {_y => 1} : @board[_x][_y] = 1 | |
} | |
end | |
def neighbor_ar x,y | |
[[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]] | |
end | |
def is_alive x,y,vv=false | |
neighbors = neighbor_ar x,y | |
currently_alive = begin @board[x][y] rescue 0 end | |
_res = neighbors.collect {|n,m| @board[n].nil? ? 0 : (@board[n][m].nil? ? 0 : @board[n][m])} | |
_ncount = _res.inject(0) {|k,v| k + v } | |
_slot = if [2,3].include?(_ncount) && currently_alive == 1 | |
1 | |
elsif (_ncount == 3) && currently_alive != 1 | |
1 | |
else | |
0 | |
end | |
_slot | |
end | |
def generation disp=false | |
nboard = {} | |
self.displayrange.each {|i| | |
line = "" | |
nboard[i] = {} | |
self.displayrange.each {|j| | |
nboard[i][j] = self.is_alive(i,j) | |
line << "+" if nboard[i][j] == 1 | |
line << " " if nboard[i][j] == 0 | |
} | |
puts "|#{line}|" if disp | |
} | |
@board = nboard | |
end | |
end | |
c = Conway.new 0..30 | |
c.randomize 175 | |
while true do | |
puts "\e[H\e[2J" | |
c.generation true | |
sleep(1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment