Advertisement
artem211

OC_Robot_API

Jun 10th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.14 KB | None | 0 0
  1.  
  2.  
  3.  
  4. local APIS={}
  5. local inv_size = 16
  6. local inv_side = require("sides").left
  7. local charge_side = require("sides").right
  8. local battery_side = require("sides").bottom
  9. local scrap = {
  10.     "minecraft:stone",
  11.     "minecraft:cobblestone",
  12.     "minecraft:dirt",
  13.     "minecraft:gravel",
  14.     "minecraft:sand",
  15.     "minecraft:grass"}
  16. local lc = {x=0, y=0, z=0, dr=3}
  17.  
  18. function APIS.charge(charge_side)
  19. --функция зарядки робота от чарджера, т.к. в этом билде ОС он категорически не принимает
  20. --ред сигнал робота, временно переориентировал на рычаг.
  21. comp = require("computer")
  22. while comp.energy() < (comp.maxEnergy()/2) do
  23. --local rs = require("component").redstone
  24. --rs.setOutput(charge_side, 15)
  25. require("term").clear()
  26. APIS.use(charge_side)
  27. print("Зарядка...")
  28. os.sleep(60)
  29. --rs.setOutput(charge_side, 0)
  30. APIS.use(charge_side)
  31. end
  32. print("Батарея заряжена")
  33. return true
  34. end
  35. function APIS.charge_tool(s)
  36. --функция проверки заряда бура в руках робота, передача его на зарядку в батбокс/чарджер
  37. local inv = require("component").inventory_controller
  38. local r = require("robot") 
  39. if r.durability() < 0.2 then
  40. r.select(1)
  41. inv.equip()
  42. if s == 1 then
  43. r.dropUp()
  44. os.sleep(15)
  45. r.suckUp()
  46. elseif s == 2 then
  47. r.turnAround()
  48. r.drop()
  49. os.sleep(15)
  50. r.suck()
  51. r.turnAround()
  52. elseif s == 3 then
  53. r.drop()
  54. os.sleep(15)
  55. r.suck()
  56. elseif s == 4 then
  57. r.turnRight()
  58. r.drop()
  59. os.sleep(15)
  60. r.suck()
  61. r.turnLeft()
  62. elseif s==5 then
  63. r.turnLeft()
  64. r.drop()
  65. os.sleep(15)
  66. r.suck()
  67. r.turnRight()
  68. else
  69. r.dropDown()
  70. os.sleep(15)
  71. r.suckDown()
  72. end
  73. end
  74. end
  75. function APIS.use(s)
  76. --функция юза в заданную сторону.
  77. local r = require("robot")
  78. if s == 1 then r.useUp()
  79. elseif s == 2 then
  80. r.turnAround()
  81. r.use()
  82. r.turnAround()
  83. elseif s == 3 then r.use()
  84. elseif s == 4 then
  85. r.turnRight()
  86. r.use()
  87. r.turnLeft()
  88. elseif s==5 then
  89. r.turnLeft()
  90. r.use()
  91. r.turnRight()
  92. else
  93. r.useDown()
  94. end
  95. end
  96. function APIS.drop()
  97. --функция дропа всего инвентаря в сундук, если таковой стоит перед носом
  98.  local inv = require("component").inventory_controller
  99.  local r= require("robot")
  100.  if r.detect() then
  101.   if inv.getInventorySize(3) ~= nil then
  102.    for i=1,inv_size do
  103.     r.select(i)
  104.     r.drop()
  105.    end
  106.   else
  107.    print("Блок не является сундуком.")
  108.   end
  109.  else
  110.   print("Нет сундука.")
  111.  end
  112.  r.select(1)
  113. end
  114. function APIS.printState()
  115. --используется для отладки движений робота
  116. print("Статус:")
  117. print(lc.x, lc.y, lc.z, lc.dr)
  118. end
  119. function APIS.harvest(count)
  120. --функция для фермера на IC кропсах, аргумент - сколько раз собирать с 1 места
  121.  local r=require("robot")
  122.  for i=1,count do
  123.   r.useDown()
  124.  end
  125. end
  126. function APIS.dig(arg)
  127. --функция целевого копания по стороне-аргументу, скорее всего потру ее, при оптимизации
  128.  r = require("robot")
  129.  event = require("event")
  130.  if arg == 3 then
  131.   r.swing()
  132.  elseif arg == 1 then
  133.   while r.detectUp() do
  134.    r.swingUp()
  135.   end
  136.  elseif arg == 0 then
  137.   r.swingDown()
  138.  end
  139. end
  140. function APIS.isScrap(name)
  141.  --проверка является ли итем по имени мусором.
  142.  for i, nm in pairs(scrap) do
  143.   if name == nm then  
  144.    return true
  145.   end  
  146.  end
  147.  return false
  148. end
  149. function APIS.ore_analyze(arg)
  150.  --метод проверки, является ли блок "немусором"
  151.  if arg ~= nil then
  152.   if require("component").isAvailable("geolyzer") then
  153.    local lyz = require("component").geolyzer
  154.    if APIS.isScrap(lyz.analyze(arg).name) then
  155.     return false
  156.    else
  157.     return true
  158.    end
  159.   else
  160.    print("Геолайзер не обнаружен в системе.")
  161.    return false
  162.   end
  163.  else
  164.   print("Не указан аргумент(сторона проверки).")
  165.  end
  166. end
  167. function APIS.dig_ore()
  168. --метод для копания только руды, в слоеном карьере.
  169.  local r=require("robot")
  170.  if r.detectUp() then
  171.   if APIS.ore_analyze(1) then
  172.    APIS.dig(1)
  173.   end
  174.  end
  175.  if r.detectDown() then
  176.   if APIS.ore_analyze(0) then
  177.    APIS.dig(0)
  178.   end
  179.  end
  180. end
  181. function APIS.turnLeft()
  182. --повертяйка для координатной системы, скорее всего будет удалена
  183. local r = require("robot")
  184. r.turnLeft()
  185. if lc.dr == 3 then
  186. lc.dr = 5
  187. elseif lc.dr == 4 then
  188. lc.dr = 3
  189. elseif lc.dr == 2 then
  190. lc.dr = 4
  191. elseif lc.dr == 5 then
  192. lc.dr = 2
  193. end
  194. end
  195. function APIS.rot(side)
  196. --повертяйка для координатной системы, требует модернизации, для удаления лишних поворотов.
  197.  if (side ~= 1) and (side ~= 0) then
  198.   local sides = require("sides")
  199.   local r = require("robot")  
  200.   while lc.dr ~= side do
  201.    APIS.turnLeft()
  202.   end
  203.  end
  204.  APIS.printState()
  205. end
  206. function APIS.mUp()
  207. --функция движения вверх, сквозь породу.
  208.  local r = require("robot")
  209.  local try = 1
  210.  while not r.up() == true do
  211.   r.swingUp()
  212.   try = try + 1
  213.   if try >= 10 then
  214.    APIS.mTo(lc.x-3,lc.y,lc.z)  
  215.    APIS.back_to_the_future()  
  216.    --APIS.printState()
  217.    return false
  218.   end
  219.  end
  220.  if try < 10 then
  221.   lc.y = lc.y + 1
  222.   APIS.printState()
  223.   return true
  224.  end
  225. end
  226. function APIS.mDown()
  227. --функция движения вниз, сквозь породу.
  228. local r = require("robot")
  229. local event = require("event")
  230. local try = 1
  231. while not r.down() == true do
  232.  r.swingDown()
  233.  try = try + 1
  234.  if try >= 10 then
  235.   --APIS.printState()
  236.   APIS.back_to_the_future()
  237.   return false
  238.  end
  239. end
  240.  if try < 10 then
  241.   lc.y = lc.y - 1
  242.   return true
  243.  end
  244. end
  245. function APIS.mForw(action,arg)
  246. --шаг вперед с действием или безБ сквозь породу, координатные отметки
  247. local r = require("robot")
  248. local event = require("event")
  249. local try = 1
  250. local sides = require("sides")
  251. if action ~= nil then
  252.  action(arg)
  253. end
  254. while not r.forward() do
  255.  r.swing()
  256.  try = try + 1
  257. if try >= 10 then
  258.  APIS.back_to_the_future()
  259.  return false  
  260. end
  261. end
  262. if try < 10 then
  263. if lc.dr==2 then
  264.  lc.x = lc.x - 1
  265. elseif lc.dr==3 then
  266.  lc.x = lc.x + 1
  267. elseif lc.dr==4 then
  268.  lc.z = lc.z + 1
  269. elseif lc.dr==5 then
  270.  lc.z = lc.z - 1
  271. end  
  272.  APIS.printState()
  273.  return true
  274. end
  275. end
  276. function APIS.mTo(x, y, z, action, arg)
  277. --движение в заданную точку с заданым действием и аргументом действия. Координатное.
  278. local r = require("robot")
  279. local sides = require("sides")
  280.  if lc.x > x then
  281.   APIS.rot(sides.back)
  282.   while lc.x > x do
  283.    APIS.mForw(action,arg)
  284.   end
  285.  end
  286.  if lc.x < x then
  287.   APIS.rot(sides.forward)
  288.   while lc.x < x do
  289.    APIS.mForw(action,arg)
  290.   end
  291.  end
  292.  if lc.z > z then
  293.   APIS.rot(sides.left)
  294.   while lc.z > z do
  295.    APIS.mForw(action,arg)
  296.   end  
  297.  end
  298.  if lc.z < z then
  299.   APIS.rot(sides.right)
  300.   while lc.z < z do
  301.    APIS.mForw(action,arg)
  302.   end
  303.  end
  304.  while lc.y > y do
  305.   APIS.mDown()
  306.   --print("едем вниз")
  307.  end
  308.  while lc.y < y do
  309.   APIS.mUp()
  310.   --print("едем вверх")
  311.  end
  312. end
  313. function APIS.plane(x, y, z, action, arg, forward)
  314. --проходка горизонтальной плоскости, координатная. Слоеный карьер, фермер.
  315.  local dir = "forward"  
  316.  if forward then
  317.   print("Плоскость вперед")
  318.   for j=0,z do
  319.    if dir == "forward" then
  320.     print("Движение вперед")
  321.     for i=0,x do
  322.      print("шаг вперед")
  323.      APIS.mTo(i,y,j,action,arg)
  324.     end
  325.     APIS.check_state()
  326.     dir = "back"
  327.     print("Поворот назад")
  328.    else
  329.     print("Движение назад")
  330.     for i=x,0,-1 do
  331.      print("шаг назад")
  332.      APIS.mTo(i,y,j,action,arg)
  333.     end
  334.     APIS.check_state()
  335.     dir = "forward"
  336.     print("Поворот вперед")
  337.    end
  338.   end
  339.  else
  340.  if z%2==0 then dir = "back" end
  341.   print("Плоскость обратная")
  342.   for j=z,0,-1 do
  343.    print(dir)
  344.    if dir == "forward" then
  345.     for i=0,x do
  346.      APIS.mTo(i,y,j,action,arg)
  347.     end
  348.     APIS.check_state()
  349.     dir = "back"
  350.    else
  351.     for i=x,0,-1 do
  352.      APIS.mTo(i,y,j,action,arg)
  353.     end
  354.     APIS.check_state()
  355.     dir = "forward"
  356.    end
  357.   end
  358.  end
  359. end
  360. function APIS.home(action,arg)
  361.  --функция возврата к сундуку для очистки инвентаря.
  362.  temp_state = lc
  363.  APIS.mTo(0,0,0, action,arg)
  364.  APIS.rot(2)
  365.  APIS.drop()
  366.  APIS.rot(3)
  367. end
  368. function APIS.back_to_mine(action,arg)
  369.  --возврат на точку останова(после очистки инвентаря) для возобновления работы.
  370.  APIS.mTo(0,temp_state.y,0, action,arg)
  371.  APIS.mTo(temp_state.x,temp_state.y,temp_state.z, action,arg)
  372.  APIS.rot(temp_state.dr)
  373. end
  374. function APIS.back_to_the_future()
  375.  --Завершение программы ввиду непреодолимого препятствия.
  376.  print("Ошибка, препятствие. Возврат робота.")
  377.  APIS.mTo(lc.x, 0, lc.z)
  378.  APIS.home()
  379.  print("Робот на исходной. Завершение программы.")
  380.  os.exit()
  381. end
  382. function APIS.check_inv()
  383. --вычисление величины собственного инвентаря
  384.  local r = require("robot")
  385.  local i = 16
  386.  local count = 16
  387.  while pcall(r, i) do
  388.   count = i
  389.   i=i+1
  390.  end
  391.  return count
  392. end
  393. function APIS.inv_sorting()
  394.  --Функция сортировки инвентаря(перекладывание содержимого без пустых ячеек)
  395.  --возвращает процентное заполнение инвентаря в целом
  396.  local inv = require("component").inventory_controller
  397.  local r = require("robot")
  398.  local items_stored = 0
  399.  for i=1, inv_size do
  400.   for j=inv_size, 1, -1 do
  401.    r.select(j)
  402.    r.transferTo(i)
  403.   end
  404.  end
  405.  for i=1,inv_size do
  406.   if r.count(i) > 0 then
  407.    items_stored = items_stored + 1
  408.   end
  409.  end
  410.  r.select(1)
  411.  return inv_size/items_stored
  412. end
  413. function APIS.check_state()
  414.  --функция проверки состояния инвентаря и заряда батареи робота
  415.  --выбрасывание мусора из карманов и пожирание угля, если требуется
  416.  local r = require("robot")
  417.  local inv = require("component").inventory_controller
  418.  local comp = require("computer")
  419.  local need_fuel = comp.energy() < (comp.maxEnergy()/8)
  420.  if (r.count(inv_size-2) > 0) then
  421.   for i=1, inv_size do  
  422.    local slot = inv.getStackInInternalSlot(i)  
  423.    if APIS.isScrap(slot.name) then
  424.     r.select(i)
  425.     r.drop()
  426.    end
  427.   end
  428.  end  
  429.  if need_fuel and comp.isAvailable("generator") then
  430.   if inv.getInventorySize(lc.dr) ~= nil then
  431.    local iSize = inv.getInventorySize(lc.dr)
  432.    for i=1, iSize do
  433.     if comp.generator.count() == 0 then
  434.      if inv.getStackInSlot(lc.dr, i).name == "minecraft:coal" then   
  435.       inv.suckFromSlot(lc.dr, i)
  436.      end
  437.     end
  438.    end
  439.   end  
  440.    local slt = APIS.inv_scaner("minecraft:coal")  
  441.    if slt~=0 then
  442.     local gen = require("component").generator
  443.     if gen.count() ~= 0 then
  444.      r.select(slt)
  445.      gen.insert()
  446.     end
  447.    end
  448.  end
  449.   if APIS.inv_sorting() > 0.8 then
  450.    APIS.home()
  451.    APIS.back_to_mine()
  452.   end
  453.  r.select(1)
  454. end
  455. function APIS.quarry(x, z)
  456. --слоистый геокарьер, копает слои 1 через 2, проверяет все блоки, берет только руду.
  457.  inv_size = APIS.check_inv()
  458.  for i=0, -256, -3 do  
  459.   if i%2 == 0 then  
  460.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, true)  
  461.   else  
  462.    APIS.plane((x - 1),i,(z - 1), APIS.dig_ore, 3, false)  
  463.   end  
  464.  end
  465.  APIS.home()
  466. end
  467. function APIS.field(x, z, time)
  468. --фермер для кропсов, длинна, ширина, таймер повторения в минутах(время созревания)
  469. --нуждается в модернизации, автоматизированной настройке таймера повторений.
  470.  while true do
  471.   APIS.charge(require("sides").top)
  472.   APIS.plane(x-1, 0, z-1, APIS.harvest, 2, true)
  473.   APIS.use(require("sides").down)
  474.   APIS.use(require("sides").down)
  475.   APIS.home()
  476.   print("Ожидание созревания...", time, "минут.")
  477.   os.sleep(60*time)
  478.  end
  479. end
  480. function APIS.chop_single()
  481. --сырая автолесорубка для 1 дерева, пассивная, магнит апгрейд необходим. Рабочая.
  482.  local inv = require("component").inventory_controller
  483.  local beam = require("component").tractor_beam
  484.  local r = require("robot")
  485.  local function start()
  486.   APIS.rot(inv_side)
  487.   APIS.drop()
  488.   inv.suckFromSlot(3, APIS.inv_scaner("minecraft:sapling"), 1)     
  489.   APIS.rot(3)
  490.   r.place()
  491.  end
  492.  start()
  493.  while true do
  494.   require("term").clear()      
  495.   print("Лесоруб, одиночное дерево. Ожидание роста саженца.")
  496.   local _, wood = r.detect()
  497.   if wood == "solid" then
  498.    print("Рубка дерева.")           
  499.    r.swing()
  500.    os.sleep(5)
  501.    for i=1, 8 do
  502.     beam.suck()
  503.    end
  504.    start()     
  505.    require("term").clear()
  506.    APIS.charge(charge_side)
  507.    APIS.charge_tool(battery_side)
  508.   end
  509.   os.sleep(10)
  510.  end
  511. end
  512. function APIS.inv_scaner(filter)
  513. --автопоисковик заданного итема в своем инвентаре по системному имени.
  514. --возвращает номер ячейки итема, первого найденного от начала ивентаря.
  515.  local inv = require("component").inventory_controller
  516.  ins = inv.getInventorySize(3)
  517.  if ins ~= nil then
  518.   for i=1, ins do
  519.    if inv.getStackInSlot(3, i).name == filter then
  520.     print(filter.."найден!")
  521.     return i
  522.    end
  523.   end
  524.  print("Найти "..filter.."не удалось.")
  525.  return 0
  526.  end
  527. end
  528.  
  529.  
  530. return APIS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement