Monday, January 3, 2011

Netbeans Template for Ruby SDL.

This blog post contains a template based on a tutorial from www.SDLTutorials.com. While there is a myriad other ways for you to create an SDL window, I have found this pleasing to the eye.

Find steps below to save this in your Netbeans templates.

--> Copy the code below into a file and save it as rubysdl_template.rb
--> Go to Tools -> Templates
--> In the template tree view click on Ruby
--> Press Add button on the right side and open up the rubysdl_template.rb file.
--> Give the template a name, say Ruby SDL Window.

You are done. Now when you create a new ruby file you will see this template in the list of files.

This code will run and show a window without adding anything else provided you have Ruby/SDL installed. Ruby/SDL works with c implementation of Ruby so it is also assumed that you have ruby from www.ruby-lang.org installed. Another assumption is that SDL 1.2.14 is installed.

To run this code press Shift-F6 with the file open in Netbeans , you will see a dialog prompting to choose ruby implementation and various other options, choose ruby from www.ruby-lang.org and you should see a window.

I have used Ruby / SDL 2.1.1.1, but the code is simple enough that it will run with any version of Ruby / SDL.

So here goes the code.




# To change this template, choose Tools | Templates
# and open the template in the editor.

require 'sdl'

class CApp

def initialize
surfDisplay = nil
@running = true
end

def onExecute
return -1 if(onInit==false)

while @running
while event=SDL::Event2.poll
onEvent(event);
end
onLoop
onRender
end

onCleanup

return 0;
end

##
# Initiates the SDL system. Starts the basic display window.
##
def onInit
SDL.init(SDL::INIT_EVERYTHING)
return false if((@surfDisplay = SDL::Screen.open(640,480,32,SDL::HWSURFACE | SDL::DOUBLEBUF)) == nil)
return true
end

##
# This function performs actions on various events.
# Only an event object can be passed as an argument.
##
def onEvent(event)
case event
when event = SDL::Event2::Quit
@running = false;
end
end

def onLoop

end

def onRender

end

##
# Cleans up before quitting. It is a good practice to free up any surface that
# is no longer being used.
##
def onCleanup
@surfDisplay.destroy
SDL.quit
end

##
# Main block. SDL Window is instantiated from this.
##
if __FILE__==$0
cApp = CApp.new # This variable has not been initialized.
cApp.onExecute
end

end