Advertisement
Guest User

Untitled

a guest
Jul 29th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. local buttons = {
  2. [1] = {
  3. x = 3,
  4. y = 3,
  5. on_state = "Turn off reactor",
  6. off_state = "Turn on reactor",
  7. current_state = true, -- Initially the button is off
  8. onClick = function(state) -- Turn the reactor on or off
  9. if state then -- Currently on, turning off
  10. term.setCursorPos(1,1)
  11. term.write("Turning off the reactor")
  12. sleep(1)
  13. -- The current state is off: turn off the reactor
  14. else
  15. term.setCursorPos(1,1)
  16. term.write("Turning on the reactor")
  17. sleep(1)
  18. -- The current state is off: turn on the reactor
  19. end
  20. end
  21. }
  22. }
  23.  
  24. local function drawButton(button)
  25. term.setCursorPos(button.x, button.y)
  26. if button.current_state then -- If it’s on, our button is green
  27. term.setBackgroundColor(colors.green)
  28. else -- Otherwise it’s red
  29. term.setBackgroundColor(colors.red)
  30. end
  31.  
  32. term.setTextColor(colors.white)
  33.  
  34. local button_text -- We’ll store what text we want to write here
  35. if button.current_state then
  36. button_text = button.on_state
  37. else
  38. button_text = button.off_state
  39. end
  40.  
  41. local button_length = #button.on_state -- How long is our button?
  42. if #button.off_state > #button.on_state then -- We want the longest it ever gets
  43. button_length = #button.off_state
  44. end
  45.  
  46. term.write(string.rep(" ", 2 + button_length)) -- Give it a little space on each side
  47. term.setCursorPos(button.x + 1 + button_length / 2 -
  48. #button_text / 2, button.y) -- Nothing too complicated here: just centering the text inside of the button
  49. term.write(button_text) -- Draw our text
  50. end
  51.  
  52. local function checkClick(x, y)
  53. for index, button in pairs(buttons) do
  54. local button_length = #button.on_state + 2
  55. if #button.off_state > #button.on_state then
  56. button_length = #button.off_state + 2
  57. end
  58.  
  59. if button.y == y and
  60. x >= button.x and
  61. x <= button.x + button_length then
  62. -- Yep, we clicked this button
  63. button.onClick(button.current_state)
  64. button.current_state = not button.current_state
  65. end
  66. end
  67. end
  68.  
  69. while true do
  70. term.setBackgroundColor(colors.black)
  71. term.clear()
  72. for index, button in pairs(buttons) do drawButton(button) end
  73. local e = {os.pullEvent("mouse_click")} -- Change to "monitor_touch" if you’re working with a monitor
  74. checkClick(e[3], e[4])
  75. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement