From 0d0bb010b4aaf2c8ada8101e32f37f7ff02e03e4 Mon Sep 17 00:00:00 2001 From: Igor Timofeev Date: Thu, 31 Mar 2016 21:54:20 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A2=D0=B0=D0=BA=D1=81!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Applications/TurretControl/TurretControl.lua | 165 +++++++++++++ .../Фирменный компьютер ECS.json | 112 +++++++++ lib/buttons.lua | 216 +++++++++--------- lib/doubleBuffering.lua | 9 +- 4 files changed, 395 insertions(+), 107 deletions(-) create mode 100644 Applications/TurretControl/TurretControl.lua create mode 100644 PoleznayaHuynaPoMaynu/Фирменный компьютер ECS.json diff --git a/Applications/TurretControl/TurretControl.lua b/Applications/TurretControl/TurretControl.lua new file mode 100644 index 00000000..1440d739 --- /dev/null +++ b/Applications/TurretControl/TurretControl.lua @@ -0,0 +1,165 @@ + +local component = require("component") +local buffer = require("doubleBuffering") +local image = require("image") +local event = require("event") +local ecs = require("ECSAPI") +local unicode = require("unicode") + +buffer.start() +local pathToTurretPicture = "turret.pic" +local turretImage = image.load(pathToTurretPicture) +local turrets = {} +local proxies = {} + +local yTurrets = 2 +local spaceBetweenTurretsHorizontal = 2 +local spaceBetweenTurretsVertical = 1 +local turretHeight = turretImage.height + 12 +local turretWidth = turretImage.width + 8 +local countOfTurretsCanBeShowByWidth = math.floor(buffer.screen.width / (turretWidth + spaceBetweenTurretsHorizontal)) +local xTurrets = math.floor(buffer.screen.width / 2 - (countOfTurretsCanBeShowByWidth * (turretWidth + spaceBetweenTurretsHorizontal)) / 2 ) + math.floor(spaceBetweenTurretsHorizontal / 2) + +local yellowColor = 0xFFDB40 + +local function getProxiesOfAllComponents(name) + for address in pairs(component.list(name)) do + table.insert(proxies, component.proxy(address)) + end +end + +local function getTurrets() + getProxiesOfAllComponents("tierOneTurretBase") + getProxiesOfAllComponents("tierTwoTurretBase") + getProxiesOfAllComponents("tierThreeTurretBase") + getProxiesOfAllComponents("tierFourTurretBase") + getProxiesOfAllComponents("tierFiveTurretBase") + for i = 1, #proxies do + if type(proxies[i].getCurrentEnergyStorage()) ~= "string" then + local turret = {} + turret.address = proxies[i].address + turret.type = proxies[i].type + turret.isActive = proxies[i].getActive() + turret.energyPercent = math.ceil(proxies[i].getCurrentEnergyStorage() / proxies[i].getMaxEnergyStorage() * 100) + table.insert(turrets, turret) + end + end +end + +local function progressBar(x, y, width, height, background, foreground, percent) + buffer.square(x, y, width, height, background) + buffer.frame(x, y, width, height, foreground) + width = width - 2 + local cykaWidth = math.ceil(width * percent / 100) + buffer.text(x + 1, y + 1, foreground, string.rep("▒", cykaWidth)) +end + +local function enableOrDisableEveryTurret(enable) + for turret = 1, #turrets do + turrets[turrets].setActive(enable) + end +end + +local function changeUserListOnEveryTurret(userlist) + for i = 1, #userlist do + + end +end + +local function drawTurrets(y) + local counter = 0 + local x = xTurrets + + for turret = 1, #turrets do + local yPos = y + buffer.frame(x, yPos, turretWidth, turretHeight, yellowColor) + yPos = yPos + 1 + buffer.text(x + 2, yPos, yellowColor, ecs.stringLimit("end", "Турель " .. turrets[turret].address, turretWidth - 4)) + yPos = yPos + 2 + buffer.image(x + 4, yPos, turretImage) + yPos = yPos + turretImage.height + 1 + buffer.text(x + 2, yPos, yellowColor, "Энергия:") + yPos = yPos + 1 + progressBar(x + 1, yPos, turretWidth - 2, 3, 0x000000, yellowColor, turrets[turret].energyPercent) + yPos = yPos + 4 + local widthOfButton = 13 + -- local isActive = turrets[turret].getActive() + local isActive = turrets[turret].isActive + buffer.button(x + 2, yPos, widthOfButton, 1, isActive and yellowColor or 0x000000, isActive and 0x000000 or yellowColor, "ВКЛ") + buffer.button(x + 2 + widthOfButton + 2, yPos, widthOfButton, 1, not isActive and yellowColor or 0x000000, not isActive and 0x000000 or yellowColor, "ВЫКЛ") + yPos = yPos + 1 + + x = x + turretWidth + spaceBetweenTurretsHorizontal + counter = counter + 1 + if counter % countOfTurretsCanBeShowByWidth == 0 then + x = xTurrets + y = y + turretHeight + spaceBetweenTurretsVertical + end + end +end + +local function drawSeparator(y) + buffer.text(1, y, yellowColor, string.rep("─", buffer.screen.width)) +end + +local function drawBottomBar() + local height = 6 + local y = buffer.screen.height - height + 1 + buffer.square(1, y, buffer.screen.width, height, 0x000000, yellowColor, " ") + drawSeparator(y) + local text = " ECS® Security Systems™ " + local x = math.floor(buffer.screen.width / 2 - unicode.len(text) / 2) + buffer.text(x, y, yellowColor, text) + + y = y + 2 + + local widthOfButton = 17 + local totalWidth = (widthOfButton + 2) * 6 + local x = math.floor(buffer.screen.width / 2 - totalWidth / 2) + 1 + + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Турели ВКЛ"); x = x + widthOfButton + 2 + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Турели ВЫКЛ"); x = x + widthOfButton + 2 + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Добавить игрока"); x = x + widthOfButton + 2 + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Атака мобов"); x = x + widthOfButton + 2 + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Атака нейтралов"); x = x + widthOfButton + 2 + buffer.button(x, y, widthOfButton, 3, yellowColor, 0x000000, "Атака игроков"); x = x + widthOfButton + 2 +end + +local function drawAll() + buffer.clear(0x000000) + drawTurrets(yTurrets) + drawBottomBar() + buffer.draw() +end + +local function refresh() + getTurrets() + drawAll() +end + +refresh() + +while true do + local e = {event.pull()} + if e[1] == "touch" then + + elseif e[1] == "scroll" then + if e[5] == 1 then + yTurrets = yTurrets - 2 + else + yTurrets = yTurrets + 2 + end + drawAll() + end +end + + + + + + + + + + + diff --git a/PoleznayaHuynaPoMaynu/Фирменный компьютер ECS.json b/PoleznayaHuynaPoMaynu/Фирменный компьютер ECS.json new file mode 100644 index 00000000..b5b6b886 --- /dev/null +++ b/PoleznayaHuynaPoMaynu/Фирменный компьютер ECS.json @@ -0,0 +1,112 @@ +/minecraft:give @a[r=5,name=ECS] OpenComputers:caseCreative 1 0 { + display:{ + Name:"Фирменный компьютер от ECS", + Lore:[ + " ", + " Мощнейшее железо в стильном фиолетовом ", + " корпусе было подобрано лучшими специалистами ", + " нашей компании специально для вас. ", + " ", + " Данный компьютер оснащен квантовым генератором, ", + " что позволит вам навсегда забыть о бесконечных ", + " счетах за свет. Также в нем установлена передовая ", + " материнская плата без ограничений на уровень ", + " компонентов. Кроме того, мы встроили сверхбыстрый ", + " преобразователь энергии, распределяющий ее между ", + " компонентами более эффективно.", + " ", + " Спасибо за покупку!", + " " + ] + } +} + +/minecraft:give @a[r=5,name=ECS] OpenComputers:item 1 103 { + display:{ + Name:"Фирменный процессор от ECS", + Lore:[ + " ", + " Сверхбыстрый процессор, созданный лучшими ", + " инженерами нашей компании. Имеет встроенную ", + " видеокарту 3 уровня с водяным охлаждением. ", + " ", + ] + } +} + +/minecraft:give @a[r=5,name=ECS] OpenComputers:item 1 91 { + display:{ + Name:"Фирменный корпус дрона от ECS", + Lore:[ + " ", + " Стильный корпус дрона, идеально сбалансированный ", + " в аэродинамическом плане. Наши инженеры добавили ", + " несколько дополнительных слотов для улучшений, ", + " так что вас теперь ничто не ограничивает! ", + " ", + ] + } +} + +/minecraft:give @a[r=5,name=ECS] OpenComputers:item 1 69 { + display:{ + Name:"Фирменный сервер от ECS", + Lore:[ + " ", + " Мощь и красота - вот наш девиз! ", + " В этом серверном корпусе идеально практически ", + " все - от поддержки компонентов любых уровней ", + " до стильного фиолетового корпуса. Ведь именно ", + " за это вы готовы заплатить втридорога, верно? ", + " ", + ] + } +} + +/minecraft:give @a[r=5,name=ECS] OpenComputers:item 1 93 { + display:{ + Name:"Фирменный планшет от ECS", + Lore:[ + " ", + " Кто сказал, что планшет должен быть хуже ", + " настольного ПК? Наши инженеры постарались ", + " на славу - убрано ограничение по уровню ", + " копмонентов и улучшений, а также нанесена ", + " фирменная аэрография, демонстрирующая ", + " окружающим вашу элитарность и особенность", + " ", + ] + } +} + +/minecraft:give @a[r=5,name=ECS] OpenComputers:item 1 4 { + display:{ + Name:"Фирменный установщик MineOS от ECS", + Lore:[ + " ", + " Покупая эту дискету, вы демонстрируете ", + " окружающим свое богатство и социальный ", + " статус. Хотя по факту вас, скорее, примут ", + " за дебила, не умеющего качать ОС бесплатно. ", + " ", + " Впрочем, у богатых свои причуды, и вас ", + " насмешки бедняков вряд ли будут беспокоить.", + " ", + ] + } +} + + +Если ты богат, и деньги сыпятся рекой - то самое время приобрести элитную технику, которую простолюдины себе никогда не позволят. Помимо улучшенных характеристик каждое из наших устройств произведено с хирургической точнстью путем эксплуатации рабского труда китайских детей. + + + + + + + + + + + + diff --git a/lib/buttons.lua b/lib/buttons.lua index 1cdebb07..6eda79cc 100644 --- a/lib/buttons.lua +++ b/lib/buttons.lua @@ -1,134 +1,142 @@ -local event = require("event") -local computer = require("computer") ----------------------------------------------------------------------------------------------------------------- +if not _G.buffer then _G.buffer = require("doubleBuffering") end +if not _G.unicode then _G.unicode = require("unicode") end local buttons = {} +buttons.IDs = {} buttons.pressTime = 0.2 -buttons.objects = {} -function buttons.setPressTime(time) - buttons.pressTime = time +-------------------------------------------------------------------------------------------------------------------------------- + +local function getRandomID() + local ID + repeat + ID = math.floor(math.random(1, 0xFFFFFF)) + until not buttons.IDs[ID] + return ID end -function buttons.getPressTime() - return buttons.pressTime -end +local function drawButton(ID) + local state = buttons.IDs[ID].isPressed and "pressed" or "default" -local function checkError(class, name) - if not buttons.objects[class] then error("Несуществующий класс кнопки \"" .. class .. "\"") end - if not buttons.objects[class][name] then error("Несуществующее имя кнопки \"" .. name .. "\" в классе \"" .. class .. "\"" ) end -end - -function buttons.draw(class, name) - checkError(class, name) - if buttons.objects[class][name].visible then - if buttons.objects[class][name].pressed then - ecs.drawButton(buttons.objects[class][name].x, buttons.objects[class][name].y, buttons.objects[class][name].width, buttons.objects[class][name].height, name, buttons.objects[class][name].backgroundWhenPressed, buttons.objects[class][name].foregroundWhenPressed) - else - ecs.drawButton(buttons.objects[class][name].x, buttons.objects[class][name].y, buttons.objects[class][name].width, buttons.objects[class][name].height, name, buttons.objects[class][name].background, buttons.objects[class][name].foreground) - end + if buttons.IDs[ID] then + buffer.button(buttons.IDs[ID].x, buttons.IDs[ID].y, buttons.IDs[ID].width, buttons.IDs[ID].height, buttons.IDs[ID].style[state].buttonColor, buttons.IDs[ID].style[state].textColor, buttons.IDs[ID].text) + else + error("Button ID \"" .. ID .. "\" doesn't exists.\n") end end -function buttons.add(class, name, x, y, width, height, background, foreground, backgroundWhenPressed, foregroundWhenPressed, justAddNoDraw) - buttons.objects[class] = buttons.objects[class] or {} - buttons.objects[class][name] = { - ["x"] = x, - ["y"] = y, - ["width"] = width, - ["height"] = height, - ["background"] = background, - ["foreground"] = foreground, - ["backgroundWhenPressed"] = backgroundWhenPressed, - ["foregroundWhenPressed"] = foregroundWhenPressed, - ["visible"] = not justAddNoDraw, - ["pressed"] = false, - } - if not justAddNoDraw then - buttons.draw(class, name) +local function clickedAtArea(x, y, x1, y1, x2, y2) + if x >= x1 and x <= x2 and y >= y1 and y <= y2 then + return true end end -function buttons.remove(class, name) - checkError(class, name) - buttons.objects[class][name] = nil -end +-------------------------------------------------------------------------------------------------------------------------------- -function buttons.setVisible(class, name, state) - checkError(class, name) - buttons.objects[class][name].visible = state -end - -function buttons.press(class, name) - checkError(class, name) - buttons.objects[class][name].pressed = true - buttons.draw(class, name) - os.sleep(buttons.pressTime) - buttons.objects[class][name].pressed = false - buttons.draw(class, name) -end - -function buttons.drawAll() - for class in pairs(buttons.objects) do - for name in pairs(buttons.objects[class]) do - buttons.draw(class, name) - end - end -end - -local function listener(...) - local e = {...} - local exit = false - if e[1] == "touch" then - for class in pairs(buttons.objects) do - if exit then break end - for name in pairs(buttons.objects[class]) do - if ecs.clickedAtArea(e[3], e[4], buttons.objects[class][name].x, buttons.objects[class][name].y, buttons.objects[class][name].x + buttons.objects[class][name].width - 1, buttons.objects[class][name].y + buttons.objects[class][name].height - 1) then - if buttons.objects[class][name].visible then - buttons.press(class, name) - computer.pushSignal("button_pressed", class, name, buttons.objects[class][name].x, buttons.objects[class][name].y, buttons.objects[class][name].width, buttons.objects[class][name].height) - end - exit = true - break +function buttons.checkEventData(eventData) + if eventData[1] == "touch" then + for ID in pairs(buttons.IDs) do + if clickedAtArea(eventData[3], eventData[4], buttons.IDs[ID].x, buttons.IDs[ID].y, buttons.IDs[ID].x2, buttons.IDs[ID].y2) then + buttons.IDs[ID].isPressed = true + drawButton(ID) + buffer.draw() + + os.sleep(buttons.pressTime or 0.2) + + buttons.IDs[ID].isPressed = nil + drawButton(ID) + buffer.draw() + + if buttons.IDs[ID].callback then + pcall(buttons.IDs[ID].callback) end end end end end -function buttons.start() - event.listen("touch", listener) +function buttons.newStyle(buttonColor, textColor, buttonColorWhenPressed, textColorWhenPressed) + return { + default = { + buttonColor = buttonColor, + textColor = textColor, + }, + pressed = { + buttonColor = buttonColorWhenPressed, + textColor = textColorWhenPressed, + }, + } end -function buttons.stop() - event.ignore("touch", listener) +function buttons.draw(...) + local IDs = { ... } + if #IDs > 0 then + for ID in pairs(IDs) do + if buttons.IDs[ID] then + drawButton(ID) + else + error("Button ID \"" .. ID .. "\" doesn't exists.\n") + end + end + buffer.draw() + else + for ID in pairs(buttons.IDs) do + drawButton(ID) + end + buffer.draw() + end end ------------------------------------------- Тест программы ------------------------------------------------------------------- +function buttons.add(x, y, width, height, style, text, callback) + checkArg(1, x, "number") + checkArg(2, y, "number") + checkArg(3, width, "number") + checkArg(4, height, "number") + checkArg(5, style, "table") + checkArg(6, text, "string") + if callback then checkArg(7, callback, "function") end --- ecs.prepareToExit() --- buttons.start() --- local xPos, yPos, width, height, counter = 2, 6, 6, 3, 1 --- for i = 1, 10 do --- for j = 1, 20 do --- buttons.add("Test", tostring(counter), xPos, yPos, width, height, ecs.colors.green, 0xFFFFFF, ecs.colors.red, 0xFFFFFF) --- xPos = xPos + width + 2; counter = counter + 1 --- end --- xPos = 2; yPos = yPos + height + 1 --- end --- buttons.add("Test", "Выйти отсюдова", 2, 2, 30, 3, ecs.colors.orange, 0xFFFFFF, ecs.colors.red, 0xFFFFFF) + local ID = getRandomID() + + buttons.IDs[ID] = { + x = x, + y = y, + x2 = x + width - 1, + y2 = y + height - 1, + width = width, + height = height, + style = style, + text = text, + callback = callback + } + + return ID +end + +function buttons.remove( ... ) + local IDs = { ... } + if #IDs > 0 then + for ID in pairs(IDs) do + if buttons.IDs[ID] then + buttons.IDs[ID] = nil + else + error("Button ID \"" .. ID .. "\" doesn't exists.\n") + end + end + else + buttons.IDs = {} + end +end + +function buttons.setPressTime(time) + buttons.pressTime = time +end + +-------------------------------------------------------------------------------------------------------------------------------- + +return buttons --- while true do --- local e = {event.pull()} --- if e[1] == "button_pressed" then --- if e[2] == "Test" and e[3] == "Выйти отсюдова" then --- buttons.stop() --- ecs.prepareToExit() --- break --- end --- end --- end diff --git a/lib/doubleBuffering.lua b/lib/doubleBuffering.lua index f653f46d..103999f0 100644 --- a/lib/doubleBuffering.lua +++ b/lib/doubleBuffering.lua @@ -334,9 +334,12 @@ end -- Кнопка фиксированных размеров function buffer.button(x, y, width, height, background, foreground, text) - local textPosX = math.floor(x + width / 2 - unicode.len(text) / 2) + local textLength = unicode.len(text) + if textLength > width - 2 then text = unicode.sub(text, 1, width - 2) end + + local textPosX = math.floor(x + width / 2 - textLength / 2) local textPosY = math.floor(y + height / 2) - buffer.square(x, y, width, height, background, 0xFFFFFF, " ") + buffer.square(x, y, width, height, background, foreground, " ") buffer.text(textPosX, textPosY, foreground, text) return x, y, (x + width - 1), (y + height - 1) @@ -430,7 +433,7 @@ function buffer.framedButton(x, y, width, height, backColor, buttonColor, text) buffer.frame(x, y, width, height, buttonColor) x = x + math.floor(width / 2 - unicode.len(text) / 2) - y = y + math.floor(width / 2 - 1) + y = y + math.floor(height / 2 - 1) buffer.text(x, y, buttonColor, text) end