Skip to content

Instantly share code, notes, and snippets.

@mmb
Created October 25, 2009 03:48
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 mmb/217883 to your computer and use it in GitHub Desktop.
Save mmb/217883 to your computer and use it in GitHub Desktop.
add methods to rmagick to generate Conway's life iterations
require 'rubygems'
require 'RMagick'
# add methods to rmagick to generate Conway's life iterations
module Magick
class Image
def occupied?(x, y); pixel_color(x, y).to_color == 'black' end
def neighbors(x, y)
[
[x - 1, y - 1],
[x, y - 1],
[x + 1, y - 1],
[x + 1, y],
[x + 1, y + 1],
[x, y + 1],
[x - 1, y + 1],
[x - 1, y]].collect { |x,y| occupied?(x, y) ? 1 : 0 }.
inject { |sum,n| sum + n }
end
def life_next
next_iter = copy
(0...rows).each do |x|
(0...columns).each do |y|
nb = neighbors(x, y)
next_iter.pixel_color(x, y,
(nb == 3 or (occupied?(x, y) and nb == 2)) ? 'black' : 'white')
end
end
next_iter
end
end
class Magick::ImageList
def add_life_next(n=1)
n.times { self << last.life_next }
end
end
end
blob = <<-eos
/* XPM */
static char * xpm[] = {
"32 32 2 1",
" c #ffffff",
". c #000000",
" ",
" ...... ",
" .......... ",
" ........... ",
" .............. ",
" .............. ",
" ................ ",
" .... .. .. ",
" .. ... ",
" .. ... ",
" .. .. ",
" . .. ",
" .. .. . .. ",
" . . .. ..... .. ",
" . . . .... .. ",
" . .. . ",
" ",
" . ",
" ",
" . .. . ",
" . .... . ",
" .. ....... . ",
" .. ............ ",
" .... ... . ",
" .... ......... ",
" ..... ... .... ",
" ............ ",
" ............ ",
" ........ ",
" .... ",
" . ",
" "};
eos
img = Magick::ImageList.new
img.from_blob(blob)
img.add_life_next(82)
img.delay = 75
# img.to_a.each do |i|
# i.resize!(512, 512, filter=Magick::LanczosFilter, support=0.0)
# end
img.write('anim.gif')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment