Advertisement
artem211

OC_Robot_API_test

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