Last active
August 29, 2015 14:14
-
-
Save AlexEscalante/a307ebef06975d365780 to your computer and use it in GitHub Desktop.
Conway's Game Of Life
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
require_relative '../life_window.rb' | |
RSpec.describe LifeWindow do | |
describe "#count_around" do | |
it "counts elements around, not ibcluding, the specified coordinate" do | |
m1 = Matrix[[false, true, false], [true, true, true], [false, true, false]] | |
m2 = Matrix[[false, false, false], [true, true, true], [false, true, false]] | |
m3 = Matrix[[false, false, false], [true, true, true], [false, false, false]] | |
expect(LifeWindow.count_around(m1, 1, 1)).to eq(4) | |
expect(LifeWindow.count_around(m2, 1, 1)).to eq(3) | |
expect(LifeWindow.count_around(m3, 1, 1)).to eq(2) | |
end | |
end | |
end |
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 and dirty version of Conway's Game of Life | |
# | |
# Please install Gosu, more info: http://www.libgosu.org/ | |
require 'gosu' | |
require 'matrix' | |
class LifeWindow < Gosu::Window | |
include Gosu | |
@@screen_width = 640 | |
@@screen_height = 480 | |
def self.create_world size | |
Matrix.build(size) { | |
rand(1..100) < 10 # life chance | |
} | |
end | |
def self.count_around m, x, y | |
[ m[x - 1, y - 1], m[x, y - 1], m[x + 1, y - 1], | |
m[x - 1, y], m[x + 1, y], | |
m[x - 1, y + 1], m[x, y + 1], m[x + 1, y + 1] ].count { |x| x } | |
end | |
def initialize(world_size = 100, update_interval = 100) | |
super(@@screen_width, @@screen_height, false, update_interval) | |
self.caption = "Conway's Game Of Life" | |
@world_size = world_size | |
@world = LifeWindow.create_world(@world_size) | |
end | |
def update | |
@world = Matrix.build(@world_size) { |x, y| | |
[false, false, @world[x, y], true, false, false, false, false][LifeWindow.count_around(@world, x, y)] | |
} | |
end | |
def draw | |
block_width, block_height = @@screen_width / @world_size, @@screen_height / @world_size | |
@world.each_with_index { |e, x, y| | |
color = e ? Color::RED : Color::BLACK | |
draw_quad(block_width * x, block_width * y, color, | |
block_width * (x + 1), block_width * y, color, | |
block_width * (x + 1), block_width * (y + 1), color, | |
block_width * x, block_width * (y + 1), color) | |
} | |
end | |
def button_down id | |
@world = LifeWindow.create_world(@world_size) | |
end | |
end | |
if __FILE__==$0 | |
window = LifeWindow.new | |
window.show | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment