zed_com

new копалка

Mar 22nd, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. local internet = require("component").internet
  254. --используется для отладки движений робота
  255. --print("Статус:")
  256. --print(lc.x, lc.y, lc.z, lc.dr)
  257. --tunnel.send("x: "..lc.x + xxx.." y: "..lc.y + yyy.." z: "..lc.z + zzz)
  258. local int_x = lc.x + xxx;
  259. local int_y = lc.y + yyy;
  260. local int_z = lc.z + zzz;
  261. internet.request("http://myserverhost.esy.es/mine/?id=1&x="..int_x.."&y="..int_y.."&z="..int_z)
  262. --print("x:"..lc.x + xxx.." y:"..lc.y + yyy.." z:"..lc.z + zzz)
  263. --print(temp_state.x, temp_state.y, temp_state.z, temp_state.dr)
  264. end
  265.  
  266. function APIS.harvest(count)
  267. --функция для фермера на IC кропсах, аргумент - сколько раз собирать с 1 места
  268.  local r=require("robot")
  269.  for i=1,count do
  270.   r.useDown()
  271.  end
  272. end
  273. function APIS.dig(arg)
  274. --функция целевого копания по стороне-аргументу, скорее всего потру ее, при оптимизации
  275.  r = require("robot")
  276.  event = require("event")
  277.  if arg == 3 then
  278.   r.swing()
  279.  elseif arg == 1 then
  280.   while r.detectUp() do
  281.    r.swingUp()
  282.   end
  283.  elseif arg == 0 then
  284.   r.swingDown()
  285.  end
  286. end
  287. function APIS.isScrap(name)
  288.  --проверка является ли итем по имени мусором.
  289.  for i, nm in pairs(scrap) do
  290.   if name == nm then  
  291.    return true
  292.   end  
  293.  end
  294.  return false
  295. end
  296. function APIS.ore_analyze(arg)
  297.  --метод проверки, является ли блок "немусором"
  298.  if arg ~= nil then
  299.   if require("component").isAvailable("geolyzer") then
  300.    local lyz = require("component").geolyzer
  301.    if APIS.isScrap(lyz.analyze(arg).name) then
  302.     return false
  303.    else
  304.     return true
  305.    end
  306.   else
  307.    print("Геолайзер не обнаружен в системе.")
  308.    return false
  309.   end
  310.  else
  311.   print("Не указан аргумент(сторона проверки).")
  312.  end
  313. end
  314. function APIS.dig_ore()
  315. --метод для копания только руды, в слоеном карьере.
  316.  local r=require("robot")
  317.  if r.detectUp() then
  318.   if APIS.ore_analyze(1) then
  319.    APIS.dig(1)
  320.   end
  321.  end
  322.  if r.detectDown() then
  323.   if APIS.ore_analyze(0) then
  324.    APIS.dig(0)
  325.   end
  326.  end
  327. end
  328. function APIS.turnLeft()
  329. local r = require("robot")
  330. r.turnLeft()
  331. if lc.dr == 3 then
  332. lc.dr = 5
  333. elseif lc.dr == 4 then
  334. lc.dr = 3
  335. elseif lc.dr == 2 then
  336. lc.dr = 4
  337. elseif lc.dr == 5 then
  338. lc.dr = 2
  339. end
  340. end
  341. function APIS.turnRight()
  342. local r = require("robot")
  343. r.turnRight()
  344. if lc.dr == 3 then
  345. lc.dr = 4
  346. elseif lc.dr == 4 then
  347. lc.dr = 2
  348. elseif lc.dr == 2 then
  349. lc.dr = 5
  350. elseif lc.dr == 5 then
  351. lc.dr = 3
  352. end
  353. end
  354. function APIS.turnAround()
  355.  local r = require("robot")
  356.     r.turnAround()
  357.     if lc.dr == 3 then
  358.         lc.dr = 2
  359.     elseif lc.dr == 4 then
  360.         lc.dr = 5
  361.     elseif lc.dr == 2 then
  362.         lc.dr = 3
  363.     elseif lc.dr == 5 then
  364.         lc.dr = 4
  365.     end
  366. end
  367. function APIS.rot(side)
  368.  if (side ~= 1) and (side ~= 0) and lc.dr-side ~=0 then
  369.   local sides = require("sides")
  370.   local r = require("robot")
  371.   if lc.dr == 3 then
  372.     if side == 4 then APIS.turnRight()
  373.     elseif side == 2 then APIS.turnAround()
  374.     elseif side == 5 then APIS.turnLeft()
  375.     end
  376.   elseif lc.dr == 4 then
  377.     if side == 2 then APIS.turnRight()
  378.     elseif side == 5 then APIS.turnAround()
  379.     elseif side == 3 then APIS.turnLeft()
  380.     end
  381.   elseif lc.dr == 2 then
  382.     if side == 5 then APIS.turnRight()
  383.     elseif side == 3 then APIS.turnAround()
  384.     elseif side == 4 then APIS.turnLeft()
  385.     end
  386.   else--5
  387.     if side == 3 then APIS.turnRight()
  388.     elseif side == 4 then APIS.turnAround()
  389.     elseif side == 2 then APIS.turnLeft()
  390.     end
  391.   end
  392.  end
  393.  APIS.printState()
  394. end
  395. function APIS.mUp()
  396. --функция движения вверх, сквозь породу.
  397.  local r = require("robot")
  398.  local try = 1
  399.  repeat
  400.   r.swingUp()
  401.   try = try + 1
  402.   if try >= 15 then
  403.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr=вверх"..lc.dr)
  404.    local _, det = require("robot").detectUp()
  405.    print(det.." сверху.")
  406.    print(require("component").geolyzer.analyze(1).name)
  407.    APIS.mTo(lc.x+2,lc.y,lc.z)  
  408.    APIS.back_to_the_future()  
  409.    APIS.printState()
  410.    return false
  411.   elseif try > 12 then
  412.    if require("component").geolyzer.analyze(1).name == "ExtraBees:hive" then
  413.     local inv = require("component").inventory_controller
  414.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  415.      inv.equip()
  416.      r.swingUp()
  417.      inv.equip()
  418.      r.select(1)
  419.     end
  420.    end
  421.   end
  422.  until not r.detectUp()
  423.  while try < 15 and not r.up() do
  424.   r.swingUp()
  425.   try = try + 1
  426.  end
  427.  if try < 15 then
  428.   lc.y = lc.y + 1
  429.   way = way + 1
  430. APIS.printState()
  431.   return true
  432.  end
  433. end
  434.  
  435. function APIS.mDown(action, arg)
  436. --функция движения вниз, сквозь породу.
  437.  local r = require("robot")
  438.  local event = require("event")
  439.  local try = 1
  440.  if action ~= nil then
  441.   action(arg)
  442.  end
  443.  repeat
  444.   r.swingDown()
  445.   try = try + 1
  446.   if try >= 15 then
  447.    APIS.printState()
  448.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr= вниз"..lc.dr)
  449.    local _, det = require("robot").detectDown()
  450.    print(det.." снизу.")
  451.    print(require("component").geolyzer.analyze(0).name)
  452.    APIS.back_to_the_future()
  453.    return false
  454.   elseif try > 12 then
  455.    if require("component").geolyzer.analyze(0).name == "ExtraBees:hive" then
  456.     local inv = require("component").inventory_controller
  457.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  458.      inv.equip()
  459.      r.swingDown()
  460.      inv.equip()
  461.      r.select(1)
  462.     end
  463.    end
  464.   end
  465.  until not r.detectDown()
  466.  while try < 15 and not r.down() do
  467.   r.swingDown()
  468.   try = try + 1
  469.  end
  470.  
  471.  if try < 15 then
  472.   lc.y = lc.y - 1
  473.   way = way + 1
  474.   return true
  475.  end
  476. end
  477.  
  478. function APIS.mForw(action,arg)
  479. --шаг вперед с действием или безБ сквозь породу, координатные отметки
  480.  local r = require("robot")
  481.  local event = require("event")
  482.  local try = 1
  483.  local sides = require("sides")
  484.  if action ~= nil then
  485.   action(arg)
  486.  end
  487.  repeat
  488.   r.swing()
  489.   try = try + 1
  490.   if try >= 15 then
  491.    print("Препятствие у точки: x="..lc.x.." z="..lc.z.." y="..lc.y.." Направление Dr="..lc.dr)
  492.    local _, det = require("robot").detect()
  493.    print(det.." спереди.")
  494.    print(require("component").geolyzer.analyze(3).name)
  495.    APIS.back_to_the_future()
  496.    return false
  497.   elseif try > 12 then
  498.    if require("component").geolyzer.analyze(3).name == "ExtraBees:hive" then
  499.     local inv = require("component").inventory_controller
  500.     if pcall(r.select,APIS.inv_scaner("Forestry:scoop", true)) then
  501.      inv.equip()
  502.      r.swing()
  503.      inv.equip()
  504.      r.select(1)
  505.     end
  506.    end
  507.   end
  508.  until not r.detect()
  509.  while try < 15 and not r.forward() do
  510.   r.swing()
  511.   try = try + 1
  512.  end
  513.  if try < 15 then
  514.   way = way + 1
  515.  if lc.dr==2 then
  516.   lc.x = lc.x - 1
  517.  elseif lc.dr==3 then
  518.   lc.x = lc.x + 1
  519.  elseif lc.dr==4 then
  520.   lc.z = lc.z + 1
  521.  elseif lc.dr==5 then
  522.   lc.z = lc.z - 1
  523.  end  
  524.  APIS.printState()
  525.  return true
  526.  end
  527. end
  528.  
  529. function APIS.mTo(x, y, z, action, arg)
  530. --движение в заданную точку с заданым действием и аргументом действия. Координатное.
  531. local r = require("robot")
  532. local sides = require("sides")
  533.  if lc.x > x then
  534.   APIS.rot(sides.back)
  535.   while lc.x > x do
  536.    APIS.mForw(action,arg)
  537.   end
  538.  end
  539.  if lc.x < x then
  540.   APIS.rot(sides.forward)
  541.   while lc.x < x do
  542.    APIS.mForw(action,arg)
  543.   end
  544.  end
  545.  if lc.z > z then
  546.   APIS.rot(sides.left)
  547.   while lc.z > z do
  548.    APIS.mForw(action,arg)
  549.   end  
  550.  end
  551.  if lc.z < z then
  552.   APIS.rot(sides.right)
  553.   while lc.z < z do
  554.    APIS.mForw(action,arg)
  555.   end
  556.  end
  557.  while lc.y > y do
  558.   APIS.mDown(action,arg)
  559.   --print("едем вниз")
  560.  end
  561.  while lc.y < y do
  562.   APIS.mUp(action,arg)
  563.   --print("едем вверх")
  564.  end
  565. end
  566.  
  567. function APIS.plane(x, y, z, action, arg, forward)
  568. --проходка горизонтальной плоскости, координатная. Слоеный карьер, фермер.
  569.  local dir = "forward"  
  570.  if forward then
  571.   print("Плоскость вперед")
  572.   for j=0,z do
  573.    if dir == "forward" then
  574.     print("Движение вперед")
  575.     for i=0,x do
  576.      print("шаг вперед")
  577.      APIS.mTo(i,y,j,action,arg)
  578.     end
  579.     APIS.check_state()
  580.     dir = "back"
  581.     print("Поворот назад")
  582.    else
  583.     print("Движение назад")
  584.     for i=x,0,-1 do
  585.      print("шаг назад")
  586.      APIS.mTo(i,y,j,action,arg)
  587.     end
  588.     APIS.check_state()
  589.     dir = "forward"
  590.     print("Поворот вперед")
  591.    end
  592.   end
  593.  else
  594.  if z%2==0 then dir = "back" end
  595.   print("Плоскость обратная")
  596.   for j=z,0,-1 do
  597.    print(dir)
  598.    if dir == "forward" then
  599.     for i=0,x do
  600.      APIS.mTo(i,y,j,action,arg)
  601.     end
  602.     APIS.check_state()
  603.     dir = "back"
  604.    else
  605.     for i=x,0,-1 do
  606.      APIS.mTo(i,y,j,action,arg)
  607.     end
  608.     APIS.check_state()
  609.     dir = "forward"
  610.    end
  611.   end
  612.  end
  613. end
  614. function APIS.home(action,arg)
  615.  --функция возврата к сундуку для очистки инвентаря.
  616.  
  617.  temp_state.x = lc.x
  618.  temp_state.y = lc.y
  619.  temp_state.z = lc.z
  620.  temp_state.dr = lc.dr
  621.  APIS.mTo(0,0,0, action,arg)
  622.  APIS.rot(2)
  623.  APIS.drop_scrap()
  624.  APIS.drop()
  625.  --APIS.rot(3)
  626. end
  627.  
  628. function APIS.drop_scrap()
  629.  local r = require("robot")
  630.  local inv = require("component").inventory_controller
  631.   for i=1, inv_size do  
  632.    local slot = inv.getStackInInternalSlot(i)
  633.    if slot ~= nil then  
  634.     if APIS.isScrap(slot.name) then
  635.      r.select(i)
  636.      r.dropDown()
  637.     end
  638.    end
  639.   end
  640.   return APIS.inv_sorting()  
  641. end
  642. function APIS.back_to_mine(action,arg)
  643.  --возврат на точку останова(после очистки инвентаря) для возобновления работы.
  644.  APIS.mTo(0,temp_state.y,0, action,arg)
  645.  APIS.mTo(temp_state.x,temp_state.y,temp_state.z, action,arg)
  646.  APIS.rot(temp_state.dr)
  647. end
  648.  
  649. function APIS.back_to_the_future()
  650.  --Завершение программы ввиду непреодолимого препятствия.
  651.  print("Ошибка/препятствие. Возврат робота.")
  652.  APIS.mTo(lc.x, 0, lc.z)
  653.  APIS.home()
  654.  APIS.rot(3)
  655.  print("Робот на исходной. Завершение программы.")
  656.  os.exit()
  657. end
  658.  
  659. function APIS.check_inv()
  660. --вычисление величины собственного инвентаря
  661.  local r = require("robot")
  662.  local i = 16
  663.  local count = 16
  664.  while pcall(r.count, i) do
  665.   count = i
  666.   i=i+1
  667.  end
  668.  return count
  669. end
  670. function APIS.inv_sorting()
  671.  --Функция сортировки инвентаря(перекладывание содержимого без пустых ячеек)
  672.  --возвращает процентное заполнение инвентаря в целом
  673.  local inv = require("component").inventory_controller
  674.  local r = require("robot")
  675.  local items_stored = 0
  676.  inv_size = APIS.check_inv()
  677.  --цикл от начала до конца ищет пустые ячейки, когда находит - второй цикл от конца до
  678.  --начала ищет не пустые и перемещает на место пустых(упорядочивает)
  679.  --когда цикл начальный и конечный пересекается - перестает запускаться цикл с конца
  680.  --чтоб не было бесконечного перемешивания. После подсчет % занятого пространства и возврат значений.
  681.  for i=1, inv_size-1 do
  682.   if r.count(i) == 0 then
  683.    for j=inv_size-1, 1, -1 do
  684.     if r.count(j) > 0 then
  685.      if j<i then
  686.      break
  687.      end
  688.      r.select(j)
  689.      r.transferTo(i)
  690.      break
  691.     end
  692.    end
  693.   end
  694.  end
  695.  for i=1,inv_size do
  696.   if r.count(i) > 0 then
  697.    items_stored = items_stored + 1
  698.   end
  699.  end
  700.  --print(items_stored)
  701.  r.select(1)
  702.  return items_stored/inv_size
  703. end
  704.  
  705. function APIS.check_state()
  706.  --функция проверки состояния инвентаря и заряда батареи робота
  707.  --выбрасывание мусора из карманов и пожирание угля, если требуется
  708.  local r = require("robot")
  709.  local inv = require("component").inventory_controller
  710.  local comp = require("computer")
  711.  local c = require("component")
  712.  local need_fuel = comp.energy() < (comp.maxEnergy()*0.90)
  713.  
  714.  local function inventory()
  715.   local need_to_home = false
  716.   if (r.count(inv_size-2) > 0) then  
  717.     if APIS.drop_scrap() > 0.9 then
  718.      need_to_home = true
  719.     else
  720.      need_to_home = false
  721.     end
  722.   end
  723.   return need_to_home
  724.  end
  725.  
  726.  local function fuel(internal)
  727.   local need_to_home = false
  728.   if need_fuel and c.isAvailable("generator") and c.generator.count() == 0 then
  729.     local slt = APIS.inv_scaner(fuel_list, internal)
  730.     if slt ~= 0 and not internal then
  731.      r.select(inv_size-2)
  732.      inv.suckFromSlot(3, slt)
  733.      c.generator.insert()
  734.      r.select(1)
  735.      need_to_home = false
  736.     else
  737.      slt = APIS.inv_scaner(fuel_list, internal)
  738.      if slt ~= 0 and internal then  
  739.       r.select(slt)
  740.       c.generator.insert()
  741.       r.select(1)
  742.       need_to_home = false
  743.      else
  744.       need_to_home = true
  745.      end
  746.     end
  747.   elseif not c.isAvailable("generator") and need_fuel then
  748.    need_to_home = true
  749.   end
  750.   return need_to_home
  751.  end
  752.  
  753.     if  inventory() or fuel(true) or APIS.charge_tool(charge_side, inv_size-2) then
  754.         APIS.home()
  755.         os.sleep(15)
  756.         APIS.charge_tool(charge_side, inv_size-2)  
  757.         fuel(false)
  758.         APIS.back_to_mine()
  759.     end    
  760. end
  761.  
  762. function APIS.quarry(x, z)
  763. --слоистый геокарьер, копает слои 1 через 2, проверяет все блоки, берет только руду.
  764.  inv_size = APIS.check_inv()
  765.  for i=0, -256, -3 do  
  766.   if i%2 == 0 then  
  767.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, true)  
  768.   else  
  769.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, false)  
  770.   end  
  771.  end
  772.  APIS.home()
  773. end
  774.  
  775. function APIS.inv_scaner(filter, internal, start_slot)
  776. --автопоисковик заданного итема в своем инвентаре по системному имени.
  777. --возвращает номер ячейки итема, первого найденного от начала ивентаря.
  778.     local inv = require("component").inventory_controller
  779.     ins = inv.getInventorySize(3)
  780.     if start_slot == nil then
  781.         start_slot = 1
  782.     end
  783.     if filter == "empty" then
  784.         if internal then
  785.             for i=start_slot, inv_size do
  786.                 if inv.getStackInInternalSlot(i) == nil then
  787.                     return i
  788.                 end
  789.             end
  790.         else
  791.             for i=start_slot, inv.getInventorySize(3) do
  792.                 if inv.getStackInSlot(3, i) == nil then
  793.                     return i
  794.                 end
  795.             end
  796.         end
  797.     end  
  798.     if internal then
  799.         for i=start_slot, inv_size do
  800.             if inv.getStackInInternalSlot(i) ~= nil then
  801.                 if pcall(pairs, filter) then
  802.                     for j, name in pairs(filter) do
  803.                         if inv.getStackInInternalSlot(i).name == name then
  804.                             --print(filter.." найден!")
  805.                             return i
  806.                         end
  807.                     end
  808.                 else
  809.                     if inv.getStackInInternalSlot(i).name == filter then
  810.                         --print(filter.." найден!")
  811.                         return i
  812.                     end
  813.                 end
  814.             end
  815.         end
  816.         --print("Найти "..filter.." не удалось.")
  817.         return 0  
  818.     else
  819.         if ins ~= nil  then
  820.             for i=start_slot, ins do
  821.                 if inv.getStackInSlot(3, i) ~= nil then
  822.                     if pcall(pairs, filter) then
  823.                         for j, name in pairs(filter) do
  824.                             if inv.getStackInSlot(3, i).name == name then
  825.                                 --print(filter.." найден!")
  826.                                 return i
  827.                             end
  828.                         end
  829.                     else
  830.                         if inv.getStackInSlot(3, i).name == filter then
  831.                             --print(filter.." найден!")
  832.                             return i
  833.                         end
  834.                     end
  835.                 end
  836.             end
  837.             --print("Найти "..filter.." не удалось.")
  838.             return 0
  839.         else
  840.             return 0
  841.         end
  842.     end
  843. end
  844. function APIS.distance(blockA, blockB)
  845.  local dist = math.sqrt(math.pow(blockA.x - blockB.x,2) +
  846.    math.pow(blockA.z - blockB.z,2) + math.pow(blockA.y - blockB.y,2))
  847.  return dist
  848. end
  849. function APIS.closest_point(point, points)
  850.  local cl_num = 1
  851.  local length = APIS.distance(point, points[1])
  852.  for i=1, #points do
  853.   local l = APIS.distance(point, points[i])
  854.   if l < length then
  855.    cl_num = i
  856.    length = l
  857.   end
  858.  end
  859.  return cl_num
  860. end
  861. function APIS.waypoints(ores_table, last)
  862.  local way_table = {}
  863.  local count = #ores_table
  864.  table.insert(way_table, {x=lc.x, z=lc.z, y=lc.y})
  865.  while count ~= #way_table - 1 do
  866.   local j = APIS.closest_point(way_table[#way_table], ores_table)
  867.   table.insert(way_table, ores_table[j])
  868.   table.remove(ores_table, j)
  869.  end
  870.  return way_table, last
  871. end
  872. function APIS.scanVolume(xn,zn, bedrock, side, hight_border)
  873.  --сканирование карьерного "этажа" заданного радиуса -10 блоков вниз+сканер+10 блоков вверх
  874.  local geo = require("component").geolyzer
  875.  local ores_table = {}
  876.  local last = false
  877.  local x_limit = 0
  878.  local z_limit = 0
  879.  local x_increment = 1
  880.  local z_increment = 1
  881.  
  882.  if side == "north" or side == "север" then
  883.   x_limit = zn
  884.   x_increment = 1
  885.   z_limit = -xn
  886.   z_increment = -1
  887.  -- print("Выбранное направление: Север. Старт сканирования.")
  888.  elseif side == "west" or side == "запад" then
  889.   x_limit = -xn
  890.   x_increment = -1
  891.   z_limit = -zn
  892.   z_increment = -1
  893.  -- print("Выбранное направление: Запад. Старт сканирования.")
  894.  elseif side == "south" or side == "юг" then
  895.   x_limit = -zn
  896.   x_increment = -1
  897.   z_limit = xn
  898.   z_increment = 1
  899.  -- print("Выбранное направление: Юг. Старт сканирования.")
  900.  elseif side == "east" or side == "восток" or side == nil then
  901.   x_limit = xn
  902.   x_increment = 1
  903.   z_limit = zn
  904.   z_increment = 1
  905.  -- print("Выбранное направление: Запад. сканирования.")
  906.  end
  907.  
  908.  if xn == 0 and zn == 0 then
  909.     --print("Сканирование границ бедрока")
  910.   local tempr=geo.scan(0,0)
  911.   for i=10, 32 do
  912.    if tempr[i] < -0.3 then
  913.     --print("Бедрок обнаружен на уровне "..i-33+lc.y)
  914.     return i-33+lc.y, true
  915.    end
  916.   end
  917.   return 0, false
  918.  end
  919.  --print("Сканирование заданного объема, может занять несколько минут...")
  920.  for xt=0,x_limit,x_increment do
  921.   for zt=0,z_limit,z_increment do
  922.    local scan = geo.scan(xt,zt,true)
  923.    for yt=hight_border+33, 33+math.abs(hight_border) do
  924.     if scan[yt] > 2.05 and scan[yt] < 40 and ((yt-33)+lc.y) > bedrock then
  925.       if side == "north" or side == "север" then
  926.        table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
  927.       elseif side == "west" or side == "запад" then
  928.        table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
  929.       elseif side == "south" or side == "юг" then
  930.        table.insert(ores_table, {x=math.abs(zt)+lc.x, z=math.abs(xt)+lc.z, y=(yt-33)+lc.y})
  931.       elseif side == "east" or side == "восток" or side == nil then
  932.        table.insert(ores_table, {x=math.abs(xt)+lc.x, z=math.abs(zt)+lc.z, y=(yt-33)+lc.y})
  933.       end    
  934.     end
  935.    end
  936.   end
  937.  end
  938.  return ores_table
  939. end
  940. function APIS.whatsSide()
  941.  local geo = require("component").geolyzer
  942.  local r= require("robot")
  943.  local function isBlock(dens)
  944.   if dens ~= nil and dens ~= 0 then
  945.    return 1
  946.   elseif dens == 0 then
  947.    return 0
  948.   end
  949.  end
  950.  local function check(fig, front)
  951.   local figure1 = {
  952.    east = isBlock(geo.scan(1,0)[33]),
  953.    south = isBlock(geo.scan(0,1)[33]),
  954.    west = isBlock(geo.scan(-1,0)[33]),  
  955.    north = isBlock(geo.scan(0,-1)[33])
  956.    }  
  957.   if front then
  958.    if fig.east > figure1.east  then
  959.     return "east"
  960.    elseif fig.south > figure1.south then
  961.     return "south"
  962.    elseif fig.west > figure1.west then
  963.     return "west"
  964.    elseif fig.north > figure1.north then
  965.     return "north"
  966.    end
  967.   elseif not front then
  968.    if fig.east < figure1.east  then
  969.     return "east"
  970.    elseif fig.south < figure1.south then
  971.     return "south"
  972.    elseif fig.west < figure1.west then
  973.     return "west"
  974.    elseif fig.north < figure1.north then
  975.     return "north"
  976.    end  
  977.   end
  978.  end
  979.  local figure = {
  980.    east = isBlock(geo.scan(1,0)[33]),
  981.    south = isBlock(geo.scan(0,1)[33]),
  982.    west = isBlock(geo.scan(-1,0)[33]),  
  983.    north = isBlock(geo.scan(0,-1)[33])
  984.    }
  985.  APIS.rot(3)
  986.  while true do
  987.   if r.detect() then
  988.    r.swing()
  989.    local direction = check(figure, true)
  990.    r.place()
  991.    return direction
  992.   elseif r.detectDown() then
  993.    r.swingDown()
  994.    r.place()
  995.    local direction = check(figure, false)
  996.    r.swing()
  997.    r.placeDown()
  998.    return direction
  999.   end
  1000.   print("Для ориентирования в пространстве недостаточно данных.")
  1001.   print("Пожалуйста установите любой блок перед или под роботом и повторите попытку")
  1002.   os.exit()
  1003.  end
  1004. end
  1005.  
  1006. function APIS.findoutBedrockLevel()
  1007.  local bedrock = -1
  1008.  local start_level = lc.y
  1009.  for i = lc.y, -256, -10 do
  1010.   local bed, catch = APIS.scanVolume(0,0)
  1011.   --print("Сканирование бедрока")
  1012.   if not catch then
  1013.    APIS.mTo(lc.x, i, lc.z)
  1014.   elseif bed < lc.y - 5 then
  1015.    --print("Найден бедрок")
  1016.    APIS.mTo(lc.x, i-4, lc.z)
  1017.    bedrock = APIS.scanVolume(0,0)
  1018.    break
  1019.   end
  1020.  end
  1021.  APIS.mTo(lc.x, start_level, lc.z)
  1022.  return bedrock
  1023. end
  1024.  
  1025. function APIS.clusterDigger(start_point, x,z, bedrock, side)
  1026.     --print("Кластер диггер")
  1027.     if side == nil then
  1028.         --print("В функцию кластер диггер сайд не поступила")
  1029.         side = APIS.whatsSide()
  1030.         --print("Направление: "..side)
  1031.     end
  1032.     if start_point == nil then
  1033.         start_point = lc
  1034.     end
  1035.     inv_size = APIS.check_inv()  
  1036.     APIS.mTo(start_point.x, start_point.y, start_point.z)
  1037.     for Y=lc.y, bedrock+6, -1 do
  1038.         if Y%21 == 0 or Y == bedrock + 9 then
  1039.             APIS.mTo(start_point.x, Y, start_point.z)
  1040.             APIS.rot(3)
  1041.             arr=APIS.waypoints(APIS.scanVolume(x-1,z-1, bedrock+4, side, -11))
  1042.             ore_count = ore_count + (#arr-1)
  1043.             for i=1, #arr do
  1044.                 APIS.mTo(arr[i].x, arr[i].y, arr[i].z)
  1045.                 if i%10 == 0 then
  1046.                     APIS.check_state()
  1047.                 end
  1048.                 if way%30 == 0 then
  1049.                     APIS.check_state()
  1050.                 end
  1051.             end
  1052.         end
  1053.     end
  1054. end
  1055.  
  1056. function APIS.geoMiner(x, z, bedrock, side, x_lim, z_lim)
  1057.  local start_point = {x=0, y=0, z=0}
  1058.  local x_limit = x_lim
  1059.  local z_limit = z_lim
  1060.  if x_lim == nil then
  1061.   x_limit = 32
  1062.  end
  1063.  if z_lim == nil then
  1064.   z_limit = 32
  1065.  end
  1066.  if side == nil then
  1067.   --print("В функцию геомайнер сайд не поступила.")
  1068.   side = APIS.whatsSide()
  1069.  end
  1070.  
  1071.  local function z_glide()
  1072.  
  1073.   if z/z_limit < 1 then
  1074.    APIS.clusterDigger(start_point, x_limit, z, bedrock, side)
  1075.   else
  1076.    for j=1, math.floor(z/z_limit) do
  1077.     --print("Карьер заданных лимитов по Z")
  1078.     APIS.clusterDigger(start_point, x_limit, z_limit, bedrock, side)
  1079.     start_point.z = j*z_limit+1
  1080.    end
  1081.    if z%z_limit > 0 then
  1082.     --print("Карьер остатков по Z")
  1083.     APIS.clusterDigger(start_point, x_limit, z%z_limit, bedrock, side)
  1084.    end
  1085.    start_point.z = 0
  1086.   end
  1087.  end
  1088.  
  1089.  if x/x_limit < 1 then
  1090.   local temp = x_limit
  1091.   x_limit = x
  1092.   z_glide()
  1093.   x_limit = temp
  1094.  else
  1095.   for i=1, math.floor(x/x_limit) do
  1096.    --print("Карьер заданных лимитов по X")
  1097.    z_glide()
  1098.    start_point.x = i*x_limit+1
  1099.   end
  1100.   if x%x_limit > 0 then
  1101.    x_limit = x%x_limit
  1102.    --print("Карьер остатков по x")
  1103.    z_glide()
  1104.   end
  1105.  end
  1106.  APIS.home()
  1107.  APIS.rot(3)
  1108.  print("Итого руды добыто: "..ore_count)
  1109.  print("Всего блоков пройдено: "..way)
  1110.  ore_count = 0
  1111. end
  1112. function APIS.mine(x,z, bedrock, side,x_lim, z_lim)
  1113.     APIS.check_components()
  1114.     way = 0
  1115.     local term = require("term")
  1116.     local r = require("robot")
  1117.     local comp = require("component")
  1118.     term.clear()
  1119.     print("Координаты робота для передачи по сетевой карте где он:")
  1120.     print("x")
  1121.     xxx = io.read()
  1122.     print("y")
  1123.     yyy = io.read()
  1124.     print("z")
  1125.     zzz = io.read()
  1126.     print("Старт карьера: "..x.."x"..z.." блоков.")
  1127.     APIS.check_state()
  1128.     local side = APIS.whatsSide()
  1129.  
  1130.     if bedrock == nil then
  1131.         print("Проверка уровня бедрока. Вертикальная шахта до дна и обратно.")
  1132.         bedrock = APIS.findoutBedrockLevel()
  1133.     end
  1134.     print("Сканирование заданного объема, может занять несколько минут...")
  1135.     --APIS.geoMiner(x, z, bedrock, side, x_lim, z_lim)
  1136.     if not pcall(APIS.geoMiner, x, z, bedrock, side, x_lim, z_lim) then
  1137.         pcall(APIS.back_to_the_future)
  1138.     end
  1139. end
  1140.  
  1141. function APIS.check_components()
  1142.     local c = require("component")
  1143.     local r = require("robot")
  1144.     inv_size = APIS.check_inv()
  1145.     if c.isAvailable("inventory_controller") then
  1146.         print("\t Контроллер инвентаря....доступен.")
  1147.     else
  1148.         print("\t Контроллер инвентаря не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1149.         os.exit()
  1150.     end
  1151.     if c.isAvailable("tunnel") then
  1152.         print("\t Соединённая карта....доступен.")
  1153.     else
  1154.         print("\t Соединённая карта не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1155.         --os.exit()
  1156.     end
  1157.     if c.isAvailable("geolyzer") then
  1158.         print("\t Геосканер....доступен.")
  1159.     else
  1160.         print("\t Геосканер не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1161.         os.exit()
  1162.     end
  1163.     if r.durability() ~= nil then
  1164.         print("\t Инструмент....доступен.")
  1165.     else
  1166.         print("\t Инструмент не обнаружен, возможны проблемы и ошибки. Принудительная остановка программы.")
  1167.         os.exit()
  1168.     end
  1169.     print("\n Все компоненты в наличии.\n Программа может быть запущена.")
  1170. end
  1171.  
  1172. return APIS
  1173. --pastebin get -f gqZ1Qdqi lib/api.lua
  1174. --pastebin get -f Uw9p9BTU lib/api.lua  testing
  1175. --a=require("api") a.clusterDigger(32,32) k=a.waypoints(t) print(#k)
  1176.  
  1177. --repeat robot.swing() until not robot.detect() robot.forward()
  1178. --for i=1, 50 do while not robot.forward() do robot.swing() end end
  1179. --for i=1, 50 do robot.swing() robot.forward() end
  1180. --for i=1, 50 do if robot.detect() then robot.swing() end robot.forward() end
  1181.  
  1182. --os.execute("pastebin get -f gqZ1Qdqi lib/api.lua")
  1183. --require("api").mine(io.read(), io.read())
  1184. --require("api").mine(io.read(), io.read())
  1185. --require("api").mine(args[1], args[2])
Advertisement
Add Comment
Please, Sign In to add comment