Advertisement
serafim7

quarry карьер Без замены инструмента [OpenComputers]

Nov 5th, 2020 (edited)
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 16.68 KB | None | 0 0
  1. --[[ opencomputers карьер by serafim
  2.      pastebin.com/V16CNBz3   update 13.06.21
  3.  
  4. Без замены инструмента для не ломаемой кирки !!!
  5.  
  6. Копает змейкой квадрат проходя три слоя блоков за один подход,
  7. пока не выкопает весь объём до бэдрока или не упрётся в
  8. не разрушаемый блок, при этом вернётся к старту и сообщит о проблеме,
  9. также предложит продолжить копать с последней позиции.
  10.  
  11. требования:
  12. инвентарь, контроллер инвентаря, генератор, улучшение парение.
  13.  
  14. пример сборки:
  15. https://i.imgur.com/fR7F4fA.png
  16.  
  17. использование:
  18. на старте, сзади робота поставить сундук, уголь больше 20 штук.
  19. Робот может работать без сундука и всего прочего, нужна только кирка.
  20.  
  21. пример запуска: (по умолчанию один чанк)
  22. quarry 16 16 2  или  quarry
  23. -- 2 опустится в низ на 2 блока от старта.
  24.  
  25. получить список предметов:
  26. https://pastebin.com/au9etcfF
  27. ]]--
  28.  
  29. local a = {...}
  30. local width = tonumber(a[1]) or 16 --ширина
  31. local length = tonumber(a[2]) or 16 --длина
  32. local down = tonumber(a[3]) or 2 --опустится в низ
  33.  
  34. --список мусора
  35. local scrap = {
  36.   "cobblestone", --булыжник
  37.   "stone",       --камень
  38.   "dirt",        --земля
  39.   "gravel",      --гравий
  40.   "flint",       --кремень
  41.   "sand",        --песок
  42.   "sandstone"    --песчаник
  43. }
  44.  
  45. local event = require("event")
  46. local com = require('component')
  47. local computer = require("computer")
  48. local cheststart,fuelchest,fuelinv,refuel = true,true,true,true
  49. local depth,xPos,zPos,xDir,zDir = 0,0,0,0,1
  50. local ridht,bedrock,unloaded = true,false,0
  51. local timestart = computer.uptime()
  52. local x,y,z,xd,zd
  53.  
  54. if not com.isAvailable("robot") then
  55.   print("только роботы могут использовать эту программу")
  56.   os.exit()
  57. end
  58. local r = require("robot")
  59.  
  60. local invsize = r.inventorySize()
  61. local coal = invsize
  62. local tools = invsize-1
  63.  
  64. if not com.isAvailable("inventory_controller") then
  65.   print("нет контроллера инвентаря")
  66.   os.exit()
  67. end
  68. local i_c = com.inventory_controller
  69.  
  70. if not com.isAvailable("generator") then
  71.   print("нет генератора")
  72.   os.exit()
  73. end
  74. local gen = com.generator
  75.  
  76. --статус
  77. local function status(message)
  78.   print("[ "..os.date("%H:%M:%S",computer.uptime()-timestart).." ] "..message)
  79. end
  80.  
  81. --чанк лоадер
  82. local function chunkload(state)
  83.   if com.isAvailable("chunkloader") then
  84.     if state then
  85.       com.chunkloader.setActive(true)
  86.       print("чанк лоадер активен")
  87.     else
  88.       com.chunkloader.setActive(false)
  89.       print("чанк лоадер деактивирован".."\n")
  90.     end
  91.   end
  92. end
  93.  
  94. --поиск предмета в инвентаре робота
  95. local function slotitem(slot, list)
  96.   local item = i_c.getStackInInternalSlot(slot)
  97.   if item then
  98.     for j, name in pairs(list) do
  99.       if string.find(item.name,name) then
  100.         if item.charge == nil or item.charge/item.maxCharge > toolstrength then
  101.           return true
  102.         end
  103.       end
  104.     end
  105.   end
  106.   for i = 1,invsize do
  107.     if r.count(i) > 0 then
  108.       for j, name in pairs(list) do
  109.         local item = i_c.getStackInInternalSlot(i)
  110.         if item and string.find(item.name,name) then
  111.           r.select(i)
  112.           r.transferTo(slot)
  113.           return true
  114.         end
  115.       end
  116.     end
  117.   end
  118.   return false
  119. end
  120.  
  121. --взять из сундука расходники
  122. local function servise(slotinv, list)
  123.   local inv = i_c.getInventorySize(3)
  124.   if inv then
  125.     if slotitem(slotinv, list) then
  126.       return true
  127.     end
  128.     r.select(slotinv)
  129.     if r.count(slotinv) > 0 and not r.drop() then
  130.       returnHome("в сундуке нет места")
  131.       return false
  132.     end
  133.     for slot = 1,inv do
  134.       for j, name in pairs(list) do
  135.         local item = i_c.getStackInSlot(3,slot)
  136.         if item and string.find(item.name,name) then
  137.           i_c.suckFromSlot(3, slot)
  138.           return true
  139.         end
  140.       end
  141.     end
  142.     return false
  143.   else
  144.     returnHome("нет сундука")
  145.   end
  146. end
  147.  
  148. --заряжаемся от зарядчика
  149. local function charging()
  150.   local chardg = true
  151.   while true do
  152.     local e1 = computer.energy()
  153.     os.sleep(2)
  154.     local e2 = computer.energy()  
  155.     if e2 > e1 + 500 then
  156.       if chardg then
  157.         chardg = false
  158.         status("заряжаюсь...")
  159.       end
  160.       os.sleep(2)
  161.     else
  162.       break
  163.     end
  164.   end
  165. end
  166.  
  167. --сортируем лут
  168. local function sortlut(droplut)
  169.   status("сортирую лут...")
  170.   r.swingDown()
  171.   for i = 1,invsize do      
  172.     if r.count(i) > 0 then
  173.       local item = i_c.getStackInInternalSlot(i)
  174.       if string.find(item.name,"coal") then
  175.         r.select(i)
  176.         r.transferTo(coal)
  177.       else
  178.         for n = 1,#scrap do
  179.           if scrap[n] == item.name:gsub('%g+:','') then
  180.             r.select(i)
  181.             r.dropDown()
  182.             break
  183.           end
  184.         end
  185.       end
  186.     end
  187.   end
  188.   for i = 1,invsize-1 do
  189.     if r.count(i) == 0 then
  190.       for j = invsize-1,1,-1 do
  191.         if r.count(j) > 0 then
  192.           if j < i then
  193.             break
  194.           end
  195.           r.select(j)
  196.           r.transferTo(i)
  197.           break
  198.         end
  199.       end
  200.     end
  201.   end
  202.   local unload = function()
  203.     local inv = i_c.getInventorySize(3)
  204.     if inv then
  205.       cheststart = true
  206.       for i = 1,invsize-1 do
  207.         if r.count(i) > 0 then
  208.           r.select(i)
  209.           unloaded = unloaded + r.count(i)
  210.           if not r.drop() then
  211.             returnHome("в сундуке нет места")
  212.             return
  213.           end
  214.         end
  215.       end
  216.       r.select(coal)
  217.       gen.insert()
  218.       servise(coal, {"coal"})
  219.       charging()
  220.     elseif not cheststart then
  221.       returnHome("инвентарь заполнен")
  222.     else
  223.       returnHome("нет сундука")
  224.     end
  225.     fuelchest = true
  226.     status("всего добыто руды: "..unloaded)
  227.   end
  228.   if r.count(invsize-6) > 0 then
  229.     status("возвращаюсь к сундуку сложить лут")
  230.     x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
  231.     goTo( 0,0,0,0,-1 )
  232.     unload()
  233.     goTo( x,y,z,xd,zd )
  234.   end
  235.   if droplut and cheststart then
  236.     unload()
  237.   end
  238.   r.select(1)
  239. end
  240.  
  241. --стоп
  242. local function stop(message)
  243.   print("\n".."!!! стоп !!!".."\n"..message.."\n")
  244.   r.setLightColor(0xFF0000)
  245.   r.turnAround()
  246.   chunkload(false)
  247.   computer.beep(1000, 1)
  248.   status("программа завершена")
  249.   os.exit()
  250. end
  251.  
  252. --возврат к старту
  253. function returnHome(message, save)
  254.   r.setLightColor(0xFF0000)
  255.   if save then
  256.     x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
  257.   end
  258.   if y ~= nil then
  259.     print("последняя ширина "..width..", длина "..length..", глубина "..y)
  260.   end
  261.   goTo( 0,0,0,0,-1 )
  262.   if save and cheststart and r.count(1) > 0 then
  263.     sortlut(true)
  264.   end
  265.   goTo( 0,0,0,0,1 )
  266.   status("!!! стоп !!!".."\n"..message.."\n")
  267.   chunkload(false)
  268.   print("продолжить копать ? [Y/n]")
  269.   while true do
  270.     r.setLightColor(0xFFFFFF)
  271.     computer.beep(1000, 1)
  272.     r.setLightColor(0xFF0000)
  273.     local e = ({event.pull(10,"key_down")})[4]
  274.     if e == 49 then
  275.       computer.beep(500, 0.1)
  276.       print("программа завершена")
  277.       os.exit()
  278.     elseif e == 21 or e == 28 then
  279.       computer.beep(500, 0.1)
  280.       r.setLightColor(0xFFFFFF)
  281.       print("продолжаю копать...")
  282.       chunkload(true)
  283.       goTo( x,y,z,xd,zd )
  284.       break
  285.     end
  286.   end
  287. end
  288.  
  289. --дозаправка углём
  290. local function checkfuel()
  291.   if computer.energy() <= 6000 then
  292.     refuel = true
  293.   end
  294.   if gen.count() <= 10 and refuel then
  295.     for i = 1,invsize do
  296.       local item = i_c.getStackInInternalSlot(i)
  297.       if item and string.find(item.name,"coal") then
  298.         r.select(i)
  299.         r.transferTo(coal)
  300.       end
  301.     end
  302.     r.select(coal)
  303.     if gen.insert() then
  304.       fuelinv = true
  305.       status("заправился, угля в генераторе = "..gen.count())
  306.     elseif fuelchest and cheststart then
  307.       x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
  308.       status("возвращаюсь к сундуку за углем")
  309.       goTo( 0,0,0,0,-1 )
  310.       if servise(coal, {"coal"}) then
  311.         r.select(coal)
  312.         gen.insert()
  313.         status("заправился, угля в генераторе = "..gen.count())
  314.       else
  315.         fuelchest = false
  316.         status("в сундуке нет угля")
  317.       end
  318.       charging()
  319.       goTo( x,y,z,xd,zd )
  320.     else
  321.       refuel = false
  322.       if fuelinv then
  323.         fuelinv = false
  324.         status("нет угля в инвентаре робота !!!")
  325.       end
  326.     end
  327.     r.select(1)
  328.   end
  329.   if computer.energy() <= 5000 then
  330.     x,y,z,xd,zd = xPos,depth,zPos,xDir,zDir
  331.     status("энергии < 5 000 возвращаюсь")
  332.     goTo( 0,0,0,0,1 )
  333.     charging()
  334.     if computer.energy() >= 10000 then
  335.       status("зарядился :)")
  336.       goTo( x,y,z,xd,zd )
  337.       return
  338.     elseif gen.count() >= 10 then
  339.       status("мало энергии, заряжаюсь до 10 000")
  340.       while true do
  341.         os.sleep(10)
  342.         if computer.energy() >= 10000 then
  343.           status("зарядился :)")
  344.           goTo( x,y,z,xd,zd )
  345.           break
  346.         elseif gen.count() == 0 then
  347.           returnHome("закончился уголь")
  348.           break
  349.         end
  350.       end
  351.     else
  352.       returnHome("закончился уголь")
  353.     end
  354.   end
  355. end
  356.  
  357. --движение в сторону side
  358. local function robotMove(side)
  359.   while true do
  360.     local ok,reason = com.robot.move(side)
  361.     if ok then
  362.       return true
  363.     elseif reason and reason == "already moving" then
  364.       os.sleep(0.1)
  365.     else
  366.       return false,reason
  367.     end
  368.   end
  369. end
  370.  
  371. --идём по Х в 0 координат
  372. local function x_forward()
  373.   for xx = 1,width-1 do
  374.     while true do
  375.       if robotMove(3) then
  376.         xPos = xPos - 1
  377.         break
  378.       else
  379.         r.swing()
  380.       end
  381.     end
  382.   end
  383. end
  384.  
  385. --движемся в верх
  386. local function tryUp()
  387.   local tru = 0
  388.   while true do
  389.     if robotMove(1) then
  390.       depth = depth - 1
  391.       break
  392.     else
  393.       r.swingUp()
  394.     end
  395.     tru = tru + 1
  396.     if tru >= 7 then
  397.       tru = 0
  398.       returnHome("не могу подняться",true)
  399.     end
  400.   end
  401. end
  402.  
  403. --обнаружение бедрока
  404. local function checkbedrock()
  405.   for i = 1,3 do
  406.     if r.detectDown() and not r.swingDown() then
  407.       if bedrock then
  408.         break
  409.       elseif i == 3 then
  410.         status("низ достигнут !")
  411.         bedrock = true
  412.         if y ~= nil then
  413.           status("глубина "..y)
  414.         end
  415.       end
  416.     else
  417.       break
  418.     end
  419.   end
  420. end
  421.  
  422. --копаем и движемся вперед
  423. local function digForward()
  424.   r.swingUp()
  425.   r.swing()
  426.   checkbedrock()
  427.   if r.count(invsize-2) > 0 then
  428.     sortlut()
  429.   end
  430.   local tru,reason = 0
  431.   while true do
  432.     if r.detect() then
  433.       _,reason = r.swing()
  434.     else
  435.       ok,reason = robotMove(3)
  436.       if ok then
  437.         xPos = xPos + xDir
  438.         zPos = zPos + zDir
  439.         break
  440.       end
  441.     end
  442.     tru = tru + 1
  443.     if tru == 4 or tru == 5 then
  444.       if bedrock then
  445.         tryUp()
  446.       end
  447.     elseif tru >= 20 then
  448.       if reason then
  449.         print("причина возврата: "..reason)
  450.       end
  451.       tru = 0
  452.       returnHome("непреодолимое препятствие",true)
  453.     end
  454.   end
  455. end
  456.  
  457. --спускаемся в низ
  458. local function go_down()
  459.   for zz = 1,down do
  460.     while true do
  461.       checkbedrock()
  462.       if robotMove(0) then
  463.         depth = depth + 1
  464.         break
  465.       elseif bedrock then
  466.         while true do
  467.           r.swing()
  468.           if r.detect() then
  469.             tryUp()
  470.           else
  471.             return
  472.           end
  473.         end
  474.       end
  475.     end
  476.   end
  477. end
  478.  
  479. --поворот в лево
  480. local function turnLeft()
  481.   while not r.turnLeft() do
  482.     os.sleep(0.1)
  483.   end
  484.   xDir, zDir = -zDir, xDir
  485. end
  486.  
  487. --поворот в право
  488. local function turnRight()
  489.   while not r.turnRight() do
  490.     os.sleep(0.1)
  491.   end
  492.   xDir, zDir = zDir, -xDir
  493. end
  494.  
  495. --навигация к сундуку
  496. function goTo( x,y,z,xd,zd )
  497.   local Xposition = function()
  498.     if xPos > x then
  499.       while xDir ~= -1 do
  500.         turnLeft()
  501.       end
  502.       while xPos > x do
  503.         if robotMove(3) then
  504.           xPos = xPos - 1
  505.         else
  506.           r.swing()
  507.         end
  508.       end
  509.     elseif xPos < x then
  510.       while xDir ~= 1 do
  511.         turnRight()
  512.       end
  513.       while xPos < x do
  514.         if robotMove(3) then
  515.           xPos = xPos + 1
  516.         else
  517.           r.swing()
  518.         end
  519.       end
  520.     end
  521.   end
  522.   local Zposition = function()
  523.     if zPos > z then
  524.       while zDir ~= -1 do
  525.         turnLeft()
  526.       end
  527.       while zPos > z do
  528.         if robotMove(3) then
  529.           zPos = zPos - 1
  530.         else
  531.           r.swing()
  532.         end
  533.       end
  534.     elseif zPos < z then
  535.       while zDir ~= 1 do
  536.         turnRight()
  537.       end
  538.       while zPos < z do
  539.         if robotMove(3) then
  540.           zPos = zPos + 1
  541.         else
  542.           r.swing()
  543.         end
  544.       end
  545.     end
  546.   end
  547.   r.select(1)
  548.   while depth < y do
  549.     while xDir ~= 0 or zDir ~= 1 do
  550.       turnRight()
  551.     end
  552.     if robotMove(0) then
  553.       depth = depth + 1
  554.     else
  555.       r.swingDown()
  556.     end
  557.   end
  558.   if y > 0 then
  559.     Zposition()
  560.     Xposition()
  561.   else
  562.     Xposition()
  563.     Zposition()
  564.   end
  565.   while depth > y do
  566.     if robotMove(1) then
  567.       depth = depth - 1
  568.     else
  569.       r.swingUp()
  570.     end
  571.   end
  572.   while xDir ~= xd or zDir ~= zd do
  573.     turnRight()
  574.   end
  575. end
  576.  
  577. --копаем
  578. local function dig()
  579.   os.execute("cls")
  580.   print("Только для для не ломаемой кирки".."\n")
  581.   print("размер карьера:  ширина "..width.."  длина "..length)
  582.   print("угля в генераторе = "..gen.count())
  583.   print("энергии = "..math.floor(100*computer.energy()/computer.maxEnergy()).." %")
  584.   print("подготовка...")
  585.   goTo( 0,0,0,0,-1 )
  586.   for slot = 1,invsize do
  587.     if r.count(slot) == 0 then
  588.       r.select(slot)
  589.       i_c.equip()
  590.       break
  591.     end
  592.     if slot == invsize then
  593.       stop("в инвентаре робота нет пустых слотов")
  594.     end
  595.   end
  596.   local inv = i_c.getInventorySize(3)
  597.   if inv then
  598.     cheststart = true
  599.     print("доступен сундук")
  600.     if servise(coal, {"coal"}) then
  601.       r.select(coal)
  602.       if gen.insert() then
  603.         print("заправился, угля в генераторе = "..gen.count())
  604.         servise(coal, {"coal"})
  605.       end
  606.     else
  607.       fuelchest = false
  608.     end
  609.     if servise(tools, {"ickaxe"}) then
  610.       r.select(tools)
  611.       i_c.equip()
  612.     else
  613.       stop("нет инструмента")
  614.     end
  615.   else
  616.     cheststart = false
  617.     print("сундук сзади робота не найден")
  618.     checkfuel()
  619.     if slotitem(tools, {"ickaxe"}) then
  620.       r.select(tools)
  621.       i_c.equip()
  622.     else
  623.       stop("нет инструмента")
  624.     end
  625.   end
  626.   goTo( 0,0,0,0,1 )
  627.   charging()
  628.   r.setLightColor(0xFFFFFF)
  629.   chunkload(true)
  630.   print("опускаюсь на "..down.." блока(ов)")
  631.   for height = 1,256 do
  632.     refuel = true
  633.     checkfuel()
  634.     go_down()
  635.     down = 3
  636.     for xx = 1,width do
  637.       for yy = 1,length-1 do
  638.         digForward()
  639.       end
  640.       checkfuel()
  641.       if xx ~= width then
  642.         if ridht then
  643.           turnRight()
  644.           digForward()
  645.           turnRight()
  646.           ridht = false
  647.         else
  648.           turnLeft()
  649.           digForward()
  650.           turnLeft()
  651.           ridht = true
  652.         end
  653.       end
  654.     end
  655.     r.swingUp()
  656.     r.swingDown()
  657.     if ridht then
  658.       turnLeft()
  659.       x_forward()
  660.       turnLeft()
  661.       ridht = false
  662.     else
  663.       turnRight()
  664.       x_forward()
  665.       turnRight()
  666.       ridht = true
  667.     end
  668.     if bedrock then
  669.       goTo( 0,0,0,0,-1 )
  670.       sortlut(true)
  671.       stop("завершил копать :)")
  672.     end
  673.   end
  674. end
  675.  
  676. dig()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement