zed_com

Копалка

Jul 20th, 2015
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 35.53 KB | None | 0 0
  1. local APIS={}
  2. local inv_size = 16
  3. local inv_side = require("sides").back
  4. local charge_side = require("sides").left
  5. local battery_side = require("sides").bottom
  6. local temp_state = {x=0, y=0, z=0, dr=3}
  7. local lc = {x=0, y=0, z=0, dr=3}
  8. local way = 0
  9. local ore_count = 0
  10. local xxx = 0
  11. local yyy = 0
  12. local zzz = 0
  13. local scrap = {
  14.     "minecraft:stone",
  15.     "minecraft:cobblestone",
  16.     "minecraft:dirt",
  17.     "minecraft:gravel",
  18.     "minecraft:sand",
  19.     "minecraft:grass",
  20.     "minecraft:sandstone",
  21.     "minecraft:mossy_cobblestone",
  22.     "minecraft:stonebrick",
  23. "minecraft:nether_brick",
  24. "minecraft:netherrack",
  25. "minecraft:soulsand"}
  26.  
  27. local fuel_list = {
  28.   "minecraft:fence",
  29.   "minecraft:planks",
  30.   "minecraft:log",
  31.   "minecraft:coal_block",
  32.   "minecraft:coal",
  33. "minecraft:nether_brick_fence",
  34. "minecraft:nether_brick_stairs"}  
  35.  
  36. local mining_tools_list = {
  37.   "minecraft:stone_pickaxe",
  38.   "minecraft:iron_pickaxe",
  39.   "minecraft:golden_pickaxe",
  40.   "appliedenergistics2:item.ToolCertusQuartzPickaxe",
  41.   "appliedenergistics2:item.ToolNetherQuartzPickaxe",
  42.   "IC2:itemToolBronzePickaxe",
  43.   "Forestry:bronzePickaxe",
  44.   "minecraft:diamond_pickaxe",
  45.   "IC2:itemToolDrill",
  46.   "IC2:itemToolDDrill",
  47.   "IC2:itemToolIridiumDrill",
  48.   "GraviSuite:advDDrill"}
  49.  
  50.  
  51. function APIS.duster(tmr)
  52.  local inv = require("component").inventory_controller
  53.  local r = require("robot")
  54.  while true do
  55.   for i=1,7 do
  56.    local temp = inv.getStackInSlot(3,i)
  57.    if temp then
  58.     if  temp.name == "IC2:itemDustSmall" and math.floor(temp.size/9) > 0 then
  59.      for j=1,3 do
  60.       r.select(j)
  61.       inv.suckFromSlot(3,i,math.floor(temp.size/9))
  62.      end
  63.      for j=5,7 do
  64.       r.select(j)
  65.       inv.suckFromSlot(3,i,math.floor(temp.size/9))
  66.      end
  67.      for j=9,11 do
  68.       r.select(j)
  69.       inv.suckFromSlot(3,i,math.floor(temp.size/9))
  70.      end
  71.      r.select(4)
  72.      require("component").crafting.craft(math.floor(temp.size/9))
  73.      r.drop()
  74.     end
  75.    end
  76.   end
  77.   os.sleep(tmr)
  78.  end
  79. end
  80. function APIS.charge(charge_side)
  81. --функция зарядки робота от чарджера, т.к. в этом билде ОС он категорически не принимает
  82. --ред сигнал робота, временно переориентировал на рычаг.
  83. comp = require("computer")
  84. while comp.energy() < (comp.maxEnergy()/2) do
  85. --local rs = require("component").redstone
  86. --rs.setOutput(charge_side, 15)
  87. require("term").clear()
  88. APIS.use(charge_side)
  89. print("Зарядка...")
  90. os.sleep(60)
  91. --rs.setOutput(charge_side, 0)
  92. APIS.use(charge_side)
  93. end
  94. print("Батарея заряжена")
  95. return true
  96. end
  97. function APIS.charge_tool(chargerSide, slot)
  98. --функция проверки заряда бура в руках робота, передача его на зарядку в батбокс/чарджер
  99.     local inv = require("component").inventory_controller
  100.     local r = require("robot")    
  101.     local side = 3
  102.     local tool = nil
  103.     if chargerSide == 1 then
  104.         side=1
  105.     elseif chargerSide == 0 then
  106.         side=0
  107.     end
  108.     if r.durability() == nil then
  109.         return false
  110.     end
  111.     if r.durability() < 0.3 then
  112.         r.select(slot)
  113.         inv.equip()
  114.         tool = inv.getStackInInternalSlot(slot)
  115.         inv.equip()
  116.         if not(lc.x == 0 and lc.y == 0 and lc.z == 0) then
  117.             return true
  118.         end
  119.     else
  120.         return false
  121.     end
  122.  
  123.     local function isElectric(device)
  124.         if device.maxCharge ~= nil then
  125.             return true
  126.         else
  127.             return false
  128.         end
  129.     end
  130.     local function find_new_tool()
  131.         APIS.rot(inv_side)
  132.         local temp = APIS.inv_scaner(mining_tools_list, false, start_slot)
  133.         print("Поиск замены инструменту в сундуке.")
  134.         while temp ~= 0 do
  135.             local temp_device = inv.getStackInSlot(3, temp)
  136.             if isElectric(temp_device) then
  137.                 if temp_device.charge/temp_device.maxCharge > 0.6 then
  138.                     break
  139.                 else
  140.                     temp = APIS.inv_scaner(mining_tools_list, false, temp+1)
  141.                 end
  142.             else
  143.                 if temp_device.damage/temp_device.maxDamage < 0.4 then
  144.                     break
  145.                 else
  146.                     temp = APIS.inv_scaner(mining_tools_list, false, temp+1)
  147.                 end
  148.             end
  149.         end
  150.         return temp
  151.     end
  152.     local function service(device)
  153.         if isElectric(device) then
  154.             APIS.rot(chargerSide)  
  155.             if not inv.getInventorySize(3) ~= nil then
  156.                 print("Зарядник не найден. Установите зарядник.")
  157.                 while not inv.getInventorySize(3) ~= nil do
  158.                     os.sleep(5)
  159.                 end
  160.             end
  161.             r.select(slot)
  162.             inv.equip()
  163.             inv.dropIntoSlot(3,1)
  164.             print("Зарядка инструмента.")
  165.             while inv.getStackInSlot(3,1).charge < device.maxCharge do
  166.                 os.sleep(10)
  167.             end
  168.             inv.suckFromSlot(3,1)
  169.             inv.equip()            
  170.         else
  171.             print("Поиск инструмента в сундуке.")
  172.             APIS.rot(inv_side)
  173.             while true do
  174.                 local temp = find_new_tool()
  175.                 if temp ~= 0 then
  176.                     r.select(slot)
  177.                     inv.equip()
  178.                     if not r.drop() then
  179.                         print("Нет места в сундуке. Освободите место.")
  180.                         while not r.drop() do
  181.                             os.sleep(10)
  182.                         end
  183.                     end
  184.                     inv.suckFromSlot(3, temp)
  185.                     inv.equip()
  186.                     r.select(1)
  187.                     break
  188.                 end
  189.             end
  190.         end
  191.     end
  192.  
  193.  
  194.     if lc.x == 0 and lc.y == 0 and lc.z == 0 then
  195.         print("Сервис инструмента.")
  196.         service(tool)
  197.     else
  198.         return false
  199.     end  
  200. end
  201. function APIS.use(s)
  202. --функция юза в заданную сторону.
  203. local r = require("robot")
  204. if s == 1 then r.useUp()
  205. elseif s == 2 then
  206. r.turnAround()
  207. r.use()
  208. r.turnAround()
  209. elseif s == 3 then r.use()
  210. elseif s == 4 then
  211. r.turnRight()
  212. r.use()
  213. r.turnLeft()
  214. elseif s==5 then
  215. r.turnLeft()
  216. r.use()
  217. r.turnRight()
  218. else
  219. r.useDown()
  220. end
  221. end
  222. function APIS.drop()
  223. --функция дропа всего инвентаря в сундук, если таковой стоит перед носом
  224.  local inv = require("component").inventory_controller
  225.  local r= require("robot")
  226.  while true do
  227.   if r.detect() then
  228.    if inv.getInventorySize(3) ~= nil then
  229.     for i=1,inv_size-1 do
  230.      if inv.getStackInInternalSlot(i) ~= nil then
  231.       r.select(i)
  232.       if not r.drop() then
  233.        print("Сундук переполнен. Освободите место под складирование.")
  234.        while not r.drop() do
  235.         os.sleep(5)
  236.        end
  237.       end
  238.      end
  239.     end
  240.     break
  241.    else
  242.     print("Блок не является сундуком.")
  243.     os.sleep(5)
  244.    end
  245.   else
  246.    print("Установите сундук!")
  247.    os.sleep(5)
  248.   end
  249.  end
  250. end
  251. function APIS.printState()
  252.     local tunnel = require("component").tunnel
  253. --используется для отладки движений робота
  254. --print("Статус:")
  255. --print(lc.x, lc.y, lc.z, lc.dr)
  256.   tunnel.send("x: "..lc.x + xxx.." y: "..lc.y + yyy.." z: "..lc.z + zzz)
  257. --print("x:"..lc.x + xxx.." y:"..lc.y + yyy.." z:"..lc.z + zzz)
  258. --print(temp_state.x, temp_state.y, temp_state.z, temp_state.dr)
  259. end
  260.  
  261. function APIS.harvest(count)
  262. --функция для фермера на IC кропсах, аргумент - сколько раз собирать с 1 места
  263.  local r=require("robot")
  264.  for i=1,count do
  265.   r.useDown()
  266.  end
  267. end
  268. function APIS.dig(arg)
  269. --функция целевого копания по стороне-аргументу, скорее всего потру ее, при оптимизации
  270.  r = require("robot")
  271.  event = require("event")
  272.  if arg == 3 then
  273.   r.swing()
  274.  elseif arg == 1 then
  275.   while r.detectUp() do
  276.    r.swingUp()
  277.   end
  278.  elseif arg == 0 then
  279.   r.swingDown()
  280.  end
  281. end
  282. function APIS.isScrap(name)
  283.  --проверка является ли итем по имени мусором.
  284.  for i, nm in pairs(scrap) do
  285.   if name == nm then  
  286.    return true
  287.   end  
  288.  end
  289.  return false
  290. end
  291. function APIS.ore_analyze(arg)
  292.  --метод проверки, является ли блок "немусором"
  293.  if arg ~= nil then
  294.   if require("component").isAvailable("geolyzer") then
  295.    local lyz = require("component").geolyzer
  296.    if APIS.isScrap(lyz.analyze(arg).name) then
  297.     return false
  298.    else
  299.     return true
  300.    end
  301.   else
  302.    print("Геолайзер не обнаружен в системе.")
  303.    return false
  304.   end
  305.  else
  306.   print("Не указан аргумент(сторона проверки).")
  307.  end
  308. end
  309. function APIS.dig_ore()
  310. --метод для копания только руды, в слоеном карьере.
  311.  local r=require("robot")
  312.  if r.detectUp() then
  313.   if APIS.ore_analyze(1) then
  314.    APIS.dig(1)
  315.   end
  316.  end
  317.  if r.detectDown() then
  318.   if APIS.ore_analyze(0) then
  319.    APIS.dig(0)
  320.   end
  321.  end
  322. end
  323. function APIS.turnLeft()
  324. local r = require("robot")
  325. r.turnLeft()
  326. if lc.dr == 3 then
  327. lc.dr = 5
  328. elseif lc.dr == 4 then
  329. lc.dr = 3
  330. elseif lc.dr == 2 then
  331. lc.dr = 4
  332. elseif lc.dr == 5 then
  333. lc.dr = 2
  334. end
  335. end
  336. function APIS.turnRight()
  337. local r = require("robot")
  338. r.turnRight()
  339. if lc.dr == 3 then
  340. lc.dr = 4
  341. elseif lc.dr == 4 then
  342. lc.dr = 2
  343. elseif lc.dr == 2 then
  344. lc.dr = 5
  345. elseif lc.dr == 5 then
  346. lc.dr = 3
  347. end
  348. end
  349. function APIS.turnAround()
  350.  local r = require("robot")
  351.     r.turnAround()
  352.     if lc.dr == 3 then
  353.         lc.dr = 2
  354.     elseif lc.dr == 4 then
  355.         lc.dr = 5
  356.     elseif lc.dr == 2 then
  357.         lc.dr = 3
  358.     elseif lc.dr == 5 then
  359.         lc.dr = 4
  360.     end
  361. end
  362. function APIS.rot(side)
  363.  if (side ~= 1) and (side ~= 0) and lc.dr-side ~=0 then
  364.   local sides = require("sides")
  365.   local r = require("robot")
  366.   if lc.dr == 3 then
  367.     if side == 4 then APIS.turnRight()
  368.     elseif side == 2 then APIS.turnAround()
  369.     elseif side == 5 then APIS.turnLeft()
  370.     end
  371.   elseif lc.dr == 4 then
  372.     if side == 2 then APIS.turnRight()
  373.     elseif side == 5 then APIS.turnAround()
  374.     elseif side == 3 then APIS.turnLeft()
  375.     end
  376.   elseif lc.dr == 2 then
  377.     if side == 5 then APIS.turnRight()
  378.     elseif side == 3 then APIS.turnAround()
  379.     elseif side == 4 then APIS.turnLeft()
  380.     end
  381.   else--5
  382.     if side == 3 then APIS.turnRight()
  383.     elseif side == 4 then APIS.turnAround()
  384.     elseif side == 2 then APIS.turnLeft()
  385.     end
  386.   end
  387.  end
  388.  APIS.printState()
  389. end
  390. function APIS.mUp()
  391. --функция движения вверх, сквозь породу.
  392.  local r = require("robot")
  393.  local try = 1
  394.  repeat
  395.   r.swingUp()
  396.   try = try + 1
  397.   if try >= 15 then
  398.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr=вверх"..lc.dr)
  399.    local _, det = require("robot").detectUp()
  400.    print(det.." сверху.")
  401.    print(require("component").geolyzer.analyze(1).name)
  402.    APIS.mTo(lc.x+2,lc.y,lc.z)  
  403.    APIS.back_to_the_future()  
  404.    APIS.printState()
  405.    return false
  406.   elseif try > 12 then
  407.    if require("component").geolyzer.analyze(1).name == "ExtraBees:hive" then
  408.     local inv = require("component").inventory_controller
  409.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  410.      inv.equip()
  411.      r.swingUp()
  412.      inv.equip()
  413.      r.select(1)
  414.     end
  415.    end
  416.   end
  417.  until not r.detectUp()
  418.  while try < 15 and not r.up() do
  419.   r.swingUp()
  420.   try = try + 1
  421.  end
  422.  if try < 15 then
  423.   lc.y = lc.y + 1
  424.   way = way + 1
  425. APIS.printState()
  426.   return true
  427.  end
  428. end
  429.  
  430. function APIS.mDown(action, arg)
  431. --функция движения вниз, сквозь породу.
  432.  local r = require("robot")
  433.  local event = require("event")
  434.  local try = 1
  435.  if action ~= nil then
  436.   action(arg)
  437.  end
  438.  repeat
  439.   r.swingDown()
  440.   try = try + 1
  441.   if try >= 15 then
  442.    APIS.printState()
  443.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr= вниз"..lc.dr)
  444.    local _, det = require("robot").detectDown()
  445.    print(det.." снизу.")
  446.    print(require("component").geolyzer.analyze(0).name)
  447.    APIS.back_to_the_future()
  448.    return false
  449.   elseif try > 12 then
  450.    if require("component").geolyzer.analyze(0).name == "ExtraBees:hive" then
  451.     local inv = require("component").inventory_controller
  452.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  453.      inv.equip()
  454.      r.swingDown()
  455.      inv.equip()
  456.      r.select(1)
  457.     end
  458.    end
  459.   end
  460.  until not r.detectDown()
  461.  while try < 15 and not r.down() do
  462.   r.swingDown()
  463.   try = try + 1
  464.  end
  465.  
  466.  if try < 15 then
  467.   lc.y = lc.y - 1
  468.   way = way + 1
  469.   return true
  470.  end
  471. end
  472.  
  473. function APIS.mForw(action,arg)
  474. --шаг вперед с действием или безБ сквозь породу, координатные отметки
  475.  local r = require("robot")
  476.  local event = require("event")
  477.  local try = 1
  478.  local sides = require("sides")
  479.  if action ~= nil then
  480.   action(arg)
  481.  end
  482.  repeat
  483.   r.swing()
  484.   try = try + 1
  485.   if try >= 15 then
  486.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr="..lc.dr)
  487.    local _, det = require("robot").detect()
  488.    print(det.." спереди.")
  489.    print(require("component").geolyzer.analyze(3).name)
  490.    APIS.back_to_the_future()
  491.    return false
  492.   elseif try > 12 then
  493.    if require("component").geolyzer.analyze(3).name == "ExtraBees:hive" then
  494.     local inv = require("component").inventory_controller
  495.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  496.      inv.equip()
  497.      r.swing()
  498.      inv.equip()
  499.      r.select(1)
  500.     end
  501.    end
  502.   end
  503.  until not r.detect()
  504.  while try < 15 and not r.forward() do
  505.   r.swing()
  506.   try = try + 1
  507.  end
  508.  if try < 15 then
  509.   way = way + 1
  510.  if lc.dr==2 then
  511.   lc.x = lc.x - 1
  512.  elseif lc.dr==3 then
  513.   lc.x = lc.x + 1
  514.  elseif lc.dr==4 then
  515.   lc.z = lc.z + 1
  516.  elseif lc.dr==5 then
  517.   lc.z = lc.z - 1
  518.  end  
  519.  APIS.printState()
  520.  return true
  521.  end
  522. end
  523.  
  524. function APIS.mTo(x, y, z, action, arg)
  525. --движение в заданную точку с заданым действием и аргументом действия. Координатное.
  526. local r = require("robot")
  527. local sides = require("sides")
  528.  if lc.x > x then
  529.   APIS.rot(sides.back)
  530.   while lc.x > x do
  531.    APIS.mForw(action,arg)
  532.   end
  533.  end
  534.  if lc.x < x then
  535.   APIS.rot(sides.forward)
  536.   while lc.x < x do
  537.    APIS.mForw(action,arg)
  538.   end
  539.  end
  540.  if lc.z > z then
  541.   APIS.rot(sides.left)
  542.   while lc.z > z do
  543.    APIS.mForw(action,arg)
  544.   end  
  545.  end
  546.  if lc.z < z then
  547.   APIS.rot(sides.right)
  548.   while lc.z < z do
  549.    APIS.mForw(action,arg)
  550.   end
  551.  end
  552.  while lc.y > y do
  553.   APIS.mDown(action,arg)
  554.   --print("едем вниз")
  555.  end
  556.  while lc.y < y do
  557.   APIS.mUp(action,arg)
  558.   --print("едем вверх")
  559.  end
  560. end
  561.  
  562. function APIS.plane(x, y, z, action, arg, forward)
  563. --проходка горизонтальной плоскости, координатная. Слоеный карьер, фермер.
  564.  local dir = "forward"  
  565.  if forward then
  566.   print("Плоскость вперед")
  567.   for j=0,z do
  568.    if dir == "forward" then
  569.     print("Движение вперед")
  570.     for i=0,x do
  571.      print("шаг вперед")
  572.      APIS.mTo(i,y,j,action,arg)
  573.     end
  574.     APIS.check_state()
  575.     dir = "back"
  576.     print("Поворот назад")
  577.    else
  578.     print("Движение назад")
  579.     for i=x,0,-1 do
  580.      print("шаг назад")
  581.      APIS.mTo(i,y,j,action,arg)
  582.     end
  583.     APIS.check_state()
  584.     dir = "forward"
  585.     print("Поворот вперед")
  586.    end
  587.   end
  588.  else
  589.  if z%2==0 then dir = "back" end
  590.   print("Плоскость обратная")
  591.   for j=z,0,-1 do
  592.    print(dir)
  593.    if dir == "forward" then
  594.     for i=0,x do
  595.      APIS.mTo(i,y,j,action,arg)
  596.     end
  597.     APIS.check_state()
  598.     dir = "back"
  599.    else
  600.     for i=x,0,-1 do
  601.      APIS.mTo(i,y,j,action,arg)
  602.     end
  603.     APIS.check_state()
  604.     dir = "forward"
  605.    end
  606.   end
  607.  end
  608. end
  609. function APIS.home(action,arg)
  610.  --функция возврата к сундуку для очистки инвентаря.
  611.  
  612.  temp_state.x = lc.x
  613.  temp_state.y = lc.y
  614.  temp_state.z = lc.z
  615.  temp_state.dr = lc.dr
  616.  APIS.mTo(0,0,0, action,arg)
  617.  APIS.rot(2)
  618.  APIS.drop_scrap()
  619.  APIS.drop()
  620.  --APIS.rot(3)
  621. end
  622.  
  623. function APIS.drop_scrap()
  624.  local r = require("robot")
  625.  local inv = require("component").inventory_controller
  626.   for i=1, inv_size do  
  627.    local slot = inv.getStackInInternalSlot(i)
  628.    if slot ~= nil then  
  629.     if APIS.isScrap(slot.name) then
  630.      r.select(i)
  631.      r.dropDown()
  632.     end
  633.    end
  634.   end
  635.   return APIS.inv_sorting()  
  636. end
  637. function APIS.back_to_mine(action,arg)
  638.  --возврат на точку останова(после очистки инвентаря) для возобновления работы.
  639.  APIS.mTo(0,temp_state.y,0, action,arg)
  640.  APIS.mTo(temp_state.x,temp_state.y,temp_state.z, action,arg)
  641.  APIS.rot(temp_state.dr)
  642. end
  643.  
  644. function APIS.back_to_the_future()
  645.  --Завершение программы ввиду непреодолимого препятствия.
  646.  print("Ошибка/препятствие. Возврат робота.")
  647.  APIS.mTo(lc.x, 0, lc.z)
  648.  APIS.home()
  649.  APIS.rot(3)
  650.  print("Робот на исходной. Завершение программы.")
  651.  os.exit()
  652. end
  653.  
  654. function APIS.check_inv()
  655. --вычисление величины собственного инвентаря
  656.  local r = require("robot")
  657.  local i = 16
  658.  local count = 16
  659.  while pcall(r.count, i) do
  660.   count = i
  661.   i=i+1
  662.  end
  663.  return count
  664. end
  665. function APIS.inv_sorting()
  666.  --Функция сортировки инвентаря(перекладывание содержимого без пустых ячеек)
  667.  --возвращает процентное заполнение инвентаря в целом
  668.  local inv = require("component").inventory_controller
  669.  local r = require("robot")
  670.  local items_stored = 0
  671.  inv_size = APIS.check_inv()
  672.  --цикл от начала до конца ищет пустые ячейки, когда находит - второй цикл от конца до
  673.  --начала ищет не пустые и перемещает на место пустых(упорядочивает)
  674.  --когда цикл начальный и конечный пересекается - перестает запускаться цикл с конца
  675.  --чтоб не было бесконечного перемешивания. После подсчет % занятого пространства и возврат значений.
  676.  for i=1, inv_size-1 do
  677.   if r.count(i) == 0 then
  678.    for j=inv_size-1, 1, -1 do
  679.     if r.count(j) > 0 then
  680.      if j<i then
  681.      break
  682.      end
  683.      r.select(j)
  684.      r.transferTo(i)
  685.      break
  686.     end
  687.    end
  688.   end
  689.  end
  690.  for i=1,inv_size do
  691.   if r.count(i) > 0 then
  692.    items_stored = items_stored + 1
  693.   end
  694.  end
  695.  --print(items_stored)
  696.  r.select(1)
  697.  return items_stored/inv_size
  698. end
  699.  
  700. function APIS.check_state()
  701.  --функция проверки состояния инвентаря и заряда батареи робота
  702.  --выбрасывание мусора из карманов и пожирание угля, если требуется
  703.  local r = require("robot")
  704.  local inv = require("component").inventory_controller
  705.  local comp = require("computer")
  706.  local c = require("component")
  707.  local need_fuel = comp.energy() < (comp.maxEnergy()*0.90)
  708.  
  709.  local function inventory()
  710.   local need_to_home = false
  711.   if (r.count(inv_size-2) > 0) then  
  712.     if APIS.drop_scrap() > 0.9 then
  713.      need_to_home = true
  714.     else
  715.      need_to_home = false
  716.     end
  717.   end
  718.   return need_to_home
  719.  end
  720.  
  721.  local function fuel(internal)
  722.   local need_to_home = false
  723.   if need_fuel and c.isAvailable("generator") and c.generator.count() == 0 then
  724.     local slt = APIS.inv_scaner(fuel_list, internal)
  725.     if slt ~= 0 and not internal then
  726.      r.select(inv_size-2)
  727.      inv.suckFromSlot(3, slt)
  728.      c.generator.insert()
  729.      r.select(1)
  730.      need_to_home = false
  731.     else
  732.      slt = APIS.inv_scaner(fuel_list, internal)
  733.      if slt ~= 0 and internal then  
  734.       r.select(slt)
  735.       c.generator.insert()
  736.       r.select(1)
  737.       need_to_home = false
  738.      else
  739.       need_to_home = true
  740.      end
  741.     end
  742.   elseif not c.isAvailable("generator") and need_fuel then
  743.    need_to_home = true
  744.   end
  745.   return need_to_home
  746.  end
  747.  
  748.     if  inventory() or fuel(true) or APIS.charge_tool(charge_side, inv_size-2) then
  749.         APIS.home()
  750.         os.sleep(15)
  751.         APIS.charge_tool(charge_side, inv_size-2)  
  752.         fuel(false)
  753.         APIS.back_to_mine()
  754.     end    
  755. end
  756.  
  757. function APIS.quarry(x, z)
  758. --слоистый геокарьер, копает слои 1 через 2, проверяет все блоки, берет только руду.
  759.  inv_size = APIS.check_inv()
  760.  for i=0, -256, -3 do  
  761.   if i%2 == 0 then  
  762.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, true)  
  763.   else  
  764.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, false)  
  765.   end  
  766.  end
  767.  APIS.home()
  768. end
  769.  
  770. function APIS.inv_scaner(filter, internal, start_slot)
  771. --автопоисковик заданного итема в своем инвентаре по системному имени.
  772. --возвращает номер ячейки итема, первого найденного от начала ивентаря.
  773.     local inv = require("component").inventory_controller
  774.     ins = inv.getInventorySize(3)
  775.     if start_slot == nil then
  776.         start_slot = 1
  777.     end
  778.     if filter == "empty" then
  779.         if internal then
  780.             for i=start_slot, inv_size do
  781.                 if inv.getStackInInternalSlot(i) == nil then
  782.                     return i
  783.                 end
  784.             end
  785.         else
  786.             for i=start_slot, inv.getInventorySize(3) do
  787.                 if inv.getStackInSlot(3, i) == nil then
  788.                     return i
  789.                 end
  790.             end
  791.         end
  792.     end  
  793.     if internal then
  794.         for i=start_slot, inv_size do
  795.             if inv.getStackInInternalSlot(i) ~= nil then
  796.                 if pcall(pairs, filter) then
  797.                     for j, name in pairs(filter) do
  798.                         if inv.getStackInInternalSlot(i).name == name then
  799.                             --print(filter.." найден!")
  800.                             return i
  801.                         end
  802.                     end
  803.                 else
  804.                     if inv.getStackInInternalSlot(i).name == filter then
  805.                         --print(filter.." найден!")
  806.                         return i
  807.                     end
  808.                 end
  809.             end
  810.         end
  811.         --print("Найти "..filter.." не удалось.")
  812.         return 0  
  813.     else
  814.         if ins ~= nil  then
  815.             for i=start_slot, ins do
  816.                 if inv.getStackInSlot(3, i) ~= nil then
  817.                     if pcall(pairs, filter) then
  818.                         for j, name in pairs(filter) do
  819.                             if inv.getStackInSlot(3, i).name == name then
  820.                                 --print(filter.." найден!")
  821.                                 return i
  822.                             end
  823.                         end
  824.                     else
  825.                         if inv.getStackInSlot(3, i).name == filter then
  826.                             --print(filter.." найден!")
  827.                             return i
  828.                         end
  829.                     end
  830.                 end
  831.             end
  832.             --print("Найти "..filter.." не удалось.")
  833.             return 0
  834.         else
  835.             return 0
  836.         end
  837.     end
  838. end
  839. function APIS.distance(blockA, blockB)
  840.  local dist = math.sqrt(math.pow(blockA.x - blockB.x,2) +
  841.    math.pow(blockA.z - blockB.z,2) + math.pow(blockA.y - blockB.y,2))
  842.  return dist
  843. end
  844. function APIS.closest_point(point, points)
  845.  local cl_num = 1
  846.  local length = APIS.distance(point, points[1])
  847.  for i=1, #points do
  848.   local l = APIS.distance(point, points[i])
  849.   if l < length then
  850.    cl_num = i
  851.    length = l
  852.   end
  853.  end
  854.  return cl_num
  855. end
  856. function APIS.waypoints(ores_table, last)
  857.  local way_table = {}
  858.  local count = #ores_table
  859.  table.insert(way_table, {x=lc.x, z=lc.z, y=lc.y})
  860.  while count ~= #way_table - 1 do
  861.   local j = APIS.closest_point(way_table[#way_table], ores_table)
  862.   table.insert(way_table, ores_table[j])
  863.   table.remove(ores_table, j)
  864.  end
  865.  return way_table, last
  866. end
  867. function APIS.scanVolume(xn,zn, bedrock, side, hight_border)
  868.  --сканирование карьерного "этажа" заданного радиуса -10 блоков вниз+сканер+10 блоков вверх
  869.  local geo = require("component").geolyzer
  870.  local ores_table = {}
  871.  local last = false
  872.  local x_limit = 0
  873.  local z_limit = 0
  874.  local x_increment = 1
  875.  local z_increment = 1
  876.  
  877.  if side == "north" or side == "север" then
  878.   x_limit = zn
  879.   x_increment = 1
  880.   z_limit = -xn
  881.   z_increment = -1
  882.  -- print("Выбранное направление: Север. Старт сканирования.")
  883.  elseif side == "west" or side == "запад" then
  884.   x_limit = -xn
  885.   x_increment = -1
  886.   z_limit = -zn
  887.   z_increment = -1
  888.  -- print("Выбранное направление: Запад. Старт сканирования.")
  889.  elseif side == "south" or side == "юг" then
  890.   x_limit = -zn
  891.   x_increment = -1
  892.   z_limit = xn
  893.   z_increment = 1
  894.  -- print("Выбранное направление: Юг. Старт сканирования.")
  895.  elseif side == "east" or side == "восток" or side == nil then
  896.   x_limit = xn
  897.   x_increment = 1
  898.   z_limit = zn
  899.   z_increment = 1
  900.  -- print("Выбранное направление: Запад. сканирования.")
  901.  end
  902.  
  903.  if xn == 0 and zn == 0 then
  904.     --print("Сканирование границ бедрока")
  905.   local tempr=geo.scan(0,0)
  906.   for i=10, 32 do
  907.    if tempr[i] < -0.3 then
  908.     --print("Бедрок обнаружен на уровне "..i-33+lc.y)
  909.     return i-33+lc.y, true
  910.    end
  911.   end
  912.   return 0, false
  913.  end
  914.  --print("Сканирование заданного объема, может занять несколько минут...")
  915.  for xt=0,x_limit,x_increment do
  916.   for zt=0,z_limit,z_increment do
  917.    local scan = geo.scan(xt,zt,true)
  918.    for yt=hight_border+33, 33+math.abs(hight_border) do
  919.     if scan[yt] > 2.05 and scan[yt] < 40 and ((yt-33)+lc.y) > bedrock then
  920.       if side == "north" or side == "север" then
  921.        table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
  922.       elseif side == "west" or side == "запад" then
  923.        table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
  924.       elseif side == "south" or side == "юг" then
  925.        table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
  926.       elseif side == "east" or side == "восток" or side == nil then
  927.        table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
  928.       end    
  929.     end
  930.    end
  931.   end
  932.  end
  933.  return ores_table
  934. end
  935. function APIS.whatsSide()
  936.  local geo = require("component").geolyzer
  937.  local r= require("robot")
  938.  local function isBlock(dens)
  939.   if dens ~= nil and dens ~= 0 then
  940.    return 1
  941.   elseif dens == 0 then
  942.    return 0
  943.   end
  944.  end
  945.  local function check(fig, front)
  946.   local figure1 = {
  947.    east = isBlock(geo.scan(1,0)[33]),
  948.    south = isBlock(geo.scan(0,1)[33]),
  949.    west = isBlock(geo.scan(-1,0)[33]),  
  950.    north = isBlock(geo.scan(0,-1)[33])
  951.    }  
  952.   if front then
  953.    if fig.east > figure1.east  then
  954.     return "east"
  955.    elseif fig.south > figure1.south then
  956.     return "south"
  957.    elseif fig.west > figure1.west then
  958.     return "west"
  959.    elseif fig.north > figure1.north then
  960.     return "north"
  961.    end
  962.   elseif not front then
  963.    if fig.east < figure1.east  then
  964.     return "east"
  965.    elseif fig.south < figure1.south then
  966.     return "south"
  967.    elseif fig.west < figure1.west then
  968.     return "west"
  969.    elseif fig.north < figure1.north then
  970.     return "north"
  971.    end  
  972.   end
  973.  end
  974.  local figure = {
  975.    east = isBlock(geo.scan(1,0)[33]),
  976.    south = isBlock(geo.scan(0,1)[33]),
  977.    west = isBlock(geo.scan(-1,0)[33]),  
  978.    north = isBlock(geo.scan(0,-1)[33])
  979.    }
  980.  APIS.rot(3)
  981.  while true do
  982.   if r.detect() then
  983.    r.swing()
  984.    local direction = check(figure, true)
  985.    r.place()
  986.    return direction
  987.   elseif r.detectDown() then
  988.    r.swingDown()
  989.    r.place()
  990.    local direction = check(figure, false)
  991.    r.swing()
  992.    r.placeDown()
  993.    return direction
  994.   end
  995.   print("Для ориентирования в пространстве недостаточно данных.")
  996.   print("Пожалуйста установите любой блок перед или под роботом и повторите попытку")
  997.   os.exit()
  998.  end
  999. end
  1000.  
  1001. function APIS.findoutBedrockLevel()
  1002.  local bedrock = -1
  1003.  local start_level = lc.y
  1004.  for i = lc.y, -256, -10 do
  1005.   local bed, catch = APIS.scanVolume(0,0)
  1006.   --print("Сканирование бедрока")
  1007.   if not catch then
  1008.    APIS.mTo(lc.x, i, lc.z)
  1009.   elseif bed < lc.y - 5 then
  1010.    --print("Найден бедрок")
  1011.    APIS.mTo(lc.x, i-4, lc.z)
  1012.    bedrock = APIS.scanVolume(0,0)
  1013.    break
  1014.   end
  1015.  end
  1016.  APIS.mTo(lc.x, start_level, lc.z)
  1017.  return bedrock
  1018. end
  1019.  
  1020. function APIS.clusterDigger(start_point, x,z, bedrock, side)
  1021.     --print("Кластер диггер")
  1022.     if side == nil then
  1023.         --print("В функцию кластер диггер сайд не поступила")
  1024.         side = APIS.whatsSide()
  1025.         --print("Направление: "..side)
  1026.     end
  1027.     if start_point == nil then
  1028.         start_point = lc
  1029.     end
  1030.     inv_size = APIS.check_inv()  
  1031.     APIS.mTo(start_point.x, start_point.y, start_point.z)
  1032.     for Y=lc.y, bedrock+6, -1 do
  1033.         if Y%21 == 0 or Y == bedrock + 9 then
  1034.             APIS.mTo(start_point.x, Y, start_point.z)
  1035.             APIS.rot(3)
  1036.             arr=APIS.waypoints(APIS.scanVolume(x-1,z-1, bedrock+4, side, -11))
  1037.             ore_count = ore_count + (#arr-1)
  1038.             for i=1, #arr do
  1039.                 APIS.mTo(arr[i].x, arr[i].y, arr[i].z)
  1040.                 if i%10 == 0 then
  1041.                     APIS.check_state()
  1042.                 end
  1043.                 if way%30 == 0 then
  1044.                     APIS.check_state()
  1045.                 end
  1046.             end
  1047.         end
  1048.     end
  1049. end
  1050.  
  1051. function APIS.geoMiner(x, z, bedrock, side, x_lim, z_lim)
  1052.  local start_point = {x=0, y=0, z=0}
  1053.  local x_limit = x_lim
  1054.  local z_limit = z_lim
  1055.  if x_lim == nil then
  1056.   x_limit = 32
  1057.  end
  1058.  if z_lim == nil then
  1059.   z_limit = 32
  1060.  end
  1061.  if side == nil then
  1062.   --print("В функцию геомайнер сайд не поступила.")
  1063.   side = APIS.whatsSide()
  1064.  end
  1065.  
  1066.  local function z_glide()
  1067.  
  1068.   if z/z_limit < 1 then
  1069.    APIS.clusterDigger(start_point, x_limit, z, bedrock, side)
  1070.   else
  1071.    for j=1, math.floor(z/z_limit) do
  1072.     --print("Карьер заданных лимитов по Z")
  1073.     APIS.clusterDigger(start_point, x_limit, z_limit, bedrock, side)
  1074.     start_point.z = j*z_limit+1
  1075.    end
  1076.    if z%z_limit > 0 then
  1077.     --print("Карьер остатков по Z")
  1078.     APIS.clusterDigger(start_point, x_limit, z%z_limit, bedrock, side)
  1079.    end
  1080.    start_point.z = 0
  1081.   end
  1082.  end
  1083.  
  1084.  if x/x_limit < 1 then
  1085.   local temp = x_limit
  1086.   x_limit = x
  1087.   z_glide()
  1088.   x_limit = temp
  1089.  else
  1090.   for i=1, math.floor(x/x_limit) do
  1091.    --print("Карьер заданных лимитов по X")
  1092.    z_glide()
  1093.    start_point.x = i*x_limit+1
  1094.   end
  1095.   if x%x_limit > 0 then
  1096.    x_limit = x%x_limit
  1097.    --print("Карьер остатков по x")
  1098.    z_glide()
  1099.   end
  1100.  end
  1101.  APIS.home()
  1102.  APIS.rot(3)
  1103.  print("Итого руды добыто: "..ore_count)
  1104.  print("Всего блоков пройдено: "..way)
  1105.  ore_count = 0
  1106. end
  1107. function APIS.mine(x,z, bedrock, side,x_lim, z_lim)
  1108.     APIS.check_components()
  1109.     way = 0
  1110.     local term = require("term")
  1111.     local r = require("robot")
  1112.     local comp = require("component")
  1113.     term.clear()
  1114.     print("Координаты робота для передачи по сетевой карте где он:")
  1115.     print("x")
  1116.     xxx = io.read()
  1117.     print("y")
  1118.     yyy = io.read()
  1119.     print("z")
  1120.     zzz = io.read()
  1121.     print("Старт карьера: "..x.."x"..z.." блоков.")
  1122.     APIS.check_state()
  1123.     local side = APIS.whatsSide()
  1124.  
  1125.     if bedrock == nil then
  1126.         print("Проверка уровня бедрока. Вертикальная шахта до дна и обратно.")
  1127.         bedrock = APIS.findoutBedrockLevel()
  1128.     end
  1129.     print("Сканирование заданного объема, может занять несколько минут...")
  1130.     --APIS.geoMiner(x, z, bedrock, side, x_lim, z_lim)
  1131.     if not pcall(APIS.geoMiner, x, z, bedrock, side, x_lim, z_lim) then
  1132.         pcall(APIS.back_to_the_future)
  1133.     end
  1134. end
  1135.  
  1136. function APIS.check_components()
  1137.     local c = require("component")
  1138.     local r = require("robot")
  1139.     inv_size = APIS.check_inv()
  1140.     if c.isAvailable("inventory_controller") then
  1141.         print("\t Контроллер инвентаря....доступен.")
  1142.     else
  1143.         print("\t Контроллер инвентаря не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1144.         os.exit()
  1145.     end
  1146.     if c.isAvailable("tunnel") then
  1147.         print("\t Соединённая карта....доступен.")
  1148.     else
  1149.         print("\t Соединённая карта не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1150.         os.exit()
  1151.     end
  1152.     if c.isAvailable("geolyzer") then
  1153.         print("\t Геосканер....доступен.")
  1154.     else
  1155.         print("\t Геосканер не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1156.         os.exit()
  1157.     end
  1158.     if r.durability() ~= nil then
  1159.         print("\t Инструмент....доступен.")
  1160.     else
  1161.         print("\t Инструмент не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1162.         os.exit()
  1163.     end
  1164.     print("\n Все компоненты в наличии.\n Программа может быть запущена.")
  1165. end
  1166.  
  1167. return APIS
  1168. --pastebin get -f gqZ1Qdqi lib/api.lua
  1169. --pastebin get -f Uw9p9BTU lib/api.lua  testing
  1170. --a=require("api") a.clusterDigger(32,32) k=a.waypoints(t) print(#k)
  1171.  
  1172. --repeat robot.swing() until not robot.detect() robot.forward()
  1173. --for i=1, 50 do while not robot.forward() do robot.swing() end end
  1174. --for i=1, 50 do robot.swing() robot.forward() end
  1175. --for i=1, 50 do if robot.detect() then robot.swing() end robot.forward() end
  1176.  
  1177. --os.execute("pastebin get -f gqZ1Qdqi lib/api.lua")
  1178. --require("api").mine(io.read(), io.read())
  1179. --require("api").mine(io.read(), io.read())
  1180. --require("api").mine(args[1], args[2])
Advertisement
Add Comment
Please, Sign In to add comment