Advertisement
LeshaInc

GUI API 0.1

Apr 5th, 2015
1,630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 7.36 KB | None | 0 0
  1. --            *  *  *
  2. -- GUI API (OpenComputers) (1.0)
  3. -- 05/04/2015 (c) computercraft.ru
  4. -- Created by Totoro, LeshaInc, Xom and some magic
  5. --            *  *  *
  6.  
  7. -- Создаем таблицу
  8. local API = {}
  9. local param= {}
  10.  
  11. -- Подключаем системные API
  12. local event = require('event')
  13. local term = require("term")
  14. local component = require("component")
  15. local gpu = component.gpu
  16.  
  17. -- Константы
  18. -- Получаем разрешение монитора
  19. local WIDTH, HEIGHT = gpu.getResolution()  -- понятные названия - наше все =)
  20. -- Цвета
  21. local color = {}
  22. color.green = 0x00AA00
  23. color.red   = 0xAA0000
  24. color.black = 0x000000
  25. color.white = 0xFFFFFF
  26. -- Символы из Юникода
  27. local LOWER_HALF_BLOCK = "▄"
  28. local UPPER_HALF_BLOCK = "▀"
  29. local LEFT_HALF_BLOCK = "▌"
  30. local RIGHT_HALF_BLOCK = "▐"
  31. -- Восстановители рассудка.
  32. local FLOWERS = "✽ ✾ ✿ ❁ ❃ ❋ ❀"
  33.  
  34. -- Функция очистки экрана
  35. function API.clear(color)
  36.     gpu.setBackground(color)
  37.     gpu.fill(1, 1, WIDTH, HEIGHT,  " ")
  38. end
  39.  
  40. -- ========================== Кнопочки =) ========================== --
  41. -- интерактивные кнопки от Totoro
  42. -- создаем кнопку
  43. Button = {}
  44. Button.__index = Button
  45. function Button.new(func, x, y, text, fore, back, width, nu)
  46.   self = setmetatable({}, Button)
  47.  
  48.   self.form = '[ '
  49.   if width == nil then width = 0
  50.     else width = (width - unicode.len(text))-4 end
  51.   for i=1, math.floor(width/2) do
  52.     self.form = self.form.. ' '
  53.   end
  54.   self.form = self.form..text
  55.   for i=1, math.ceil(width/2) do
  56.     self.form = self.form.. ' '
  57.   end
  58.   self.form = self.form..' ]'
  59.  
  60.   self.func = func
  61.  
  62.   self.x = math.floor(x); self.y = math.floor(y)
  63.   self.fore = fore
  64.   self.back = back
  65.   self.visible = true
  66.  
  67.   self.notupdate = nu or false
  68.  
  69.   return self
  70. end
  71.  
  72. -- рисуем кнопку
  73. function Button:draw(fore, back)
  74.   if self.visible then
  75.     local fore = fore or self.fore
  76.     local back = back or self.back
  77.     gpu.setForeground(fore)
  78.     gpu.setBackground(back)
  79.     gpu.set(self.x, self.y, self.form)
  80.   end
  81. end
  82.  
  83. -- обрабатываем клик по кнопке
  84. function Button:click(x, y)
  85.   if self.visible then
  86.     if y == self.y then
  87.       if x >= self.x and x < self.x+unicode.len(self.form) then
  88.         self:draw(self.back, self.fore)
  89.         local data = self.func()
  90.         if not self.notupdate then self:draw() end
  91.         return true, data
  92.       end
  93.     end
  94.   end
  95.   return false
  96. end
  97.  
  98. -- набор вспомогательных функций для работы с группами кнопок
  99. -- добавляем кнопку в группу
  100. function buttonNew(buttons, func, x, y, text, fore, back, width, notupdate)
  101.   button = Button.new(func, x, y, text, fore, back, width, notupdate)
  102.   table.insert(buttons, button)
  103.   return button
  104. end
  105. -- рисуем группу кнопок
  106. function buttonsDraw(buttons)
  107.   for i=1, #buttons do
  108.     buttons[i]:draw()
  109.   end
  110. end
  111. -- обработка клика на группе кнопок
  112. function buttonsClick(buttons, x, y)
  113.   for i=1, #buttons do
  114.     ok, data = buttons[i]:click(x, y)
  115.     if ok then return data end
  116.   end
  117.   return nil
  118. end
  119.  
  120.  
  121. -- ========================= Псевдографика ========================= --
  122. -- Функция рисования пикселя
  123. function API.pixel(x,y,color)
  124.     gpu.setBackground(color)
  125.     gpu.set(x,y," ")
  126. end
  127.  
  128. -- Линия от А до Б (by Xom)
  129. -- (Запасной вариант) LeshaInc опять ничего не понял.
  130. -- Осторожно: неоттестировано!
  131. function API.xline(x1, y1, x2, y2, color, symbol)
  132.     local deltax,deltay,stat,errors,temp,nextstep= 0,0,1,0,0,0
  133.     deltax= x1-x2
  134.     deltay= y1-y2
  135.     errors= deltax/deltay
  136.     if (x1 < x2) then
  137.        stat= -1
  138.     end
  139.     for i=x1,x2,stat do
  140.        temp= x1+errors
  141.        c,d= math.fmod(temp)
  142.        while true do
  143.           temp= x1+errors
  144.           c,d= math.fmod(temp)
  145.           if (d > 5) then
  146.              y1= y1-1
  147.              API.pixel(x1,y1)
  148.           else
  149.              break
  150.           end
  151.        end
  152.     end
  153. end
  154.  
  155. -- Функция создания заполненной коробки
  156. function API.box(x,y,WIDTH,HEIGHT,color,symbol) --Поставте symbol " " и будет чистый пиксель
  157.     gpu.setBackground(color)
  158.     gpu.fill(x,y,WIDTH,HEIGHT,symbol)
  159. end
  160.  
  161. -- Функция выдачи позиции курсора
  162. function API.getClick()
  163.     local name, x, y, button, playerName = event.pull()
  164.     return x, y, button, playerName
  165. end
  166.  
  167. -- Функция написания текста, центрированного относительно X
  168. function API.centerTextX(y,text,color)
  169.     gpu.setForeground(color)
  170.     gpu.set(w/2 - #text/2, y, text)
  171. end
  172.  
  173. -- Функция написания текста, центрированного относительно Y
  174. function API.centerTextY(x,text,color)
  175.     gpu.setForeground(color)
  176.     gpu.set(x,h/2-#text/2,text)
  177. end
  178.  
  179. -- Функция написания текста, центрированного относительно XY
  180. function API.centerTextXY(text,color)
  181.     gpu.setForeground(color)
  182.     gpu.set(x-#text/2,y-#text/2,text)
  183.    
  184. -- Функция отображения 'пустой' коробки 
  185. -- Поставте symbol " " и будет чистый пиксель
  186. function API.emptyBox(x,y,WIDTH,HEIGHT,color_inside,color_side,strip_thickness,symbol_side,symbol_inside)
  187.     gpu.setBackground(color_side)
  188.     gpu.fill(x,y,WIDTH,HEIGHT, symbol_side)
  189.     gpu.setBackground(color_inside)
  190.     gpu.fill(x+strip_thickness,y+strip_thickness,WIDTH-strip_thickness,HEIGHT-strip_thickness, symbol_inside)
  191. end
  192.  
  193. -- Линия от А до Б
  194. -- Ported from CC paintutils lib
  195. -- LeshaInc говорит:"Это за грани моего понимания."
  196. function API.line(startX, startY, endX, endY, nColor)
  197.     if type(startX) ~= "number" or type(startX) ~= "number" or
  198.        type(endX) ~= "number" or type(endY) ~= "number" or
  199.        (nColor ~= nil and type(nColor) ~= "number") then
  200.         error("Expected startX, startY, endX, endY, color", 2)
  201.     end
  202.    
  203.     startX = math.floor(startX)
  204.     startY = math.floor(startY)
  205.     endX = math.floor(endX)
  206.     endY = math.floor(endY)
  207.  
  208.     if startX == endX and startY == endY then
  209.         API.pixel(startX, startY, nColor)
  210.         return
  211.     end
  212.    
  213.     local minX = math.min(startX, endX)
  214.     if minX == startX then
  215.         minY = startY
  216.         maxX = endX
  217.         maxY = endY
  218.     else
  219.         minY = endY
  220.         maxX = startX
  221.         maxY = startY
  222.     end
  223.  
  224.     -- TODO: clip to screen rectangle?
  225.    
  226.     local xDiff = maxX - minX
  227.     local yDiff = maxY - minY
  228.            
  229.     if xDiff > math.abs(yDiff) then
  230.         local y = minY
  231.         local dy = yDiff / xDiff
  232.         for x=minX,maxX do
  233.             API.pixel(x, math.floor(y + 0.5), nColor)
  234.             y = y + dy
  235.         end
  236.     else
  237.         local x = minX
  238.         local dx = xDiff / yDiff
  239.         if maxY >= minY then
  240.             for y=minY,maxY do
  241.                 API.pixel(math.floor(x + 0.5), y, nColor)
  242.                 x = x + dx
  243.             end
  244.         else
  245.             for y=minY,maxY,-1 do
  246.                 API.pixel(math.floor(x + 0.5 ), y, nColor)
  247.                 x = x - dx
  248.             end
  249.         end
  250.     end
  251. end
  252.  
  253. return API
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement