serafim7

diamond digger [OpenComputers]

Feb 7th, 2021 (edited)
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.50 KB | None | 0 0
  1. --[[   opencomputers копатель алмазов by serafim
  2.        pastebin.com/qAeXekby     update 13.06.21
  3.  
  4. Копает бесконечный туннель 1х3 змейкой ряд за рядом,
  5. предназначен для добычи алмазов по горизонту,
  6. оптимальная высота = 12 (так как на 11 лава)
  7.  
  8. требования:
  9. инвентарь, контроллер инвентаря,
  10. генератор, желателен чанк лоадер.
  11.  
  12. пример сборки:
  13. https://i.imgur.com/fR7F4fA.png
  14.  
  15. использование:
  16. положить в инвентарь робота инструмент (кирка, бур и т.д.),
  17. эндер-сундук (можно обычные сундуки, 64 шт. например),
  18. уголь больше 20 штук.
  19.  
  20. пример запуска:
  21. tunnel 30 1 или tunnel
  22. ]]--
  23.  
  24. local a = {...}
  25. local width = tonumber(a[1]) or 30 --ширина туннеля
  26. local stepline = tonumber(a[2]) or 1 --отступ между рядами
  27.  
  28. --список мусора
  29. local scrap = {
  30.   "cobblestone", --булыжник
  31.   "stone",       --камень
  32.   "dirt",        --земля
  33.   "gravel",      --гравий
  34.   "flint",       --кремень
  35.   "sand",        --песок
  36.   "sandstone"    --песчаник
  37. }
  38.  
  39. --список инструмента
  40. local toollist = {
  41.   "ickaxe",
  42.   "rill",
  43.   "pick",
  44.   "vajra"
  45. }
  46.  
  47. local com = require('component')
  48. local computer = require("computer")
  49. local event = require("event")
  50.  
  51. local timestart = computer.uptime()
  52. local fuelinv,refuel,chestcoal = true,true,true
  53. local unloaded,durability,placeside = 0,0,false
  54. local toolstrength = 0.07
  55.  
  56. if not com.isAvailable("robot") then
  57.   print("только роботы могут использовать эту программу")
  58.   os.exit()
  59. end
  60. local r = require("robot")
  61.  
  62. local invsize = r.inventorySize()
  63. local tools = invsize
  64. local coal = invsize-1
  65. local chest = invsize-2
  66.  
  67. if not com.isAvailable("inventory_controller") then
  68.   print("нет контроллера инвентаря")
  69.   os.exit()
  70. end
  71. local i_c = com.inventory_controller
  72.  
  73. if not com.isAvailable("generator") then
  74.   print("нет генератора")
  75.   os.exit()
  76. end
  77. local gen = com.generator
  78.  
  79. --статус
  80. local function status(msg)
  81.   print("[ "..os.date("%H:%M:%S",computer.uptime()-timestart).." ] "..msg)
  82. end
  83.  
  84. --чанк лоадер
  85. local function chunkload(state)
  86.   if com.isAvailable("chunkloader") then
  87.     if state then
  88.       com.chunkloader.setActive(true)
  89.       print("чанк лоадер активен")
  90.     else
  91.       com.chunkloader.setActive(false)
  92.       print("чанк лоадер деактивирован".."\n")
  93.     end
  94.   end
  95. end
  96.  
  97. --стоп
  98. local function stop(msg,reason)
  99.   print("всего выгрузил руды: "..unloaded.."\n")
  100.   if reason then
  101.     print("причина остановки: "..reason)
  102.   end
  103.   status("!!! стоп !!!".."\n"..msg.."\n")
  104.   chunkload(false)
  105.   print("продолжить копать ? [Y/n]")
  106.   while true do
  107.     r.setLightColor(0xFFFFFF)
  108.     computer.beep(1000, 1)
  109.     r.setLightColor(0xFF0000)
  110.     local e = ({event.pull(10,"key_down")})[4]
  111.     if e == 49 then
  112.       computer.beep(500, 0.1)
  113.       print("программа завершена")
  114.       os.exit()
  115.     elseif e == 21 or e == 28 then
  116.       computer.beep(500, 0.1)
  117.       r.setLightColor(0xFFFFFF)
  118.       print("продолжаю копать...")
  119.       chunkload(true)
  120.       break
  121.     end
  122.   end
  123. end
  124.  
  125. --поиск предмета в инвентаре робота
  126. local function slotitem(slot, list)
  127.   local item = i_c.getStackInInternalSlot(slot)
  128.   if item then
  129.     for j, name in pairs(list) do
  130.       if string.find(item.name,name) then
  131.         if item.charge == nil or item.charge/item.maxCharge > toolstrength then
  132.           return true
  133.         end
  134.       end
  135.     end
  136.   end
  137.   for i = 1,invsize do
  138.     if r.count(i) > 0 then
  139.       for j, name in pairs(list) do
  140.         local item = i_c.getStackInInternalSlot(i)
  141.         if item and string.find(item.name,name) then
  142.           if item.charge == nil or item.charge/item.maxCharge > toolstrength then
  143.             r.select(i)
  144.             r.transferTo(slot)
  145.             return true
  146.           end
  147.         end
  148.       end
  149.     end
  150.   end
  151.   return false
  152. end
  153.  
  154. --ставим и забираем сундук по трём сторонам
  155. local function placechest(place)
  156.   if place then
  157.     local tryplase = function()
  158.       for i, side in ipairs({0,1,3}) do
  159.         r.select(1)
  160.         com.robot.swing(side)
  161.         r.select(chest)
  162.         local ok = com.robot.place(side)
  163.         if ok then
  164.           placeside = side
  165.           return true
  166.         end
  167.       end
  168.       return false
  169.     end
  170.     while not tryplase() do
  171.       if not slotitem(chest,{"hest","ender"}) then
  172.         stop("сундук в инвентаре не найден")
  173.       else
  174.         stop("не могу поставить сундук")
  175.       end
  176.     end
  177.   else
  178.     while r.durability() == nil do
  179.       if slotitem(tools,toollist) then
  180.         r.select(tools)
  181.         i_c.equip()
  182.         break
  183.       else
  184.         stop("нет инструмента")
  185.       end
  186.     end
  187.     local detect = function()
  188.       return com.robot.detect(placeside)
  189.     end
  190.     r.select(chest)
  191.     while detect() do
  192.       com.robot.swing(placeside)
  193.     end
  194.   end
  195. end
  196.  
  197. --ожидаем пока в сундуке появится место
  198. local function waitdrop()
  199.   local drop = function()
  200.     com.robot.drop(placeside)
  201.     if r.count() == 0 then
  202.       return true
  203.     end
  204.     return false
  205.   end
  206.   if not drop() then
  207.     status("в сундуке нет места")
  208.     while not drop() do
  209.       r.setLightColor(0xFFFFFF)
  210.       computer.beep(1000, 1)
  211.       r.setLightColor(0xFF0000)
  212.       os.sleep(5)
  213.     end  
  214.     r.setLightColor(0xFFFFFF)    
  215.   end
  216. end
  217.  
  218. --проверяем электроинструмент
  219. local function electric()
  220.   local item = i_c.getStackInInternalSlot(tools)
  221.   if item and item.charge ~= nil then
  222.     return true
  223.   end
  224.   return false
  225. end
  226.  
  227. --берем запасной инструмент
  228. local function tool()
  229.   local checktool = r.durability()
  230.   if checktool == nil or checktool <= toolstrength then
  231.     if slotitem(tools,toollist) then
  232.       r.select(tools)
  233.       i_c.equip()
  234.       status("взял инструмент в инвентаре робота")
  235.       if not electric() then
  236.         r.drop()
  237.       end
  238.       durability = 0
  239.     elseif slotitem(chest,{"ender"}) then
  240.       local findtool = function()
  241.         local inv = i_c.getInventorySize(placeside)
  242.         if inv then
  243.           for slot = 1,inv do
  244.             for j, name in pairs(toollist) do
  245.               local item = i_c.getStackInSlot(placeside,slot)
  246.               if item and string.find(item.name,name) then
  247.                 if item.charge == nil or item.charge/item.maxCharge > toolstrength then
  248.                   i_c.suckFromSlot(placeside,slot)
  249.                   i_c.equip()
  250.                   status("взял запасной инструмент из сундука")
  251.                   durability = 0
  252.                   return true
  253.                 end
  254.               end
  255.             end
  256.           end
  257.           return false
  258.         else
  259.           stop("нет эндер-сундука")
  260.         end
  261.       end
  262.       status("ищу инструмент в эндер-сундуке")
  263.       placechest(true)
  264.       r.select(tools)
  265.       i_c.equip()
  266.       if electric() then
  267.         waitdrop()  
  268.         status("положил разряженный инструмент")
  269.       else
  270.         r.drop()
  271.       end
  272.       if not findtool() then
  273.         status("в сундуке нет инструмента")
  274.         while not findtool() do
  275.           r.setLightColor(0xFFFFFF)
  276.           computer.beep(1000, 1)
  277.           r.setLightColor(0xFF0000)
  278.           os.sleep(5)
  279.         end
  280.         r.setLightColor(0xFFFFFF)
  281.       end
  282.       placechest()
  283.     else
  284.       stop("в инвентаре робота нет инструмента")
  285.     end
  286.     r.select(1)
  287.   elseif r.detect() then
  288.     local d1 = string.format("%.3f",r.durability())
  289.     for i, side in ipairs({1,3,0}) do
  290.       com.robot.swing(side)
  291.       local d2 = string.format("%.3f",r.durability())
  292.       if d2 < d1 then
  293.         durability = math.floor(d2/(d1-d2))
  294.         break
  295.       end
  296.     end
  297.   end
  298. end
  299.  
  300. --сортируем лут
  301. local function sortlut()
  302.   status("сортирую лут...")
  303.   r.swingDown()
  304.   for i = 1,invsize do      
  305.     if r.count(i) > 0 then
  306.       local item = i_c.getStackInInternalSlot(i)
  307.       if string.find(item.name,"coal") then
  308.         r.select(i)
  309.         r.transferTo(coal)
  310.       else
  311.         for n = 1,#scrap do
  312.           if scrap[n] == item.name:gsub('%g+:','') then
  313.             r.select(i)
  314.             r.dropDown()
  315.             break
  316.           end
  317.         end
  318.       end
  319.     end
  320.   end
  321.   for i = 1,invsize-3 do
  322.     if r.count(i) == 0 then
  323.       for j = invsize-3,1,-1 do
  324.         if r.count(j) > 0 then
  325.           if j < i then
  326.             break
  327.           end
  328.           r.select(j)
  329.           r.transferTo(i)
  330.           break
  331.         end
  332.       end
  333.     end
  334.   end
  335.   if r.count(invsize-6) > 0 then
  336.     local unload = function()
  337.       local inv = i_c.getInventorySize(placeside)
  338.       local dropcount = 0
  339.       if inv then
  340.         for i = 1,invsize-3 do
  341.           if r.count(i) > 0 then
  342.             r.select(i)
  343.             unloaded = unloaded + r.count(i)
  344.             dropcount = dropcount + 1
  345.             if dropcount < inv then
  346.               waitdrop()
  347.             else
  348.               break
  349.             end
  350.           end
  351.         end
  352.         chestcoal = true
  353.       else
  354.         stop("нет сундука")
  355.         return
  356.       end
  357.       status("всего добыто: "..unloaded)
  358.     end
  359.     slotitem(coal,{"coal"})
  360.     if slotitem(chest,{"ender"}) then
  361.       placechest(true)
  362.       unload()
  363.       placechest()
  364.     elseif slotitem(chest,{"hest"}) then
  365.       placechest(true)
  366.       unload()
  367.     else
  368.       stop("инвентарь заполнен")
  369.     end
  370.   end
  371.   r.select(1)
  372. end
  373.  
  374. --дозоправка углём
  375. local function checkfuel()
  376.   local energy = computer.energy()
  377.   if energy <= 6000 then
  378.     refuel = true
  379.     chestcoal = true
  380.   end
  381.   if gen.count() <= 10 and refuel then
  382.     for i = 1,invsize do
  383.       local item = i_c.getStackInInternalSlot(i)
  384.       if item and string.find(item.name,"coal") then
  385.         r.select(i)
  386.         r.transferTo(coal)
  387.       end
  388.     end
  389.     r.select(coal)
  390.     if gen.insert() then
  391.       fuelinv = true
  392.       status("заправился, угля в генераторе = "..gen.count())
  393.     elseif fuelinv then
  394.       fuelinv = false
  395.       refuel = false
  396.       status("нет угля в инвентаре робота !!!")
  397.     elseif chestcoal and slotitem(chest,{"ender"}) then
  398.       status("ищу уголь в эндер-сундуке")
  399.       placechest(true)
  400.       local inv = i_c.getInventorySize(placeside)
  401.       if inv then
  402.         for slot = 1,inv do
  403.           local item = i_c.getStackInSlot(placeside,slot)
  404.           if item and string.find(item.name,"coal") then
  405.             r.select(coal)
  406.             i_c.suckFromSlot(placeside,slot,32)
  407.             status("взял уголь из сундука")
  408.             if gen.insert() then
  409.               status("заправился, угля в генераторе = "..gen.count())
  410.             end
  411.             break
  412.           end
  413.           if slot == inv then
  414.             chestcoal = false
  415.             status("нет угля в сундуке")
  416.           end
  417.         end
  418.       end
  419.       placechest()
  420.     end
  421.     r.select(1)
  422.   end
  423.   if energy <= 5000 then
  424.     if gen.count() >= 10 then
  425.       status("мало энергии, заряжаюсь до 10 000")
  426.       while true do
  427.         os.sleep(10)
  428.         if computer.energy() >= 10000 then
  429.           status("зарядился :)")
  430.           break
  431.         end
  432.         if gen.count() == 0 then
  433.           stop("закончился уголь")
  434.         end
  435.       end
  436.     else
  437.       stop("закончился уголь")  
  438.     end
  439.   end
  440. end
  441.  
  442. --движение в сторону side
  443. local function robotMove(side)
  444.   while true do
  445.     local ok,reason = com.robot.move(side)
  446.     if ok then
  447.       return true
  448.     elseif reason and reason == "already moving" then
  449.       os.sleep(0.1)
  450.     else
  451.       return false,reason
  452.     end
  453.   end
  454. end
  455.  
  456. --копаем и движемся вперед
  457. local function digForward(step)
  458.   for i = 1,step do
  459.     if durability <= 3 then
  460.       tool()
  461.     end
  462.     r.swingUp()
  463.     r.swing()
  464.     r.swingDown()
  465.     durability = durability - 3
  466.     if r.count(invsize-3) > 0 then
  467.       sortlut()
  468.     end
  469.     local tru,reason = 0
  470.     while true do
  471.       if r.detect() then
  472.         _,reason = r.swing()
  473.         durability = durability - 1
  474.       else
  475.         ok,reason = robotMove(3)
  476.         if ok then
  477.           break
  478.         end
  479.       end
  480.       tru = tru + 1
  481.       if tru == 3 then
  482.         tool()
  483.       elseif tru >= 20 then
  484.         tru = 0
  485.         stop("непреодолимое препятствие",reason)
  486.       end
  487.     end
  488.   end
  489. end
  490.  
  491. --копаем
  492. os.execute("cls")
  493. print("копатель алмазов by serafim")
  494. if width > 100 or width < 10 then
  495.   print("\n".."     ширина тунеля")
  496.   print("должна быть от 10 до 100".."\n")
  497.   os.exit()
  498. end
  499. print("угля в генераторе = "..gen.count())
  500. print("энергии = "..math.floor(100*computer.energy()/computer.maxEnergy()).." %")
  501. print("подготовка...")
  502. for slot = 1,invsize do
  503.   if r.count(slot) == 0 then
  504.     r.select(slot)
  505.     i_c.equip()
  506.     break
  507.   end
  508.   if slot == invsize then
  509.     print("в инвентаре робота нет пустых слотов")
  510.     os.exit()
  511.   end
  512. end
  513. if slotitem(tools,toollist) then
  514.   r.select(tools)
  515.   i_c.equip()
  516.   slotitem(tools,toollist)
  517. else
  518.   print("в инвентаре робота нет инструмента")
  519.   os.exit()
  520. end
  521. slotitem(chest,{"hest","ender"})
  522. slotitem(coal, {"coal"})
  523. print("ширина тунеля = "..width)
  524. r.setLightColor(0xFFFFFF)
  525. r.select(1)
  526. chunkload(true)
  527. while true do
  528.   checkfuel()
  529.   digForward(width-1)
  530.   r.turnRight()
  531.   digForward(stepline)
  532.   r.turnRight()
  533.   checkfuel()
  534.   digForward(width-1)
  535.   r.turnLeft()
  536.   digForward(stepline)
  537.   r.turnLeft()
  538. end
Add Comment
Please, Sign In to add comment