Sunday, May 20, 2007

Rubygame Tutorial Part 2

NOTE: This tutorial is replaced by The Rubygame Book.

In part 2 of the Rubygame tutorial series we will be learning how to control a Rubygame application's CPU resource usage.

If you did not complete part 1 of this tutorial, it is highly recommended that you do so before continuing this tutorial. Otherwise you will miss a critical proportion of knowledge required to write video games with Rubygame. You may not also understand newer parts of this tutorial.

We'll jump right in learning how to control CPU usage so your Rubygame applications doesn't suck your computer's CPU resource dry. By controlling CPU usage, we also get the added advantage of consistent frame-rate.

CPU Usage Control

Before we go any further, I request you to run dodgeball.rb and record the CPU usage of the game. Please record it in a place where you can refer back to(Not your brain, a paper is a much better place). This data will be used to determine if whether our code actually work or not. You'll need to look at the ruby process. Please make sure the ruby process is actually dodgeball.rb and that application alone.

My data show me that dodgeball.rb uses about 99.9% of CPU.

Now that we're done recording the data, we can start writing some code.

Modify the file named loop.rb in the rubies_dodgeball's lib directory:

class GameLoop
def initialize
@screen =[800,600],0,[Rubygame::HWSURFACE, Rubygame::DOUBLEBUF])
@q =
@clock =
@clock.target_framerate= 40
def run
loop do
@q.each do |ev|
case ev
when Rubygame::QuitEvent

The Rubygame::Clock class is used primary for delaying executions of Rubygame applications. It can also tracks running time. You must specify the frame-rate of your application before executing the main game loop( in our code, we used @clock.target_framerate= ). The method tick for @clock is used for frame-rate limiting to a specified frame-rate.

When you run this program, you should notice a great reduction in CPU usage. It should be a lower than your recorded CPU usage before you modified the code. My data show me that dodgeball.rb uses about a mere 6.7% of CPU. So it work like a charm.

If you made this far, you finished the second part of this tutorial. Well done! In the next part of the tutorial, we'll show you how to how to move images.

Anyway, happy hacking!


P.S If you have any problem with the tutorial, please email me at

NOTES: There used to be a lot of content packed into this part of tutorial. It was decided that there are too much content. Plus there are many bugs in the code shown so it is removed in order to preserve the quality of the tutorial.


Kiki said...


Great intro to the tutorial, both first part and this one.

What I do want to mention is that in the GameLoop class, in the initialize method, the @screen variable should be @screen = Rubygame::Screen..... not @screen = Screen....

Julian said...

buy viagra

viagra online

generic viagra