丸いボールが、バウンドする奴

#!/usr/bin/env ruby

require 'sdl'
require 'cairo'

class Sprite
  attr_accessor :x, :y, :alive, :enabled, :idx, :info
  attr_writer :draw, :matrix

  def initialize
    @x, @y = 0, 0
    @alive = true
    @enabled = true
    @idx = 0
    @info = {}
    @matrix = Cairo::Matrix.identity
  end

  def renew(cr)
    return if !@enabled
    cr.matrix = @matrix * Cairo::Matrix.translate(@x, @y)
    @draw[cr]
  end
end

class Phase
  attr_accessor :handles, :task

  def initialize(w, h, info=nil)
    @image = Cairo::ImageSurface.new(w, h)
    @info = info
    @sprites = []
    @handles = {}
  end

  def addSprite
    @sprites << Sprite.new
    yield(@sprites.last)
    @sprites.last
  end

  def renew(drawFlag=true)
    @task[] if @task
    if drawFlag
      cr = Cairo::Context.new(@image)
      @sprites.reject!{|obj| !obj.alive}
      @sprites.each {|obj| obj.renew(cr)}
      @image
    else
      nil
    end
  end

  def layerSort
    @sprites.sort!{|a, b| a.idx <=> b.idx}
  end
end

SDL.init(SDL::INIT_VIDEO)
SDL::WM.set_caption("Bound of The Ball","")
w, h = 350, 250
screen = SDL::Screen.open(w, h, 32, 0)
phase = Phase.new(w, h)
phase.addSprite do |obj|
  obj.draw = proc do |cr|
    cr.set_source_color(:black)
    cr.rectangle(0, 0, w, h)
    cr.fill
  end
end
r = 8
ball = phase.addSprite do |obj|
  obj.x, obj.y = w / 2, h / 2
  obj.info[:rx] = Range.new(r, w - r)
  obj.info[:ry] = Range.new(r, h - r)
  obj.info[:dx] = rand(5) + 2
  obj.info[:dx] *=  -1 if rand(9) < 5
  obj.info[:dy] = rand(5) + 2
  obj.info[:dy] *=  -1 if rand(9) < 5
  obj.draw = proc do |cr|
    cr.set_source_color(:red)
    cr.circle(0, 0, r)
    cr.fill
  end
end
phase.task = proc do
  ball.info[:dx] *=  -1 if !ball.info[:rx].include?(ball.x + ball.info[:dx])
  ball.info[:dy] *=  -1 if !ball.info[:ry].include?(ball.y + ball.info[:dy])
  ball.x += ball.info[:dx]
  ball.y += ball.info[:dy]
end
phase.handles[SDL::Event::Quit] = proc{exit}
phase.handles[SDL::Event::KeyDown] = proc{|e| exit if e.sym == SDL::Key::ESCAPE}
loop do
  while e = SDL::Event.poll
    if handle = phase.handles[e.class]
      handle[e]
    end
  end
  image = phase.renew
  surface = SDL::Surface.new_from(image.data, w, h, 32, image.stride, 0, 0, 0, 0)
  screen.put(surface,0,0)
  screen.flip
  SDL.delay(20)
end