Advertisement
VeryPiderast

Untitled

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