Advertisement
Noki1111111

shop2.1 prodaja

Sep 14th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 16.97 KB | None | 0 0
  1. --Задается при установке
  2. local shell = require("shell")
  3. local args = shell.parse(...)
  4. local authServerKey = args[1]
  5. local url = args[2]
  6. local port = tonumber(args[3])
  7. local craftNum = tonumber(args[4])
  8. --добавлять отсутствующие в прайсе, но присутствующие в бд предметы в прайс
  9. local smart = true
  10. local serialization = require("serialization")
  11. local component = require("component")
  12. local event = require("event")
  13. local term = require("term")
  14. local unicode = require("unicode")
  15. local gpu = component.gpu
  16. local bg = gpu.getBackground()
  17. local fg = gpu.getForeground()
  18. --Интциализация переменных
  19. local start = true
  20. --Здесь храниться инфа о человеке, который залогинился
  21. local account = {nick="",balance=0,credit=0}
  22. local posScroll = 1
  23. --расстояние авторизации
  24. local rd_from = 1.86
  25. local rd_to = 2.77
  26. --размер улучшения базы данных
  27. local sizeDatabase = 81
  28. --Проверка и инициализация компонентов
  29. local function log(text)
  30.     gpu.fill(1,49,160,2," ")
  31.     gpu.set(2,49,text)
  32. end
  33. function _G.package.loaded.event.shouldInterrupt(...)
  34.     return false
  35. end
  36. function _G.package.loaded.event.shouldSoftInterrupt(...)
  37.     return false
  38. end
  39. function _G.package.loaded.computer.addUser(...)
  40.     return false
  41. end
  42. do
  43.     if component.getPrimary("internet").address~= nil then print("Check inrternet card is ok") else print("Check inrternet card is absent") start = false end
  44.     if component.getPrimary("gpu").address~= nil then print("Check gpu card is ok") else print("Check gpu card is absent") start = false end
  45.     if component.getPrimary("me_interface").address~= nil then print("Check me interface is ok") else print("Check me interface is absent") start = false end
  46.     if component.getPrimary("redstone").address~= nil then print("Check redstone is ok") else print("Check redstone is absent") start = false end
  47.     if component.getPrimary("database").address~= nil then print("Check database is ok") else print("Check database is absent") start = false end
  48. end
  49. --Работа со скриптом
  50. local base = {}
  51. if start then
  52.     local function getFromBD(post)
  53.         log("Ожидание ответа от базы данных")
  54.         local result, response
  55.         local j = 0
  56.         local str =""
  57.         local i,k
  58.         while not result or str == "" do
  59.             if j>10 then os.sleep(60) end
  60.             j = j + 1
  61.             log("Попытка №" .. j .. " соединиться с бд")
  62.             result, response = pcall(component.internet.connect, url, port)
  63.             response.write()
  64.             response.write(post .. '\n')
  65.             i = 0
  66.             k = nil
  67.             while i<10 and k == nil do
  68.                 i = i + 1
  69.                 k = response.read(1024)
  70.             end
  71.             i = 0
  72.             while i<100 and k ~= nil do
  73.                 i = i + 1
  74.                 str = str .. tostring(k)
  75.                 k = response.read(1024)
  76.             end
  77.         end
  78.         return serialization.unserialize(str)
  79.     end
  80.     function base.getAccount(nick)
  81.         return getFromBD("authkey=".. authServerKey .."&bdquery=getac&nick=" .. nick)
  82.     end
  83.     function base.getAccounts()
  84.         return getFromBD("authkey=".. authServerKey .."&bdquery=getacs")
  85.     end
  86.     function base.updAccount(nick,money)
  87.         return getFromBD("authkey=".. authServerKey .."&bdquery=updac&nick=".. nick .."&money=" .. money)
  88.     end
  89.     function base.getPrice(uid)
  90.         return getFromBD("authkey=".. authServerKey .."&bdquery=getpr&uid=" .. uid)
  91.     end
  92.     function base.getPrices()
  93.         return getFromBD("authkey=".. authServerKey .."&bdquery=getprs")
  94.     end
  95.     function base.updPrice(uid,label,buy,sell)
  96.         return getFromBD("authkey=".. authServerKey .."&bdquery=updpr&uid=".. uid .."&label=".. label .."&buy=".. buy .."&sell=".. sell)
  97.     end
  98. end
  99. --Проверяем me_interface, если находит предметы - добавляет в бд
  100. if start then
  101.     log("Проверка мэ интерфейса")
  102.     for i=1,9,1 do
  103.         local record = {}
  104.         slot = component.me_interface.getInterfaceConfiguration(i)
  105.         if slot~=nil then
  106.             print("Add new item in list(" .. slot.label .. ", " .. slot.name .. ").\n Enter label: ")
  107.             record.label = io.read()
  108.             print("Enter buy: ")
  109.             record.buy = io.read()
  110.             print("Enter sell: ")
  111.             record.sell = io.read()
  112.             print("Added: " .. tostring(base.updPrice("{name;*" .. slot.name .. "*,label;*" .. slot.label .. "*,damage;" .. tostring(slot.damage) .. ",hasTag;" .. tostring(slot.hasTag) .. "}", record.label,  record.buy,  record.sell)))
  113.             component.me_interface.setInterfaceConfiguration(i)
  114.         end
  115.         slot = nil
  116.     end
  117. end
  118. --Авторизация игрока на радаре
  119. local player = ""
  120. local lastActive = 0
  121. ----------------------------- добавить авторизацию по модему
  122. --fix io.read() вызвать перед использованием io.read -- event.timer(30,ioreadFix,1)
  123. function ioreadFix( )
  124.     event.push("key_down",component.keyboard.address,13,28)
  125. end  
  126. --Подгрузка price происходит автоматически раз 6 мин
  127. local priceList = {}
  128. local craftList = {}
  129. function loadPrice( )
  130.     if start then
  131.         log("Загрузка прайслиста")
  132.         priceList = base.getPrices()
  133.         for k,v in pairs(priceList) do
  134.             if v.buy==nil then
  135.                 priceList[k] = nil
  136.             end
  137.         end
  138.         local me = component.me_interface.getCraftables()
  139.         local k = {}
  140.         craftList = {}
  141.         for i=1,#me do
  142.             k = me[i].getItemStack()
  143.             if priceList["{name;*" .. k.name .. "*,label;*" .. k.label .. "*,damage;" .. tostring(k.damage) .. ",hasTag;" .. tostring(k.hasTag) .. "}"]~=nil then
  144.                 craftList[#craftList+1] = {}
  145.                 craftList[#craftList].is = k
  146.                 craftList[#craftList].is.size = nil
  147.                 craftList[#craftList].request = me[i].request
  148.             end
  149.         end
  150.     end
  151. end
  152. loadPrice()
  153.  
  154. --Автокрафт
  155. function getSize(name,label,damage,hasTag)
  156.     local msize = 0
  157.     for k,v in pairs(component.me_interface.getItemsInNetwork({["name"]=name,["label"]=label,["damage"]=damage,["hasTag"]=hasTag})) do
  158.         if tonumber(k)~= nil then
  159.             if v.size > msize then msize = v.size end
  160.         end
  161.     end
  162.     return msize
  163. end
  164. local numCraft = 0
  165. local queue = nil
  166. function autocraft( )
  167.     if player=="" then
  168.         if numCraft ==nil or numCraft==#craftList then numCraft=0 end
  169.         log("Проверка списка предметов " .. #craftList)
  170.         if queue~=nil and ( queue.isDone() or queue.isCanceled() ) then log("очередь очищена") queue = nil end
  171.         if queue==nil then  
  172.             numCraft = numCraft + 1
  173.             local pr = getSize(craftList[numCraft].is.name, craftList[numCraft].is.label, craftList[numCraft].is.damage, craftList[numCraft].is.hasTag)
  174.             if  pr~=nil and pr<craftNum then
  175.                 local crnum = craftNum
  176.                 queue = craftList[numCraft].request(crnum)
  177.                 while queue.isCanceled() and crnum>1 do
  178.                     crnum = math.floor(crnum/2)
  179.                     queue = craftList[numCraft].request(crnum)
  180.                 end
  181.             end
  182.         end
  183.         log("поставлен предмет под номером " .. i .. ", " .. craftList[i].is.name .. ", " .. craftList[i].is.label)
  184.     end
  185. end
  186. if _G.package.loaded.autocraft==nil then
  187.     _G.package.loaded.autocraft=true
  188.     event.timer(10, autocraft, math.huge)
  189. end
  190. --Фикс монитора
  191. function ScreenFix()
  192.     component.gpu.bind(component.screen.address,true)
  193. end
  194. event.timer(10,ScreenFix,math.huge)
  195. --Окно соглашения
  196. function drawBorder(x,y,width,height)
  197.         width = width - 1
  198.         height = height - 1
  199.         gpu.fill(x+1        ,y          ,width  ,1          ,unicode.char(10249))
  200.         gpu.fill(x          ,y          ,1      ,1          ,unicode.char(10319))
  201.         gpu.fill(x+1+width  ,y          ,1      ,1          ,unicode.char(10425))
  202.         gpu.fill(x          ,y+1        ,1      ,height     ,unicode.char(10311))
  203.         gpu.fill(x+1+width  ,y+1        ,1      ,height     ,unicode.char(10424))
  204.         gpu.fill(x+1        ,y+1+height ,width  ,1          ,unicode.char(10432))
  205.         gpu.fill(x          ,y+1+height ,1      ,1          ,unicode.char(10439))
  206.         gpu.fill(x+1+width  ,y+1+height ,1      ,1          ,unicode.char(10488))
  207. end
  208. function interfaceIsEmpty()
  209.     for i = 1,9,1 do
  210.         if component.me_interface.getInterfaceConfiguration(i) ~= nil then return false end
  211.     end
  212.     return true
  213. end
  214. function redstone(bool)
  215.     local output = 0
  216.     if bool then output = 15 end
  217.     for i=0,5,1 do component.redstone.setOutput(i,output) end
  218. end
  219. function acceptable(kPrice,vPrice)
  220.     log("Формирование заказа")
  221.     gpu.setBackground(0x301945)
  222.     term.clear()
  223.     gpu.setForeground(0xb3bd57)
  224.     gpu.set(70,2,"Формирование заказа ...")
  225.     drawBorder(69,1,24,2)
  226.     gpu.set(5,10,"Ваш заказ:   " .. vPrice.label)
  227.     gpu.set(10,12,"Цена за 1 штуку: " .. vPrice.buy)
  228.     local maxSize = 0
  229.     local inME = component.me_interface.getItemsInNetwork(serialization.unserialize(kPrice:gsub(";","="):gsub("*","\'")))[1]
  230.     if inME~=nil then maxSize = inME.maxSize inME = inME.size end
  231.     if inME==nil then inME = 0 end
  232.     gpu.set(10,13,"В МЭ храниться: " .. inME)
  233.     gpu.set(10,14,"Выбранное количетсво(нажмите, чтобы ввести): 0")
  234.     gpu.set(20,46,"Купить выбранное")
  235.     drawBorder(19,44,17,4)
  236.     gpu.set(120,46,"Отменить")
  237.     drawBorder(119,44,9,4)
  238.     local amount = 0
  239.     local cancel = false
  240.     while not cancel and lastActive>0 do
  241.         _,_,x,y,_,name = event.pull(5,"touch")
  242.         if name~=nil then
  243.             lastActive = 30
  244.             if player ~= name then cancel = true end
  245.         else
  246.             lastActive = lastActive - 5  
  247.         end
  248.         if account.nick ~= player then cancel = true end
  249.         if name~=nil and player == name and not cancel then
  250.             if account.credit~=0 then
  251.                 cancel = true
  252.             end
  253.             if not cancel and 119<=x and x<=130 and 44<=y and y<=48 then cancel = true log("отмена") end
  254.             if not cancel and 55<=x and x<=130 and 13<=y and y<=15 then
  255.                 log("Выбор количетсва")
  256.                 term.setCursor(55,14)
  257.                 ioread=true
  258.                 local _,txt = pcall(io.read)
  259.                 if txt==nil then txt = "" end
  260.                 amount = tonumber(txt)
  261.                 gpu.setBackground(0x301945)
  262.                 gpu.setForeground(0xb3bd57)
  263.                 term.clear()
  264.                 gpu.set(70,2,"Формирование заказа ...")
  265.                 drawBorder(69,1,24,2)
  266.                 gpu.set(5,10,"Ваш заказ:   " .. vPrice.label)
  267.                 gpu.set(10,12,"Цена за 1 штуку: " .. vPrice.buy)
  268.                 maxSize = 0
  269.                 inME = component.me_interface.getItemsInNetwork(serialization.unserialize(kPrice:gsub(";","="):gsub("*","\'")))[1]
  270.                 if inME~=nil then maxSize = inME.maxSize inME = inME.size end
  271.                 if inME==nil then inME = 0 end
  272.                 gpu.set(10,13,"В МЭ храниться: " .. inME)
  273.                 gpu.set(10,14,"Выбранное количетсво(нажмите, чтобы ввести): 0")
  274.                 gpu.set(20,46,"Купить выбранное")
  275.                 drawBorder(19,44,17,4)
  276.                 gpu.set(120,46,"Отменить")
  277.                 drawBorder(119,44,9,4)
  278.                 if amount == nil then amount = 0 end
  279.                 if amount<0 then amount = 0 end
  280.                 if account.balance*2 < vPrice.buy*amount then
  281.                     amount = math.floor(account.balance*2 / vPrice.buy)
  282.                 end
  283.                 if amount>inME then amount = inME end
  284.                 if amount>maxSize*9 then amount = maxSize*9 end
  285.                 gpu.fill(55,14,106,1," ")
  286.                 gpu.set(55,14,"" .. amount)
  287.             end
  288.             if not cancel and 19<=x and x<=36 and 44<=y and y<=48 then
  289.                 local i = 0
  290.                 local amt = 0
  291.                 base.updAccount(account.nick,-vPrice.buy*amount)
  292.                 account = base.getAccount(player)
  293.                 while i<9 and amount>0 do
  294.                     i = i+1
  295.                     if amount<maxSize then
  296.                         amt = amount
  297.                         amount = 0
  298.                     else
  299.                         amt = maxSize
  300.                         amount = amount - amt
  301.                     end
  302.                     component.database.clear(1)
  303.                     component.me_interface.store(serialization.unserialize(kPrice:gsub(";","="):gsub("*","\'")),component.database.address,1)
  304.                     component.me_interface.setInterfaceConfiguration(i,component.database.address,1,amt)
  305.                 end
  306.                 redstone(true)
  307.                 for i=1,9,1 do component.me_interface.setInterfaceConfiguration(i) end
  308.                 os.sleep(1)
  309.                 redstone(false)
  310.                 cancel = true
  311.             end
  312.         else if lastActive==0 then cancel = true  end
  313.         end
  314.     end
  315.     gpu.setBackground(bg)
  316.     gpu.setForeground(fg)
  317. end
  318. function drawHeader()
  319.     if account==nil then account = {} end
  320.     if account.nick==nil or account.balance==nil or account.credit == nil then account.nick=""  account.balance=0  account.credit =0 end
  321.     gpu.setBackground(0x301945)
  322.     gpu.setForeground(0xb3bd57)
  323.     gpu.fill(1,2,160,1," ")
  324.     drawBorder(0,1,161,2)
  325.     gpu.set(1,2,"Аккаунт:")
  326.     gpu.set(9,2,account.nick)
  327.     gpu.set(30,2,"Баланс:")
  328.     gpu.set(38,2,account.balance .. "")
  329.     gpu.set(55,2,"Задолженность:")
  330.     gpu.set(70,2,account.credit .. "")
  331.     gpu.set(85,2,"Поиск:")
  332.     gpu.fill(92,2,69,1,"_")
  333.     gpu.setBackground(bg)
  334.     gpu.setForeground(fg)
  335. end
  336. function drawScroll()
  337.     gpu.setBackground(0x6a0d73)
  338.     gpu.setForeground(0xe5df25)
  339.     gpu.fill(158,4,3,22," ")
  340.     gpu.fill(159,5,1,1,unicode.char(9650))
  341.     gpu.setBackground(0x730d37)
  342.     gpu.fill(158,26,3,22," ")
  343.     gpu.fill(159,46,1,1,unicode.char(9660))
  344.     gpu.setBackground(bg)
  345.     gpu.setForeground(fg)
  346. end
  347. function drawBody()
  348.     gpu.setBackground(0x301945)
  349.     gpu.fill(1,8,157,40," ")
  350.     gpu.setBackground(0x421f63)
  351.     gpu.setForeground(0xe5df25)
  352.     gpu.fill(1,4,157,4," ")
  353.     gpu.fill(1,12,157,4," ")
  354.     gpu.fill(1,20,157,4," ")
  355.     gpu.fill(1,28,157,4," ")
  356.     gpu.fill(1,36,157,4," ")
  357.     gpu.fill(1,44,157,4," ")
  358.     gpu.setBackground(bg)
  359.     gpu.setForeground(fg)
  360. end
  361. function drawItemList(price)
  362.     local i = 0
  363.     gpu.setForeground(0xe5df25)
  364.     for k,v in pairs(price) do
  365.         i = i + 1
  366.         if posScroll<=i and i<=posScroll+10 then
  367.             if ((posScroll+1)%2+i)%2==1 then
  368.                 gpu.setBackground(0x421f63)
  369.             else
  370.                 gpu.setBackground(0x301945)
  371.             end
  372.             gpu.set(3, 4 + 4 * (i - posScroll), "Предмет:      " .. v.label)
  373.             gpu.set(3, 6 + 4 * (i - posScroll), "Цена продажи: " .. v.buy)
  374.         end
  375.  
  376.     end
  377.     gpu.setBackground(bg)
  378.     gpu.setForeground(fg)
  379. end
  380. function starting( )
  381.     start = false
  382.     local fprice = {}
  383.     local filtered = false
  384.     local prices = {}
  385.     while true do
  386.         log("Стартуем!")
  387.         filtered = false
  388.         drawHeader()
  389.         if player~="" and lastActive>0 then
  390.             term.clear()
  391.             drawHeader()
  392.             drawScroll()
  393.             drawBody()
  394.             drawItemList(priceList)
  395.             while lastActive>0 do
  396.                 log("Ожидание дейcтвий пользователя")
  397.                 local _,_,x,y,_,name = event.pull(5,"touch")
  398.                 if name~=nil then
  399.                     lastActive = 30
  400.                     player = name
  401.                 else
  402.                     lastActive = lastActive - 5  
  403.                 end
  404.                 if account.nick ~= player then account = base.getAccount(player) drawHeader() end
  405.                 if x~=nil and y~=nil and name~=nil then
  406.                     if filtered then
  407.                         prices = fprice
  408.                     else
  409.                         prices = priceList
  410.                     end
  411.                      --скрол
  412.                     if 157<=x and x<=160 and 4<=y and y<=25 then posScroll = posScroll - 1 if posScroll <1 then posScroll = 1 end drawBody() drawItemList(prices) end
  413.                     if 157<=x and x<=160 and 26<=y and y<=47 then posScroll = posScroll + 1 if posScroll >78 then posScroll = 1 end drawBody() drawItemList(prices) end
  414.                     --Поиск
  415.                     if 92<=x and x<=160 and 1<=y and y<=3 then
  416.                         drawHeader()
  417.                         posScroll = 1
  418.                         term.setCursor(92,2)
  419.                         ioread=true
  420.                         local _,filter = pcall(io.read)
  421.                         if filter==nil then filter = "" end
  422.                         if #filter>200 then
  423.                             drawHeader()
  424.                             drawScroll()
  425.                         end
  426.                         fprice = {}
  427.                         local pr = true
  428.                         if filter == "" then pr = false end
  429.                         if pr then
  430.                             pr = false
  431.                             for k,v in pairs(priceList) do
  432.                                 if v.label:lower():find(filter:lower())~=nil then
  433.                                     pr = true
  434.                                     fprice[k] = v
  435.                                 end
  436.                             end
  437.                         end
  438.                         if pr then
  439.                             drawBody()
  440.                             posScroll = 1
  441.                             drawItemList(fprice)
  442.                             filtered = true
  443.                         else
  444.                             drawBody()
  445.                             posScroll = 1
  446.                             drawItemList(priceList)
  447.                             filtered = false
  448.                         end
  449.                     end
  450.                     --Выбор
  451.                     if 1<=x and x<=156 and 4<=y and y<=47 then
  452.                         local i = 0
  453.                         for k,v in pairs(prices) do
  454.                             i = i + 1
  455.                             if i == (posScroll + math.floor((y-4)/4)) then
  456.                                 pcall(acceptable,k,v)
  457.                                 term.clear()
  458.                                 drawHeader()
  459.                                 drawScroll()
  460.                                 drawBody()
  461.                                 posScroll = 1
  462.                                 drawItemList(priceList)
  463.                                 filtered = false
  464.                                 if account.credit~=0 then
  465.                                     log("Погаси задолженность " .. account.nick .. "!")
  466.                                     os.sleep(2)
  467.                                 end
  468.                             end
  469.                         end
  470.                     end
  471.                 end
  472.             end
  473.         else
  474.             gpu.setBackground(0x421f63)
  475.             gpu.setForeground(0xe5df25)
  476.             term.clear()
  477.             gpu.set(25,25,"Для авторизации коснитесь экрана")
  478.             lastActive = 0
  479.             player = ""
  480.             posScroll = 1
  481.             account = {nick="",balance=0,credit=0}
  482.             _,_,_,_,_,player = event.pull("touch")
  483.             account = base.getAccount(player)
  484.             lastActive = 30
  485.             gpu.setBackground(bg)
  486.             gpu.setForeground(fg)
  487.         end
  488.     end
  489. end
  490. while true do pcall(starting) end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement