I am trying to make a very simple click counter and I am stuck on getting the click counter to increment, both onscreen and in the code itself.
require 'rubygems'
require 'gosu'
module ZOrder
BACKGROUND, MIDDLE, TOP = *0..2
end
WIN_WIDTH = 640
WIN_HEIGHT = 400
class GameWindow < Gosu::Window
def initialize
super(WIN_WIDTH, WIN_HEIGHT, false)
@background = Gosu::Color::WHITE
@button_font = Gosu::Font.new(20)
@info_font = Gosu::Font.new(15)
end
def needs_cursor?
true
end
def draw
Gosu.draw_rect(0, 0, WIN_WIDTH, WIN_HEIGHT, @background, ZOrder::BACKGROUND, mode=:default)
Gosu.draw_rect(50, 50, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
Gosu.draw_rect(50, 150, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
@button_font.draw("Click me", 65, 65, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
@button_font.draw("Reset", 75, 165, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
@info_font.draw("Clicks: #{counter}", 160, 50, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
end
def counter
i += 1
i
end
def mouse_over_button?(mouse_x, mouse_y)
if ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 50 and mouse_y < 100))
true
else
false
end
end
def button_down(id)
case id
when Gosu::MsLeft
if mouse_over_button?(mouse_x, mouse_y)
counter
else
counter
end
end
end
end
GameWindow.new.show
I am aware that my issue most likely lies in the 'counter' function and the 'button_down' function however I have been unable to figure out how to make it work. Any help would be appreciated, thanks.
You were so close to having it! You need to add @counter = 0
to initialize. Then change your def counter
to that shown bellow
def counter
@counter += 1
end
To get your reset button to work we can now make another procedure called def reset
as shown bellow
def reset
@counter = 0
end
Then to make it all work change your def mouse_over_button?(mouse_x, mouse_y)
to the following:
def mouse_over_button?(mouse_x, mouse_y)
if ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 50 and mouse_y < 100))
return_value = 1
return return_value
elsif ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 150 and mouse_y < 200))
return_value = 2
return return_value
end
end
Finally change the def button_down(id)
to the following:
def button_down(id)
case id
when Gosu::MsLeft
if mouse_over_button?(mouse_x, mouse_y) == 1
counter
elsif mouse_over_button?(mouse_x, mouse_y) == 2
reset
end
end
end
All the right ideas were there! Nice work! If you are unsure why any of this was done, please just let me know and I am happy to explain it further! Hope I helped :)