Krobys

[Computer] Draconic Blocks Charger Shop

Mar 25th, 2023 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.05 KB | Gaming | 0 0
  1. local component = require("component")
  2. local gpu = component.gpu
  3. local GUI = require("GUI")
  4. local application = GUI.application()
  5. local unicode = require("unicode")
  6. local computer = require("computer")
  7. local io = require("io")
  8. local maxWidth, maxHeight = gpu.getViewport()
  9. local event = require("event")
  10. gpu.setResolution((maxWidth/3) * 2 , (maxHeight/3) * 2)
  11. local crystal = component.isAvailable("crystal") and component.crystal or error("Нет буферного сундука")
  12. local interface = component.me_interface or error("Не найден МЭ интерфейс")
  13. local db = component.isAvailable("database") and component.database or error("Нет улучшения базы данных")
  14. local screenWidth, screenHeight = gpu.getResolution()
  15.  
  16. local notChargedDraconicBlockInfo = {displayName = "Дракониевый блок", id = "DraconicEvolution:draconium", dmg = 0}
  17. local chargedDraconicBlockInfo = {displayName = "Заряженный дракониевый блок", id = "DraconicEvolution:draconium", dmg = 2}
  18. local pricePerBlock = {
  19.     money = {displayName= "Деньги(Банкомат на /warp shop)", id = "customnpcs:npcMoney", dmg = 0, count = 8},
  20. }
  21.  
  22. local constants = {
  23.     log_file_name = "/home/LogDraconicBlocs.txt"
  24. }
  25. local localize = {
  26.     shop_title = "Магазин для зарядки ДК блоков",
  27.     shop_details_1 = "Это магазин в котором вы можете зарядить ваши Дракониевые блоки блоки id: (0967/0)",
  28.     shop_details_2 = "Поместите денежную оплату в размере "..pricePerBlock.money.count.." эмов за блок (можно снять на /warp shop)",
  29.     shop_details_3 = "А так же поместите обычные Дракониевые блоки id: (0967/0) в сундук.",
  30.     shop_details_4 = "Нажми кнопку \"Сделать заряженные блоки\" и ожидай зарядки (очень быстро)",
  31.     buy_button_text = "Сделать заряженные дракониевые блоки",
  32.     check_price_text = "Проверить стоимость",
  33.  
  34.     need_draconic_blocks_text = "Дракониевых блоков не найдено",
  35.     need_money_text_mask = "Для оплаты за %d ДК блока нужно %d Денег",
  36.     need_more_money = "Для оплаты за %d ДК блоков нужно еще %d %s. Сейчас %d/%d",
  37.  
  38.     item_was_taken_mask = "Предмет %s в нужном количестве был взят из сундука",
  39.     sorry_not_enought_price_mask = "Извините, вы достали из сундука %d %s предметов. Положите обратно",
  40.     wait_for_craft = "Ожидайте, в процессе создания...",
  41.     thanks_for_buying = "Спасибо за ожидание! Ваши %d %s были выданы в сундук",
  42.  
  43.     last_buyer_mask = "Посл. покупатель: %s",
  44.     count_buyers_mask = "Всего покупателей: %d"
  45. }
  46.  
  47. local constraints = {
  48.     leftBorder = 5
  49. }
  50.  
  51. local function showInfo(infoText, durationSeconds)
  52.     infoTextField.text = infoText
  53.     infoTextField.hidden = false
  54.     application:draw()
  55.     if durationSeconds then
  56.         computer.pullSignal(durationSeconds)
  57.         infoTextField.hidden = true
  58.         application:draw()
  59.     end
  60. end
  61.  
  62. local function pushItem(itemObject, count)
  63.     local convertedObject = {name = itemObject.id, damage = itemObject.dmg}
  64.     db.clear(1)
  65.     interface.store(convertedObject, db.address, 1)
  66.     interface.setInterfaceConfiguration(1, db.address, 1, 64)
  67.     local drop = 0
  68.     while true do
  69.         if drop == count then
  70.             interface.setInterfaceConfiguration(1, db.address, 1, 0)
  71.             break
  72.         else
  73.             local dropcount = interface.pushItem("UP", 1, count-drop)
  74.             drop = drop + dropcount
  75.         end
  76.     end
  77. end
  78.  
  79. local function takeItem(itemObject, count)
  80.     local takeItemsLeft = count
  81.     local data = crystal.getAllStacks(0)
  82.     local size = crystal.getInventorySize()
  83.     for slot = 1, size do
  84.         if data[slot] and data[slot].id == itemObject.id and data[slot].dmg == itemObject.dmg then
  85.             if takeItemsLeft > 0 then
  86.                 if takeItemsLeft > 64 then
  87.                     local item_count = crystal.pushItem("DOWN",slot,64)
  88.                     takeItemsLeft = takeItemsLeft - item_count
  89.                 elseif takeItemsLeft > 0 and takeItemsLeft <= 64 then
  90.                     local item_count = crystal.pushItem("DOWN",slot,takeItemsLeft)
  91.                     takeItemsLeft = takeItemsLeft - item_count
  92.                 end
  93.             else
  94.                 break
  95.             end
  96.         end
  97.     end
  98.     if takeItemsLeft > 0 then
  99.         infoTextField.text = string.format(localize.sorry_not_enought_price_mask, takeItemsLeft, itemObject.displayName)
  100.         infoTextField.hidden = false
  101.         application:draw()
  102.         computer.pullSignal(1)
  103.         takeItem(itemObject, takeItemsLeft)
  104.     else
  105.         showInfo(string.format(localize.item_was_taken_mask, itemObject.displayName), 1)
  106.     end
  107. end
  108.  
  109. local function lookForItemInChest(id, damage)
  110.     local data = crystal.getAllStacks(0)
  111.     local size = crystal.getInventorySize()
  112.     local count = 0
  113.     for slot = 1, size do
  114.         if data[slot] and data[slot].id == id and data[slot].dmg == damage then
  115.             count = count + data[slot].qty
  116.         end
  117.     end
  118.     return count
  119. end
  120.  
  121. local function checkCurrentPrice()
  122.     local draconicBlocksCount = lookForItemInChest(notChargedDraconicBlockInfo.id, notChargedDraconicBlockInfo.dmg)
  123.     local moneyCountNeeded = draconicBlocksCount * pricePerBlock.money.count
  124.     if draconicBlocksCount == 0 then
  125.         showInfo(string.format(localize.need_draconic_blocks_text), 5)
  126.     else
  127.         showInfo(string.format(localize.need_money_text_mask, draconicBlocksCount, moneyCountNeeded), 5)
  128.     end
  129. end
  130.  
  131.  
  132. local function requestCraft(itemObject, count)
  133.     local craftable = interface.getCraftables({name = itemObject.id, damage = itemObject.dmg})
  134.     if craftable then
  135.         if craftable[1] then
  136.             local request = craftable[1].request(count)
  137.             repeat
  138.                 showInfo(localize.wait_for_craft)
  139.                 computer.pullSignal(3)
  140.             until request.isDone() or request.isCanceled()
  141.         end
  142.     end
  143. end
  144.  
  145. local function giveDraconicBlocksBack(count)
  146.     pushItem(chargedDraconicBlockInfo, count)
  147.     logUserBuy(userNickName, pricePerBlock.money.displayName, moneyCountNeeded)
  148.     loadBuyersInfo()
  149.     showInfo(string.format(localize.thanks_for_buying, count, chargedDraconicBlockInfo.displayName), 10)
  150. end
  151.  
  152. local function startChargingDcBlocks()
  153.     local draconicBlocksCount = lookForItemInChest(notChargedDraconicBlockInfo.id, notChargedDraconicBlockInfo.dmg)
  154.     if draconicBlocksCount == 0 then
  155.         showInfo(string.format(localize.need_draconic_blocks_text), 5)
  156.     else
  157.         local moneyCountNeeded = draconicBlocksCount * pricePerBlock.money.count
  158.         local moneyInChest = lookForItemInChest(pricePerBlock.money.id, pricePerBlock.money.dmg)
  159.         if moneyInChest < moneyCountNeeded then
  160.             showInfo(string.format(localize.need_more_money, draconicBlocksCount, moneyCountNeeded - moneyInChest, pricePerBlock.money.displayName, moneyInChest, moneyCountNeeded), 5)
  161.         else
  162.             takeItem(notChargedDraconicBlockInfo, draconicBlocksCount)
  163.             takeItem(pricePerBlock.money, moneyCountNeeded)
  164.             requestCraft(chargedDraconicBlockInfo, draconicBlocksCount)
  165.             giveDraconicBlocksBack(draconicBlocksCount)
  166.         end
  167.     end
  168. end
  169.  
  170. application:addChild(GUI.panel(1, 1, application.width, application.height, 0xCCCCCC))
  171. application:addChild(GUI.text(constraints.leftBorder, 1, 0x000000, localize.shop_title))
  172. application:addChild(GUI.text(constraints.leftBorder, 5, 0x000000, localize.shop_details_1))
  173. application:addChild(GUI.text(constraints.leftBorder, 6, 0x000000, localize.shop_details_2))
  174. application:addChild(GUI.text(constraints.leftBorder, 7, 0x000000, localize.shop_details_3))
  175. application:addChild(GUI.text(constraints.leftBorder, 8, 0x000000, localize.shop_details_4))
  176. infoTextField = application:addChild(GUI.text(constraints.leftBorder, 11, 0x000000, " "))
  177. local widthStartChargingButton = unicode.len(localize.buy_button_text) + 2
  178. local startChargingDcBlocksButton = application:addChild(GUI.button(5, 14, widthStartChargingButton, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, localize.buy_button_text))
  179. startChargingDcBlocksButton.animated = false
  180. startChargingDcBlocksButton.onTouch = function()
  181.     startChargingDcBlocks()
  182. end
  183.  
  184. local widthPriceButton = unicode.len(localize.check_price_text) + 2
  185. local checkPriceButton = application:addChild(GUI.button(5 + widthStartChargingButton + 1, 14, widthPriceButton, 3, 0xFFFFFF, 0x555555, 0x880000, 0xFFFFFF, localize.check_price_text))
  186. checkPriceButton.animated = false
  187. checkPriceButton.onTouch = function()
  188.     checkCurrentPrice()
  189. end
  190.  
  191. local userNameText = application:addChild(GUI.text(constraints.leftBorder + widthStartChargingButton + widthPriceButton + 2, 14, 0x000000, " "))
  192. local countOfBuyersText = application:addChild(GUI.text(constraints.leftBorder + widthStartChargingButton + widthPriceButton + 2, 15, 0x000000, " "))
  193.  
  194. function readTable(path)
  195.     local file = io.open(path, "r")
  196.     if file then
  197.         local result, reason = file:read("*all")
  198.         if result then
  199.             return require("serialization").unserialize(result) or {}
  200.         end
  201.     end
  202.  
  203.  
  204.     return result, reason
  205. end
  206.  
  207. local function writeTable(path, ...)
  208.     local file = io.open(path, "w")
  209.     file:write(require("serialization").serialize(...))
  210.     file:close()
  211. end
  212.  
  213. function getAllUsersBought()
  214.     return readTable(constants.log_file_name) or {}
  215. end
  216.  
  217. function logUserBuy(userName, itemPrice, count)
  218.     local usersTable = readTable(constants.log_file_name)
  219.     usersTable = usersTable and usersTable or {}
  220.     --local humanTime = os.date("%d %b %Y %H:%M:%S", system.getTime())
  221.     local userBuyItemLog = {user = userName, itemBought = itemPrice, count = count}
  222.     table.insert(usersTable, userBuyItemLog)
  223.  
  224.     writeTable(constants.log_file_name, usersTable)
  225.  
  226.     countBuyersTmp = #usersTable
  227. end
  228.  
  229. function loadBuyersInfo()
  230.     local usersBuyers = getAllUsersBought()
  231.     if #usersBuyers > 0 then
  232.         userNameText.text = string.format(localize.last_buyer_mask, usersBuyers[#usersBuyers].user)
  233.         userNameText.hidden = false
  234.         countOfBuyersText.text = string.format(localize.count_buyers_mask, #usersBuyers)
  235.         countOfBuyersText.hidden = false
  236.     else
  237.         userNameText.hidden = true
  238.         countOfBuyersText.hidden = true
  239.     end
  240.     application:draw()
  241. end
  242.  
  243. application.eventHandler = function(workspace, object, ...)
  244.     local args = table.pack(...)
  245.     userNickName = args[6]--get nickname
  246.     return false
  247. end
  248.  
  249. function event.shouldInterrupt()
  250.     return false
  251. end
  252.  
  253. loadBuyersInfo()
  254. application:draw()
  255. application:start()
  256.  
  257.  
Add Comment
Please, Sign In to add comment