Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --pastebin get -f XVVaPbYL mag.lua && start.lua
- local un = require('unicode')
- local c = require("component")
- local pull_e = require('event').pull
- local com = require("computer")
- local fs = require("filesystem")
- local term = require('term')
- local gpu = c.gpu
- local me = c.me_interface
- local W, H = gpu.getResolution()
- local b_color, f_color = gpu.getBackground(), gpu.getForeground()
- local tr = 0
- local tr_me = 0
- local blackList = {}
- local pim = c.pim
- local red = c.redstone
- local mod = c.modem
- term.clear() term.setCursor(1,1)
- gpu.setResolution(80,25)
- name = ''
- local setting = {0,2,3,'north',4,5}--сундук обмена(тр);сундук сбоев(тр);зарядка rf;сторона пим; зарядка eu; зарядка газа;
- local setting_me = {1,3,'up','2-5'}--сундук обмена(тр);МЭ;сторона куда скидывать из МЭ; коэфициэнт обработки
- local admin = 'Asior'
- local listOre = {}
- local rHi = {'Приветствую', 'Салют', 'Даров', 'Hi', 'Здравствуйте', 'Дай краба', 'Ку', 'Хаюшки'}
- local text = {}
- mod.open(1)
- mod.setWakeMessage('START')
- nameTerm = ...
- local setting_gpu_tr = {24,8}
- local screen = {
- {{ --экран 1 авторизация
- visible = false,
- X = 33,
- Y = 11,
- W = 15,
- H = 1,
- color = 0x005500,
- textColor = 0xffffff,
- text = '[ Авторизация ]',
- action = function()
- if seachBlackList(nameUp) then
- unloadScreen(1)
- loadScreen(3)
- activBottom()
- blockUser()
- unloadScreen(3)
- loadScreen(1)
- activBottom()
- menu0()
- else
- name = nameUp
- logger(name,'Авторизация')
- logger('List_name',tostring(name))
- red.setOutput(0,255)
- unloadScreen(1)
- loadScreen(2)
- activBottom()
- menu1(name)
- end
- end
- },
- {
- visible = false,
- X = 34,
- Y = 13,
- W = 12,
- H = 1,
- color = 0x0000ff, --0x00aa00
- textColor = 0xffffff,
- text = '[ Лицензия ]',
- action = function()
- unloadScreen(1)
- loadScreen(4)
- activBottom()
- menu_L()
- end
- },
- {
- visible = false,
- X = 80,
- Y = 25,
- W = 1,
- H = 1,
- color = 0x000000, --0x00aa00
- textColor = 0xffffff,
- text = '╝',
- action = function()
- if nameUp == admin then
- logger(name,'Выход из программы')
- logger('List_name',tostring(nameUp)..' #########ВЫХОД#########')
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- term.clear()
- com.addUser(admin)
- os.exit()
- end
- end
- }},
- {{ --экран 2 выбор действия
- visible = false,
- X = 31,
- Y = 6,
- W = 19,
- H = 1,
- color = 0x005500,
- textColor = 0xffffff,
- text = '[ Зарядка вещей ]',
- action = function()
- logger(name,'****ЗАРЯДКА****')
- unloadScreen(2)
- loadScreen(3)
- activBottom()
- menu2()
- --os.sleep(3)
- clearCharg(name)
- charg()
- name = ''
- unloadScreen(3)
- loadScreen(1)
- activBottom()
- menu0()
- red.setOutput(0,0)
- end
- },
- {
- visible = false,
- X = 29,
- Y = 8,
- W = un.len('[ Обменник руды '..setting_me[4]..'Х ]'),
- H = 1,
- color = 0x005500, --0x00aa00
- textColor = 0xffffff,
- text = '[ Обменник руды '..setting_me[4]..'Х ]',
- action = function()
- logger(name,'****РУДООБМЕННИК****')
- unloadScreen(2)
- loadScreen(3)
- activBottom()
- menu3()
- ores()
- name = ''
- unloadScreen(3)
- loadScreen(1)
- activBottom()
- menu0()
- red.setOutput(0,0)
- end
- },
- {
- visible = false,
- X = 31,
- Y = 14,
- W = 19,
- H = 1,
- color = 0xff0000,
- textColor = 0xffffff,
- text = '[ Выход ]',
- action = function()
- name = ''
- unloadScreen(2)
- loadScreen(1)
- activBottom()
- menu0()
- red.setOutput(0,0)
- end
- },
- {
- visible = false,
- X = 53,
- Y = 6,
- W = 5,
- H = 1,
- color = 0x005555,
- textColor = 0xffffff,
- text = '[ ? ]',
- action = function()
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- gpu.fill(2, 16, 78, 9, ' ')
- menu1_sp(1)
- end
- },
- {
- visible = false,
- X = 53,
- Y = 8,
- W = 5,
- H = 1,
- color = 0x005555,
- textColor = 0xffffff,
- text = '[ ? ]',
- action = function()
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- gpu.fill(2, 16, 78, 9, ' ')
- menu1_sp(2)
- end
- },
- },
- {{ --экран 3 пустышка для обменников
- visible = false,
- X = 36,
- Y = 18,
- W = 1,
- H = 1,
- color = 0xff0000,
- textColor = 0xffffff,
- text = '[ Выход ]',
- action = function()
- end
- }},
- {{ --экран 4 лицензия
- visible = false,
- X = 37,
- Y = 20,
- W = 7,
- H = 1,
- color = 0xff0000,
- textColor = 0xffffff,
- text = '[ Назад ]',
- action = function()
- name = ''
- unloadScreen(4)
- loadScreen(1)
- activBottom()
- menu0()
- end
- }},
- {{ --экран 5 экран торговли/продажи
- visible = false,
- X = 70,
- Y = 2,
- W = 9,
- H = 1,
- color = 0xff0000,
- textColor = 0xffffff,
- text = '[ Выход ]',
- action = function()
- name = ''
- unloadScreen(5)
- loadScreen(1)
- activBottom()
- red.setOutput(0,0)
- menu0()
- str = 1
- end
- },
- {
- visible = false,
- X = 3,
- Y = 24,
- W = 6,
- H = 1,
- color = 0x005500,
- textColor = 0xffffff,
- text = '[ ◄◄ ]',
- action = function()
- if str - 1 > 0 then
- str = str-1
- end
- tableProduct(str)
- end
- },
- {
- visible = false,
- X = 73,
- Y = 24,
- W = 6,
- H = 1,
- color = 0x005500,
- textColor = 0xffffff,
- text = '[ ►► ]',
- action = function()
- if str + 1 <= math.ceil(#baseT/34) then
- str = str+1
- end
- tableProduct(str)
- end
- },
- {
- visible = false,
- X = 57,
- Y = 2,
- W = 11,
- H = 1,
- color = 0x005555,
- textColor = 0xffffff,
- text = '[ Продажа ]',
- action = function()
- end
- },
- }
- }
- tButtons = {}
- local timezone = 3
- local function getTime() --определение системного времени
- local file = io.open('/tmp/clock.dt', 'w')
- file:write('time')
- file:close()
- local lastmod = fs.lastModified('/tmp/clock.dt')/1000+3600*timezone
- return os.date("%H:%M ", lastmod)
- end
- function logger(nm,sms) --логирование данных
- mod.broadcast(1,tostring(nm), getTime()..' '..nameTerm..' '..sms)
- end
- local function loadBaseBlackList()
- f = io.open('/home/listBlack.csv')
- local line = f:read()
- while line ~= nil do
- if line ~= '/n' then
- local vr = curPhrase(line)
- blackList[#blackList+1] = vr[1]
- end
- line = f:read()
- end
- f:close()
- end
- function seachBlackList(name)
- for i=1, #blackList do
- if blackList[i] == name then
- return true
- end
- end
- return false
- end
- local function readBaseTransposer() --подкгрузка базы транспозеров
- f = io.open('/home/listTransposer.csv')
- local line = f:read()
- local vr = curPhrase(line)
- f:close()
- tr = c.proxy(c.get(vr[1]))
- tr_me = c.proxy(c.get(vr[2]))
- end
- local function gpuSetLine(x,y,text)
- gpu.set(x,y,string.rep(' ', 78-x))
- gpu.set(x,y,tostring(text))
- end
- function blockUser()
- text =
- {'░░░░░░░░░░░░░░║░░░░░░░░░░░░░░░░',
- '░░░░░▄█▀▄░░░░░║░░░░░░▄▀▄▄░░░░░░',
- '░░░░░░░░░▀▄░░░║░░░░▄▀░░░░░░░░░░',
- '░░░░▄▄▄░░░░█▄▄▄▄▄▄█░░░░▄▄▄░░░░░',
- '░░░▀░░░▀█░█▀░░▐▌░░▀█░█▀░░░▀░░░░',
- '░░░░░░░░░██░░▀▐▌▀░░██░░░░░░░░░░',
- '░░░░▄█▀▀▀████████████▀▀▀█░░░░░░',
- '░░░█░░░░░░██████████░░░░░▀▄░░░░',
- '░░░█▄░░░█▀░░▀▀▀▀▀▀░░▀█░░░▄█░░░░',
- '░░░░▀█░░░█░░░░░░░░░░█░░░█▀░░░░░',
- 'Поглядел? Молодец, теперь вали.',
- 'Для тебя магаз закрыт. Читор!',
- 'Активация изъятия вещей через:',}
- for i=1,#text do
- gpuSetLine(28,4+i,text[i])
- end
- for i=8,1,-1 do
- gpuSetLine(28,18,i)
- os.sleep(0.7)
- end
- os.sleep(1)
- gpuSetLine(28,17,'Поверил ?? ахаха!')
- os.sleep(2)
- gpuSetLine(22,18,'В следующий раз поговоришь с турелью')
- os.sleep(3)
- end
- function numer() --отладка
- for i=1,25 do
- gpu.set(1,i,tostring(i))
- end
- end
- local function drawButton(n) -- функция рисования кнопки
- gpu.setBackground(tButtons[n].color) -- задаем цвет кнопки
- gpu.setForeground(tButtons[n].textColor) -- задаем цвет текста
- gpu.fill(tButtons[n].X, tButtons[n].Y, tButtons[n].W, tButtons[n].H, ' ') -- заливаем область
- gpu.set(tButtons[n].X+(tButtons[n].W/2)-(un.len(tButtons[n].text)/2), tButtons[n].Y+(tButtons[n].H/2), tButtons[n].text) -- пишем текст по центру
- end
- function toggleVisible(n) -- переключение видимости кнопки
- if tButtons[n].visible then -- если кнопка видима
- tButtons[n].visible = false -- отключаем
- gpu.setBackground(b_color) -- берем цвет фона, полученный при старте программы
- gpu.fill(tButtons[n].X, tButtons[n].Y, tButtons[n].W, tButtons[n].H, ' ') -- стираем кнопку
- else -- если кнопка не активна
- tButtons[n].visible = true -- активируем
- drawButton(n) -- запускаем отрисовку
- end
- end
- local function blink(n) -- мигание кнопки
- local temp = ''
- for i=tButtons[n].X, tButtons[n].W+tButtons[n].X-1 do
- temp = temp..gpu.get(i,tButtons[n].Y)
- end
- tButtons[n].color, tButtons[n].textColor = tButtons[n].textColor, tButtons[n].color -- меняем местами цвета фона и текста
- drawButton(n) -- отрисовываем кнопку
- os.sleep(0.09) -- делаем задержку
- tButtons[n].color, tButtons[n].textColor = tButtons[n].textColor, tButtons[n].color -- меняем цвета обратно
- drawButton(n) -- перерисовываем кнопку
- gpu.set(tButtons[n].X,tButtons[n].Y,temp)
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- end
- function activBottom() --активатор кнопок
- for i = 1, #tButtons do
- toggleVisible(i) -- активируем каждую кнопку
- end
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- end
- function unloadScreen(num) --деактиватор кнопок
- for i = 1, #tButtons do
- if tButtons[i].visible then
- tButtons[i].visible = false
- end
- end
- end
- local function posCent(num) --рассчет положения в раснении по центру
- return math.ceil(40 - num/2)
- end
- function menu0()
- text = {
- 'Торгово-зарядный аппарат',
- 'Только у нас! Коэфициэнт переработки руды '..setting_me[4]..'Х !',
- 'Для перехода в магазин встаньте на ПИМ и авторизуйтесь'}
- for i=1,#text do
- gpu.set(posCent(un.len(text[i])),1+i,text[i])
- end
- text = {
- 'ВСТАНЬТЕ НА ПИМ',
- ' █▀█ █▀█',
- ' █ █ █ █',
- '▀▄ ▄▀ ▀▄ ▄▀',
- ' ▀ ▀'}
- for i=1,#text do
- gpu.set(60,14+i,text[i])
- end
- text = {
- 'Иногда проходят акции по обмену руды до 1 к 7!',
- 'Если аппарат что-то не вернул обращаться к',
- 'Asior или в дискорд Asior#0138.',
- 'Нажимая кнопку авторизоваться, вы автоматически соглашаетесь с лицензией'}
- for i=1,#text do
- gpu.set(posCent(un.len(text[i])),20+i,text[i])
- end
- end
- function menu1(name)
- vr = rHi[math.random(1,#rHi)]..' '..tostring(name)..' !'
- gpu.set(posCent(un.len(vr)),2, vr)
- gpu.set(posCent(19),4,'Выберите категорию:')
- gpu.set(posCent(46),18,'Не знаете что выбрать? Нажмите на кнопку с "?"')
- end
- function menu1_sp(tupe)
- text = {}
- if tupe == 1 then
- text = {
- 'Зарядка вещей - заряжает любой инструмент работающий на РФ,',
- 'EУ, а так-же Газовые вещи. Омнитулы, винтовки, буры и многое другое!',
- 'Какие вещи можно тут заряжать можно увидеть на стенде у входа.',
- 'Зарядка проходит за 15 сек на электрических вещах и за 80 сек на газовых.',
- 'Время может немного отличаться, в связи с лагами сервера.',
- 'Для зарядки необходимо наступить на панель ПИМ и активировать кнопку зарядки',
- 'НЕ ПОКИДАЙТЕ ПИМ ДО ОКОНЧАНИЯ ЗАРЯДКИ! За это с шансом в 10% вы можете',
- 'получить очень ценный приз! Вплоть до ИРИДИЯ! БЕСПЛАТНО!'}
- elseif tupe == 2 then
- text = {
- 'Обменник руды - уникальная технология обработки всех типов руд. (кроме урана)',
- 'К сожалению данная технология несовершенна, универсальный алгоритм обработки',
- 'сильно сбавляет точность обработки в связи с чем проходят сильные потери.',
- 'Процент обработки руды ~'..setting_me[4]..'Х. Для обработки необходимо встать на ПИМ и',
- 'активировать кнопку. Руда с 1 слота инвентаря будет автоматически извлечена,',
- 'обработана и возвращена вам в виде слитков.',
- 'Убедитесь что у вас достаточно свободного места!'}
- end
- for i=1,#text do
- gpu.set(2,16+i,text[i])
- end
- end
- function menu2()--зарядка оружия
- text = {
- 'Спасибо что выбираете нашу зарядную станцию!',
- 'Для зарядки положите рф инструмент в 1 слот ВАШЕГО ИНВЕНТАРЯ',
- 'и встаньте на кнопку PIM. Инструмент будет автоматически извлечен,',
- 'и по окончании зарядки вернется к вам в 1 слот.',
- 'Длительность РФ/ЕУ зарядки 15 секунд, ГАЗ - 80 секунд',
- 'Пожалуйста не сходите с PIM до окончания зарядки.',}
- for i=1,#text do
- gpu.set(posCent(un.len(text[i])),3+i,text[i])
- end
- end
- function menu_L()
- text = {
- 'Лицензия',
- '1.1 Данный аппарат не контроллируется администрацией сервера',
- '1.2 Используя аппарат, вы автоматически даете разрешение на анализ 1 слота',
- '1.3 При сбое аппарата вы можете подать жалобу его владельцу "Asior"',
- 'по контактам на главном экране.',
- '1.4 Выдача утерянных предметов, если их утеря доказана логами аппарата,',
- 'и скриншотами потерпевшего, производится или по почте (foresty),',
- 'или из рук владельца.',
- '1.5 Если ресурсы автомат выдал не вам, а вашему другу/знакомому/врагу/вору',
- 'вся ответственность лежит на вас. Использовать автомат разрешено только',
- 'одному игроку за сессию.',
- '1.6 Если вы меняете руду на слитки, для дальнейшей продажи в своем магазине,',
- 'вы будете заблокированы владельцем данного обменного автомата. Игроки',
- 'сообщившие о продаже слитков будут награждены.',
- 'Лицензия составлена и закреплена от 25.10.2019. ©Asior'}
- gpu.set(posCent(un.len(text[1])),2,text[1])
- for i=2,#text do
- gpu.set(2,2+i,text[i])
- end
- end
- function menu3()
- text = {
- 'Спасибо что выбираете нашу рудообменную станцию!',
- 'Встаньте на кнопку ПИМ, в 1 слот ВАШЕГО ИНВЕНТАРЯ положите',
- 'руду для обработки. Коэфициэнт переработки '..setting_me[4]..'Х'}
- for i=1,#text do
- gpu.set(posCent(un.len(text[i])),3+i,text[i])
- end
- end
- function curPhrase(line) --вырезка фразы с разделителем
- local tbl = {}
- for part in line:gmatch("[^;]+") do
- table.insert(tbl, part)
- end
- return tbl
- end
- local function readBaseOre() --подкгрузка базы руды
- f = io.open('/home/listOre.csv')
- local line = f:read()
- while line ~= nil do
- if line ~= '/n' then
- local vr = curPhrase(line)
- listOre[#listOre+1] = {['fingerprint']={['dmg'] = tonumber(vr[1]), ['id'] = vr[2]}, ['raw'] = vr[3], ['name'] = vr[4],['kf'] = tonumber(vr[5])}
- end
- line = f:read()
- end
- f:close()
- end
- local function seachNameOre(name) --поисковик
- for i=1,#listOre do
- if listOre[i].raw == name then
- return true, i
- end
- end
- return false
- end
- function resursesME()
- local temp = {'Количество руды для обмена:'}
- local vr = ''
- local all = me.getAvailableItems()
- for i=1, #all do
- for i1=1,#listOre do
- if listOre[i1].name ~= vr then
- if all[i].fingerprint.id==listOre[i1].fingerprint.id and all[i].fingerprint.dmg==listOre[i1].fingerprint.dmg then
- temp[#temp+1] = listOre[i1].name..'.....'..math.floor(all[i].size/listOre[i1].kf)..'...1 к '..listOre[i1].kf
- vr = listOre[i1].name
- end
- end
- end
- end
- for i=1,#temp do
- gpu.set(5,10+i,temp[i])
- end
- end
- local function screenError(text)
- com.beep(1000)
- gpuSetLine(2,2,'ERROR!!!')
- gpuSetLine(2,3,text)
- os.sleep(3)
- end
- local function itemTransfer(tp, mass)
- local err = 0
- local vr = 0
- if tp == 'InventoryImport' then
- repeat
- vr = pim.pushItem(setting[4],1,mass[1])
- err = err+1
- os.sleep(0.2)
- until err > 10 or vr == mass[1] --vr~=0
- logger(name,'Перемещение из инвентаря в обменник: '..tostring(vr))
- if err >= 10 and vr < mass[1] then
- screenError('Не смог забрать из инвентаря предмет')
- return false
- end
- elseif tp == 'ChargImport' then
- repeat
- vr = tr.transferItem(setting[1],mass[1],1)
- err = err+1
- os.sleep(0.2)
- until err > 10 or vr~=nil
- logger(name,'Перемещение из обменника в зарядку типа '..mass[2]..' статус:'..tostring(vr))
- if err >= 10 then
- screenError('Не смог переместить предмет из обменника в зарядку')
- return false
- end
- elseif tp == 'ChargExport' then
- repeat
- vr = tr.transferItem(mass[1],setting[1])
- err = err+1
- until err > 10 or vr~=nil
- logger(name,'Перемещение из зарядки в обменник: '..tostring(vr))
- if err >= 10 then
- screenError('Не смог переместить предмет из зарядки в обменник')
- return false
- end
- elseif tp == 'InventoryExport' then
- for i=1,54 do
- vr = pim.pullItem(setting[4],i)
- if vr>0 then
- logger(name,'Перемещение из обменника слот: '..i..' в инвентарь: '..vr)
- err = err + vr
- end
- end
- --print(err,mass[1],mass[1]-err)
- if err <= mass[1] then
- return false, mass[1]-err
- end
- elseif tp == 'TransferExportMe' then
- vr = tr_me.getStackInSlot(setting_me[1],1).name
- local tbl = {}
- for tmp in string.gmatch(vr,'[o,O]re') do
- table.insert(tbl, tmp)
- end
- if #tbl == 1 then
- repeat
- vr = tr_me.transferItem(setting_me[1],setting_me[2])
- err = err+1
- logger(name,'Перемещение руды из обменника в МЭ: '..tostring(vr))
- until vr == mass[1] or err > 10
- else
- err = 10
- end
- if err >= 10 then
- screenError('Не смог переместить предмет из обменника в МЭ')
- return false
- end
- end
- return true
- end
- function ores()
- local time = 0
- local vr = false
- local temp = {}
- resursesME()
- repeat
- local tEvent = {pull_e(1)} -- ждем клика
- if tEvent[1] == 'touch' or tEvent[1] == 'drop' then
- nameUp = tEvent[6]
- if nameUp == name or name == '' or nameUp == admin then
- for i = 1, #tButtons do -- перебираем все кнопки
- if tButtons[i].visible then -- если кнопка активна
- if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
- blink(i) -- мигнуть кнопкой
- return
- end
- end
- end
- end
- elseif tEvent[1] == 'player_off' then
- blink(1)
- logger(name, 'Ушел с ПИМ')
- return
- else
- if pim.getInventorySize()>0 then
- gpuSetLine(10,8,'Сканирую 1 слот ...')
- if pim.getStackInSlot(1) then
- err, num = seachNameOre(pim.getStackInSlot(1).raw_name)
- if err then
- vr = pim.getInventoryName()
- if vr~='pim' and vr ~= name then
- gpuSetLine(10,8,'Вас слишком много на пим!')
- gpuSetLine(10,9,'Работа с автоматом строго по одному!')
- for i=1,3 do
- com.beep(1500,1)
- end
- logger(name,'Отбой. Много игроков на ПИМ. Сессия: '..name..' Долбаеб: '..vr)
- return
- end
- gpuSetLine(10,8,'Обнаружена руда ...')
- size = pim.getStackInSlot(1).qty
- logger(name,'Руда: '..listOre[num].raw..'; Количество: '..size)
- local all = me.getAvailableItems()
- for i=1, #all do
- if all[i].fingerprint.id==listOre[num].fingerprint.id and all[i].fingerprint.dmg==listOre[num].fingerprint.dmg then
- logger(name,'Найден металл в МЭ')
- if all[i].size >= math.floor(size*listOre[num].kf) then
- logger(name,'Количество металла в МЭ: '..all[i].size)
- if not itemTransfer('InventoryImport', {size}) then
- gpuSetLine(10,8,'ПОПЫТКА ВЗЛОМА!')
- os.sleep(3)
- return
- end
- if not itemTransfer('TransferExportMe', {size}) then
- gpuSetLine(10,8,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
- os.sleep(3)
- return
- end
- size = math.floor(size*listOre[num].kf)
- local sizeTm = size
- repeat
- vr = me.exportItem(all[i].fingerprint, setting_me[3], size)
- logger(name,'Перемещение руды из МЭ в обменник: '..vr.size)
- size = size - vr.size
- until size <= 0
- gpuSetLine(10,8,'Обработка завершена!')
- for i=1,30 do
- gpuSetLine(10,8,'Встаньте на ПИМ для получения слитков')
- gpuSetLine(10,9,'Сброс сессии через '..(30-i)..' сек')
- if pim.getInventorySize()>0 and pim.getInventoryName() == name then
- vr, sizeTm = itemTransfer('InventoryExport', {sizeTm})
- if not vr and sizeTm~=0 then
- gpuSetLine(10,8,'Освободите 1 слот! Не могу выдать вам руду!')
- com.beep(1000)
- else
- gpuSetLine(10,9,'Рудообработка завершена! Спасибо, что выбираете нас!')
- os.sleep(1)
- time = 0
- break
- end
- end
- os.sleep(1)
- end
- logger(name,'Сбой, нет игрока на ПИМ')
- else
- gpuSetLine(10,8,'Металл закончился. Подождите пару минут.')
- end
- end
- end
- else
- gpuSetLine(10,8,'Руда не обнаружена!')
- end
- else
- gpuSetLine(10,8,'Положите в 1 слот руду')
- end
- end
- gpuSetLine(10,9,'Завершение сессии через '..30-time..' сек')
- time = time + 1
- end
- until time > 30
- logger(name,'Отбой. Игрок не наступил на ПИМ')
- return
- end
- local function borders()
- gpu.set(2, 1, string.rep('═', 78))
- gpu.set(2, 25, string.rep('═', 78))
- gpu.set(1, 2, string.rep('║', 23),true)
- gpu.set(80, 2, string.rep('║', 23),true)
- gpu.set(1, 1, '╔')
- gpu.set(80, 1, '╗')
- gpu.set(1, 25, '╚')
- gpu.set(80, 25, '╝')
- end
- function loadScreen(num)
- gpu.setBackground(b_color)
- gpu.setForeground(f_color)
- gpu.fill(1, 1, W, H, ' ')
- tButtons = {}
- tButtons = screen[num]
- borders()
- --numer()
- end
- function clearCharg() --для очистки если че сломалось
- if tr.transferItem(setting[3],setting[2])>0 then
- logger('List_name','Обнуление из зарядки рф')
- end
- if tr.transferItem(setting[5],setting[2])>0 then
- logger('List_name','Обнуление из зарядки еу')
- end
- if tr.transferItem(setting[6],setting[2])>0 then
- logger('List_name','Обнуление из зарядки газа')
- end
- for i=1, 54 do
- if tr.transferItem(setting[1],setting[2],1)>0 then
- logger('List_name','Обнуление из обменника')
- end
- end
- end
- local function seachName(name)
- local rf = {'mo:omni_tool', 'mo:phaser', 'mo:phaser_rifle', 'mo:plasma_shotgun', 'mo:ion_sniper','simplyjetpacks:jetpacks', 'simplyjetpacks:jetpacksEIO', 'Mekanism:FreeRunners'}
- local ic = {'IC2:itemToolDrill', 'IC2:itemToolDDrill', 'IC2:itemToolChainsaw', 'IC2:itemToolWrenchElectric', 'IC2:itemTreetapElectric','IC2:itemArmorJetpackElectric', 'IC2:itemBatRE'}
- local mk = {'Mekanism:Jetpack', 'Mekanism:ArmoredJetpack', 'Mekanism:Flamethrower'}
- for i=1,#rf do
- if rf[i] == name then
- return true, 'rf'
- end
- end
- for i=1,#ic do
- if ic[i] == name then
- return true, 'ic'
- end
- end
- for i=1,#mk do
- if mk[i] == name then
- return true, 'mk'
- end
- end
- return false
- end
- function charg() --зарядка с поиском
- local time = 0
- local vr = false
- repeat
- local tEvent = {pull_e(1)} -- ждем клика
- if tEvent[1] == 'touch' or tEvent[1] == 'drop' then
- nameUp = tEvent[6]
- if nameUp == name or name == '' or nameUp == admin then
- for i = 1, #tButtons do -- перебираем все кнопки
- if tButtons[i].visible then -- если кнопка активна
- if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
- blink(i) -- мигнуть кнопкой
- return
- end
- end
- end
- end
- else
- if pim.getInventorySize()>0 then
- if pim.getStackInSlot(1) then
- item, tupe = seachName(pim.getStackInSlot(1).id)
- if item then
- vr = pim.getInventoryName()
- if vr~='pim' and vr ~= name then
- gpuSetLine(10,14,'Вас слишком много на пим!')
- gpuSetLine(10,15,'Работа с автоматом строго по одному!')
- for i=1,3 do
- com.beep(1500,1)
- end
- logger(name,'Отбой. Много игроков на ПИМ. Сессия: '..name..' Долбаеб: '..vr)
- return
- end
- logger(name,'Обнаружен инструмент: '..pim.getStackInSlot(1).id)
- gpuSetLine(10,14,'Инструмент подходит под тип зарядки')
- if not itemTransfer('InventoryImport', {1}) then
- gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
- os.sleep(3)
- return
- end
- local sl = 15
- local side = setting[1]
- if tupe == 'rf' then
- side = setting[3]
- elseif tupe == 'ic' then
- side = setting[5]
- else
- side = setting[6]
- sl = 80
- end
- if not itemTransfer('ChargImport', {side, tupe}) then
- gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
- os.sleep(3)
- return
- end
- gpuSetLine(10,14,'Выполняется зарядка, оставайтесь на ПИМ')
- for i=1,sl do
- gpuSetLine(10,15,'До окончания зарядки '..sl-i..' сек')
- os.sleep(1)
- end
- if not itemTransfer('ChargExport', {side}) then
- gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
- os.sleep(3)
- return
- end
- for i=1,30 do
- gpuSetLine(10,14,'Встаньте на ПИМ для возврата инструмента')
- gpuSetLine(10,15,'Сброс сессии через '..(30-i)..' сек')
- vr = pim.getInventoryName()
- if vr~='pim' and vr ~= name then
- gpuSetLine(10,14,'Вас слишком много на пим! '..name..', наступите на ПИМ!')
- com.beep(1500,1)
- logger(name,'Попытка перехвата. Сессия: '..name..' Долбаеб: '..vr)
- elseif pim.getInventorySize()>0 and vr == name then
- sizeTm = 1
- vr, sizeTm = itemTransfer('InventoryExport', {sizeTm})
- if not vr and sizeTm~=0 then
- gpuSetLine(10,14,'Освободите 1 слот! Не могу вернуть вам инструмент!')
- com.beep(1000)
- else
- gpuSetLine(10,14,'')
- gpuSetLine(10,15,'Зарядка завершена! Удачи и спасибо, что выбираете нас!')
- os.sleep(3)
- return
- end
- end
- os.sleep(0.7)
- end
- logger(name,'Сбой, нет игрока на ПИМ')
- end
- else
- gpuSetLine(10,14,'В 1 слоте нет инструмента для зарядки')
- end
- else
- gpuSetLine(10,14,'Положите в 1 слот инструмент для зарядки')
- end
- end
- gpuSetLine(10,15,'Завершение сессии через '..30-time..' сек')
- time = time + 1
- until time > 30
- logger(name,'Отбой. Игрок не наступил на ПИМ')
- return
- end
- ------------------------------------------------------
- require("process").info().data.signal = function() end
- if not fs.exists('/log') then
- fs.makeDirectory('/log')
- end
- while com.users() do
- com.removeUser(com.users())
- end
- logger('List_name','######СТАРТ ПРОГРАММЫ#######')
- logger('List_name','######Чтение базы руды######')
- readBaseOre()
- logger('List_name','##Чтение базы транспозеров##')
- readBaseTransposer()
- logger('List_name','##Чтение базы заблоченных###')
- loadBaseBlackList()
- logger('List_name','####Загрузка интерфейса#####')
- str = 1
- trade = 1
- loadScreen(1)
- menu0()
- activBottom()
- name = ''
- local cl = 0
- while true do
- local tEvent = {pull_e(1)} -- ждем клика
- if tEvent[1] == 'modem_message' then
- if tEvent[6] == 'infoDrop' and tEvent[7] == nameTerm then
- local data = tr.getAllStacks(setting[2]).getAll()
- vr = ''
- for i=0,#data do
- if data[i].label then
- vr = vr..'#'..(i+1)..':'..data[i].label..' '
- end
- end
- mod.broadcast(1,'infoDropReturn', nameTerm, vr)
- vr = 0
- data = 0
- elseif tEvent[6] == 'reboot' and tEvent[7] == nameTerm then
- logger('List_name','####Удаленная перезагрузка#####')
- mod.broadcast(1,'rebootReturn', nameTerm)
- com.shutdown(true)
- elseif tEvent[6] == 'PING' and tEvent[7] == nameTerm then
- mod.broadcast(1,'PONG', nameTerm)
- end
- end
- if tEvent[1] == 'player_on' then --нажатие на ПИМ должно сработать как кнопка авторизации
- nameUp = tEvent[2]
- if name == '' then
- blink(1)
- cl = 0
- tButtons[1].action() -- выполнить назначенный код
- end
- end
- if tEvent[1] == 'touch' then
- nameUp = tEvent[6]
- if nameUp == name or name == '' or nameUp == admin then
- for i = 1, #tButtons do -- перебираем все кнопки
- if tButtons[i].visible then -- если кнопка активна
- if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
- blink(i) -- мигнуть кнопкой
- cl = 0
- tButtons[i].action() -- выполнить назначенный код
- break
- end
- end
- end
- end
- else
- cl = cl+1
- if cl > 30 then
- if name~= '' then
- name = ''
- unloadScreen(2)
- loadScreen(1)
- activBottom()
- menu0()
- red.setOutput(0,0)
- end
- cl = 0
- red.setOutput(0,0)
- end
- end
- end
- --all = me.getAvailableItems()
- --me.exportItem(all[1].fingerprint, DIR, 1, rSlot)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement