88 lines
2.0 KiB
Lua
88 lines
2.0 KiB
Lua
local Object = require "lib/classic"
|
|
|
|
---@class MultiMenu
|
|
local MultiMenu = Object:extend()
|
|
|
|
---Creates a new multimenu.
|
|
---@param font Font
|
|
---@param options table
|
|
function MultiMenu:new(font, options, x, y, bg)
|
|
self.font = font
|
|
self.options = options
|
|
self.selected = 1
|
|
self.x = x
|
|
self.y = y
|
|
self.bg = bg
|
|
self.padding = 16
|
|
|
|
local inner_width = 0
|
|
local inner_height = #options * self.font.sh
|
|
|
|
for idx, option in ipairs(options) do
|
|
local text_width = string.len(option.text) * self.font.sw
|
|
inner_width = math.max(inner_width, text_width)
|
|
end
|
|
|
|
local bg_width = inner_width + self.padding * 2
|
|
local bg_height = inner_height + self.padding * 2
|
|
|
|
self.bg_width = math.ceil(bg_width / bg.atlas.sw)
|
|
self.bg_height = math.ceil(bg_height / bg.atlas.sh)
|
|
end
|
|
|
|
function MultiMenu:draw()
|
|
-- option drawing constants
|
|
local x = self.x
|
|
local y = self.y
|
|
local spacing = self.font.sh
|
|
local padding = self.padding
|
|
|
|
--draw the background
|
|
self.bg:draw(x, y, self.bg_width, self.bg_height)
|
|
|
|
-- draw all the options
|
|
for idx, option in ipairs(self.options) do
|
|
local ty = y + (idx - 1) * spacing
|
|
self.font:draw(option.text, x + padding, ty + padding)
|
|
end
|
|
|
|
-- cursor metric constants
|
|
local cursor_width = 4
|
|
local cursor_depth = 8
|
|
local cursor_spacing = 4
|
|
local cursor_offset = 4
|
|
|
|
-- calculate the cursor's position
|
|
local cursor_x = x - cursor_spacing + padding
|
|
local cursor_y = y + cursor_offset + (self.selected - 1) * spacing + padding
|
|
|
|
-- draw the cursor
|
|
love.graphics.polygon("fill",
|
|
cursor_x, cursor_y,
|
|
cursor_x - cursor_depth, cursor_y - cursor_width,
|
|
cursor_x - cursor_depth, cursor_y + cursor_width
|
|
)
|
|
end
|
|
|
|
function MultiMenu:up()
|
|
if self.selected == 1 then
|
|
self.selected = #self.options
|
|
else
|
|
self.selected = self.selected - 1
|
|
end
|
|
end
|
|
|
|
function MultiMenu:down()
|
|
if self.selected == #self.options then
|
|
self.selected = 1
|
|
else
|
|
self.selected = self.selected + 1
|
|
end
|
|
end
|
|
|
|
function MultiMenu:select()
|
|
self.options[self.selected].callback()
|
|
end
|
|
|
|
return MultiMenu
|