Skip to content

Instantly share code, notes, and snippets.

@kp666
Last active February 28, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kp666/41cbdd3445bbef872e3833485c367dd7 to your computer and use it in GitHub Desktop.
Save kp666/41cbdd3445bbef872e3833485c367dd7 to your computer and use it in GitHub Desktop.
require 'gosu'
class Tutorial < Gosu::Window
def initialize(board_width, board_height, pattern_file)
@board_width = board_width
@board_height = board_height
@columns = board_width / 12
@rows = board_height / 12
super @board_width, @board_height, update_interval: 100
self.caption = "Game of life"
@back_ground_color = Gosu::Color.argb(0xff_808080)
@white = Gosu::Color.argb(0xff_ffffff)
@black = Gosu::Color.argb(0xff_000000)
pattern = pattern_file.to_s.empty? ? random_pattern : read_pattern(pattern_file)
@pattern = prefill_pattern(pattern)
end
def read_pattern(file)
lines = Array.new
File.open(file).each do |line|
line.chomp!
next if line.empty? || line =~ /#/
lines << line.split('').map {|x| (x.ord % 7 == 0) || (x.ord == 88) ? 1 : 0}
end
lines
end
def update
tmp_pattern = Array.new(@columns * 2) {Array.new(@rows * 2, 0)}
(@columns * 2).times do |x|
(@rows * 2).times do |y|
number_of_neighbours = neighbour_count(x, y)
if @pattern[x][y] == alive && (number_of_neighbours == 2 || number_of_neighbours == 3)
tmp_pattern[x][y] = alive
elsif @pattern[x][y] == dead && (number_of_neighbours == 3)
tmp_pattern[x][y] = alive
else
tmp_pattern[x][y] = dead
end
end
end
@pattern = tmp_pattern
end
def neighbour_count(x, y)
anyone_there(x - 1, y - 1) + anyone_there(x - 1, y) + anyone_there(x - 1, y + 1) +
anyone_there(x, y - 1) + anyone_there(x, y + 1) +
anyone_there(x + 1, y - 1) + anyone_there(x + 1, y) + anyone_there(x + 1, y + 1)
end
def anyone_there(x, y, pattern = @pattern)
(x < 0 || y < 0) ? 0 : pattern[x][y].to_i rescue 0
end
def alive
1
end
def dead
0
end
def generate_pattern
array = Array.new(@columns * 2) {Array.new(@rows * 2, 0)}
x = 0
while x < @columns do
y = 0
while y < @rows do
array[x][y] = yield(x, y)
y = y + 1
end
x = x + 1
end
array
end
def prefill_pattern(pattern)
generate_pattern {|x, y| anyone_there(x, y, pattern)}
end
def random_pattern
generate_pattern {|x, y| rand(2)}
end
def draw
draw_quad(
0, 0, @back_ground_color,
@board_width, 0, @back_ground_color,
0, @board_height, @back_ground_color,
@board_width, @board_height, @back_ground_color,
0
)
x = 0
while x < @rows do
y = 0
while y < @columns do
life = @pattern[x][y]
color = life == alive ? @black : @white
draw_rect(y * 12, x * 12, 10, 10, color)
y = y + 1
end
x = x + 1
end
end
end
t = Tutorial.new(640, 480, ARGV[0])
t.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment