Created
May 21, 2013 10:09
-
-
Save plexus/5618764 to your computer and use it in GitHub Desktop.
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
# Quick rendition of Conway's game of life | |
class Grid | |
def initialize | |
@width = 100 | |
@height = 30 | |
generate_grid | |
end | |
def generate_grid | |
@grid = (0...@width).map do | |
(0...@height).map do | |
[0, 1].sample | |
end | |
end | |
end | |
def to_s | |
(0...@height).map do |y| | |
(0...@width).map do |x| | |
[' ', '@'][@grid[x][y]] | |
end.join | |
end.join("\n") | |
end | |
def sibling_sum(x,y) | |
[-1, 0, 1].flat_map do |offset_x| | |
[-1, 0, 1].map do |offset_y| | |
if (offset_x == 0 && offset_y == 0) || outside_grid?(x+offset_x,y+offset_y) | |
0 | |
else | |
raise "#{x}, #{y}" if @grid[x + offset_x][y + offset_y] == nil | |
@grid[x + offset_x][y + offset_y] | |
end | |
end | |
end.inject(:+) | |
end | |
def outside_grid?(x, y) | |
x < 0 || x >= @width || y < 0 || y >= @height | |
end | |
def generation | |
@grid = @grid.map.with_index do |row, x| | |
row.map.with_index do |point, y| | |
case sibling_sum(x,y) | |
when 0..1 | |
0 | |
when 2 | |
point | |
when 3 | |
1 | |
when 4..8 | |
0 | |
else | |
raise sibling_sum(x,y) | |
end | |
end | |
end | |
end | |
end | |
g = Grid.new | |
loop do | |
puts g | |
puts "\x1b[#{30}A" | |
g.generation | |
sleep 0.1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dork :-)