Key Listener Example

require 'gosu'

class KeyListenerExample < Gosu::Window
	def initialize
		super 640, 480
		self.caption = "Keyboard Example"
		@font = Gosu::Font.new(32, name: "Nimbus Mono L")
	end

	def button_up(key_id)
		if key_id == Gosu::KbEscape then
			self.close
		end
	end

	def draw
		@font.draw("Pressing <Escape> will close this window.", 40, 40, 0)
	end
end 

KeyListenerExample.new.show

Gosu::Window allows us to “listen” for keyboard input by overloading methods that get called when a key is lowered or raised. They simply get called with the ID of the key involved. Fortunately, Gosu provides us with a set of constants so that we don’t have to remember the key codes. They take the form of Gosu::Kb + the name of the key (e.g. Gosu::KbEscape or Gosu::KbW).

This is very useful for when we want our game logic to wait for the player to release the key.