Advertisement
Ktlo

OpenComputers Object API

Jun 11th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 9.10 KB | None | 0 0
  1. --Загрузка библиотек
  2. local term = require("term")
  3. local gpu = require("component").gpu
  4. local component = require("component")
  5. local event = require("event")
  6. --Локальные функции всех классов
  7. local function copyTable(orig) --Копирование таблиц
  8.     local orig_type = type(orig)
  9.     local copy
  10.     if orig_type == 'table' then
  11.         copy = { }
  12.             for orig_key, orig_value in next, orig, nil do
  13.             copy[copyTable(orig_key)] = copyTable(orig_value)
  14.         end
  15.         setmetatable(copy, copyTable(getmetatable(orig)))
  16.     else
  17.         copy = orig
  18.     end
  19.     return copy
  20. end
  21. local function isConnect(address, kind) --Проверка подключения по адресу
  22.     local result = false
  23.     for value in component.list(kind) do
  24.         if address == value then
  25.             result = true
  26.             break
  27.         end
  28.     end
  29.     return result
  30. end
  31. local function findComp(kind) --Находит любой компонент по типу
  32.     local result = false
  33.     for value in component.list(kind) do
  34.         result = value
  35.         break
  36.     end
  37.     return result
  38. end
  39. local function toLines(str, w) --Переносит текст на следующую строку, если не хватает места
  40.     local lines = { }
  41.     for i=1, math.ceil(#str/w) do
  42.         lines[i] = string.sub(str, (i-1)*w+1, i*w)
  43.     end
  44.     return lines
  45. end
  46. local function rusType(var) --Руссифицированная функция type
  47.     var = type(var)
  48.     if var == "number" then return "число"
  49.     elseif var == "table" then return "таблица"
  50.     elseif var == "function" then return "функция"
  51.     elseif var == "string" then return "строка"
  52.     elseif var == "boolean" then return "логическое значение"
  53.     elseif var == "nil" then return "ничего"
  54.     else return var end
  55. end
  56. local function button_error(list) --Детектирует ошибки в кнопке
  57.     if type(list) ~= "table" then
  58.         error("Задан неверный параметр.")
  59.     end
  60.     list.Draw = nil
  61.     list.Set = nil
  62.     list.Detect = nil
  63.     list.Screen = list.Screen or gpu.getScreen()
  64.     list.Text = tostring(list.Text or "")
  65.     list.TextColor = list.TextColor or 0xE6E6FA
  66.     list.BackgroundColor = list.BackgroundColor or 0x085eff
  67.     list.ActiveColor = list.ActiveColor or 0x13c000
  68.     list.InactiveColor = list.InactiveColor or 0x696969
  69.     list.Time = list.Time or 0.3
  70.     list.Style = list.Style or "round"
  71.     if list.Visible == nil then list.Visible = true end
  72.     --Ошибки
  73.     if type(list.Screen) ~= "string" then
  74.         error("Адрес монитора должен быть строкой!", 2)
  75.     end
  76.     if not isConnect(list.Screen, "screen") then
  77.         error("Не найдено \"screen\" по адресу: \""..list.Screen.."\".", 2)
  78.     end
  79.     if type(list.xPos) ~= "number" then
  80.         local var = rusType(list.xPos)
  81.         list.xPos = tonumber(list.xPos)
  82.         if not list.xPos then
  83.             error("Параметр xPos должен быть числом, получено "..var..".", 2)
  84.         end
  85.     end
  86.     if type(list.yPos) ~= "number" then
  87.         local var = rusType(list.yPos)
  88.         list.yPos = tonumber(list.yPos)
  89.         if not list.yPos then
  90.             error("Параметр yPos должен быть числом, получено "..var..".", 2)
  91.         end
  92.     end
  93.     if type(list.Width) ~= "number" then
  94.         local var = rusType(list.Width)
  95.         list.Width = tonumber(list.Width)
  96.         if not list.Width then
  97.             error("Параметр Width должен быть числом, получено "..var..".", 2)
  98.         end
  99.     end
  100.     if type(list.Height) ~= "number" then
  101.         local var = rusType(list.Height)
  102.         list.Height = tonumber(list.Height)
  103.         if not list.Height then
  104.             error("Параметр Height должен быть числом, получено "..var..".", 2)
  105.         end
  106.     end
  107.     if type(list.TextColor) ~= "number" then
  108.         local var = rusType(list.TextColor)
  109.         list.TextColor = tonumber(list.TextColor)
  110.         if not list.TextColor then
  111.             error("Цвет текста должен быть числом, получено "..var..".", 2)
  112.         end
  113.     end
  114.     if type(list.BackgroundColor) ~= "number" then
  115.         local var = rusType(list.BackgroundColor)
  116.         list.BackgroundColor = tonumber(list.BackgroundColor)
  117.         if not list.BackgroundColor then
  118.             error("Цвет кнопки должен быть числом, получено "..var..".", 2)
  119.         end
  120.     end
  121.     if type(list.ActiveColor) ~= "number" then
  122.         local var = rusType(list.ActiveColor)
  123.         list.ActiveColor = tonumber(list.ActiveColor)
  124.         if not list.ActiveColor then
  125.             error("Цвет активной кнопки должен быть числом, получено "..var..".", 2)
  126.         end
  127.     end
  128.     if type(list.InactiveColor) ~= "number" then
  129.         local var = rusType(list.InactiveColor)
  130.         list.InactiveColor = tonumber(InactiveColor)
  131.         if not list.InactiveColor then
  132.             error("Цвет неактивной кнопки должен быть числом, получено "..var..".", 2)
  133.         end
  134.     end
  135.     if type(list.Visible) ~= "boolean" then
  136.         error("Параметр видимости должен быть логическим значением, получено "..rusType(list.Visible)..".", 2)
  137.     end
  138.     if type(list.Time) ~= "number" then
  139.         local var = rusType(list.Time)
  140.         list.Time = tonumber(list.Time)
  141.         if not list.Time then
  142.             error("Время нажатия должно быть числом, получено "..var..".", 2)
  143.         end
  144.     end
  145.     if list.Style ~= "round" and list.Style ~= "square" then
  146.         error("Стиль кнопки может быть \"round\" или \"square\", получено \""..list.Style.."\".", 2)
  147.     end
  148. end
  149. local function object_set(object, list) --Меняет свойства любого объекта
  150.     for key, value in pairs(list) do
  151.         object[key] = value
  152.     end
  153.     if object.Object == "button" then
  154.         button_error(object)
  155.     end
  156.     if object.Visible then
  157.         object.Draw()
  158.     end
  159. end
  160. local function object_detect(object, list) --Детектирует взаимодействия со всем
  161.     if list.Action ~= "touch" and list.Action ~= "drag" and list.Action ~= "drop" and list.Action ~= "scroll" then
  162.         error("Получено незарегистрированное действие, \""..list.Action.."\".", 2)
  163.     end
  164.     list.Button = list.Button or 2
  165.     if not list.x then
  166.         _, list.Screen, list.x, list.y, list.CurrentButton = event.pull(list.Action)
  167.     end
  168.     list.Screen = list.Screen or object.Screen
  169.     if list.x >= object.xPos
  170.     and list.x <= object.xPos+object.Width-1
  171.     and list.y >= object.yPos
  172.     and list.y <= object.yPos+object.Height-1
  173.     and (list.Button == list.CurrentButton or list.Button == 2)
  174.     and list.Screen == object.Screen then
  175.         return true, list.CurrentButton
  176.     else
  177.         return false
  178.     end
  179. end
  180. --[[
  181.     Классы
  182. ]]
  183. local Object = {}
  184. Object.New = { } --Таблица с классами
  185. do --Класс  кнопки
  186.     local function button_draw(object, state) --Рисует кнопку
  187.         local screen = gpu.getScreen()
  188.         local RES1, RES2 = gpu.getResolution()
  189.         local BG = gpu.getBackground()
  190.         local FG = gpu.getForeground()
  191.         if object.Screen ~= screen then gpu.bind(object.Screen) end
  192.         local backColor
  193.         if state == "active" then
  194.             backColor = object.ActiveColor
  195.         elseif state == "inactive" then
  196.             backColor = object.InactiveColor
  197.         else
  198.             backColor = object.BackgroundColor
  199.         end
  200.             gpu.setBackground(backColor)
  201.             gpu.fill(object.xPos, object.yPos, object.Width, object.Height, " ")
  202.         if object.Style == "round" then
  203.             gpu.setBackground(BG)
  204.             gpu.setForeground(backColor)
  205.             gpu.set(object.xPos, object.yPos, "▄")
  206.             gpu.set(object.xPos+object.Width-1, object.yPos, "▄")
  207.             gpu.set(object.xPos, object.yPos+object.Height-1, "▀")
  208.             gpu.set(object.xPos+object.Width-1, object.yPos+object.Height-1, "▀")
  209.         end
  210.         do
  211.             gpu.setBackground(backColor)
  212.             gpu.setForeground(object.TextColor)
  213.             local text = toLines(object.Text, object.Width)
  214.             for i=1, #text do
  215.                 gpu.set(math.floor(object.Width/2+object.xPos-#text[i]/2), math.ceil(object.yPos+object.Height/2-#text/2+(i-1)), text[i])
  216.             end
  217.         end
  218.         if object.Screen ~= screen then
  219.             gpu.setResolution(RES1, RES2)
  220.             gpu.bind(screen)
  221.         end
  222.         gpu.setForeground(FG)
  223.         gpu.setBackground(BG)
  224.     end
  225.     local function button_detect(object, list) --Детектирование действий с кнопкой
  226.         local bool, n = object_detect(object, list)
  227.         if object.Visible and bool then
  228.             object.Draw("active")
  229.             os.sleep(object.Time)
  230.             object.Draw()
  231.         end
  232.         print(bool, n)
  233.         return bool, n
  234.     end
  235.     function Object.New.Button(list) --Класс кнопки
  236.         local object = copyTable(list)
  237.         button_error(object)
  238.         object.Object = "button"
  239.         list = nil
  240.         local Me = {
  241.             ["Draw"] = function(state) --Рисует кнопку
  242.                 button_draw(object, state)
  243.             end;
  244.             ["Set"] = function(list) --Меняет значения кнопки
  245.                 object_set(object, list)
  246.             end;
  247.             ["Detect"] = function(list) --Детектирует взаимодействия с кнопкой
  248.                 local bool, n = button_detect(object, list)
  249.                 return bool, n
  250.             end;
  251.         }
  252.         setmetatable(Me, {__index = object})
  253.         setmetatable(object, {__index = Me})
  254.         --Cоздание объекта
  255.         if object.Visible then Me.Draw() end
  256.         return Me
  257.     end
  258. end
  259.  
  260. return Object
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement