Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local APIS={}
- local inv_size = 16
- local inv_side = require("sides").back
- local charge_side = require("sides").left
- local battery_side = require("sides").bottom
- local temp_state = {x=0, y=0, z=0, dr=3}
- local lc = {x=0, y=0, z=0, dr=3, xMax = 0, zMax = 0}
- local way = 0
- local ore_count = 0
- local directives = {
- pause = false,
- home = false,
- report = false,
- move = false
- }
- local scrap = {
- "minecraft:stone",
- "minecraft:cobblestone",
- "minecraft:dirt",
- "minecraft:gravel",
- "minecraft:sand",
- "minecraft:grass",
- "minecraft:sandstone",
- "minecraft:mossy_cobblestone",
- "minecraft:stonebrick",
- "minecraft:brown_mushroom",
- "minecraft:red_mushroom"
- }
- local fuel_list = {
- "minecraft:fence",
- "minecraft:planks",
- "minecraft:log",
- "minecraft:coal_block",
- "minecraft:coal"
- }
- local mining_tools_list = {
- "minecraft:iron_pickaxe",
- "minecraft:golden_pickaxe",
- "appliedenergistics2:item.ToolCertusQuartzPickaxe",
- "appliedenergistics2:item.ToolNetherQuartzPickaxe",
- "IC2:itemToolBronzePickaxe",
- "Forestry:bronzePickaxe",
- "minecraft:diamond_pickaxe",
- "IC2:itemToolDrill",
- "IC2:itemToolDDrill",
- "IC2:itemToolIridiumDrill",
- "GraviSuite:advDDrill"
- }
- function APIS.duster(tmr)
- local inv = require("component").inventory_controller
- local r = require("robot")
- while true do
- for i=1,7 do
- local temp = inv.getStackInSlot(3,i)
- if temp then
- if temp.name == "IC2:itemDustSmall" and math.floor(temp.size/9) > 0 then
- for j=1,3 do
- r.select(j)
- inv.suckFromSlot(3,i,math.floor(temp.size/9))
- end
- for j=5,7 do
- r.select(j)
- inv.suckFromSlot(3,i,math.floor(temp.size/9))
- end
- for j=9,11 do
- r.select(j)
- inv.suckFromSlot(3,i,math.floor(temp.size/9))
- end
- r.select(4)
- require("component").crafting.craft(math.floor(temp.size/9))
- r.drop()
- end
- end
- end
- os.sleep(tmr)
- end
- end
- function APIS.charge(charge_side)
- --функция зарядки робота от чарджера, т.к. в этом билде ОС он категорически не принимает
- --ред сигнал робота, временно переориентировал на рычаг.
- comp = require("computer")
- while comp.energy() < (comp.maxEnergy()/2) do
- --local rs = require("component").redstone
- --rs.setOutput(charge_side, 15)
- require("term").clear()
- APIS.use(charge_side)
- print("Зарядка...")
- os.sleep(60)
- --rs.setOutput(charge_side, 0)
- APIS.use(charge_side)
- end
- print("Батарея заряжена")
- return true
- end
- function APIS.charge_tool(chargerSide, slot)
- --функция проверки заряда бура в руках робота, передача его на зарядку в батбокс/чарджер
- local inv = require("component").inventory_controller
- local r = require("robot")
- local side = 3
- local tool = nil
- if chargerSide == 1 then
- side=1
- elseif chargerSide == 0 then
- side=0
- end
- if r.durability() == nil then
- return false
- end
- if r.durability() < 0.3 then
- r.select(slot)
- inv.equip()
- tool = inv.getStackInInternalSlot(slot)
- inv.equip()
- if not(lc.x == 0 and lc.y == 0 and lc.z == 0) then
- return true
- end
- else
- return false
- end
- local function isElectric(device)
- if device.maxCharge ~= nil then
- return true
- else
- return false
- end
- end
- local function find_new_tool()
- APIS.rot(inv_side)
- local temp = APIS.inv_scaner(mining_tools_list, false, start_slot)
- print("Поиск замены инструменту в сундуке.")
- while temp ~= 0 do
- local temp_device = inv.getStackInSlot(3, temp)
- if isElectric(temp_device) then
- if temp_device.charge/temp_device.maxCharge > 0.6 then
- break
- else
- temp = APIS.inv_scaner(mining_tools_list, false, temp+1)
- end
- else
- if temp_device.damage/temp_device.maxDamage < 0.4 then
- break
- else
- temp = APIS.inv_scaner(mining_tools_list, false, temp+1)
- end
- end
- end
- return temp
- end
- local function service(device)
- if isElectric(device) then
- APIS.rot(chargerSide)
- if not inv.getInventorySize(3) ~= nil then
- print("Зарядник не найден. Установите зарядник.")
- while not inv.getInventorySize(3) ~= nil do
- os.sleep(5)
- end
- end
- r.select(slot)
- inv.equip()
- inv.dropIntoSlot(3,1)
- print("Зарядка инструмента.")
- while inv.getStackInSlot(3,1).charge < device.maxCharge do
- os.sleep(10)
- end
- inv.suckFromSlot(3,1)
- inv.equip()
- else
- print("Поиск инструмента в сундуке.")
- APIS.rot(inv_side)
- while true do
- local temp = find_new_tool()
- if temp ~= 0 then
- r.select(slot)
- inv.equip()
- if not r.drop() then
- print("Нет места в сундуке. Освободите место.")
- while not r.drop() do
- os.sleep(10)
- end
- end
- inv.suckFromSlot(3, temp)
- inv.equip()
- r.select(1)
- break
- end
- end
- end
- end
- if lc.x == 0 and lc.y == 0 and lc.z == 0 then
- print("Сервис инструмента.")
- service(tool)
- else
- return false
- end
- end
- function APIS.use(s)
- --функция юза в заданную сторону.
- local r = require("robot")
- if s == 1 then r.useUp()
- elseif s == 2 then
- r.turnAround()
- r.use()
- r.turnAround()
- elseif s == 3 then r.use()
- elseif s == 4 then
- r.turnRight()
- r.use()
- r.turnLeft()
- elseif s==5 then
- r.turnLeft()
- r.use()
- r.turnRight()
- else
- r.useDown()
- end
- end
- function APIS.drop()
- --функция дропа всего инвентаря в сундук, если таковой стоит перед носом
- local inv = require("component").inventory_controller
- local r= require("robot")
- while true do
- if r.detect() then
- if inv.getInventorySize(3) ~= nil then
- for i=1,inv_size-1 do
- if inv.getStackInInternalSlot(i) ~= nil then
- r.select(i)
- if not r.drop() then
- -- print("Сундук переполнен. Освободите место под складирование.")
- while not r.drop() do
- os.sleep(5)
- end
- end
- end
- end
- break
- else
- print("Блок не является сундуком.")
- os.sleep(5)
- end
- else
- print("Установите сундук!")
- os.sleep(5)
- end
- end
- end
- function APIS.printState()
- --используется для отладки движений робота
- print("Статус:")
- print(lc.x, lc.y, lc.z, lc.dr)
- print(temp_state.x, temp_state.y, temp_state.z, temp_state.dr)
- end
- function APIS.harvest(count)
- --функция для фермера на IC кропсах, аргумент - сколько раз собирать с 1 места
- local r=require("robot")
- for i=1,count do
- r.useDown()
- end
- end
- function APIS.dig(arg)
- --функция целевого копания по стороне-аргументу, скорее всего потру ее, при оптимизации
- r = require("robot")
- event = require("event")
- if arg == 3 then
- r.swing()
- elseif arg == 1 then
- while r.detectUp() do
- r.swingUp()
- end
- elseif arg == 0 then
- r.swingDown()
- end
- end
- function APIS.isScrap(name)
- --проверка является ли итем по имени мусором.
- for i, nm in pairs(scrap) do
- if name == nm then
- return true
- end
- end
- return false
- end
- function APIS.ore_analyze(arg)
- --метод проверки, является ли блок "немусором"
- if arg ~= nil then
- if require("component").isAvailable("geolyzer") then
- local lyz = require("component").geolyzer
- if APIS.isScrap(lyz.analyze(arg).name) then
- return false
- else
- return true
- end
- else
- print("Геолайзер не обнаружен в системе.")
- return false
- end
- else
- print("Не указан аргумент(сторона проверки).")
- end
- end
- function APIS.dig_ore()
- --метод для копания только руды, в слоеном карьере.
- local r=require("robot")
- if r.detectUp() then
- if APIS.ore_analyze(1) then
- APIS.dig(1)
- end
- end
- if r.detectDown() then
- if APIS.ore_analyze(0) then
- APIS.dig(0)
- end
- end
- end
- function APIS.turnLeft()
- local r = require("robot")
- r.turnLeft()
- if lc.dr == 3 then
- lc.dr = 5
- elseif lc.dr == 4 then
- lc.dr = 3
- elseif lc.dr == 2 then
- lc.dr = 4
- elseif lc.dr == 5 then
- lc.dr = 2
- end
- end
- function APIS.turnRight()
- local r = require("robot")
- r.turnRight()
- if lc.dr == 3 then
- lc.dr = 4
- elseif lc.dr == 4 then
- lc.dr = 2
- elseif lc.dr == 2 then
- lc.dr = 5
- elseif lc.dr == 5 then
- lc.dr = 3
- end
- end
- function APIS.turnAround()
- local r = require("robot")
- r.turnAround()
- if lc.dr == 3 then
- lc.dr = 2
- elseif lc.dr == 4 then
- lc.dr = 5
- elseif lc.dr == 2 then
- lc.dr = 3
- elseif lc.dr == 5 then
- lc.dr = 4
- end
- end
- function APIS.rot(side)
- if (side ~= 1) and (side ~= 0) and lc.dr-side ~=0 then
- local sides = require("sides")
- local r = require("robot")
- if lc.dr == 3 then
- if side == 4 then APIS.turnRight()
- elseif side == 2 then APIS.turnAround()
- elseif side == 5 then APIS.turnLeft()
- end
- elseif lc.dr == 4 then
- if side == 2 then APIS.turnRight()
- elseif side == 5 then APIS.turnAround()
- elseif side == 3 then APIS.turnLeft()
- end
- elseif lc.dr == 2 then
- if side == 5 then APIS.turnRight()
- elseif side == 3 then APIS.turnAround()
- elseif side == 4 then APIS.turnLeft()
- end
- else--5
- if side == 3 then APIS.turnRight()
- elseif side == 4 then APIS.turnAround()
- elseif side == 2 then APIS.turnLeft()
- end
- end
- end
- --APIS.printState()
- end
- function APIS.mUp()
- --функция движения вверх, сквозь породу.
- local r = require("robot")
- local try = 1
- repeat
- r.swingUp()
- try = try + 1
- if try >= 15 then
- print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr=вверх"..lc.dr)
- local _, det = require("robot").detectUp()
- print(det.." сверху.")
- print(require("component").geolyzer.analyze(1).name)
- APIS.mTo(lc.x+2,lc.y,lc.z)
- APIS.back_to_the_future()
- --APIS.printState()
- return false
- elseif try > 12 then
- if require("component").geolyzer.analyze(1).name == "ExtraBees:hive" then
- local inv = require("component").inventory_controller
- if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
- inv.equip()
- r.swingUp()
- inv.equip()
- r.select(1)
- end
- end
- end
- until not r.detectUp()
- while try < 15 and not r.up() do
- r.swingUp()
- try = try + 1
- end
- if try < 15 then
- lc.y = lc.y + 1
- way = way + 1
- --APIS.printState()
- return true
- end
- end
- function APIS.mDown(action, arg)
- --функция движения вниз, сквозь породу.
- local r = require("robot")
- local event = require("event")
- local try = 1
- if action ~= nil then
- action(arg)
- end
- repeat
- r.swingDown()
- try = try + 1
- if try >= 15 then
- --APIS.printState()
- print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr= вниз"..lc.dr)
- local _, det = require("robot").detectDown()
- print(det.." снизу.")
- print(require("component").geolyzer.analyze(0).name)
- APIS.back_to_the_future()
- return false
- elseif try > 12 then
- if require("component").geolyzer.analyze(0).name == "ExtraBees:hive" then
- local inv = require("component").inventory_controller
- if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
- inv.equip()
- r.swingDown()
- inv.equip()
- r.select(1)
- end
- end
- end
- until not r.detectDown()
- while try < 15 and not r.down() do
- r.swingDown()
- try = try + 1
- end
- if try < 15 then
- lc.y = lc.y - 1
- way = way + 1
- return true
- end
- end
- function APIS.mForw(action,arg)
- --шаг вперед с действием или безБ сквозь породу, координатные отметки
- local r = require("robot")
- local event = require("event")
- local try = 1
- local sides = require("sides")
- if action ~= nil then
- action(arg)
- end
- repeat
- r.swing()
- try = try + 1
- if try >= 15 then
- print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr="..lc.dr)
- local _, det = require("robot").detect()
- print(det.." спереди.")
- print(require("component").geolyzer.analyze(3).name)
- APIS.back_to_the_future()
- return false
- elseif try > 12 then
- if require("component").geolyzer.analyze(3).name == "ExtraBees:hive" then
- local inv = require("component").inventory_controller
- if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
- inv.equip()
- r.swing()
- inv.equip()
- r.select(1)
- end
- end
- end
- until not r.detect()
- while try < 15 and not r.forward() do
- r.swing()
- try = try + 1
- end
- if try < 15 then
- way = way + 1
- if lc.dr==2 then
- lc.x = lc.x - 1
- elseif lc.dr==3 then
- lc.x = lc.x + 1
- elseif lc.dr==4 then
- lc.z = lc.z + 1
- elseif lc.dr==5 then
- lc.z = lc.z - 1
- end
- --APIS.printState()
- return true
- end
- end
- function APIS.mTo(x, y, z, action, arg)
- --движение в заданную точку с заданым действием и аргументом действия. Координатное.
- if directives.pause then
- APIS.execDirective()
- end
- local r = require("robot")
- local sides = require("sides")
- if lc.x > x then
- APIS.rot(sides.back)
- while lc.x > x do
- APIS.mForw(action,arg)
- end
- end
- if lc.x < x then
- APIS.rot(sides.forward)
- while lc.x < x do
- APIS.mForw(action,arg)
- end
- end
- if lc.z > z then
- APIS.rot(sides.left)
- while lc.z > z do
- APIS.mForw(action,arg)
- end
- end
- if lc.z < z then
- APIS.rot(sides.right)
- while lc.z < z do
- APIS.mForw(action,arg)
- end
- end
- while lc.y > y do
- APIS.mDown(action,arg)
- --print("едем вниз")
- end
- while lc.y < y do
- APIS.mUp(action,arg)
- --print("едем вверх")
- end
- end
- function APIS.plane(x, y, z, action, arg, forward)
- --проходка горизонтальной плоскости, координатная. Слоеный карьер, фермер.
- local dir = "forward"
- if forward then
- for j=0,z do
- if dir == "forward" then
- for i=0,x do
- APIS.mTo(i,y,j,action,arg)
- end
- APIS.check_state()
- dir = "back"
- else
- for i=x,0,-1 do
- APIS.mTo(i,y,j,action,arg)
- end
- APIS.check_state()
- dir = "forward"
- end
- end
- else
- if z%2==0 then dir = "back" end
- for j=z,0,-1 do
- if dir == "forward" then
- for i=0,x do
- APIS.mTo(i,y,j,action,arg)
- end
- APIS.check_state()
- dir = "back"
- else
- for i=x,0,-1 do
- APIS.mTo(i,y,j,action,arg)
- end
- APIS.check_state()
- dir = "forward"
- end
- end
- end
- end
- function APIS.home(action,arg)
- --функция возврата к сундуку для очистки инвентаря.
- temp_state.x = lc.x
- temp_state.y = lc.y
- temp_state.z = lc.z
- temp_state.dr = lc.dr
- APIS.mTo(0,0,0, action,arg)
- APIS.rot(2)
- APIS.drop_scrap()
- APIS.drop()
- --APIS.rot(3)
- end
- function APIS.drop_scrap()
- local r = require("robot")
- local inv = require("component").inventory_controller
- for i=1, inv_size do
- local slot = inv.getStackInInternalSlot(i)
- if slot ~= nil then
- if APIS.isScrap(slot.name) then
- r.select(i)
- r.dropDown()
- end
- end
- end
- return APIS.inv_sorting()
- end
- function APIS.back_to_mine(action,arg)
- --возврат на точку останова(после очистки инвентаря) для возобновления работы.
- APIS.mTo(0,temp_state.y,0, action,arg)
- APIS.mTo(temp_state.x,temp_state.y,temp_state.z, action,arg)
- APIS.rot(temp_state.dr)
- temp_state.x = 0
- temp_state.y = 0
- temp_state.z = 0
- temp_state.dr = 3
- end
- function APIS.back_to_the_future()
- --Завершение программы ввиду непреодолимого препятствия.
- print("Ошибка/препятствие. Возврат робота.")
- APIS.mTo(lc.x, 0, lc.z)
- APIS.home()
- APIS.rot(3)
- print("Робот на исходной. Завершение программы.")
- os.exit()
- end
- function APIS.check_inv()
- --вычисление величины собственного инвентаря
- local r = require("robot")
- local i = 16
- local count = 16
- while pcall(r.count, i) do
- count = i
- i=i+1
- end
- return count
- end
- function APIS.inv_sorting()
- --Функция сортировки инвентаря(перекладывание содержимого без пустых ячеек)
- --возвращает процентное заполнение инвентаря в целом
- local inv = require("component").inventory_controller
- local r = require("robot")
- local items_stored = 0
- inv_size = APIS.check_inv()
- --цикл от начала до конца ищет пустые ячейки, когда находит - второй цикл от конца до
- --начала ищет не пустые и перемещает на место пустых(упорядочивает)
- --когда цикл начальный и конечный пересекается - перестает запускаться цикл с конца
- --чтоб не было бесконечного перемешивания. После подсчет % занятого пространства и возврат значений.
- for i=1, inv_size-1 do
- if r.count(i) == 0 then
- for j=inv_size-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
- for i=1,inv_size do
- if r.count(i) > 0 then
- items_stored = items_stored + 1
- end
- end
- --print(items_stored)
- r.select(1)
- return items_stored/inv_size
- end
- function APIS.check_state()
- --функция проверки состояния инвентаря и заряда батареи робота
- --выбрасывание мусора из карманов и пожирание угля, если требуется
- local r = require("robot")
- local inv = require("component").inventory_controller
- local comp = require("computer")
- local c = require("component")
- local need_fuel = comp.energy() < (comp.maxEnergy()*0.90)
- local function inventory()
- local need_to_home = false
- if (r.count(inv_size-2) > 0) then
- if APIS.drop_scrap() > 0.9 then
- need_to_home = true
- else
- need_to_home = false
- end
- end
- return need_to_home
- end
- local function fuel(internal)
- local need_to_home = false
- if need_fuel and c.isAvailable("generator") and c.generator.count() == 0 then
- local slt = APIS.inv_scaner(fuel_list, internal)
- if slt ~= 0 and not internal then
- r.select(inv_size-2)
- inv.suckFromSlot(3, slt)
- c.generator.insert()
- r.select(1)
- need_to_home = false
- else
- slt = APIS.inv_scaner(fuel_list, internal)
- if slt ~= 0 and internal then
- r.select(slt)
- c.generator.insert()
- r.select(1)
- need_to_home = false
- else
- need_to_home = true
- end
- end
- elseif not c.isAvailable("generator") and need_fuel then
- need_to_home = true
- end
- return need_to_home
- end
- if inventory() or fuel(true) or APIS.charge_tool(charge_side, inv_size-2) then
- APIS.home()
- os.sleep(15)
- APIS.charge_tool(charge_side, inv_size-2)
- fuel(false)
- APIS.back_to_mine()
- end
- end
- function APIS.quarry(x, z)
- --слоистый геокарьер, копает слои 1 через 2, проверяет все блоки, берет только руду.
- inv_size = APIS.check_inv()
- for i=0, -256, -3 do
- if i%2 == 0 then
- APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, true)
- else
- APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, false)
- end
- end
- APIS.home()
- end
- function APIS.field(x, z, time)
- --фермер для кропсов, длинна, ширина, таймер повторения в минутах(время созревания)
- --нуждается в модернизации, автоматизированной настройке таймера повторений.
- if time == nil then time = 5 end
- while true do
- APIS.plane(x-1, 0, z-1, APIS.harvest, 2, true)
- APIS.use(require("sides").down)
- APIS.use(require("sides").down)
- APIS.home()
- APIS.rot(3)
- require("term").clear()
- print("Ожидание созревания...", time, "минут.")
- os.sleep(60*time)
- end
- end
- function APIS.chop_single()
- --сырая автолесорубка для 1 дерева, пассивная, магнит апгрейд необходим. Рабочая.
- local inv = require("component").inventory_controller
- local beam = require("component").tractor_beam
- local r = require("robot")
- local function start()
- APIS.rot(inv_side)
- APIS.drop()
- inv.suckFromSlot(3, APIS.inv_scaner("minecraft:sapling"), 1)
- APIS.rot(3)
- r.place()
- end
- start()
- while true do
- require("term").clear()
- print("Лесоруб, одиночное дерево. Ожидание роста саженца.")
- local _, wood = r.detect()
- if wood == "solid" then
- print("Рубка дерева.")
- r.swing()
- os.sleep(5)
- for i=1, 8 do
- beam.suck()
- end
- start()
- require("term").clear()
- APIS.charge(charge_side)
- APIS.charge_tool(battery_side)
- end
- os.sleep(10)
- end
- end
- function APIS.inv_scaner(filter, internal, start_slot)
- --автопоисковик заданного итема в своем инвентаре по системному имени.
- --возвращает номер ячейки итема, первого найденного от начала ивентаря.
- local inv = require("component").inventory_controller
- ins = inv.getInventorySize(3)
- if start_slot == nil then
- start_slot = 1
- end
- if filter == "empty" then
- if internal then
- for i=start_slot, inv_size do
- if inv.getStackInInternalSlot(i) == nil then
- return i
- end
- end
- else
- for i=start_slot, inv.getInventorySize(3) do
- if inv.getStackInSlot(3, i) == nil then
- return i
- end
- end
- end
- end
- if internal then
- for i=start_slot, inv_size do
- if inv.getStackInInternalSlot(i) ~= nil then
- if pcall(pairs, filter) then
- for j, name in pairs(filter) do
- if inv.getStackInInternalSlot(i).name == name then
- --print(filter.." найден!")
- return i
- end
- end
- else
- if inv.getStackInInternalSlot(i).name == filter then
- --print(filter.." найден!")
- return i
- end
- end
- end
- end
- --print("Найти "..filter.." не удалось.")
- return 0
- else
- if ins ~= nil then
- for i=start_slot, ins do
- if inv.getStackInSlot(3, i) ~= nil then
- if pcall(pairs, filter) then
- for j, name in pairs(filter) do
- if inv.getStackInSlot(3, i).name == name then
- --print(filter.." найден!")
- return i
- end
- end
- else
- if inv.getStackInSlot(3, i).name == filter then
- --print(filter.." найден!")
- return i
- end
- end
- end
- end
- --print("Найти "..filter.." не удалось.")
- return 0
- else
- return 0
- end
- end
- end
- function APIS.distance(blockA, blockB)
- local dist = math.sqrt(math.pow(blockA.x - blockB.x,2) +
- math.pow(blockA.z - blockB.z,2) + math.pow(blockA.y - blockB.y,2))
- return dist
- end
- function APIS.closest_point(point, points)
- local cl_num = 1
- local length = APIS.distance(point, points[1])
- for i=1, #points do
- local l = APIS.distance(point, points[i])
- if l < length then
- cl_num = i
- length = l
- end
- end
- return cl_num
- end
- function APIS.waypoints(ores_table, last)
- local way_table = {}
- local count = #ores_table
- table.insert(way_table, {x=lc.x, z=lc.z, y=lc.y})
- while count ~= #way_table - 1 do
- local j = APIS.closest_point(way_table[#way_table], ores_table)
- table.insert(way_table, ores_table[j])
- table.remove(ores_table, j)
- end
- return way_table, last
- end
- function APIS.scanVolume(xn,zn, bedrock, side, hight_border)
- --сканирование карьерного "этажа" заданного радиуса -10 блоков вниз+сканер+10 блоков вверх
- local geo = require("component").geolyzer
- local ores_table = {}
- local last = false
- local x_limit = 0
- local z_limit = 0
- local x_increment = 1
- local z_increment = 1
- if side == "north" or side == "север" then
- x_limit = zn
- x_increment = 1
- z_limit = -xn
- z_increment = -1
- -- print("Выбранное направление: Север. Старт сканирования.")
- elseif side == "west" or side == "запад" then
- x_limit = -xn
- x_increment = -1
- z_limit = -zn
- z_increment = -1
- -- print("Выбранное направление: Запад. Старт сканирования.")
- elseif side == "south" or side == "юг" then
- x_limit = -zn
- x_increment = -1
- z_limit = xn
- z_increment = 1
- -- print("Выбранное направление: Юг. Старт сканирования.")
- elseif side == "east" or side == "восток" or side == nil then
- x_limit = xn
- x_increment = 1
- z_limit = zn
- z_increment = 1
- -- print("Выбранное направление: Запад. сканирования.")
- end
- if xn == 0 and zn == 0 then
- --print("Сканирование границ бедрока")
- local tempr=geo.scan(0,0)
- for i=10, 32 do
- if tempr[i] < -0.3 then
- --print("Бедрок обнаружен на уровне "..i-33+lc.y)
- return i-33+lc.y, true
- end
- end
- return 0, false
- end
- --print("Сканирование заданного объема, может занять несколько минут...")
- for xt=0,x_limit,x_increment do
- for zt=0,z_limit,z_increment do
- local scan = geo.scan(xt,zt,true)
- for yt=hight_border+33, 33+math.abs(hight_border) do
- if scan[yt] > 2.05 and scan[yt] < 40 and ((yt-33)+lc.y) > bedrock then
- if side == "north" or side == "север" then
- table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
- elseif side == "west" or side == "запад" then
- table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
- elseif side == "south" or side == "юг" then
- table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
- elseif side == "east" or side == "восток" or side == nil then
- table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
- end
- end
- end
- end
- end
- return ores_table
- end
- function APIS.whatsSide()
- local geo = require("component").geolyzer
- local r= require("robot")
- local function isBlock(dens)
- if dens ~= nil and dens ~= 0 then
- return 1
- elseif dens == 0 then
- return 0
- end
- end
- local function check(fig, front)
- local figure1 = {
- east = isBlock(geo.scan(1,0)[33]),
- south = isBlock(geo.scan(0,1)[33]),
- west = isBlock(geo.scan(-1,0)[33]),
- north = isBlock(geo.scan(0,-1)[33])
- }
- if front then
- if fig.east > figure1.east then
- return "east"
- elseif fig.south > figure1.south then
- return "south"
- elseif fig.west > figure1.west then
- return "west"
- elseif fig.north > figure1.north then
- return "north"
- end
- elseif not front then
- if fig.east < figure1.east then
- return "east"
- elseif fig.south < figure1.south then
- return "south"
- elseif fig.west < figure1.west then
- return "west"
- elseif fig.north < figure1.north then
- return "north"
- end
- end
- end
- local figure = {
- east = isBlock(geo.scan(1,0)[33]),
- south = isBlock(geo.scan(0,1)[33]),
- west = isBlock(geo.scan(-1,0)[33]),
- north = isBlock(geo.scan(0,-1)[33])
- }
- APIS.rot(3)
- while true do
- if r.detect() then
- r.swing()
- local direction = check(figure, true)
- r.place()
- return direction
- elseif r.detectDown() then
- r.swingDown()
- r.place()
- local direction = check(figure, false)
- r.swing()
- r.placeDown()
- return direction
- end
- print("Для ориентирования в пространстве недостаточно данных.")
- print("Пожалуйста установите любой блок перед или под роботом и повторите попытку")
- os.exit()
- end
- end
- function APIS.findoutBedrockLevel()
- local bedrock = -1
- local start_level = lc.y
- for i = lc.y, -256, -10 do
- local bed, catch = APIS.scanVolume(0,0)
- --print("Сканирование бедрока")
- if not catch then
- APIS.mTo(lc.x, i, lc.z)
- elseif bed < lc.y - 5 then
- --print("Найден бедрок")
- APIS.mTo(lc.x, i-4, lc.z)
- bedrock = APIS.scanVolume(0,0)
- break
- end
- end
- APIS.mTo(lc.x, start_level, lc.z)
- return bedrock
- end
- function APIS.clusterDigger(start_point, x,z, bedrock, side)
- --print("Кластер диггер")
- if side == nil then
- --print("В функцию кластер диггер сайд не поступила")
- side = APIS.whatsSide()
- --print("Направление: "..side)
- end
- if start_point == nil then
- start_point = lc
- end
- inv_size = APIS.check_inv()
- APIS.mTo(start_point.x, start_point.y, start_point.z)
- for Y=lc.y, bedrock+6, -1 do
- if Y%21 == 0 or Y == bedrock + 9 then
- APIS.mTo(start_point.x, Y, start_point.z)
- APIS.rot(3)
- arr=APIS.waypoints(APIS.scanVolume(x-1,z-1, bedrock+4, side, -11))
- ore_count = ore_count + (#arr-1)
- for i=1, #arr do
- APIS.mTo(arr[i].x, arr[i].y, arr[i].z)
- if i%10 == 0 then
- APIS.check_state()
- end
- if way%30 == 0 then
- APIS.check_state()
- end
- end
- end
- end
- end
- function APIS.geoMiner(x, z, bedrock, side, x_lim, z_lim)
- local start_point = {x=0, y=0, z=0}
- local x_limit = x_lim
- local z_limit = z_lim
- if x_lim == nil then
- x_limit = 32
- end
- if z_lim == nil then
- z_limit = 32
- end
- if side == nil then
- --print("В функцию геомайнер сайд не поступила.")
- side = APIS.whatsSide()
- end
- local function z_glide()
- if z/z_limit < 1 then
- APIS.clusterDigger(start_point, x_limit, z, bedrock, side)
- else
- for j=1, math.floor(z/z_limit) do
- --print("Карьер заданных лимитов по Z")
- APIS.clusterDigger(start_point, x_limit, z_limit, bedrock, side)
- start_point.z = j*z_limit+1
- end
- if z%z_limit > 0 then
- --print("Карьер остатков по Z")
- APIS.clusterDigger(start_point, x_limit, z%z_limit, bedrock, side)
- end
- start_point.z = 0
- end
- end
- if x/x_limit < 1 then
- local temp = x_limit
- x_limit = x
- z_glide()
- x_limit = temp
- else
- for i=1, math.floor(x/x_limit) do
- --print("Карьер заданных лимитов по X")
- z_glide()
- start_point.x = i*x_limit+1
- end
- if x%x_limit > 0 then
- x_limit = x%x_limit
- --print("Карьер остатков по x")
- z_glide()
- end
- end
- APIS.home()
- APIS.rot(3)
- print("Итого руды добыто: "..ore_count)
- print("Всего блоков пройдено: "..way)
- ore_count = 0
- end
- function APIS.mine(x,z, bedrock, side,x_lim, z_lim)
- APIS.check_components()
- lc.xMax = x
- lc.zMax = z
- way = 0
- local term = require("term")
- local r = require("robot")
- local comp = require("component")
- term.clear()
- print("Старт карьера: "..x.."x"..z.." блоков.")
- APIS.check_state()
- local side = APIS.whatsSide()
- if bedrock == nil then
- print("Проверка уровня бедрока. Вертикальная шахта до дна и обратно.")
- bedrock = APIS.findoutBedrockLevel()
- end
- print("Сканирование заданного объема, может занять несколько минут...")
- if not pcall(APIS.geoMiner, x, z, bedrock, side, x_lim, z_lim) then
- pcall(APIS.back_to_the_future)
- end
- end
- function APIS.check_components()
- local c = require("component")
- local r = require("robot")
- inv_size = APIS.check_inv()
- if c.isAvailable("chunkloader") then
- c.chunkloader.setActive(true)
- print("\t Чанклоадер....доступен.")
- else
- print("\t Чанклоадер не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- if c.isAvailable("inventory_controller") then
- print("\t Контроллер инвентаря....доступен.")
- else
- print("\t Контроллер инвентаря не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- if c.isAvailable("generator") then
- print("\t Генератор....доступен.")
- else
- print("\t Генератор не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- if c.isAvailable("geolyzer") then
- print("\t Геосканер....доступен.")
- else
- print("\t Геосканер не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
- r.transferTo(inv_size)
- r.select(1)
- print("\t Сачек....доступен.")
- else
- print("\t Сачек не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- if r.durability() ~= nil then
- print("\t Инструмент....доступен.")
- else
- print("\t Инструмент не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
- os.exit()
- end
- print("\n Все компоненты в наличии.\n Программа может быть запущена.")
- end
- function APIS.ore_map(lc, ore_array, hight_border)
- --отрисовка карты руд в отсканированном роботом объеме
- local hol = require("component").hologram
- hol.clear()
- hol.setTranslation(0,0.3,0)
- hol.setScale(1.2)
- hol.set(lc.x+8, lc.y+math.abs(hight_border)*2+1, lc.z+8, 03)
- for i=1, #ore_array do
- hol.set(ore_array[i].x+8, ore_array[i].y+21, ore_array[i].z+8, 01)
- end
- require("term").clear()
- print("Руды найдено: "..#ore_array)
- end
- function APIS.getTunnelMessage(label, internal_adress, sender_adress, port, distance, text, power)
- local event = require("event")
- local ser = require("serialization")
- local cmpn = require("component")
- local command = ""
- local coords = {}
- event.listen("modem_message", APIS.getTunnelMessage)
- if cmpn.isAvailable("robot") then
- if text ~= nil then
- event.ignore("modem_message", APIS.getTunnelMessage)
- command = string.sub(text, 1,4)
- if #text > 4 then
- text = string.sub(text, 5, #text)
- text = ser.unserialize(text)
- end
- APIS.exec(command)
- event.listen("modem_message", APIS.getTunnelMessage)
- end
- elseif false then
- end
- end
- function APIS.pushCommand(command)
- local tunnel = require("component").tunnel
- tunnel.send(tostring(command))
- end
- function APIS.pushReport()
- local ser = require("serialization")
- local message = "repo"
- --local tunnel = require("component").tunnel
- message = message..ser.serialize({
- energy = require("computer").energy(),
- tool = require("robot").durability(),
- way=way,
- ore_count=ore_count,
- lc = lc
- })
- --tunnel.send(message)
- return message
- end
- function APIS.exec(command)
- if command ~= nil then
- if command == "back" or command == "stop" or "home" then
- directives.pause = true
- directives.home = true
- elseif command == "repo" or command == "resp" then
- directives.pause = true
- directives.report = true
- elseif command == "move" then
- directives.pause = true
- directives.move = true
- end
- end
- end
- function APIS.execDirective()
- if directives.home then
- directives.pause = false
- directives.home = false
- APIS.home()
- APIS.delay("comm")
- elseif directives.report then
- directives.pause = false
- directives.report = false
- APIS.pushReport()
- elseif directives.move then
- directives.pause = false
- directives.move = false
- APIS.mTo(temp_state.x, temp_state.y, temp_state.z)
- temp_state = {x=0, y=0, z=0, dr=3}
- end
- end
- function APIS.delay(ask)
- if ask == "comm" then
- print("Ожидание команды: ")
- pcall(APIS.exec(tostring(io.read())))
- return
- elseif ask == "stop" or ask == "exit" or ask == "break" then
- os.exit()
- end
- end
- return APIS
- --pastebin get -f dih9JmDH lib/api.lua
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement