1. Computing

Sprite Groups in Rubygame


The main loop changes very little from the addition of the EnemyFormation class. This is a good example of abstracting complex actions away from the main loop and keeping the main loop as simple and clean as possible.

Before the main loop, an EnemyFormation object is created and stored in the enemies variable. This is much like the creation of the Player object and loading the background image.

During the update phase, a call to the enemies' update method is performed in exactly the same way as the call to the player's update method. As far as the main loop is concerned, the enemies variable is just another sprite. It has no idea it's an abstraction for a formation of sprites.

def main_loop
  screen = Screen.new [640, 480]
  queue = EventQueue.new
  clock = Clock.new
  clock.target_framerate = 30

  background = Surface['background.png']
  player = Player.new
  <b>enemies = EnemyFormation.new</b>

  loop do
    # Pause and get delta in fractions of a second
    delta = clock.tick * 0.001

    queue.each do|e|
      return if e.is_a? QuitEvent



    background.blit( screen, [0,0] )
    player.draw( screen )
    <b>enemies.draw( screen )</b>



Finally, the enemies are drawn in exactly the same way the player sprite is drawn. Again, the main loop doesn't know (and doesn't need to know) that the enemies variable really represents multiple sprites.

  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Game Programming
  6. How the Main Loop Changes

©2014 About.com. All rights reserved.