Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[ opencomputers карьер by serafim
- pastebin.com/V16CNBz3 update 13.06.21
- Без замены инструмента для не ломаемой кирки !!!
- Копает змейкой квадрат проходя три слоя блоков за один подход,
- пока не выкопает весь объём до бэдрока или не упрётся в
- не разрушаемый блок, при этом вернётся к старту и сообщит о проблеме,
- также предложит продолжить копать с последней позиции.
- требования:
- инвентарь, контроллер инвентаря, генератор, улучшение парение.
- пример сборки:
- https://i.imgur.com/fR7F4fA.png
- использование:
- на старте, сзади робота поставить сундук, уголь больше 20 штук.
- Робот может работать без сундука и всего прочего, нужна только кирка.
- пример запуска: (по умолчанию один чанк)
- quarry 16 16 2 или quarry
- -- 2 опустится в низ на 2 блока от старта.
- получить список предметов:
- https://pastebin.com/au9etcfF
- ]]--
- local a = {...}
- local width = tonumber(a[1]) or 16 --ширина
- local length = tonumber(a[2]) or 16 --длина
- local down = tonumber(a[3]) or 2 --опустится в низ
- --список мусора
- local scrap = {
- "cobblestone", --булыжник
- "stone", --камень
- "dirt", --земля
- "gravel", --гравий
- "flint", --кремень
- "sand", --песок
- "sandstone" --песчаник
- }
- local event = require("event")
- local com = require('component')
- local computer = require("computer")
- local cheststart,fuelchest,fuelinv,refuel = true,true,true,true
- local depth,xPos,zPos,xDir,zDir = 0,0,0,0,1
- local ridht,bedrock,unloaded = true,false,0
- local timestart = computer.uptime()
- local x,y,z,xd,zd
- if not com.isAvailable("robot") then
- print("только роботы могут использовать эту программу")
- os.exit()
- end
- local r = require("robot")
- local invsize = r.inventorySize()
- local coal = invsize
- local tools = invsize-1
- if not com.isAvailable("inventory_controller") then
- print("нет контроллера инвентаря")
- os.exit()
- end
- local i_c = com.inventory_controller
- if not com.isAvailable("generator") then
- print("нет генератора")
- os.exit()
- end
- local gen = com.generator
- --статус
- local function status(message)
- print("[ "..os.date("%H:%M:%S",computer.uptime()-timestart).." ] "..message)
- end
- --чанк лоадер
- local function chunkload(state)
- if com.isAvailable("chunkloader") then
- if state then
- com.chunkloader.setActive(true)
- print("чанк лоадер активен")
- else
- com.chunkloader.setActive(false)
- print("чанк лоадер деактивирован".."\n")
- end
- end
- end
- --поиск предмета в инвентаре робота
- local function slotitem(slot, list)
- local item = i_c.getStackInInternalSlot(slot)
- if item then
- for j, name in pairs(list) do
- if string.find(item.name,name) then
- if item.charge == nil or item.charge/item.maxCharge > toolstrength then
- return true
- end
- end
- end
- end
- for i = 1,invsize do
- if r.count(i) > 0 then
- for j, name in pairs(list) do
- local item = i_c.getStackInInternalSlot(i)
- if item and string.find(item.name,name) then
- r.select(i)
- r.transferTo(slot)
- return true
- end
- end
- end
- end
- return false
- end
- --взять из сундука расходники
- local function servise(slotinv, list)
- local inv = i_c.getInventorySize(3)
- if inv then
- if slotitem(slotinv, list) then
- return true
- end
- r.select(slotinv)
- if r.count(slotinv) > 0 and not r.drop() then
- returnHome("в сундуке нет места")
- return false
- end
- for slot = 1,inv do
- for j, name in pairs(list) do
- local item = i_c.getStackInSlot(3,slot)
- if item and string.find(item.name,name) then
- i_c.suckFromSlot(3, slot)
- return true
- end
- end
- end
- return false
- else
- returnHome("нет сундука")
- end
- end
- --заряжаемся от зарядчика
- local function charging()
- local chardg = true
- while true do
- local e1 = computer.energy()
- os.sleep(2)
- local e2 = computer.energy()
- if e2 > e1 + 500 then
- if chardg then
- chardg = false
- status("заряжаюсь...")
- end
- os.sleep(2)
- else
- break
- end
- end
- end
- --сортируем лут
- local function sortlut(droplut)
- status("сортирую лут...")
- r.swingDown()
- for i = 1,invsize do
- if r.count(i) > 0 then
- local item = i_c.getStackInInternalSlot(i)
- if string.find(item.name,"coal") then
- r.select(i)
- r.transferTo(coal)
- else
- for n = 1,#scrap do
- if scrap[n] == item.name:gsub('%g+:','') then
- r.select(i)
- r.dropDown()
- break
- end
- end
- end
- end
- end
- for i = 1,invsize-1 do
- if r.count(i) == 0 then
- for j = invsize-1,1,-1 do
- if r.count(j) > 0 then
- if j < i then
- break
- end
- r.select(j)
- r.transferTo(i)
- break
- end
- end
- end
- end
- local unload = function()
- local inv = i_c.getInventorySize(3)
- if inv then
- cheststart = true
- for i = 1,invsize-1 do
- if r.count(i) > 0 then
- r.select(i)
- unloaded = unloaded + r.count(i)
- if not r.drop() then
- returnHome("в сундуке нет места")
- return
- end
- end
- end
- r.select(coal)
- gen.insert()
- servise(coal, {"coal"})
- charging()
- elseif not cheststart then
- returnHome("инвентарь заполнен")
- else
- returnHome("нет сундука")
- end
- fuelchest = true
- status("всего добыто руды: "..unloaded)
- end
- if r.count(invsize-6) > 0 then
- status("возвращаюсь к сундуку сложить лут")
- x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
- goTo( 0,0,0,0,-1 )
- unload()
- goTo( x,y,z,xd,zd )
- end
- if droplut and cheststart then
- unload()
- end
- r.select(1)
- end
- --стоп
- local function stop(message)
- print("\n".."!!! стоп !!!".."\n"..message.."\n")
- r.setLightColor(0xFF0000)
- r.turnAround()
- chunkload(false)
- computer.beep(1000, 1)
- status("программа завершена")
- os.exit()
- end
- --возврат к старту
- function returnHome(message, save)
- r.setLightColor(0xFF0000)
- if save then
- x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
- end
- if y ~= nil then
- print("последняя ширина "..width..", длина "..length..", глубина "..y)
- end
- goTo( 0,0,0,0,-1 )
- if save and cheststart and r.count(1) > 0 then
- sortlut(true)
- end
- goTo( 0,0,0,0,1 )
- status("!!! стоп !!!".."\n"..message.."\n")
- chunkload(false)
- print("продолжить копать ? [Y/n]")
- while true do
- r.setLightColor(0xFFFFFF)
- computer.beep(1000, 1)
- r.setLightColor(0xFF0000)
- local e = ({event.pull(10,"key_down")})[4]
- if e == 49 then
- computer.beep(500, 0.1)
- print("программа завершена")
- os.exit()
- elseif e == 21 or e == 28 then
- computer.beep(500, 0.1)
- r.setLightColor(0xFFFFFF)
- print("продолжаю копать...")
- chunkload(true)
- goTo( x,y,z,xd,zd )
- break
- end
- end
- end
- --дозаправка углём
- local function checkfuel()
- if computer.energy() <= 6000 then
- refuel = true
- end
- if gen.count() <= 10 and refuel then
- for i = 1,invsize do
- local item = i_c.getStackInInternalSlot(i)
- if item and string.find(item.name,"coal") then
- r.select(i)
- r.transferTo(coal)
- end
- end
- r.select(coal)
- if gen.insert() then
- fuelinv = true
- status("заправился, угля в генераторе = "..gen.count())
- elseif fuelchest and cheststart then
- x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
- status("возвращаюсь к сундуку за углем")
- goTo( 0,0,0,0,-1 )
- if servise(coal, {"coal"}) then
- r.select(coal)
- gen.insert()
- status("заправился, угля в генераторе = "..gen.count())
- else
- fuelchest = false
- status("в сундуке нет угля")
- end
- charging()
- goTo( x,y,z,xd,zd )
- else
- refuel = false
- if fuelinv then
- fuelinv = false
- status("нет угля в инвентаре робота !!!")
- end
- end
- r.select(1)
- end
- if computer.energy() <= 5000 then
- x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
- status("энергии < 5 000 возвращаюсь")
- goTo( 0,0,0,0,1 )
- charging()
- if computer.energy() >= 10000 then
- status("зарядился :)")
- goTo( x,y,z,xd,zd )
- return
- elseif gen.count() >= 10 then
- status("мало энергии, заряжаюсь до 10 000")
- while true do
- os.sleep(10)
- if computer.energy() >= 10000 then
- status("зарядился :)")
- goTo( x,y,z,xd,zd )
- break
- elseif gen.count() == 0 then
- returnHome("закончился уголь")
- break
- end
- end
- else
- returnHome("закончился уголь")
- end
- end
- end
- --движение в сторону side
- local function robotMove(side)
- while true do
- local ok,reason = com.robot.move(side)
- if ok then
- return true
- elseif reason and reason == "already moving" then
- os.sleep(0.1)
- else
- return false,reason
- end
- end
- end
- --идём по Х в 0 координат
- local function x_forward()
- for xx = 1,width-1 do
- while true do
- if robotMove(3) then
- xPos = xPos - 1
- break
- else
- r.swing()
- end
- end
- end
- end
- --движемся в верх
- local function tryUp()
- local tru = 0
- while true do
- if robotMove(1) then
- depth = depth - 1
- break
- else
- r.swingUp()
- end
- tru = tru + 1
- if tru >= 7 then
- tru = 0
- returnHome("не могу подняться",true)
- end
- end
- end
- --обнаружение бедрока
- local function checkbedrock()
- for i = 1,3 do
- if r.detectDown() and not r.swingDown() then
- if bedrock then
- break
- elseif i == 3 then
- status("низ достигнут !")
- bedrock = true
- if y ~= nil then
- status("глубина "..y)
- end
- end
- else
- break
- end
- end
- end
- --копаем и движемся вперед
- local function digForward()
- r.swingUp()
- r.swing()
- checkbedrock()
- if r.count(invsize-2) > 0 then
- sortlut()
- end
- local tru,reason = 0
- while true do
- if r.detect() then
- _,reason = r.swing()
- else
- ok,reason = robotMove(3)
- if ok then
- xPos = xPos + xDir
- zPos = zPos + zDir
- break
- end
- end
- tru = tru + 1
- if tru == 4 or tru == 5 then
- if bedrock then
- tryUp()
- end
- elseif tru >= 20 then
- if reason then
- print("причина возврата: "..reason)
- end
- tru = 0
- returnHome("непреодолимое препятствие",true)
- end
- end
- end
- --спускаемся в низ
- local function go_down()
- for zz = 1,down do
- while true do
- checkbedrock()
- if robotMove(0) then
- depth = depth + 1
- break
- elseif bedrock then
- while true do
- r.swing()
- if r.detect() then
- tryUp()
- else
- return
- end
- end
- end
- end
- end
- end
- --поворот в лево
- local function turnLeft()
- while not r.turnLeft() do
- os.sleep(0.1)
- end
- xDir, zDir = -zDir, xDir
- end
- --поворот в право
- local function turnRight()
- while not r.turnRight() do
- os.sleep(0.1)
- end
- xDir, zDir = zDir, -xDir
- end
- --навигация к сундуку
- function goTo( x,y,z,xd,zd )
- local Xposition = function()
- if xPos > x then
- while xDir ~= -1 do
- turnLeft()
- end
- while xPos > x do
- if robotMove(3) then
- xPos = xPos - 1
- else
- r.swing()
- end
- end
- elseif xPos < x then
- while xDir ~= 1 do
- turnRight()
- end
- while xPos < x do
- if robotMove(3) then
- xPos = xPos + 1
- else
- r.swing()
- end
- end
- end
- end
- local Zposition = function()
- if zPos > z then
- while zDir ~= -1 do
- turnLeft()
- end
- while zPos > z do
- if robotMove(3) then
- zPos = zPos - 1
- else
- r.swing()
- end
- end
- elseif zPos < z then
- while zDir ~= 1 do
- turnRight()
- end
- while zPos < z do
- if robotMove(3) then
- zPos = zPos + 1
- else
- r.swing()
- end
- end
- end
- end
- r.select(1)
- while depth < y do
- while xDir ~= 0 or zDir ~= 1 do
- turnRight()
- end
- if robotMove(0) then
- depth = depth + 1
- else
- r.swingDown()
- end
- end
- if y > 0 then
- Zposition()
- Xposition()
- else
- Xposition()
- Zposition()
- end
- while depth > y do
- if robotMove(1) then
- depth = depth - 1
- else
- r.swingUp()
- end
- end
- while xDir ~= xd or zDir ~= zd do
- turnRight()
- end
- end
- --копаем
- local function dig()
- os.execute("cls")
- print("Только для для не ломаемой кирки".."\n")
- print("размер карьера: ширина "..width.." длина "..length)
- print("угля в генераторе = "..gen.count())
- print("энергии = "..math.floor(100*computer.energy()/computer.maxEnergy()).." %")
- print("подготовка...")
- goTo( 0,0,0,0,-1 )
- for slot = 1,invsize do
- if r.count(slot) == 0 then
- r.select(slot)
- i_c.equip()
- break
- end
- if slot == invsize then
- stop("в инвентаре робота нет пустых слотов")
- end
- end
- local inv = i_c.getInventorySize(3)
- if inv then
- cheststart = true
- print("доступен сундук")
- if servise(coal, {"coal"}) then
- r.select(coal)
- if gen.insert() then
- print("заправился, угля в генераторе = "..gen.count())
- servise(coal, {"coal"})
- end
- else
- fuelchest = false
- end
- if servise(tools, {"ickaxe"}) then
- r.select(tools)
- i_c.equip()
- else
- stop("нет инструмента")
- end
- else
- cheststart = false
- print("сундук сзади робота не найден")
- checkfuel()
- if slotitem(tools, {"ickaxe"}) then
- r.select(tools)
- i_c.equip()
- else
- stop("нет инструмента")
- end
- end
- goTo( 0,0,0,0,1 )
- charging()
- r.setLightColor(0xFFFFFF)
- chunkload(true)
- print("опускаюсь на "..down.." блока(ов)")
- for height = 1,256 do
- refuel = true
- checkfuel()
- go_down()
- down = 3
- for xx = 1,width do
- for yy = 1,length-1 do
- digForward()
- end
- checkfuel()
- if xx ~= width then
- if ridht then
- turnRight()
- digForward()
- turnRight()
- ridht = false
- else
- turnLeft()
- digForward()
- turnLeft()
- ridht = true
- end
- end
- end
- r.swingUp()
- r.swingDown()
- if ridht then
- turnLeft()
- x_forward()
- turnLeft()
- ridht = false
- else
- turnRight()
- x_forward()
- turnRight()
- ridht = true
- end
- if bedrock then
- goTo( 0,0,0,0,-1 )
- sortlut(true)
- stop("завершил копать :)")
- end
- end
- end
- dig()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement