Class: MenuItem

Inherits:
Object
  • Object
show all
Defined in:
lib/game_2d/menu.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, window, font, &action) ⇒ MenuItem

Returns a new instance of MenuItem.



39
40
41
42
43
44
45
46
# File 'lib/game_2d/menu.rb', line 39

def initialize(name, window, font, &action)
  @name, @window, @font, @action = name, window, font, action
  @main_color, @select_color, @highlight_color =
    Gosu::Color::YELLOW, Gosu::Color::BLACK, Gosu::Color::CYAN

  # Default position: Upper-right corner
  @x, @y = @window.width - 1, 0
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



38
39
40
# File 'lib/game_2d/menu.rb', line 38

def name
  @name
end

#xObject

Returns the value of attribute x.



38
39
40
# File 'lib/game_2d/menu.rb', line 38

def x
  @x
end

#yObject

Returns the value of attribute y.



38
39
40
# File 'lib/game_2d/menu.rb', line 38

def y
  @y
end

Instance Method Details

#bottomObject



56
# File 'lib/game_2d/menu.rb', line 56

def bottom; @y + @font.height; end

#choose_color(selected) ⇒ Object



67
68
69
# File 'lib/game_2d/menu.rb', line 67

def choose_color(selected)
  selected ? @select_color : @main_color
end

#drawObject



58
59
60
61
62
63
64
65
# File 'lib/game_2d/menu.rb', line 58

def draw
  selected = mouse_over?
  color = choose_color(selected)
  @font.draw_rel(to_s, @x, @y, ZOrder::Text, 1.0, 0.0, 1.0, 1.0, color)
  if selected
    @window.draw_box_at(left, top, right, bottom, @highlight_color)
  end
end

#handle_clickObject

Returns a true value if it handled the click May return a Menu or MenuItem to be set as the new menu to display May return simply ‘true’ if we should redisplay the top-level menu



74
75
76
77
# File 'lib/game_2d/menu.rb', line 74

def handle_click
  return unless mouse_over?
  @action.call(self) || true
end

#leftObject



53
# File 'lib/game_2d/menu.rb', line 53

def left; @x - @font.text_width(to_s); end

#mouse_over?Boolean

Returns:

  • (Boolean)


48
49
50
51
# File 'lib/game_2d/menu.rb', line 48

def mouse_over?
  x, y = @window.mouse_x, @window.mouse_y
  (y >= top) && (y < bottom) && (x > left)
end

#rightObject



54
# File 'lib/game_2d/menu.rb', line 54

def right; @x; end

#to_sObject



79
80
81
# File 'lib/game_2d/menu.rb', line 79

def to_s
  @name.respond_to?(:call) ? @name.call(self) : @name.to_s
end

#topObject



55
# File 'lib/game_2d/menu.rb', line 55

def top; @y; end