Advertisement
GNOOR1S

Simple Button API for Monitors in ComputerCraft

Jun 12th, 2023 (edited)
2,855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.93 KB | Gaming | 0 0
  1. -- The `drawButton` function draws a button at the specified position with the specified label text.
  2. -- It returns a table that contains the position and dimensions of the button.
  3. local monitor = peripheral.find("monitor")
  4. local buttons = {}
  5.  
  6. function drawButton(x, y, label)
  7.   buttons[label] = {}
  8.   buttons[label].x1 = x
  9.   buttons[label].y1 = y
  10.   buttons[label].width = #label + 2
  11.   buttons[label].height = 3
  12.   buttons[label].x2 = x + buttons[label].width - 1
  13.   buttons[label].y2 = y + buttons[label].height - 1
  14.  
  15.   -- Draw the button frame and centered label
  16.   monitor.setCursorPos(x, y)
  17.   monitor.write("+" .. string.rep("-", buttons[label].width-2) .. "+")
  18.   monitor.setCursorPos(x, y+1)
  19.   monitor.write("|" .. centerText(label, buttons[label].width-2) .. "|")
  20.   monitor.setCursorPos(x, y+2)
  21.   monitor.write("+" .. string.rep("-", buttons[label].width-2) .. "+")
  22.  
  23. end
  24.  
  25. -- The `centerText` function centers the specified text within the specified width.
  26. function centerText(text, width)
  27.     local spacing = width - #text
  28.     local leftSpacing = math.floor(spacing / 2)
  29.     local rightSpacing = math.ceil(spacing / 2)
  30.     return string.rep(" ", leftSpacing) .. text .. string.rep(" ", rightSpacing)
  31.   end
  32.  
  33. -- The `processClick` function checks if the specified position is within any of the buttons
  34. -- and if so, calls the attached function.
  35. function processClick(x, y)
  36.   for label, button in pairs(buttons) do
  37.     if x >= button.x1 and x <= button.x2 and y >= button.y1 and y <= button.y2 then
  38.       button.func()
  39.       return
  40.     end
  41.   end
  42. end
  43.  
  44. -- The `attachFunction` function attaches the specified function to the specified button label.
  45. function attach(label, func)
  46.   buttons[label].func = func
  47. end
  48.  
  49. -- The `drawLabel` function draws a label at the specified position, centered within the specified width.
  50. function drawLabel(x, y, width, label)
  51.   monitor.setCursorPos(x, y)
  52.   monitor.write(centerText(label, width))
  53. end
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement