Code Snippet: Ruby Walks with Shoes

Posted by Ryan Baxter Tue, 30 Oct 2007 14:30:00 GMT

_Why of Why’s (Poignant) Guide to Ruby has announced the publication of a 52 page comic style book illustrating the ins and outs of his new windowing toolkit, Shoes. In his words, “Shoes is a very informal graphics and windowing toolkit. It’s for making regular old apps that run on Windows, Mac OS X and Linux. It’s a blend of my favorite things from the Web, some Ruby style, and a sprinkling of cross-platform widgets.”

Using the the latest Shoes revision, I’ve written some code to generate a Mandelbrot fractal. Try it out with the following command (assuming your script is located in the Shoes samples directory):

./shoes samples/mandelbrot.rb

You may want to go make a sandwich while you wait. Here is a sample of the output:

Here is the code:

# RB

require 'complex'

class Mandelbrot  
  def initialize(bailout=10, iterations=100)
    @bailout, @iterations = bailout, iterations   
  end  

  # A method for determining if a point is within
  # the Mandelbrot set.
  def in_set?(x, y)
    c = Complex(x, y)
    z = 0
    @iterations.times do |i|
      z = z**2 + c                       
      return false if z > @bailout
    end
    return true 
  end  
end

class Generator < Shoes
  url '/', :index

  def index()    
    render(250, 250, rgb(205, 102, 0))    
  end

  def render(height=250, width=250, color=rgb(255, 0, 0))
    nostroke
    fill color   

    mandelbrot = Mandelbrot.new

    # Render the fractal.
    0.upto(height) do |y|
      0.upto(width) do |x|
        scaled_x = -2 + (3 * x / width.to_f)
        scaled_y = 1 + (-2 * y / height.to_f)
        if mandelbrot.in_set?(scaled_x, scaled_y) then        
          rect :left => x, :top => y, :width => 1, :height => 1
          # oval :left => x, :top => y, :radius => 1, :center => true                           
        end      
      end
    end
  end
end

Shoes.app :title => 'Mandelbrot', :height => 250, :width => 250
Comments

Leave a response