1. Home
  2. Computing & Technology
  3. Ruby

Make Your Sprite Move

By , About.com Guide

3 of 5

Handling Events

Once you start handling events, you have to think of where the events should be handled. Should the main loop handle key presses move the player? If it does, should the main loop handle everything?

It's best to try to keep the main loop as clean and simple as possible. The main loop shouldn't have to know how the player moves, or even if it did move. The player should be able to keep track of that itself. For that reason, I prefer to "trickle" events to objects in the game and added an event method in the Player class. Any events that come in through the event queue should be passed on to the player. This way, the main loop doesn't have to worry about what the player does with events, it just needs to know to pass the player events when they come in.

To reflect this, the event processing loop is modified to look like the following. As more things are added to the game, they'll be added to the end and events will be sent to them as they arrive.

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

  player.event(e)
end
Explore Ruby
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Tasks & Scripts
  5. Game Programming
  6. Handling Events

©2010 About.com, a part of The New York Times Company.

All rights reserved.