File: ant.rb

Project: Invitation to Ruby

require 'tk'

class AntFarm
  SIZE=10
  
  def initialize(root)
    @canvas = TkCanvas.new(root) {
      width  20*SIZE
      height 20*SIZE
    }.pack
  end
  
  def draw_ant_at(x, y, color)
    TkcRectangle.new (
      @canvas,
      x*SIZE, y*SIZE,
      (x+1)*SIZE, (y+1)*SIZE) {
      fill color
    }
  end
end

root = TkRoot.new { title "Ant Farm" }

farm = AntFarm.new(root)

ant_drawer = proc {
  x = rand(20)
  y = rand(20)
  color = %w{ red green blue white }[rand(4)]
  farm.draw_ant_at(x, y, color)
  Tk.after(50, &ant_drawer)
}

ant_drawer.call

Tk.mainloop


[ Index ][ Table of Contents ]
Generated by [ source2html ]