In a previous post I mentioned how I was displaying a mouse pointer in a Gosu window. You can read about it here. What if you don’t wanna do that each time you need to show a mouse pointer?
Monkey patching is a technique some people don’t wanna use. I think there are cases when it can be very useful. This is one of those cases. Here’s the code that makes it possible:
#require "gosu"
# this monkey patches a gosu window so that the draw will
# also draw a mouse pointer
module Gosu
class Window
# add this method to set the mouse pointer
def pointer=(pointer_image)
# see if we already defined the mouse_pointer accessor
if self.methods.include? "mouse_pointer="
# if it's a string, it means it's the path to the image
# to be used as the pointer
if pointer_image.class.to_s == "String"
# create a gosu image from it
self.mouse_pointer = Gosu::Image.new(self,pointer_image,false)
else
# we assume it's an already build gosu image
self.mouse_pointer = pointer_image
end
else
# the mouse_pointer accessor isn't defined. let's add it
# transform the parameter into an image ( if it's a string )
pointer_image = Gosu::Image.new(self,pointer_image,false) if pointer_image.class.to_s == "String"
# modify !
class << self
# add the accessor
attr_accessor :mouse_pointer
# save the draw method by the name old_draw
alias :old_draw :draw
def draw
# invoke old draw to get stuff painted on the screen
old_draw
# draw the mouse pointer
@mouse_pointer.draw(mouse_x,mouse_y,0) if !@mouse_pointer.nil?
end
end
# finally, assign it so that it will actually paint something
self.mouse_pointer = pointer_image
end
end
end
end
This adds the method pointer= to the Gosu::Window class. Therefore, every class that inherits from Gosu::Window will have the method too. Here’s an example of how to use that:
require "gosu"
require "mouse_hack" # nice name right?
class MyWindow < Gosu::Window
# do whatever you want here
end
my_w = MyWindow.new
my_w.pointer = "pointer.png"
my_w.show
or
my_w.pointer = Gosu::Image.new(my_w,"pointer.png",false)
