The Rubygame Book Part 3
From KibaBase
Welcome to Part 3. Here we set up the controller class, which is a class where everything comes together. In this part, however, we won't teach you anything new. What we're doing here is setting up the code necessary for further learning and eventually completing the game.
A New Class
Lucky for us, we have created the controller file in the beginning of the tutorial. So it is a matter of us filling the empty file with code.
modify lib/controller.rb:
class Controller def initialize screen @screen = screen @queue = Rubygame::EventQueue.new() end def run loop do @queue.each do |ev| case ev when Rubygame::QuitEvent Rubygame.quit() exit when Rubygame::KeyDownEvent case ev.key when Rubygame::K_ESCAPE Rubygame.quit() exit end end end end end end
As you can see, it is not much different from the setup class in lib/setup.rb. However, since it is the class that pull all the game component together, you can bet that it will look vastly different than setup.rb in later stages of the tutorial.
You may have noticed that the initialize require the argument called screen. This is the same screen we used last time in setup.rb and it will be the screen that we use everywhere else in the source code.
Going Back to Setup Class
Since the Controller class is not going to initialize or execute the run method on its own, we're going back to Setup class to do these very things.
First, we got to initialize the Controller object. So modify the initialize method in Setup.
modify lib/setup.rb:
def initialize @screen = Screen.new([800,600],0,[Rubygame::HWSURFACE,Rubygame::DOUBLEBUF]) @queue = Rubygame::EventQueue.new() @control = Controller.new(@screen) end
Now we can use the Controller class in Setup. Now, we're going to add a conditional statement that allow us to execute the loop in Controller#run. For this task, modify the run method in Setup.
modify lib/setup.rb:
def run loop do @queue.each do |ev| case ev when Rubygame::QuitEvent Rubygame.quit() exit when Rubygame::KeyDownEvent case ev.key when Rubygame::K_ESCAPE Rubygame.quit() exit when Rubygame::K_RETURN @control.run() end end end end end
The changes that you see in this method is the addition of Rubygame::K_RETURN conditional statement. Here, we chosen return as the key from which to launch the game.
Running the game
Since you currently cannot know which loop you are in, it might be advisable to add something like:
puts "This is the controller."
to the controller's run method to indicates that you have entered the run loop of Controller class.
If successful, you should see this message when you press enter during the time that the game run. Once you accomplish the task, remove the message and continue on to Part 4.

