Belzebub

Untitled

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