#!/usr/bin/ruby1.9.1
require 'gosu'
class GameWindow < Gosu::Window
def initialize
super(210, 210, false)
self.caption = 'Press arrow keys'
end
def button_down(id)
if id == Gosu::KbEscape
self.caption = 'Goodbye!'
sleep 0.5
close
end
if id == Gosu::KbUp
self.caption = 'Up'
end
if id == Gosu::KbDown
self.caption = 'Down'
end
if id == Gosu::KbLeft
self.caption = 'Left'
end
if id == Gosu::KbRight
self.caption = 'Right'
end
end
end
GameWindow.new.show
Refactorings
No refactoring yet !
Fu86
July 1, 2010, July 01, 2010 06:31, permalink
#!/usr/bin/env ruby
require 'gosu'
class GameWindow < Gosu::Window
def initialize
super 210, 210, false
self.caption = 'Press arrow keys'
end
def button_down id
case id
when Gosu::KbEscape
self.caption = 'Goodbye!'
sleep 0.5
close
when Gosu::KbUp
self.caption = 'Up'
when Gosu::KbDown
self.caption = 'Down'
when Gosu::KbLeft
self.caption = 'Left'
when Gosu::KbRight
self.caption = 'Right'
end
end
end
GameWindow.new.show
Fu86
July 1, 2010, July 01, 2010 06:38, permalink
If you want to minimize the code:
#!/usr/bin/env ruby
require 'gosu'
class GameWindow < Gosu::Window
def initialize
super 210, 210, false
self.caption = 'Press arrow keys'
end
def button_down id
keys = {Gosu::KbUp => "Up", Gosu::KbDown => "Down",
Gosu::KbLeft => "Left", Gosu::KbRight => "Right",
Gosu::KbEscape => "Goodbye!"}
self.caption = keys[id] || return
if id == Gosu::KbEscape
sleep 0.5
close
end
end
end
GameWindow.new.show
Adam
July 1, 2010, July 01, 2010 15:32, permalink
I like the explicitness of Fu86's case statement. But I thought I'd have some fun with this:
require 'gosu'
class GameWindow < Gosu::Window
CAPTIONS = Gosu.constants.inject({}) { |h,n| h.merge(Gosu.const_get(n) => n.sub(/^Kb/, '')) }
CAPTIONS[Gosu::KbEscape] = 'Goodbye!'
def initialize
super(210, 210, false)
self.caption = 'Press arrow keys'
end
def button_down(id)
self.caption = CAPTIONS[id]
sleep 0.5 and close if id == Gosu::KbEscape
end
new.show
end
This is my first attempt at creating a program with the Gosu 2D graphics library.