Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ---------------------------------------------------------
- -- Программа --
- -- для автоматической ловли рыбы или хлама в Майнкрафт --
- -- на роботе из мода OpenComputers --
- -- Роборыболов v0.1 --
- -- проект http://computercraft.ru --
- -- 2016, © Asior --
- ---------------------------------------------------------
- ----------------БИБЛИОТЕКИ-------------------
- local event = require("event")
- local r = require('robot')
- local computer = require("computer")
- local unicode = require("unicode")
- local fl = require("filesystem")
- local gpu = require("component").gpu
- local term = require("term")
- --------------ПРОЦЕДУРЫ----------------------
- local function toboolean(string)
- return string == "true"
- end
- local function Settings(repetition) --загрузка или перезапись настроек в файл
- if repetition then fl.remove("../etc/Ribolov.cnf") end
- local file = io.open("../etc/Ribolov.cnf", "r")
- if file == nil then
- file = io.open("../etc/Ribolov.cnf", "w")
- file:write('fishing = '..tostring(setting[1])..'\ndrop = '..tostring(setting[2])..'\ndoSearch = '..tostring(setting[3])..'\ncraft = '..tostring(setting[4])..'\ndoRepair = '..tostring(setting[5])..'\n')
- for i = 1, #black_list do
- file:write('bl = '..black_list[i]..'\n')
- end
- else
- local line = file:read()
- while line do
- local arg = string.sub(line, 1, string.find(line, '=')-2)
- --print(arg)os.sleep(0.3)
- if arg == 'fishing' then setting[1] = string.sub(line, #arg+4)
- elseif arg == 'drop' then setting[2] = string.sub(line, #arg+4)
- elseif arg == 'doSearch' then setting[3] = string.sub(line, #arg+4)--поиск
- elseif arg == 'craft' then setting[4] = toboolean(string.sub(line, #arg+4))
- elseif arg == 'doRepair' then setting[5] = toboolean(string.sub(line, #arg+4))--ремонт doRepair
- elseif arg == 'bl' then black_list[#black_list+1] = string.sub(line, #arg+4)
- end
- line = file:read()
- end
- end
- file:close()
- if not Tsetting[2] then --если нету контроллера
- setting[3] = false
- end
- if not (Tsetting[2] and Tsetting[1]) then --если нету контроллера и верстака
- setting[4] = false
- setting[5] = false
- end
- end
- local function componentTesting() --тестирвание и начальная настройка компонентов
- --крафтовый стол, контроллер инвентаря, буфер
- term.clear()
- print('Проверка компонентов робота, подождите...')
- if require("component").isAvailable("redstone") then
- redstone = require("component").redstone
- print('Плата красного камня успешно подключена')
- else
- print("Плата красного камня не обнаружена!\nВы забыли установить плату красного камня, работа без неё невозможна, установите отсутствующее устройство и перезагрузите программу")
- os.exit()
- end
- Tsetting[3] = r.inventorySize()
- if Tsetting[3] == 0 then
- print("Нету инвентаря!\nУстановите апгрейд инвентаря и перезагрузите программу")
- os.exit()
- else
- print("Инвентарь в размере "..Tsetting[3].." слотов обнаружен")
- os.sleep(0.1)
- end
- if require("component").isAvailable("inventory_controller") then
- incontrol = require("component").inventory_controller
- print('Контроллер успешно подключен')
- Tsetting[2] = true
- os.sleep(0.1)
- else
- print("Контроллер не обнаружен!")
- Tsetting[2] = false
- os.sleep(0.5)
- end
- if require("component").isAvailable("crafting") then
- CR = require("component").crafting
- print('Крафтовый верстак успешно подключен')
- Tsetting[1] = true
- os.sleep(0.1)
- else
- print("Крафтовый верстак не обнаружен!")
- Tsetting[1] = false
- os.sleep(0.5)
- end
- setting[1]='Front'
- setting[2]='Down'
- setting[3]=tostring(Tsetting[2])
- setting[4]=tostring(Tsetting[1])
- setting[5]=tostring(Tsetting[1])
- print('Загрузка настроек из файла ...')
- Settings()
- term.clear()
- end
- local function frame(num, leng) --рамка. просто рамка
- if num == 3 then
- gpu.set(10, 5, '┌──────────────────────────────┐')
- for i=1, leng+1 do
- gpu.set(10, i+5, '│ │')
- end
- gpu.set(10, leng+7, '└──────────────────────────────┘')
- return
- end
- gpu.set(1, 1, '╔════════════════════════════════════════════════╗')
- if num == 1 then
- for i=2, 15 do
- gpu.set(1, i, '║ ║')
- end
- gpu.set(1, 3, '╠════════════════════════════════════════════════╣')
- elseif num == 2 then
- frame(1)
- gpu.set(1, 8, '╠════════════════════════════════════════════════╣')
- end
- gpu.set(1, 16, '╚════════════════════════════════════════════════╝')
- end
- function controlKey(num, smL, smR, str, rem) --контроллер клавиатуры со встроенным указателем
- if str == nil then str = 1 end
- if rem == nil then rem = 3 end
- gpu.set(smL, str+rem, " => ")
- gpu.set(50-smR-4, str+rem, " <= ")
- while true do
- local a = {event.pull('key_up')}
- if a[4] == 208 then --v
- if str == num then
- gpu.set(smL, str+rem, " ")
- gpu.set(50-smR-4, str+rem, " ")
- str = 1
- gpu.set(smL, str+rem, " => ")
- gpu.set(50-smR-4, str+rem, " <= ")
- else
- gpu.set(smL, str+rem, " ")
- gpu.set(50-smR-4, str+rem, " ")
- str = str + 1
- gpu.set(smL, str+rem, " => ")
- gpu.set(50-smR-4, str+rem, " <= ")
- end
- elseif a[4] == 200 then --^
- if str == 1 then
- gpu.set(smL, str+rem, " ")
- gpu.set(50-smR-4, str+rem, " ")
- str = num
- gpu.set(smL, str+rem, " => ")
- gpu.set(50-smR-4, str+rem, " <= ")
- else
- gpu.set(smL, str+rem, " ")
- gpu.set(50-smR-4, str+rem, " ")
- str = str - 1
- gpu.set(smL, str+rem, " => ")
- gpu.set(50-smR-4, str+rem, " <= ")
- end
- elseif a[4] == 28 then --
- return str
- elseif a[4] == 205 then -->
- return str, 1
- elseif a[4] == 203 then --<
- return str, -1
- end
- end
- end
- local function printMenu(items, sh, x, y)--выводит на экран список меню. список, центровать или ручное смещение, смещение по Х, начать со строки
- if y == nil then y = 3 end
- local i1 = 2
- if sh then
- gpu.set(math.ceil(25-(unicode.len(items[1])/2)), 2, tostring(items[1]))
- else
- i1 = 1
- end
- for i = i1, #items do
- y = y+1
- if x == nil then
- gpu.set(math.ceil(25-(unicode.len(items[i])/2)), y, tostring(items[i]))
- else
- gpu.set(x, y, tostring(items[i]))
- end
- end
- end
- local function compressionText(text, num, x, y, width, height, display) --текст, страница, начало по Х, Y, ширина, высота, отображение; подгонка текста под рамку
- if x == nil or y == nil then
- x = 2
- y = 3
- width = 47
- height = 12
- gpu.fill(x, 4, width, height, ' ')
- end
- num = (num-1)*width*height
- for i = 1, height do
- if unicode.sub(text, ((i-1)*width)+num, ((i*width)-1)+num) == '' then
- return true, i
- else
- if not display then
- gpu.set(x, i+y, unicode.sub(text, ((i-1)*width)+num, ((i*width)-1)+num))
- end
- end
- end
- if unicode.sub(text, ((height-1)*width)+num, (height*width)-1+num)~='' then
- return false
- end
- end
- local function ScreenBuffer(x1, y1, x2, y2, save) --Буфер экрана. Вырезает кусок экрана, потом возвращает. цвета не учитывает
- if save then
- Buffer = {}
- for i = y1, y2 do
- Buffer[i] = ''
- for i1 = x1, x2 do
- local s = gpu.get(i1, i)
- Buffer[i] = Buffer[i]..s
- end
- end
- gpu.fill(x1, y1, x2-x1, (y2-y1)+1, ' ')
- else
- for i = y1, y2 do
- gpu.set(x1, i, Buffer[i])
- end
- Buffer = {}
- end
- end
- local function confirmation(quest, agr) --вопрос, согласие(ОК) --окно запроса на подтверждение действия
- local uc, uc1, mem, num = -1, 0, ''
- _, num = compressionText(quest, 1, 12, 5, 29, 12, true)
- --mem = math.floor((computer.freeMemory()*100)/computer.totalMemory())..'/' -- вывод информации по памяти
- ScreenBuffer(10, 5, 42, 7+num, true)
- --mem = mem..math.floor((computer.freeMemory()*100)/computer.totalMemory())..' %' --работает невероятно криво. не запускать
- frame(3, num)
- compressionText(quest, 1, 12, 5, 29, num)
- if agr then
- gpu.set(24, num+6, '[ОК]')
- gpu.set(30, num+6, mem)
- else
- gpu.set(15, num+6, '[Да]')
- gpu.set(22, num+6, mem)
- gpu.set(32, num+6, '[Нет]')
- end
- os.sleep(0.1)
- repeat
- if agr then
- _, uc = controlKey(1, -10, -10)
- if uc == nil then
- ScreenBuffer(10, 5, 42, 7+num, false)
- return true
- end
- else
- if uc == -1 then
- gpu.set(28, num+6, ' ')
- uc1 = true
- _, uc = controlKey(1, 11, 50, 1, num+5)
- elseif uc == 1 then
- gpu.set(11, num+6, ' ')
- uc1 = false
- _, uc = controlKey(1, 28, 50, 1, num+5)
- else
- ScreenBuffer(10, 5, 42, 7+num, false)
- return uc1 --1 = да; 0 = нет
- end
- end
- until false
- end
- local function menuSetting() --меню настроек
- local y, y1, p, Set = 1, 1, 1, {}
- setting[6] = ''
- term.clear()
- frame(1)
- local items = {"Настройка", "Сторона ловли: ", "Сторона выгрузки: ", "Автопоиск удочки: ", "Автокрафт: ", "Починка удочек: ", "[Выйти и сохранить]"}
- Set[1] = {[1] = 'Front', [2] = 'Up', [5] = setting[1]}
- Set[2] = {[1] = 'Down', [2] = 'Up', [3] = 'Front', [5]=setting[2]}
- if Tsetting[2] then --проверка на контроллер
- Set[3] = {[1]=true, [2]=false, [5]=tostring(setting[3])}
- else
- Set[3] = {[1]=false, [2]=false, [5]=false}
- end
- for i = 4, 5 do
- if Tsetting[1] and Tsetting[2] then --толку от автокрафта и починки нету если нету контороллера
- Set[i] = {[1]=true, [2]=false, [5]=tostring(setting[i])}
- else
- Set[i] = {[1]=false, [2]=false, [5]=false}
- end
- end
- printMenu(items, true, 4)
- printMenu(setting, false, 24)
- os.sleep(0.1)
- repeat
- y, uc = controlKey(#items-1, -5, 15, y) --строка, боковые клавиши
- if uc ~= nil then
- if y ~= y1 then y1 = y p = 1 end
- p = p+tonumber(uc)
- if p == 0 then --круговой переключатель горизонтальный
- if y == 2 then p = 3
- else p = 2 end
- elseif p == 3 and y ~= 2 then p = 1
- elseif p == 4 and y == 2 then p = 1
- end
- if y ~= 6 then --проверка на выход
- gpu.set(24, y1+3, ' ')
- gpu.set(24, y+3, tostring(Set[y][p]))
- Set[y][5]=Set[y][p] --переменная запись для сохранения настроек
- else
- break
- end
- end
- until uc == nil
- for i=1, 5 do
- setting[i] = Set[i][5]
- --print(setting[i])
- end
- if setting[1] == setting[2] then
- if confirmation('Ошибка! Стороны выгрузки и ловли не могут быть одинаковыми. Желаете исправить?') then
- menuSetting()
- else
- setting[1] = 'Front'
- setting[2] = 'Down'
- Settings(true) --перезапись файла с настройками
- end
- else
- Settings(true) --перезапись файла с настройками
- end
- end
- local function menuHelp() --справка
- term.clear()
- frame(1)
- local items = {"Справка", "Содержание:", " 1.Конфигурация робота", " 2.Сборка робота", " 3.Сборка фермы", " 4.Настройка программы", "[Назад]"}
- local help, y, uc = {}
- help[0] = "Перемещение по меню производится при помощи стрелок [↑] [↓] на клавиатуре, подтверждение выбора - [Enter]. Для перехода на следующую страницу нажмите [→], для возврата [←]. Чтобы вернуться к содержанию, из любого места в тексте, нажмите [Enter]."
- help[1] = "Много текста про 1.Конфигурация робота"
- help[2] = "Много текста про 2.Сборка робота"
- help[3] = "Много текста про 3.Сборка фермы"
- help[4] = "Много текста про 4.Настройка программы"
- printMenu(items, true, 6)
- os.sleep(0.1)
- repeat
- y, uc = controlKey(#items-2, 2, -5, y, 4)
- if uc == nil and y ~= 5 then
- local i, ex = 1, false
- repeat
- if not ex then
- ex = compressionText(help[y], i)
- end
- local y1, uc = controlKey(1, -5, -5, 1)
- if uc == 1 and ex then gpu.set(2, 15, 'Для возврата нажмите [enter]')
- elseif uc == 1 then i = i+1
- elseif uc == -1 and i-1>0 then i = i-1
- elseif y1 == 1 and uc == nil then break end
- until false
- break
- end
- until y == 5 and uc == nil
- if y ~= 5 then menuHelp() end
- end
- local function menuAbout() --о программе
- term.clear()
- frame(1)
- local items = {"О программе"}
- printMenu(items, true)
- compressionText("Программа 'Роборыболов v0.1' создана для игры Minecraft с модом OpenComputers (далее ОС). Она позволяет автоматизировать процесс ловли рыбы при помощи робота из ОС. Разработана для проекта http://computercraft.ru 2016, © Asior", 1)
- os.sleep(0.1)
- controlKey(1, -5, -5, 1)
- end
- local function printCmd(sms, text) --статус строка
- if text ~= nil then
- sms[#sms+1] = text
- end
- while #sms>7 do
- table.remove(sms, 1)
- end
- gpu.fill(2, 9, 47, 7, ' ')
- for i = 1, 7 do
- if sms[i] ~= nil then
- gpu.set(2, 8+i, tostring(unicode.sub(sms[i], 1, 47)))
- end
- end
- return sms
- end
- local function checkingInDatabase(name, cmd) --проверка на наличие предмета в черном списке
- for i = 1, #black_list do
- if name == black_list[i] then
- cmd[#cmd+1] = 'Error object in the database.'
- return cmd
- else
- if i == #black_list then
- black_list[#black_list+1] = name
- cmd[#cmd+1] = 'Import '..black_list[#black_list]
- end
- end
- end
- return cmd
- end
- local function searchMarches(mass) --Поиск повторяющихся элементов в массиве и избавление от них
- print(#mass)
- local elem = mass[1]
- local i1 = 2
- repeat
- i = i1
- while i < #mass do
- if elem == mass[i] then
- print('del '..mass[i])
- table.remove(mass, i)
- else
- i = i+1
- end
- end
- i1 = i1+1
- elem = mass[i1+1]
- until i1 > #mass
- print(#mass)
- os.sleep(2)
- return mass
- end
- local function printList(str, an)
- str = (str*11)-11
- gpu.fill(2, 4, 47, 12, ' ')
- gpu.set(6, 15, '[Назад]')
- for i = 1, 11 do
- if black_list[i+str] ~= nil then
- gpu.set(6, i+3, tostring(unicode.sub(black_list[i+str], 1, 40)))
- end
- end
- if an then
- local list = 1
- while black_list[((list+1)*11)-11] ~= nil do
- list = list+1
- end
- return list
- end
- end
- local function editorDrop() --редактор черного списка
- local y, uc, list, str = 1, 1, 1
- frame(1)
- printMenu({"Редактор черного списка"}, true)
- str = '/'..printList(1, true)
- gpu.set(44, 2, '1'..str)
- os.sleep(0.1)
- repeat
- y, uc = controlKey(12, 2, -5, y)
- if y == 12 and uc == nil then
- break
- end
- if uc == 1 then
- if black_list[((list+1)*11)-11] ~= nil then
- list = list+1
- gpu.set(44, 2, ' '..list..str..' ')
- printList(list)
- end
- elseif uc == -1 then
- if list-1>0 then
- list = list-1
- gpu.set(44, 2, ' '..list..str..' ')
- printList(list)
- end
- else
- if black_list[(list*11)-11+y] ~= nil and confirmation('Вы действительно хотите удалить данный элемент?') then
- table.remove(black_list, (list*11)-11+y)
- printList(list)
- end
- end
- until false
- for i = 1, #black_list do
- if black_list[i] == 'nil' then
- break
- else
- if i == #black_list then
- black_list[#black_list+1] = 'nil'
- end
- end
- end
- end
- local function menuDrop() --меню черного списка
- if not Tsetting[2] then
- confirmation('Отсутствует контроллер инвентаря. Данная опция недоступна', true)
- return
- end
- term.clear()
- frame(2)
- r.select(1)
- local items = {"Черный список дропа", "Добавить из слота: 1", "[Редактировать список]", "[Очистить список]", "[Назад]"}
- local help, y, uc, num = {}, 1, 1, 1
- local cmd = {'Выберите номер слота кнопками [←][→] положите', "туда предмет который робот должен игнорировать", "и нажмите [Enter]. Обратите внимание, предметы", " из некоторых модов могут отображаться некор-", "ректно."}
- printMenu(items, true, 6)
- os.sleep(0.1)
- cmd = printCmd(cmd)
- repeat
- y, uc = controlKey(#items-1, 2, 50, y)
- if y == 1 and uc ~= nil then --выбор слота
- if uc == 1 then
- if num+1>Tsetting[3] then
- num = 0
- gpu.set(25, 4, 'Все')
- else
- num = num+1
- r.select(num)
- gpu.set(25, 4, num..' ')
- end
- elseif uc == -1 then
- if num-1<1 then
- num = Tsetting[3]+1
- gpu.set(25, 4, 'Все')
- else
- num = num-1
- r.select(num)
- gpu.set(25, 4, num..' ')
- end
- end
- elseif y == 1 and uc == nil then --если выбрали 1 пункт
- if num == 0 or num == Tsetting[3]+1 then --прогон всех слотов
- for i = 1, Tsetting[3] do
- if incontrol.getStackInInternalSlot(i) ~= nil then
- cmd = printCmd(checkingInDatabase(incontrol.getStackInInternalSlot(i).name, cmd))
- end
- end
- else
- if incontrol.getStackInInternalSlot(num) ~= nil then
- cmd = printCmd(checkingInDatabase(incontrol.getStackInInternalSlot(num).name, cmd))
- else
- cmd = printCmd(cmd, 'Slot '..num..' is empty')
- end
- end
- elseif y == 2 and uc == nil then
- cmd = printCmd(cmd, 'Запуск редактора ...')
- editorDrop()
- break
- elseif y == 3 and uc == nil then
- if confirmation('Вы действительно хотите ОЧИСТИТЬ СПИСОК?') then
- cmd = printCmd(cmd, "Очищение "..#black_list..' элементов')
- black_list = {'nil'}
- cmd = printCmd(cmd, "Успешно очищено")
- end
- elseif y == #items-1 and uc == nil then
- black_list = searchMarches(black_list)
- Settings(true)
- return
- end
- until false
- r.select(1)
- menuDrop()
- end
- local function printCounter(counter, num) --массив, ячейка; отображение данных счетчика
- for i = 1, #counter do
- if num == nil and i ~= #counter then
- gpu.set(21, i+3,tostring(counter[i])..' ')
- elseif num == i then
- gpu.set(21, i+3,tostring(counter[i])..' ')
- elseif i == #counter then
- gpu.set(2, 15,(" "):rep(29))
- gpu.set(3, 15,tostring(counter[i]))
- end
- end
- end
- local function sideNumber(side) --возвращает номер стороны
- local i = 0
- if side == 'Down' then i=0
- elseif side == 'Up' then i=1
- elseif side == 'Front' then i=3
- end
- return i
- end
- local function useSide(side)
- side = sideNumber(side)
- if side == 1 then r.useUp()
- elseif side == 3 then r.use(0)
- end
- end
- local function dropSide(side, opposite)
- if r.count()>0 and not opposite then
- if side == 0 then return r.dropDown(64)
- elseif side == 1 then return r.dropUp(64)
- elseif side == 3 then return r.drop(64)
- end
- elseif r.count()>0 and opposite then
- if side == 0 then dropSide(1)
- elseif side == 1 then dropSide(0)
- elseif side == 3 then dropSide(1)
- end
- else
- return true
- end
- end
- local function findItem(side, name, dam) --ищет в сундуке удочку, или указанное имя
- if name == nil then name = 'minecraft:fishing_rod' end
- local inv, item = incontrol.getInventorySize(side)
- if inv then
- for slot = 1, inv do
- item = incontrol.getStackInSlot(side, slot)
- if item ~= nil and item.name == name then
- if dam == nil then
- if item.damage <= 55 then
- return slot
- end
- else
- return slot
- end
- end
- end
- end
- return nil
- end
- local function itemDrop(sideInv) --очистка инвентаря
- local vr, vr1 = 0, 0 --для возврата статистики
- for i = 1, Tsetting[3] do
- r.select(i)
- if Tsetting[2] then --если есть контроллер то подключаем черный список
- for i1 = 1, #black_list do
- if incontrol.getStackInSlot(sideInv, i) ~= nil and incontrol.getStackInSlot(sideInv, i).name == black_list[i1] then
- vr1 = vr1 + r.count()
- dropSide(sideInv, true)
- end
- end
- end
- vr = vr + r.count()
- if not dropSide(sideInv) then
- printCounter({'Кажется нет места'})
- r.setLightColor(0xFF0000)
- computer.beep(2000,5)
- os.sleep(5)
- printCounter({'Повторная выгрузка'})
- itemDrop(sideInv)
- break
- end
- end
- r.select(1)
- return vr1, vr
- end
- local function repairsFind(side, c1) --рекурсивный ремонтник удочек, не остановится пока все не починит
- local StatusList, vr = {}, 0
- local inv, item = incontrol.getInventorySize(side)
- for slot = 1, inv do
- item = incontrol.getStackInSlot(side, slot)
- if item ~= nil and item.name == 'minecraft:fishing_rod' and item.damage > 0 then
- StatusList[slot] = item.damage
- --print(slot..' = '..StatusList[slot]..'||'..#StatusList)
- else
- StatusList[slot] = ''
- end
- end
- i=1
- repeat
- if StatusList[i] ~= '' then
- for i1 = i+1, inv-1 do
- if StatusList[i1] ~= '' and (64-StatusList[i]+64-tonumber(StatusList[i1]))+3 <= 64 then
- r.select(1)
- incontrol.suckFromSlot(side, i)
- r.select(2)
- incontrol.suckFromSlot(side, i1)
- CR.craft()
- os.sleep(0.5)
- --print('нашел для ремонта'..i..'||'..i1..' = '..(64-StatusList[i]+64-StatusList[i1])+3)
- itemDrop(side)
- c1 = #StatusList + c1
- StatusList = {}
- break
- end
- end
- end
- i=i+1
- until #StatusList == 0 or i == inv
- if #StatusList == 0 then repairsFind(side, c1) else return c1 end
- end
- local function craftFind(side) --крафт удочки
- local Recipe = {
- '', '', 'minecraft:stick', '',
- '', 'minecraft:stick', 'minecraft:string', '',
- 'minecraft:stick', '', 'minecraft:string', ''}
- for i = 1, #Recipe do
- if Recipe[i] ~= '' then
- local vr = nil
- vr = findItem(side, Recipe[i],0)
- if vr ~= nil then
- r.select(i)
- incontrol.suckFromSlot(side, vr, 1)
- else
- return false
- end
- end
- end
- CR.craft()
- return true
- end
- local function noSignal() --определяем причину отсутствия сигнала от датчика
- if r.durability() == nil then
- printCounter({'Сперли удочку блин'})
- if setting[3] then
- r.select(Tsetting[3])
- slot = findItem(sideNumber(setting[2]))
- if slot then
- incontrol.suckFromSlot(sideInv, vr)
- incontrol.equip()
- else
- printCounter({'Удочка не найдена'})
- end
- r.select(1)
- else
- printCounter({'Удочка сломана совсем.'})
- confirmation('Удочка сломана совсем. Починка невозможна. Дайте новую удочку.', true)
- end
- elseif incontrol and setting[3] then
- r.select(Tsetting[3])
- incontrol.equip()
- if incontrol.getStackInInternalSlot(Tsetting[3]).name == 'minecraft:fishing_rod' then
- printCounter({'Удочка на месте'})
- incontrol.equip()
- r.select(1)
- printCounter({'Нет сигнала от датчика'})
- r.setLightColor(0xFF0000)
- computer.beep(2000, 5)
- os.exit()
- else
- printCounter({'Зачем мне сунули '..incontrol.getStackInInternalSlot(Tsetting[3]).label})
- end
- else
- printCounter({'Нет сигнала от датчика'})
- r.setLightColor(0xFF0000)
- computer.beep(2000, 5)
- os.exit()
- end
- end
- local function repairsReplacementCraft(sideInv)
- local vr, c = nil, {0,0,0,0}
- printCounter({'Очищаю инвентарь'})
- c[3], c[4] = itemDrop(sideInv) --умная очистка
- r.select(Tsetting[3])
- if setting[3] then
- printCounter({'Извлекаю из руки'})
- os.sleep(0.1)
- incontrol.equip()
- vr = findItem(sideInv)
- end
- if setting[5] then
- printCounter({'Запуск ремонта'})
- os.sleep(0.1)
- c[1] = repairsFind(sideInv, c[1]) --ремонт всех удочек
- end
- --1сторона ловли, 2сундук сторона, 3крафт удочек, 4ремонт удочек, 5поиск и замена удочек
- r.select(1)
- os.sleep(0.1)
- if setting[3] and vr~=nil and incontrol.getStackInSlot(sideInv, vr).damage < 55 then --поиск удочки в сундуке и взятие в руку
- r.select(1)
- incontrol.suckFromSlot(sideInv, vr)
- incontrol.equip()
- else
- if setting[4] then --если крафт разрешен
- if craftFind(sideInv) then
- c[2] = repairsReplacementCraft(sideInv)
- else
- itemDrop(sideInv)
- end
- end
- end
- return c
- end
- local function sideDrop(inv, side) --вычисление стороны сброса мусора
- local vr = inv + side
- if vr == 4 then vr = 0
- elseif vr == 3 then vr = 1
- else vr = 3 end
- return vr
- end
- local function menuCatch() --
- frame(1)
- local stat = {'Load ...', 'Инвентарь - '..tostring(Tsetting[3]).." слотов", 'Контроллер - '..tostring(Tsetting[2]), 'Верстак - '..tostring(Tsetting[1]), 'Сторона ловли - '..tostring(setting[1]), 'Сторона сундука - '..tostring(setting[2]),'Поиск и замена удочек - '..tostring(setting[3]), 'Крафт удочек - '..tostring(setting[4]), 'Ремонт удочек - '..tostring(setting[5])}
- for i=1,#stat do
- gpu.set(2,i+3,stat[i])
- os.sleep(0.5)
- end
- os.sleep(4)
- local pic = {'══════════════ #', ' #·', '════════════ # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' #: ·', ' ▒◜◝ ·', ' ▒ ◟◞ ¿', ' ▒', ' ▒ '}
- local rand = {'За miсо!', 'Тсс!', 'А червяки где?', 'Intel рулит!', 'С новым годом!', 'Нееет!', 'Я тут справлюсь', 'Ля-ля-ля', '-рыба', '--|=====>', '---E', 'rm *', 'ЖГИ АНТИГРАВ!!!', 'Бу-га-гашечки!', 'Есть хочешь?', 'Рыбы нету!', 'Я робот-рыболов', 'х(', 'Слава мне!', 'Эээ, руки убрал', 'Тащи динамит!', 'Скууучноооо', 'Ну почему я?', 'asior - roisa', 'o7', 'rosia', 'Hello, moto', 'AMD круче Intel', 'Intel 8080', 'Да ловлю я!', 'БОЛЬШЕ ФОСФОРА!'} --16
- pic[#pic] = pic[#pic]..rand[math.random(#rand)+1]
- local items = {'Роборыболов v0.1', 'Забросил:', 'Вытянул:', 'Вытяну через:', 'Шанс вылова:', 'Ошибок:', 'Отремонтровано:', 'Скрафчено:', 'Выброшено:', 'Сложено:', '=> [Назад]'}
- local con, counter = {}, {0,0,'0 сек','0 %', 0, 0, 0, 0, 0, 'status'}
- local err, c1, c2, c3, c4 = false
- frame(1)
- for i = 1, #pic do
- gpu.set(30, i, pic[i])
- end
- printMenu(items, true,4)
- pic, items, rand, stat = {}, {}, {}, {} --чистим память, её и так мало
- local sideInv = sideNumber(setting[2])
- local drop = sideDrop(sideInv, sideNumber(setting[1]))
- timer = 60
- os.sleep(0.1)
- printCounter(counter)
- repeat
- if not ((r.durability() ~= nil) and (r.durability() >= 0.1) and ((r.count(Tsetting[3]) == 0))) then --если удочка есть и прочность более 0,1 и последний слот пустой
- local c = {0,0,0,0}
- if (r.durability() ~= nil) and (r.durability() <= 0.1) and setting[5] and setting[3] then --если удочка почти сточилась и ремонт разрешен и замена разрешена
- counter[10] = 'Сточилась удочка, меняю'
- printCounter(counter, 7)
- c = repairsReplacementCraft(sideInv)
- elseif r.count(Tsetting[3]) ~= 0 then --если буфер забился
- counter[10] = 'Буфер полный, выгружаю'
- printCounter(counter, 7)
- c[3], c[4] = itemDrop(sideInv)
- elseif r.durability() == nil and setting[3] then --если нету удочки и разрешена замена
- counter[10] = 'Нету удочки'
- printCounter(counter, 7)
- c = repairsReplacementCraft(sideInv)
- end
- counter[6], counter[7], counter[8], counter[9] = tonumber(c[1])+counter[6], tonumber(c[2])+counter[7], tonumber(c[3])+counter[8], tonumber(c[4])+counter[9]
- c = {}
- end
- local tru = 0
- while redstone.getInput(2) + redstone.getInput(1) == 0 do
- r.setLightColor(0xFF0000)
- if tru >= 5 then
- noSignal()
- os.sleep(0.1)
- break
- end
- useSide(setting[1])
- err = true
- tru = tru + 1
- counter[5] = counter[5] + 1
- counter[1] = counter[1] + 1
- printCounter(counter)
- con = {event.pull(2)}
- if con[1] == 'key_up' and con[3] == 13 then
- return
- end
- end
- r.setLightColor(0x00FF00)
- con = {event.pull(1)}
- counter[3] = math.floor(timer)..' сек'
- if con[1] == 'key_up' and con[3] == 13 then
- return
- elseif con[1] == 'redstone_changed' and err then
- useSide(setting[1])
- counter[10] = 'Что-то поймал'
- err = false
- counter[2] = counter[2]+1
- timer = 60
- end
- counter[4] = math.floor((counter[2]*100)/counter[1])..' % '
- printCounter(counter)
- timer = timer - 1
- if timer == 0 then
- err = false
- counter[2] = counter[2]+1
- counter[10] = 'Время вышло, перезакидываю'
- useSide(setting[1])
- timer = 60
- end
- until false
- end
- local function menu() --главное меню
- term.clear()
- frame(1)
- local y = 3
- local items = {"Роборыболов v0.1", "[Ловить рыбу]", "[Настройка]", "[Черный список дропа]", "[Справка]", "[О программе]", "[Выход]"}
- printMenu(items, true)
- os.sleep(0.1)
- y = 1
- repeat
- y, uc = controlKey(#items-1, 10, 10, y)
- if uc == nil then
- if y == 1 then menuCatch(); os.sleep(2) printCounter('Load ...') os.sleep(2) break;
- elseif y == 2 then menuSetting(); break;
- elseif y == 3 then menuDrop(); break;
- elseif y == 4 then menuHelp(); break;
- elseif y == 5 then menuAbout(); break;
- elseif y == 6 then term.clear() os.exit()
- end
- end
- until false
- menu()
- end
- -----------------ОСНОВНОЙ КОД-----------------
- Tsetting = {}--крафтовый стол, контроллер инвентаря, буфер
- setting = {}--1сторона ловли, 2сундук сторона, 3поиск и замена удочек, 4крафт удочек, 5ремонт удочек
- black_list = {}
- Buffer = {}
- term.clear()
- componentTesting()
- menu()
Advertisement
Add Comment
Please, Sign In to add comment