55502f40dc8b7c769880b10874abc9d0

This is my first attempt at creating a program with the Gosu 2D graphics library.

#!/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 !

Ee0505bbd355292778077fb662c88f13

Fu86

July 1, 2010, July 01, 2010 06:31, permalink

1 rating. Login to rate!
#!/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
Ee0505bbd355292778077fb662c88f13

Fu86

July 1, 2010, July 01, 2010 06:38, permalink

1 rating. Login to rate!

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
A8d3f35baafdaea851914b17dae9e1fc

Adam

July 1, 2010, July 01, 2010 15:32, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel