Skip to content
floere edited this page Sep 14, 2010 · 13 revisions

Use Generator if you want to make a thing generate other things.

Including Generator

The Generator trait can be applied as usual:

class Spaceship < Thing
  it_is_a Generator

or

class Spaceship < Thing
  it_is_a Generator do
    # …
  end

Properties

Generator has just one property: generates <thing_class>, options

It defines what is generated by the Generator.

class Spaceship < Thing
 generates Smoke

or you can define a few options:

class Spaceship < Thing
  generates Smoke,
            :every => 20, # generate Smoke every 20 steps. 10 is the default
            :until => 150, # generate Smoke until step 150
            :starting_at => 10 # generate Smoke, beginning at step 10. Default is what is given as the :every option, or 10 if not given.

Methods

Generator installs multiple methods start_generating, generate, and stop_generating.

The first one, start_generating klass, every, until, starting_at, for example when it turns left:

def turn_left
  super
  start_generating # with defaults, generates Smoke
end

With full parameters, you can generate something entirely different:

def kill!
  start_generating Debris, 10, 50, 10
end

Or generate Explosions when destroyed:

def destroyed!
  5.times { start_generating(Explosion) }
end

If you use Controllable, you can define start_generating controls as follows

controls Gosu::Button::KbS => Generator::Start

Or using the method parameters:

controls Gosu::Button::KbSpace => Generator.start(Mine, 10, 50) # omitting the starting_at parameter

The generate <thing_class> can be used to generate a single thing:

def accelerate strength = 1.0
  super strength
  generate Smoke # generates a single Smoke when accelerating. Use the sometimes method to not always generate Smoke.
end

Or just sometimes generate Smoke:

def accelerate
  super
  sometimes :accelerating, 20 do
    generate Smoke # generates Smoke every 20 steps
  end
end

The stop_generating method stops all generating on the Generator.

Notes

But what about when it is destroyed? Won’t it generate until infinity?

No problem. Generator overrides the destroy! method, and stops generation in it.