Advertisement
bob558

lib_prog

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