Advertisement
denesik

quarry2

Jul 23rd, 2014
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 27.79 KB | None | 0 0
  1. -- pastebin get erdG4yc0 quarry2
  2.  
  3. --------------------------Константы----------------------------------------
  4. -- Высота слоя
  5. local layerHeight = 3
  6.  
  7. local state_start    = 0 -- инициализция
  8. local state_mining   = 1 -- копаем ресусы
  9. local state_goto     = 2 -- идем домой или обратно копать
  10. local state_home     = 4 -- мы дома, разгружаемся и заправляемся
  11. local state_bedrock  = 5 -- натолкнулись на бедрок, пытаемся выбраться
  12. --------------------------Конец объявления констант------------------------
  13.  
  14. --------------------------Константные параметры----------------------------
  15. -- Размеры карьера
  16. local width, lenght, height = 5, 5, 256
  17.  
  18. -- Куда будет черепаха копать, вправо или влево
  19. local reflection = 0; -- 1 влево
  20.  
  21. -- Начальная позиция черепахи
  22. local startPos = vector.new((width - 1) * reflection, 0, 0)
  23. --------------------------Конец константных параметров----------------------------
  24.  
  25. --------------------------Динамические параметры----------------------------------
  26. -- Позиция черепахи
  27. -- x - ширина; y - длина; z - глубина;
  28. local pos = vector.new(startPos.x, startPos.y, startPos.z)
  29.  
  30. -- Текущее направление черепахи
  31. -- x = -1 | x = 1 | y = -1 | y = 1
  32. -- z - не используется
  33. local currDir = vector.new(0, 1, 0)
  34.  
  35. -- Заданное направление
  36. -- Черепаха должна переместиться таким образом,
  37. -- что бы текущее направление соответствовало заданному
  38. -- x = [-1, 1]; y = [-1, 1]; z = [-1, 1]
  39. -- y =  1 - мы должны ехать вперед,
  40. -- y = -1 - мы должны ехать назад
  41. -- x =  1 - мы должны повернуть направо
  42. -- x = -1 - мы должны повернуть налево
  43. -- z =  1 - мы должны ехать вверх
  44. -- z = -1 - мы должны ехать вниз
  45. local givenDir = vector.new(1- reflection * 2, 1, -1)
  46.  
  47. -- Когда выходим из состояния добычи, нужно сохранить позицию
  48. local posTmpMining = vector.new(0, 0, 0)
  49. local currDirTmpMining = vector.new(0, 0, 0)
  50. -- Куда мы хотим ехать когда используем goto
  51. local dirMining = 0
  52.  
  53. -- Количество блоков на которое должна передвинуться черепаха
  54. -- относительно заданного направления
  55. local distantion = vector.new(0, lenght - 1, 0)
  56.  
  57. -- Что мы делаем на данный момент
  58. local state = state_start
  59.  
  60. -- Завершили ли мы добычу ресурсов
  61. local miningEnd = 0
  62.  
  63. --------------------------Конец динамических параметров----------------------------
  64.  
  65. --------------------------Копия динамических параметров----------------------------
  66. local clone_pos        = vector.new(0, 0, 0)
  67. local clone_currDir    = vector.new(0, 0, 0)
  68. local clone_givenDir   = vector.new(0, 0, 0)
  69. local clone_distantion = vector.new(0, 0, 0)
  70. --------------------------Конец копии динамических параметров----------------------
  71.  
  72.  
  73. -- Скопировать текущее состояние в доп. память
  74. local function cloneState()
  75.   clone_pos.x = pos.x
  76.   clone_pos.y = pos.y
  77.   clone_pos.z = pos.z
  78.   clone_currDir.x = currDir.x
  79.   clone_currDir.y = currDir.y
  80.   clone_currDir.z = currDir.z
  81.   clone_givenDir.x = givenDir.x
  82.   clone_givenDir.y = givenDir.y
  83.   clone_givenDir.z = givenDir.z
  84.   clone_distantion.x = distantion.x
  85.   clone_distantion.y = distantion.y
  86.   clone_distantion.z = distantion.z
  87. end
  88.  
  89. -- Восстановить текущее состояние из доп. памяти
  90. local function restoreState()
  91.   pos.x = clone_pos.x
  92.   pos.y = clone_pos.y
  93.   pos.z = clone_pos.z
  94.   currDir.x = clone_currDir.x
  95.   currDir.y = clone_currDir.y
  96.   currDir.z = clone_currDir.z
  97.   givenDir.x = clone_givenDir.x
  98.   givenDir.y = clone_givenDir.y
  99.   givenDir.z = clone_givenDir.z
  100.   distantion.x = clone_distantion.x
  101.   distantion.y = clone_distantion.y
  102.   distantion.z = clone_distantion.z
  103. end
  104.  
  105. -- curr == true сохраняем текущее состояние
  106. -- curr == false сохраняем клонированное состояние
  107. local function saveState(curr)
  108.   name = shell.getRunningProgram()
  109.   local file = fs.open(name..".save","w")
  110.   file.writeLine(width)
  111.   file.writeLine(lenght)
  112.   file.writeLine(height)
  113.   file.writeLine(reflection)
  114.   file.writeLine(startPos.x)
  115.   file.writeLine(startPos.y)
  116.   file.writeLine(startPos.z)
  117.   file.writeLine(state)
  118.   file.writeLine(miningEnd)
  119.  
  120.   file.writeLine(posTmpMining.x)
  121.   file.writeLine(posTmpMining.y)
  122.   file.writeLine(posTmpMining.z)
  123.   file.writeLine(currDirTmpMining.x)
  124.   file.writeLine(currDirTmpMining.y)
  125.   file.writeLine(currDirTmpMining.z)    
  126.   file.writeLine(dirMining)
  127.  
  128.   if curr == true then
  129.     file.writeLine(pos.x)
  130.     file.writeLine(pos.y)
  131.     file.writeLine(pos.z)
  132.     file.writeLine(currDir.x)
  133.     file.writeLine(currDir.y)
  134.     file.writeLine(currDir.z)
  135.     file.writeLine(givenDir.x)
  136.     file.writeLine(givenDir.y)
  137.     file.writeLine(givenDir.z)
  138.     file.writeLine(distantion.x)
  139.     file.writeLine(distantion.y)
  140.     file.writeLine(distantion.z)
  141.   else
  142.     file.writeLine(clone_pos.x)
  143.     file.writeLine(clone_pos.y)
  144.     file.writeLine(clone_pos.z)
  145.     file.writeLine(clone_currDir.x)
  146.     file.writeLine(clone_currDir.y)
  147.     file.writeLine(clone_currDir.z)
  148.     file.writeLine(clone_givenDir.x)
  149.     file.writeLine(clone_givenDir.y)
  150.     file.writeLine(clone_givenDir.z)
  151.     file.writeLine(clone_distantion.x)
  152.     file.writeLine(clone_distantion.y)
  153.     file.writeLine(clone_distantion.z)  
  154.   end
  155.   file.close()
  156. end
  157.  
  158. local function readState()
  159.   name = shell.getRunningProgram()
  160.   if not fs.exists(name..".save") then
  161.     return false
  162.   end
  163.   local file = fs.open(name..".save","r")
  164.  
  165.   width         = tonumber(file.readLine())
  166.   lenght        = tonumber(file.readLine())
  167.   height        = tonumber(file.readLine())
  168.   reflection    = tonumber(file.readLine())
  169.   startPos.x    = tonumber(file.readLine())
  170.   startPos.y    = tonumber(file.readLine())
  171.   startPos.z    = tonumber(file.readLine())
  172.   state         = tonumber(file.readLine())
  173.   miningEnd     = tonumber(file.readLine())
  174.   posTmpMining.x         = tonumber(file.readLine())
  175.   posTmpMining.y         = tonumber(file.readLine())
  176.   posTmpMining.z         = tonumber(file.readLine())
  177.   currDirTmpMining.x     = tonumber(file.readLine())
  178.   currDirTmpMining.y     = tonumber(file.readLine())
  179.   currDirTmpMining.z     = tonumber(file.readLine())  
  180.   dirMining     = tonumber(file.readLine())  
  181.   pos.x         = tonumber(file.readLine())
  182.   pos.y         = tonumber(file.readLine())
  183.   pos.z         = tonumber(file.readLine())
  184.   currDir.x     = tonumber(file.readLine())
  185.   currDir.y     = tonumber(file.readLine())
  186.   currDir.z     = tonumber(file.readLine())
  187.   givenDir.x    = tonumber(file.readLine())
  188.   givenDir.y    = tonumber(file.readLine())
  189.   givenDir.z    = tonumber(file.readLine())
  190.   distantion.x  = tonumber(file.readLine())
  191.   distantion.y  = tonumber(file.readLine())
  192.   distantion.z  = tonumber(file.readLine())
  193.  
  194.   file.close()
  195.   return true
  196. end
  197.  
  198.  
  199. local function setStartup()
  200.   if fs.exists("startup") then
  201.     --              if fs.exists("startup.old") then
  202.     fs.delete("startup")
  203.     --              else
  204.     --                      shell.run("move","startup","startup.old")
  205.     --              end
  206.   end
  207.   name = shell.getRunningProgram()
  208.   local file = fs.open("startup","w")
  209.   file.writeLine("shell.run(\""..name.."\")")
  210.   file.close()
  211. end
  212.  
  213. local function delStartup()
  214.   if fs.exists("startup") then
  215.     fs.delete("startup")
  216.   end
  217.   --      if fs.exists("startup.old") then
  218.   --              shell.run("move","startup.old","startup")
  219.   --      end
  220.   name = shell.getRunningProgram()
  221.   if fs.exists(name..".save") then
  222.     fs.delete(name..".save")
  223.   end
  224. end
  225.  
  226.  
  227. -- зеркально отразить вектор по оси
  228. -- x [0, 1]; y [0, 1]
  229. function Reflect(vec, x, y)
  230.   vx = vec.x
  231.   vy = vec.y
  232.   if x == 1 then
  233.     vx = -vec.x
  234.   end
  235.   if y == 1 then
  236.     vy = -vec.y
  237.   end
  238.  
  239.   return vector.new(vx, vy, vec.z)
  240. end
  241.  
  242. local function inventoryFull()
  243.   for i = 1, 16 do
  244.     if turtle.getItemCount(i) <= 0 then
  245.       return false
  246.     end
  247.   end  
  248.   return true
  249. end
  250.  
  251. local function unload()
  252.   print( "Unloading items..." )
  253.   local n = 1
  254.   if not turtle.detect() then
  255.     print("no detect chest")
  256.     while not turtle.detect() do
  257.       os.sleep(1)
  258.     end
  259.   end
  260.   while n <= 16 do
  261.     turtle.select(n)
  262.     if turtle.getItemCount(n) > 0 and not turtle.drop() then
  263.       print("Don't unload to chest")
  264.       os.sleep(5)
  265.     else
  266.       n = n + 1
  267.     end
  268.   end
  269.   turtle.select(1)
  270. end
  271.  
  272. -- Сколько нужно заправить топлива, что бы доехать
  273. -- dir - true; едем на базу
  274. -- dir - false; едем копать
  275. function countFillFuel(dir)
  276.   local fuelLevel = turtle.getFuelLevel()
  277.   local needed = 0
  278.   if dir == true then
  279.     -- сколько нужно что б доехать до базы
  280.     needed = math.abs(startPos.x - pos.x) +
  281.              math.abs(startPos.y - pos.y) +
  282.              math.abs(pos.z - startPos.z) + 3
  283.   else
  284.     -- сколько нужно что б доехать до рабочего места и вернуться
  285.     needed = math.abs(startPos.x - posTmpMining.x) +
  286.              math.abs(startPos.y - posTmpMining.y) +
  287.              math.abs(posTmpMining.z - startPos.z) + 3    
  288.     needed = needed * 2        
  289.   end
  290.   if fuelLevel < needed then
  291.     return needed - fuelLevel
  292.   else
  293.     return 0
  294.   end
  295. end
  296.  
  297. -- Смогли ли мы заправиться на месте?
  298. function refuelHere()
  299.   -- Заправляемся
  300.   if countFillFuel(true) > 0 then
  301.     for i = 1, 16 do
  302.       if turtle.getItemCount(i) > 0 then
  303.         turtle.select(i)
  304.         if turtle.refuel(64) then
  305.           if countFillFuel(true) <= 0 then
  306.             turtle.select(1)
  307.             return true
  308.           end
  309.         end
  310.       end
  311.     end
  312.     turtle.select(1)
  313.     return false
  314.   else
  315.     return true
  316.   end
  317. end
  318.  
  319.  
  320. function refuel()
  321.   if countFillFuel(false) <= 0 then
  322.     return
  323.   end
  324.   print("waiting for fuel")
  325.   while countFillFuel(false) > 0 do
  326.     for i = 1, 16 do
  327.       if turtle.getItemCount(i) > 0 then
  328.         turtle.select(i)
  329.         turtle.refuel(64)
  330.       end
  331.     end
  332.     sleep(1)
  333.   end
  334. end
  335.  
  336. local function down()
  337.   while true do
  338.     if turtle.detectDown() then    
  339.       if turtle.digDown() then
  340.         -- print("detect block")
  341.       else
  342.         -- Мы не сможем переместиться
  343.         -- Восстановим прошлое состояние
  344.         restoreState()
  345.         print("detect bedrock or unbreaking block")
  346.         return false
  347.       end
  348.     elseif turtle.attackDown() then
  349.       print("detect monster or player")
  350.     else  
  351.       -- Сохраним текущее состояние
  352.       saveState(true)
  353.       if turtle.down() then
  354.         -- print("it's ok!")
  355.         -- checkBorder()
  356.         return true
  357.       else
  358.         -- Мы не смогли переместиться
  359.         -- Сохраним восстановим прошлое состояние
  360.         saveState(false)
  361.         if turtle.getFuelLevel() <= 0 then
  362.           -- Что то пошло не так, у нас резко закончилось топливо
  363.           print("ran out of fuel")
  364.           refuelHere()
  365.         else          
  366.           print("detect unknowing object")
  367.         end
  368.         os.sleep(0.5)
  369.       end
  370.     end
  371.   end
  372. end
  373.  
  374. local function up()
  375.   while true do
  376.     if turtle.detectUp() then       --обнаружен блок, сломать
  377.       if turtle.digUp() then
  378.       -- print("detect block")
  379.       else
  380.         -- Мы не сможем переместиться
  381.         -- Восстановим прошлое состояние
  382.         restoreState()
  383.         print("detect bedrock or unbreaking block")
  384.         return false
  385.       end
  386.     elseif turtle.attackUp() then -- Сверху нет блока, проверяем есть ли там существо
  387.       print("detect monster or player")
  388.     else    -- Передвигаемся вверх
  389.       -- Сохраним текущее состояние
  390.       saveState(true)
  391.       if turtle.up() then
  392.         -- it's ok!
  393.         -- print("it's ok!")
  394.         -- checkBorder()
  395.         return true
  396.       else
  397.         -- Мы не смогли переместиться
  398.         -- Сохраним восстановим прошлое состояние
  399.         saveState(false)
  400.         if turtle.getFuelLevel() <= 0 then
  401.           -- Что то пошло не так, у нас резко закончилось топливо
  402.           print("ran out of fuel")
  403.           refuelHere()
  404.         else          
  405.           print("detect unknowing object")
  406.         end
  407.         os.sleep(0.5)
  408.       end
  409.     end
  410.   end
  411. end
  412.  
  413. local function forward(mined)
  414.   if mined then
  415.     if turtle.detectUp() then
  416.       turtle.digUp()
  417.       --if inventoryFull() then
  418.       --  returnSupplies()
  419.       --end
  420.     end
  421.     if turtle.detectDown() then
  422.       turtle.digDown()
  423.       --if inventoryFull() then
  424.       --  returnSupplies()
  425.       --end
  426.     end
  427.   end
  428.        
  429.   while true do
  430.     if turtle.detect() then -- обнаружен блок, сломать
  431.       if turtle.dig() then
  432.         -- print("detect block")
  433.         --if mined and inventoryFull() then
  434.         --  returnSupplies()
  435.         --end
  436.       else
  437.         -- Мы не сможем переместиться
  438.         -- Восстановим прошлое состояние
  439.         restoreState()
  440.         print("detect bedrock or unbreaking block")
  441.         return false
  442.       end
  443.     elseif turtle.attack() then -- Впереди нет блока, проверяем есть ли там существо
  444.       print("detect monster or player")
  445.       --if mined and inventoryFull() then
  446.       --  returnSupplies()
  447.       --end
  448.     else    -- Передвигаемся вперед
  449.       if mined then -- Уберем гравий и любые падающие блоки над головой
  450.         while turtle.detectUp() do
  451.           turtle.digUp()
  452.           os.sleep(0.5)
  453.         end
  454.       end
  455.  
  456.       -- Сохраним текущее состояние
  457.       saveState(true)
  458.       if turtle.forward() then
  459.         -- print("it's ok!")
  460.         --checkBorder()
  461.         return true
  462.       else
  463.         -- Мы не смогли переместиться
  464.         -- Сохраним восстановим прошлое состояние
  465.         saveState(false)
  466.         if not turtle.detect() then  
  467.           if turtle.getFuelLevel() <= 0 then
  468.             -- Что то пошло не так, у нас резко закончилось топливо
  469.             print("ran out of fuel")
  470.             refuelHere()
  471.           else          
  472.             print("detect unknowing object")
  473.           end
  474.         end
  475.         os.sleep(0.5)
  476.       end
  477.     end
  478.   end
  479. end
  480.  
  481. -- если dir - true, едем домой
  482. -- если dir - false, едем копать
  483. function startGoTo(dir)
  484.   if dir == true then
  485.     posTmpMining.x = pos.x
  486.     posTmpMining.y = pos.y
  487.     posTmpMining.z = pos.z
  488.     currDirTmpMining.x = currDir.x
  489.     currDirTmpMining.y = currDir.y
  490.     currDirTmpMining.z = currDir.z
  491.     dirMining = 1
  492.   else
  493.     dirMining = 0
  494.   end
  495.   state = state_goto
  496.   saveState(true)
  497. end
  498.  
  499. local tPosGT = vector.new(0, 0, 0)
  500. local tDirGT = vector.new(0, 0, 0)
  501. function GoTo()
  502.   if dirMining == 1 then
  503.     tPosGT.x = startPos.x
  504.     tPosGT.y = startPos.y
  505.     tPosGT.z = startPos.z
  506.   else
  507.     tPosGT.x = posTmpMining.x
  508.     tPosGT.y = posTmpMining.y
  509.     tPosGT.z = posTmpMining.z
  510.   end
  511.  
  512.   -- идем по оси z
  513.   if pos.z ~= tPosGT.z then
  514.     if pos.z < tPosGT.z then
  515.       -- идем вверх
  516.       cloneState()
  517.       pos.z = pos.z + 1
  518.       up()
  519.     else
  520.       -- идем вниз
  521.       cloneState()
  522.       pos.z = pos.z - 1
  523.       down()
  524.     end
  525.     return
  526.   end
  527.  
  528.   -- ориентируемся и идем по x
  529.   if pos.x ~= tPosGT.x then
  530.    
  531.     local d = 1 -- нам надо ехать вправо
  532.     if pos.x > tPosGT.x then -- нет, все таки влево
  533.       d = -1
  534.     end    
  535.    
  536.     -- нам нужно повернуться на 90
  537.     if currDir.x == 0 then
  538.       if d == currDir.y then
  539.         currDir.x = d
  540.         currDir.y = 0
  541.         saveState(true)
  542.         turtle.turnRight()
  543.       else
  544.         currDir.x = d
  545.         currDir.y = 0
  546.         saveState(true)
  547.         turtle.turnLeft()
  548.       end
  549.     -- нам надо повернуться на 180
  550.     elseif currDir.x ~= d then
  551.         currDir.x = 0
  552.         currDir.y = d
  553.         saveState(true)
  554.         turtle.turnRight()        
  555.     -- мы сориентировались. пошли вперед
  556.     else
  557.       cloneState()
  558.       pos.x = pos.x + d
  559.       forward(false)  
  560.     end
  561.     return
  562.   end
  563.  
  564.   -- ориентируемся и идем по y
  565.   if pos.y ~= tPosGT.y then
  566.    
  567.     local d = 1 -- нам надо ехать вперед
  568.     if pos.y > tPosGT.y then -- нет, все таки назад
  569.       d = -1
  570.     end    
  571.    
  572.     -- нам нужно повернуться на 90
  573.     if currDir.y == 0 then
  574.       if d ~= currDir.x then
  575.         currDir.y = d
  576.         currDir.x = 0
  577.         saveState(true)
  578.         turtle.turnRight()
  579.       else
  580.         currDir.y = d
  581.         currDir.x = 0
  582.         saveState(true)
  583.         turtle.turnLeft()
  584.       end
  585.     -- нам надо повернуться на 180
  586.     elseif currDir.y ~= d then
  587.         currDir.y = 0
  588.         currDir.x = d
  589.         saveState(true)
  590.         turtle.turnLeft()        
  591.     -- мы сориентировались. пошли вперед
  592.     else
  593.       cloneState()
  594.       pos.y = pos.y + d
  595.       forward(false)  
  596.     end
  597.     return
  598.   end  
  599.  
  600.   if dirMining == 1 then
  601.     tDirGT.x = 0
  602.     tDirGT.y = -1
  603.     tDirGT.z = 0
  604.   else
  605.     tDirGT.x = currDirTmpMining.x
  606.     tDirGT.y = currDirTmpMining.y
  607.     tDirGT.z = currDirTmpMining.z
  608.   end
  609.   -- мы находимся в конечной позиции
  610.   -- возможно нужно развернуться
  611.   -- нам нужно повернуться на 180
  612.   if currDir.x == tDirGT.x and currDir.y == tDirGT.y then
  613.     -- Мы приехали
  614.     if dirMining == 1 then
  615.       state = state_home
  616.       saveState(true)
  617.     else
  618.       state = state_mining
  619.       saveState(true)
  620.     end  
  621.     return
  622.   elseif (currDir.x == 0 and tDirGT.x == 0) or
  623.      (currDir.y == 0 and tDirGT.y == 0)
  624.   then
  625.     if currDir.x ~= 0 then
  626.       currDir.y = -currDir.x
  627.       currDir.x = 0
  628.       saveState(true)
  629.       turtle.turnRight()
  630.     else
  631.       currDir.x = currDir.y
  632.       currDir.y = 0
  633.       saveState(true)
  634.       turtle.turnRight()        
  635.     end
  636.   -- нам надо повернуться на 90
  637.   elseif currDir.y == 0 then
  638.     if currDir.x == tDirGT.y then
  639.       currDir.y = tDirGT.y
  640.       currDir.x = 0
  641.       saveState(true)
  642.       turtle.turnLeft()
  643.     else
  644.       currDir.y = tDirGT.y
  645.       currDir.x = 0
  646.       saveState(true)
  647.       turtle.turnRight()
  648.     end
  649.   elseif currDir.x == 0 then
  650.     if currDir.y == tDirGT.x then
  651.       currDir.x = tDirGT.x
  652.       currDir.y = 0
  653.       saveState(true)
  654.       turtle.turnRight()
  655.     else
  656.       currDir.x = tDirGT.x
  657.       currDir.y = 0
  658.       saveState(true)
  659.       turtle.turnLeft()
  660.     end
  661.   end
  662.  
  663. end
  664.  
  665.  
  666. function Minning()
  667.   -- Нужно ли нам заправляться?
  668.   if not refuelHere() then
  669.     -- Надо съездить на базу
  670.     startGoTo(true)
  671.     return
  672.   end
  673.  
  674.   -- Нужно ли нам выгрузить ресурсы?
  675.   if inventoryFull() then
  676.     -- Надо съездить на базу
  677.     startGoTo(true)
  678.     return
  679.   end  
  680.  
  681.   -- мы должны развернуться на 180
  682.   if currDir.y ~= givenDir.y and currDir.x == 0 then
  683.      
  684.       -- Мы должны попытаться проехать по ширине карьера
  685.       if distantion.x == 1 then
  686.        
  687.       -- Поворачиваем, после поворота мы будем стоять параллельно оси x
  688.       -- тут магическое условие которое я скоро забуду и не пойму почему так работает :))
  689.       -- на самом деле направление поворота зависит от направления движения
  690.       -- если мы хотим повернуть черепаху направо то направление движения должно
  691.       -- совпадать (численно) с желаемым направлением поворота
  692.       -- -1 == -1; 1 == 1; поворот направо
  693.       -- -1 ~= 1; 1 ~= -1; поворот налево
  694.       -- 180 -> 90
  695.       if givenDir.x == currDir.y then
  696.         -- скорректируем наше текущее положение
  697.         currDir.x = givenDir.x
  698.         currDir.y = 0
  699.         saveState(true)
  700.         turtle.turnRight()
  701.          
  702.       -- 180 -> 90
  703.       else
  704.           -- скорректируем наше текущее положение
  705.         currDir.x = givenDir.x
  706.         currDir.y = 0
  707.         saveState(true)
  708.         turtle.turnLeft()
  709.          
  710.       end
  711.    
  712.     end
  713.        
  714.     -- сейчас мы стоим параллельно оси х
  715.     -- мы должны развернуться на 90%
  716.     elseif currDir.x ~= 0 then
  717.      
  718.       -- Двигаемся вбок на 1 блок если это нужно
  719.       if distantion.x == 1 then
  720.  
  721.       -- Мы хотим передвинуться вперед, но уперлись в стенку
  722.       -- Мы оказались в углу
  723.       if (pos.x == 0 and currDir.x == -1) or
  724.          (pos.x == width - 1 and currDir.x == 1)
  725.       then
  726.         -- Ехать в бок не будем
  727.         -- Нужно поехать вниз
  728.         givenDir.z = -1
  729.         distantion.x = 0
  730.         distantion.z = layerHeight
  731.         givenDir = Reflect(givenDir, 1, 0) 
  732.         -- save
  733.      
  734.         return
  735.      
  736.       end    
  737.    
  738.       -- Запоминаем текущее состояние на случай отката
  739.           cloneState()
  740.         -- Копаем и двигаемся вперед
  741.         distantion.x = 0
  742.         pos.x = pos.x + givenDir.x
  743.      
  744.       -- Мы наткнулись на бедрок спереди
  745.       -- Возможно он есть над нами, пытаемся объехать его
  746.       if not forward(true) then
  747.         --distantion.x = 0
  748.         --distantion.y = 0
  749.         state = state_bedrock
  750.         miningEnd = 1
  751.         saveState(true)
  752.         return
  753.       end
  754.      
  755.       -- Если нам нужно ехать вниз, значит мы в углу
  756.       -- Поехали вниз
  757.       elseif distantion.z > 0 then
  758.  
  759.       -- Запоминаем текущее состояние на случай отката
  760.           cloneState()
  761.       pos.z = pos.z + givenDir.z  
  762.      
  763.       -- Мы достигли дна
  764.       if pos.z <= -(height) then    
  765.         restoreState()      
  766.         -- Поехали домой, работа закончена
  767.         miningEnd = 1
  768.         startGoTo(true)
  769.         -- Едем домой
  770.         return  
  771.       end
  772.      
  773.       -- Мы только начали опускаться
  774.       if distantion.z == layerHeight then
  775.         -- и стоим на предпоследнем слое
  776.         -- Значит пора ехать домой
  777.         if pos.z <= -(height - 1) then
  778.           restoreState()      
  779.           -- Поехали домой, работа закончена
  780.           miningEnd = 1
  781.           startGoTo(true)
  782.           return
  783.         end
  784.       else
  785.         -- мы еще не проехались по этому слою
  786.         if pos.z <= -(height - 1) then
  787.           restoreState()
  788.           distantion.z = 0
  789.           return
  790.         end
  791.       end
  792.      
  793.       distantion.z = distantion.z - 1
  794.      
  795.       if givenDir.z == -1 then
  796.         -- Пытаемся спуститься
  797.         if not down() then
  798.           -- Мы наехали на бедрок
  799.           if distantion.z == layerHeight then
  800.             -- Поехали домой, работа закончена
  801.             miningEnd = 1
  802.             startGoTo(true)
  803.             return            
  804.           else
  805.             distantion.z = 0
  806.           end
  807.         end
  808.       --else
  809.       --  up()
  810.       end
  811.      
  812.       -- Нам не нужно никуда ехать. Разворачиваемся.
  813.       -- См комментарий про поворот выше
  814.       else   
  815.       if givenDir.y == currDir.x then
  816.         -- скорректируем наше текущее положение
  817.         currDir.x = 0
  818.         currDir.y = givenDir.y
  819.         saveState(true)
  820.         turtle.turnLeft()        
  821.        
  822.       else
  823.         -- скорректируем наше текущее положение
  824.         currDir.x = 0
  825.         currDir.y = givenDir.y
  826.         saveState(true)
  827.         turtle.turnRight()               
  828.         end
  829.       end
  830.      
  831.     return --?
  832.    
  833.     end
  834.  
  835.     -- Двигаемся по длине карьера
  836.     if currDir.y == givenDir.y then
  837.      
  838.       -- Мы дошли до стенки, нужно развернуться
  839.       if distantion.y == 0 then
  840.      
  841.           givenDir = Reflect(givenDir, 0, 1)
  842.           distantion.x = 1
  843.           distantion.y = lenght - 1
  844.          
  845.           -- save
  846.        
  847.           return
  848.        
  849.       else
  850.        
  851.       -- Запоминаем текущее состояние на случай отката
  852.           cloneState()
  853.         -- Копаем и двигаемся вперед
  854.         pos.y = pos.y + givenDir.y
  855.       distantion.y = distantion.y - 1
  856.       -- Мы наткнулись на бедрок спереди
  857.       -- Возможно он есть над нами, пытаемся объехать его
  858.       if not forward(true) then
  859.         --distantion.x = 0
  860.         --distantion.y = 0
  861.         state = state_bedrock
  862.         miningEnd = 1
  863.         saveState(true)
  864.         return
  865.       end
  866.      
  867.       end
  868.      
  869.     end
  870.  
  871. end
  872.  
  873.  
  874. -- Мы дома
  875. -- Выгружаем ресурсы и заправляемся если нужно
  876. function Home()
  877.   unload()
  878.   if miningEnd == 1 then
  879.     return false
  880.   end
  881.   refuel()
  882.   startGoTo(false)
  883.   return true
  884. end
  885.  
  886. local tArgs = { ... }
  887. if #tArgs == 0 then
  888.   print( "Recovering...")
  889.   readState()
  890.  
  891. elseif #tArgs == 2 then
  892.  
  893.   lenght = tonumber( tArgs[1] )
  894.   width  = tonumber( tArgs[2] )
  895.   startPos.x = (width - 1) * reflection
  896.   startPos.y = 0
  897.   startPos.z = 0
  898.  
  899.   pos.x = startPos.x
  900.   pos.y = startPos.y
  901.   pos.z = startPos.z
  902.  
  903.   givenDir.x = 1- reflection * 2
  904.   givenDir.y = 1
  905.   givenDir.z = -1
  906.  
  907.   distantion.x = 0
  908.   distantion.y = lenght - 1
  909.   distantion.z = 0
  910.  
  911.   --setStartup()
  912.  
  913.   cloneState()
  914.   pos.z = pos.z - 1
  915.   down()
  916.  
  917.   state = state_mining
  918.   miningEnd = 0
  919.  
  920. end
  921.  
  922. while true do
  923.  
  924.   if state == state_mining then
  925.     Minning()
  926.   elseif state == state_goto then
  927.     GoTo()
  928.   elseif state == state_home then
  929.     if not Home() then
  930.       print("is completed")
  931.       break
  932.     end
  933.   else
  934.     print("error state")
  935.     break
  936.   end
  937.  
  938. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement