1. Computing

Sprite Groups in Rubygame

By

To create the classic formation of Enemy aliens seen in Space Invaders, an EnemyFormation class is created. Now this class is a child class of Sprite::Group, because an enemy formation really is just a special type of sprite group.

There are a few differences from a normal sprite group. Firstly, when it's created it will automatically create aliens to fill in the ranks. It does this with a few simple loops and by creating Enemy objects at specific locations on the screen. It also manages the direction of all of the Enemy objects, keeping track of which direction the entire formation is headed.

Here's a look a the constructor for the EnemyFormation class. Note that super is called at the top. This is a good idea for all child classes. The super method call is actually a little bit of Ruby syntax magic. It will call the parent class' method of the same name with the same arguments. Note that super is not the same as super(). The first form will call the method with the same name and the same arguments, however the second form will call the method with the same name and no arguments. This is noteworthy because it breaks normal Ruby conventions.

def initialize
  super

  1.upto(8) do|x|
    1.upto(6) do|y|
      push Enemy.new( x * 45, y * 45 )
    end
  end

  @dir = 1
end

©2014 About.com. All rights reserved.