使用 Gosu.button_down 显示点击屏幕的次数

Display number of times click on screen using Gosu.button_down

我正在使用 Gosu 开发 ruby 程序。我想在每次点击屏幕上的按钮时显示鼠标点击次数。请帮我解决一下这个。非常感谢

require 'rubygems'
require 'gosu'

module ZOrder
  BACKGROUND, MIDDLE, TOP = *0..2
end

WIN_WIDTH = 640
WIN_HEIGHT = 400
class DemoWindow < 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(10)
    @locs = [60,60]
  end

  def draw
 
    Gosu.draw_rect(0, 0, WIN_WIDTH, WIN_HEIGHT, @background, ZOrder::BACKGROUND, mode=:default)
    if area_clicked(mouse_x, mouse_y)
      draw_line(50, 50, Gosu::Color::BLACK, 150, 50, Gosu::Color::BLACK, ZOrder::TOP, mode=:default)
      draw_line(50, 50, Gosu::Color::BLACK, 50, 100, Gosu::Color::BLACK, ZOrder::TOP, mode=:default)
      draw_line(150, 50, Gosu::Color::BLACK, 150, 101, Gosu::Color::BLACK, ZOrder::TOP, mode=:default)
      draw_line(50, 100, Gosu::Color::BLACK, 150, 100, Gosu::Color::BLACK, ZOrder::TOP, mode=:default)
    end
    Gosu.draw_rect(50, 50, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
    @button_font.draw_text("Click me", 60, 60, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
    @info_font.draw_text("mouse_x: #{mouse_x}", 0, 350, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
    @info_font.draw_text("mouse_y: #{mouse_y}", 100, 350, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK )

    if Gosu.button_down? Gosu::MsLeft
        index =0
        button = area_clicked(mouse_x, mouse_y)
        case button
        when 1
            index+=1
            @info_font.draw("Times Click: #{index}", 370, 350, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
  end
end
end
  def needs_cursor?; true; end



  def area_clicked(mouse_x, mouse_y)
    if ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 50 and mouse_y < 100))
      return 1
    else
    end
  end




  def button_down(id)
    if id == Gosu::KB_ESCAPE
        close
    else
        super
    end
end
end


DemoWindow.new.show

下面是我添加的代码。当我点击按钮时,它只显示点击次数为1,但是我需要它来显示我点击的次数。

这是因为每次单击鼠标时您都会将索引设置回零 (index =0)。您可能应该在 initialize 函数中将索引设置为零,并将其设为 class 变量(在前面添加 @)。

那么您的初始化代码将是:

def initialize
  super(WIN_WIDTH, WIN_HEIGHT, false)
  @background = Gosu::Color::WHITE
  @button_font = Gosu::Font.new(20)
  @info_font = Gosu::Font.new(10)
  @locs = [60,60]
  @index = 0
end

鼠标点击代码为:

if Gosu.button_down? Gosu::MsLeft
    button = area_clicked(mouse_x, mouse_y)
    case button
    when 1
        @index += 1
        @info_font.draw("Times Click: #{@index}", 370, 350, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)