Files
scriptLua/menu.lua
2025-08-04 14:01:20 +02:00

95 lines
2.9 KiB
Lua

MainMenu = {}
local function getSizeOfScreen()
local x, y = term.getSize()
return x, y
end
local function initMenu()
-- do a menu for computer craft
local menuItems = {
{ name = "Get Method", action = function() shell.run("getMethodsPeripheral") end },
{ name = "Settings", action = function() print("Opening settings...") end },
{ name = "Exit", action = function() print("Exiting...") end }
}
-- put the item in MainMenu
for _, item in ipairs(menuItems) do
table.insert(MainMenu, item)
end
end
local function displayMenu()
local selected = 1
local function drawTitle()
local x, y = getSizeOfScreen()
local title = " Main Menu "
term.setTextColor(colors.yellow)
local decorator = '='
term.write(string.rep(decorator, math.floor((x - #title) / 2)))
term.setCursorPos(math.floor((x - #title) / 2) + 1, 1)
print(title)
term.setCursorPos(math.floor((x + #title) / 2) + 1, 1)
term.write(string.rep(decorator, math.ceil((x - #title) / 2)))
term.setTextColor(colors.white)
term.write(string.rep(decorator, x))
end
local function drawMenuItems(selected)
for i, item in ipairs(MainMenu) do
term.setCursorPos(1, i + 2)
if i == selected then
term.setTextColor(colors.yellow)
else
term.setTextColor(colors.white)
end
-- put the item in the center and add [ ] before item
local itemText = string.format("[%s] %s", i == selected and ">" or " ", item.name)
local x, _ = getSizeOfScreen()
local padding = math.max(0, (x - #itemText) / 2)
term.write(string.rep(" ", padding) .. itemText)
term.setCursorPos(1, i + 2)
term.write(string.rep(" ", x - padding - #itemText))
term.setCursorPos(1, i + 2)
term.setTextColor(colors.white)
end
end
local function handleKey(selected)
local event, key = os.pullEvent("key")
if key == keys.up then
selected = selected - 1
if selected < 1 then selected = #MainMenu end
elseif key == keys.down then
selected = selected + 1
if selected > #MainMenu then selected = 1 end
elseif key == keys.enter then
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
MainMenu[selected].action()
return selected, true
end
return selected, false
end
while true do
term.clear()
term.setCursorPos(1, 1)
drawTitle()
term.setTextColor(colors.white)
term.setCursorPos(1, 3)
drawMenuItems(selected)
selected, done = handleKey(selected)
if done then break end
end
term.setTextColor(colors.white)
end
function Main()
initMenu()
displayMenu()
end
Main()