agentsix1

Personal Turtle Code v0.01

May 9th, 2015 (edited)
2,500
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 64.47 KB | None | 0 0
  1. -- ********************************************************************************** --
  2. -- ** ** --
  3. -- ** Minecraft Mining Turtle Ore Quarry v0.71 by AustinKK ** --
  4. -- ** ---------------------------------------------------- ** --
  5. -- ** ** --
  6. -- ** For instructions on how to use: ** --
  7. -- ** ** --
  8. -- ** http://www.youtube.com/watch?v=PIugLVzUz3g ** --
  9. -- ** ** --
  10. -- ** Change Log: ** --
  11. -- ** 27th Dec 2012: [v0.2] Initial Draft Release ** --
  12. -- ** 29th Dec 2012: [v0.3] Minor Performance Improvements ** --
  13. -- ** 30th Dec 2012: [v0.4] Further Performance Improvements ** --
  14. -- ** 9th Jan 2013: [v0.5] Debug Version (dropping off chest) ** --
  15. -- ** 10th Jan 2013: [v0.51] Further Debug (dropping off chest) ** --
  16. -- ** 10th Jan 2013: [v0.52] Fix for dropping off chest bug ** --
  17. -- ** 11th Jan 2013: [v0.53] Fix for dropping off chest bug (release) ** --
  18. -- ** 12th Jan 2013: [v0.6] Added support for resume ** --
  19. -- ** 31st Mar 2013: [v0.7] Fixes for ComputerCraft 1.52 ** --
  20. -- ** 25th Aug 2013: [v0.71] Support ComputerCraft 1.56 and Chunk Loader Module ** --
  21. -- ** ** --
  22. -- ********************************************************************************** --
  23.  
  24.  
  25. -- ********************************************************************************** --
  26. -- Note: If you are in a world with flat bedrock, change the value below from 5 to 2.
  27. -- You don't need to change this, but the turtle is slightly faster if you do.
  28. -- ********************************************************************************** --
  29. local bottomLayer = 5 -- The y co-ords of the layer immediately above bedrock
  30.  
  31.  
  32.  
  33. -- Enumeration to store the the different types of message that can be written
  34. messageLevel = { DEBUG=0, INFO=1, WARNING=2, ERROR=3, FATAL=4 }
  35.  
  36. -- Enumeration to store names for the 6 directions
  37. direction = { FORWARD=0, RIGHT=1, BACK=2, LEFT=3, UP=4, DOWN=5 }
  38.  
  39. -- Enumeration of mining states
  40. miningState = { START=0, LAYER=1, EMPTYCHESTDOWN=2, EMPTYINVENTORY=3 }
  41.  
  42. local messageOutputLevel = messageLevel.INFO
  43. local messageOutputFileName
  44. local fuelLevelToRefuelAt = 5
  45. local refuelItemsToUseWhenRefuelling = 63
  46. local emergencyFuelToRetain = 0
  47. local maximumGravelStackSupported = 25 -- The number of stacked gravel or sand blocks supported
  48. local noiseBlocksCount
  49. local returningToStart = false
  50. local lookForChests = false -- Determines if chests should be located as part of the quarrying
  51. local miningOffset -- The offset to the mining layer. This is set depending on whether chests are being looked for or not
  52. local lastEmptySlot -- The last inventory slot that was empty when the program started (is either 15 if not looking for chests or 14 if we are)
  53. local turtleId
  54. local isWirelessTurtle
  55. local currentlySelectedSlot = 0 -- The slot that the last noise block was found in
  56. local lastMoveNeededDig = true -- Determines whether the last move needed a dig first
  57. local haveBeenAtZeroZeroOnLayer -- Determines whether the turtle has been at (0, 0) in this mining layer
  58. local orientationAtZeroZero -- The turtle's orientation when it was at (0, 0)
  59. local levelToReturnTo -- The level that the turtle should return to in order to head back to the start to unload
  60.  
  61. -- Variables used to support a resume
  62. local startupParamsFile = "OreQuarryParams.txt"
  63. local oreQuarryLocation = "OreQuarryLocation.txt"
  64. local returnToStartFile = "OreQuarryReturn.txt"
  65. local startupBackup = "startup_bak"
  66. local supportResume = true -- Determines whether the turtle is being run in the mode that supports resume
  67. local resuming = false -- Determines whether the turtle is currently in the process of resuming
  68. local resumeX
  69. local resumeY
  70. local resumeZ
  71. local resumeOrient
  72. local resumeMiningState
  73.  
  74. -- Variables to store the current location and orientation of the turtle. x is right, left, y is up, down and
  75. -- z is forward, back with relation to the starting orientation. Y is the actual turtle level, x and z are
  76. -- in relation to the starting point (i.e. the starting point is (0, 0))
  77. local currX
  78. local currY
  79. local currZ
  80. local currOrient
  81. local currMiningState = miningState.START
  82.  
  83. -- Command line parameters
  84. local startHeight -- Represents the height (y co-ord) that the turtle started at
  85. local quarryWidth -- Represents the length of the mines that the turtle will dig
  86.  
  87. -- ********************************************************************************** --
  88. -- Writes an output message
  89. -- ********************************************************************************** --
  90. function writeMessage(message, msgLevel)
  91. if (msgLevel >= messageOutputLevel) then
  92. print(message)
  93.  
  94. -- If this turtle has a modem, then write the message to red net
  95. if (isWirelessTurtle == true) then
  96. if (turtleId == nil) then
  97. rednet.broadcast(message)
  98. else
  99. -- Broadcast the message (prefixed with the turtle's id)
  100. rednet.broadcast(message)
  101. end
  102. end
  103.  
  104. if (messageOutputFileName ~= nil) then
  105. -- Open file, write message and close file (flush doesn't seem to work!)
  106. local outputFile
  107. if (fs.exists(messageOutputFileName) == true) then
  108. outputFile = io.open(messageOutputFileName, "a")
  109. else
  110. outputFile = io.open(messageOutputFileName, "w")
  111. end
  112.  
  113. outputFile:write(message)
  114. outputFile:write("\n")
  115. outputFile:close()
  116. end
  117. end
  118. end
  119.  
  120. -- ********************************************************************************** --
  121. -- Ensures that the turtle has fuel
  122. -- ********************************************************************************** --
  123. function ensureFuel()
  124.  
  125. -- Determine whether a refuel is required
  126. local fuelLevel = turtle.getFuelLevel()
  127. if (fuelLevel ~= "unlimited") then
  128. if (fuelLevel < fuelLevelToRefuelAt) then
  129. -- Need to refuel
  130. turtle.select(16)
  131. currentlySelectedSlot = 16
  132. local fuelItems = turtle.getItemCount(16)
  133.  
  134. -- Do we need to impact the emergency fuel to continue? (always
  135. -- keep one fuel item in slot 16)
  136. if (fuelItems == 0) then
  137. writeMessage("Completely out of fuel!", messageLevel.FATAL)
  138. elseif (fuelItems == 1) then
  139. writeMessage("Out of Fuel!", messageLevel.ERROR)
  140. turtle.refuel()
  141. elseif (fuelItems <= (emergencyFuelToRetain + 1)) then
  142. writeMessage("Consuming emergency fuel supply. "..(fuelItems - 2).." emergency fuel items remain", messageLevel.WARNING)
  143. turtle.refuel(1)
  144. else
  145. -- Refuel the lesser of the refuelItemsToUseWhenRefuelling and the number of items more than
  146. -- the emergency fuel level
  147. if (fuelItems - (emergencyFuelToRetain + 1) < refuelItemsToUseWhenRefuelling) then
  148. turtle.refuel(fuelItems - (emergencyFuelToRetain + 1))
  149. else
  150. turtle.refuel(refuelItemsToUseWhenRefuelling)
  151. end
  152. end
  153. end
  154. end
  155. end
  156.  
  157. -- ********************************************************************************** --
  158. -- Checks that the turtle has inventory space by checking for spare slots and returning
  159. -- to the starting point to empty out if it doesn't.
  160. --
  161. -- Takes the position required to move to in order to empty the turtle's inventory
  162. -- should it be full as arguments
  163. -- ********************************************************************************** --
  164. function ensureInventorySpace()
  165.  
  166. -- If already returning to start, then don't need to do anything
  167. if (returningToStart == false) then
  168.  
  169. -- If the last inventory slot is full, then need to return to the start and empty
  170. if (turtle.getItemCount(lastEmptySlot) > 0) then
  171.  
  172. -- Return to the starting point and empty the inventory, then go back to mining
  173. returnToStartAndUnload(true)
  174. end
  175. end
  176. end
  177.  
  178. -- ********************************************************************************** --
  179. -- Function to move to the starting point, call a function that is passed in
  180. -- and return to the same location (if required)
  181. -- ********************************************************************************** --
  182. function returnToStartAndUnload(returnBackToMiningPoint)
  183. writeMessage("Returning to surface", messageLevel.INFO)
  184. writeMessage("returnToStartAndUnload called", messageLevel.DEBUG)
  185. returningToStart = true
  186. local storedX, storedY, storedZ, storedOrient
  187. local prevMiningState = currMiningState
  188.  
  189. if (resuming == true) then
  190. -- Get the stored parameters from the necessary file
  191. local resumeFile = fs.open(returnToStartFile, "r")
  192. if (resumeFile ~= nil) then
  193. -- Restore the parameters from the file
  194. local beenAtZero = resumeFile.readLine()
  195. if (beenAtZero == "y") then
  196. haveBeenAtZeroZeroOnLayer = true
  197. else
  198. haveBeenAtZeroZeroOnLayer = false
  199. end
  200.  
  201. local miningPointFlag = resumeFile.readLine()
  202. if (miningPointFlag == "y") then
  203. returnBackToMiningPoint = true
  204. else
  205. returnBackToMiningPoint = false
  206. end
  207.  
  208. currX = readNumber(resumeFile)
  209. currY = readNumber(resumeFile)
  210. currZ = readNumber(resumeFile)
  211. currOrient = readNumber(resumeFile)
  212. levelToReturnTo = readNumber(resumeFile)
  213. prevMiningState = readNumber(resumeFile)
  214. orientationAtZeroZero = readNumber(resumeFile)
  215. resumeFile.close()
  216.  
  217. else
  218. writeMessage("Failed to read return to start file", messageLevel.ERROR)
  219. end
  220. elseif (supportResume == true) then
  221.  
  222. local outputFile = io.open(returnToStartFile, "w")
  223.  
  224. if (haveBeenAtZeroZeroOnLayer == true) then
  225. outputFile:write("y\n")
  226. else
  227. outputFile:write("n\n")
  228. end
  229. if (returnBackToMiningPoint == true) then
  230. outputFile:write("y\n")
  231. else
  232. outputFile:write("n\n")
  233. end
  234.  
  235. outputFile:write(currX)
  236. outputFile:write("\n")
  237. outputFile:write(currY)
  238. outputFile:write("\n")
  239. outputFile:write(currZ)
  240. outputFile:write("\n")
  241. outputFile:write(currOrient)
  242. outputFile:write("\n")
  243. outputFile:write(levelToReturnTo)
  244. outputFile:write("\n")
  245. outputFile:write(prevMiningState)
  246. outputFile:write("\n")
  247. outputFile:write(orientationAtZeroZero)
  248. outputFile:write("\n")
  249.  
  250. outputFile:close()
  251. end
  252.  
  253. storedX = currX
  254. storedY = currY
  255. storedZ = currZ
  256. storedOrient = currOrient
  257.  
  258. -- Store the current location and orientation so that it can be returned to
  259. currMiningState = miningState.EMPTYINVENTORY
  260. writeMessage("last item count = "..turtle.getItemCount(lastEmptySlot), messageLevel.DEBUG)
  261.  
  262. if ((turtle.getItemCount(lastEmptySlot) > 0) or (returnBackToMiningPoint == false)) then
  263.  
  264. writeMessage("Heading back to surface", messageLevel.DEBUG)
  265.  
  266. -- Move down to the correct layer to return via
  267. if (currY > levelToReturnTo) then
  268. while (currY > levelToReturnTo) do
  269. turtleDown()
  270. end
  271. elseif (currY < levelToReturnTo) then
  272. while (currY < levelToReturnTo) do
  273. turtleUp()
  274. end
  275. end
  276.  
  277. if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == direction.FORWARD)) then
  278. -- Move back to the correct X position first
  279. if (currX > 0) then
  280. turtleSetOrientation(direction.LEFT)
  281. while (currX > 0) do
  282. turtleForward()
  283. end
  284. elseif (currX < 0) then
  285. -- This should never happen
  286. writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  287. end
  288.  
  289. -- Then move back to the correct Z position
  290. if (currZ > 0) then
  291. turtleSetOrientation(direction.BACK)
  292. while (currZ > 0) do
  293. turtleForward()
  294. end
  295. elseif (currZ < 0) then
  296. -- This should never happen
  297. writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  298. end
  299. else
  300. -- Move back to the correct Z position first
  301. if (currZ > 0) then
  302. turtleSetOrientation(direction.BACK)
  303. while (currZ > 0) do
  304. turtleForward()
  305. end
  306. elseif (currZ < 0) then
  307. -- This should never happen
  308. writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  309. end
  310.  
  311. -- Then move back to the correct X position
  312. if (currX > 0) then
  313. turtleSetOrientation(direction.LEFT)
  314. while (currX > 0) do
  315. turtleForward()
  316. end
  317. elseif (currX < 0) then
  318. -- This should never happen
  319. writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  320. end
  321. end
  322.  
  323. -- Return to the starting layer
  324. if (currY < startHeight) then
  325. while (currY < startHeight) do
  326. turtleUp()
  327. end
  328. elseif (currY > startHeight) then
  329. -- This should never happen
  330. writeMessage("Current height is greater than start height in returnToStartAndUnload", messageLevel.ERROR)
  331. end
  332.  
  333. -- Empty the inventory
  334. local slotLoop = 1
  335.  
  336. -- Face the chest
  337. turtleSetOrientation(direction.BACK)
  338.  
  339. -- Loop over each of the slots (except the 16th one which stores fuel)
  340. while (slotLoop < 16) do
  341. -- If this is one of the slots that contains a noise block, empty all blocks except
  342. -- one
  343. turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  344. if ((slotLoop <= noiseBlocksCount) or ((slotLoop == 15) and (lastEmptySlot == 14))) then
  345. writeMessage("Dropping (n-1) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)
  346. if (turtle.getItemCount(slotLoop) > 0) then
  347. turtle.drop(turtle.getItemCount(slotLoop) - 1)
  348. end
  349. else
  350. -- Not a noise block, drop all of the items in this slot
  351. writeMessage("Dropping (all) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)
  352. if (turtle.getItemCount(slotLoop) > 0) then
  353. turtle.drop()
  354. end
  355. end
  356.  
  357. slotLoop = slotLoop + 1
  358. end
  359.  
  360. -- While we are here, refill the fuel items if there is capacity
  361. if (turtle.getItemCount(16) < 64) then
  362. turtleSetOrientation(direction.LEFT)
  363. turtle.select(16) -- Don't bother updating selected slot variable as it will set later in this function
  364. local currFuelItems = turtle.getItemCount(16)
  365. turtle.suck()
  366. while ((currFuelItems ~= turtle.getItemCount(16)) and (turtle.getItemCount(16) < 64)) do
  367. currFuelItems = turtle.getItemCount(16)
  368. turtle.suck()
  369. end
  370.  
  371. slotLoop = noiseBlocksCount + 1
  372. -- Have now picked up all the items that we can. If we have also picked up some
  373. -- additional fuel in some of the other slots, then drop it again
  374. while (slotLoop <= lastEmptySlot) do
  375. -- Drop any items found in this slot
  376. if (turtle.getItemCount(slotLoop) > 0) then
  377. turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  378. turtle.drop()
  379. end
  380. slotLoop = slotLoop + 1
  381. end
  382. end
  383.  
  384. -- Select the 1st slot because sometimes when leaving the 15th or 16th slots selected it can result
  385. -- in that slot being immediately filled (resulting in the turtle returning to base again too soon)
  386. turtle.select(1)
  387. currentlySelectedSlot = 1
  388. end
  389.  
  390. -- If required, move back to the point that we were mining at before returning to the start
  391. if (returnBackToMiningPoint == true) then
  392.  
  393. -- If resuming, refresh the starting point to be the top of the return shaft
  394. if (resuming == true) then
  395. currX = 0
  396. currY = startHeight
  397. currZ = 0
  398. currOrient = resumeOrient
  399. end
  400.  
  401. -- Return back to the required layer
  402. while (currY > levelToReturnTo) do
  403. turtleDown()
  404. end
  405.  
  406. if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == direction.FORWARD)) then
  407. -- Move back to the correct Z position first
  408. writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  409. if (storedZ > currZ) then
  410. writeMessage("Orienting forward", messageLevel.DEBUG)
  411. writeMessage("Moving in z direction", messageLevel.DEBUG)
  412. turtleSetOrientation(direction.FORWARD)
  413. while (storedZ > currZ) do
  414. turtleForward()
  415. end
  416. elseif (storedZ < currZ) then
  417. -- This should never happen
  418. writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  419. end
  420.  
  421. -- Then move back to the correct X position
  422. if (storedX > currX) then
  423. writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  424. writeMessage("Orienting right", messageLevel.DEBUG)
  425. writeMessage("Moving in x direction", messageLevel.DEBUG)
  426. turtleSetOrientation(direction.RIGHT)
  427. while (storedX > currX) do
  428. turtleForward()
  429. end
  430. elseif (storedX < currX) then
  431. -- This should never happen
  432. writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  433. end
  434. else
  435. -- Move back to the correct X position first
  436. if (storedX > currX) then
  437. writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  438. writeMessage("Orienting right", messageLevel.DEBUG)
  439. writeMessage("Moving in x direction", messageLevel.DEBUG)
  440. turtleSetOrientation(direction.RIGHT)
  441. while (storedX > currX) do
  442. turtleForward()
  443. end
  444. elseif (storedX < currX) then
  445. -- This should never happen
  446. writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  447. end
  448.  
  449. -- Then move back to the correct Z position
  450. writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  451. if (storedZ > currZ) then
  452. writeMessage("Orienting forward", messageLevel.DEBUG)
  453. writeMessage("Moving in z direction", messageLevel.DEBUG)
  454. turtleSetOrientation(direction.FORWARD)
  455. while (storedZ > currZ) do
  456. turtleForward()
  457. end
  458. elseif (storedZ < currZ) then
  459. -- This should never happen
  460. writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  461. end
  462. end
  463.  
  464. -- Move back to the correct layer
  465. if (storedY < currY) then
  466. while (storedY < currY) do
  467. turtleDown()
  468. end
  469. elseif (storedY > currY) then
  470. while (storedY > currY) do
  471. turtleUp()
  472. end
  473. end
  474.  
  475. -- Finally, set the correct orientation
  476. turtleSetOrientation(storedOrient)
  477. writeMessage("Have returned to the mining point", messageLevel.DEBUG)
  478. end
  479.  
  480. -- Store the current location and orientation so that it can be returned to
  481. currMiningState = prevMiningState
  482.  
  483. returningToStart = false
  484.  
  485. end
  486.  
  487. -- ********************************************************************************** --
  488. -- Empties a chest's contents
  489. -- ********************************************************************************** --
  490. function emptyChest(suckFn)
  491.  
  492. local prevInventoryCount = {}
  493. local inventoryLoop
  494. local chestEmptied = false
  495.  
  496. -- Record the number of items in each of the inventory slots
  497. for inventoryLoop = 1, 16 do
  498. prevInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  499. end
  500.  
  501. while (chestEmptied == false) do
  502. -- Pick up the next item
  503. suckFn()
  504.  
  505. -- Determine the number of items in each of the inventory slots now
  506. local newInventoryCount = {}
  507. for inventoryLoop = 1, 16 do
  508. newInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  509. end
  510.  
  511. -- Now, determine whether there have been any items taken from the chest
  512. local foundDifferentItemCount = false
  513. inventoryLoop = 1
  514. while ((foundDifferentItemCount == false) and (inventoryLoop <= 16)) do
  515. if (prevInventoryCount[inventoryLoop] ~= newInventoryCount[inventoryLoop]) then
  516. foundDifferentItemCount = true
  517. else
  518. inventoryLoop = inventoryLoop + 1
  519. end
  520. end
  521.  
  522. -- If no items have been found with a different item count, then the chest has been emptied
  523. chestEmptied = not foundDifferentItemCount
  524.  
  525. if (chestEmptied == false) then
  526. prevInventoryCount = newInventoryCount
  527. -- Check that there is sufficient inventory space as may have picked up a block
  528. ensureInventorySpace()
  529. end
  530. end
  531.  
  532. writeMessage("Finished emptying chest", messageLevel.DEBUG)
  533. end
  534.  
  535. -- ********************************************************************************** --
  536. -- Write the current location to a file
  537. -- ********************************************************************************** --
  538. function saveLocation()
  539.  
  540. -- Write the x, y, z and orientation to the file
  541. if ((supportResume == true) and (resuming == false)) then
  542. local outputFile = io.open(oreQuarryLocation, "w")
  543. outputFile:write(currMiningState)
  544. outputFile:write("\n")
  545. outputFile:write(currX)
  546. outputFile:write("\n")
  547. outputFile:write(currY)
  548. outputFile:write("\n")
  549. outputFile:write(currZ)
  550. outputFile:write("\n")
  551. outputFile:write(currOrient)
  552. outputFile:write("\n")
  553. outputFile:close()
  554. end
  555.  
  556. end
  557.  
  558. -- ********************************************************************************** --
  559. -- If the turtle is resuming and the current co-ordinates, orientation and
  560. -- mining state have been matched, then no longer resuming
  561. -- ********************************************************************************** --
  562. function updateResumingFlag()
  563.  
  564. if (resuming == true) then
  565. if ((resumeMiningState == currMiningState) and (resumeX == currX) and (resumeY == currY) and (resumeZ == currZ) and (resumeOrient == currOrient)) then
  566. resuming = false
  567. end
  568. end
  569.  
  570. end
  571.  
  572. -- ********************************************************************************** --
  573. -- Generic function to move the Turtle (pushing through any gravel or other
  574. -- things such as mobs that might get in the way).
  575. --
  576. -- The only thing that should stop the turtle moving is bedrock. Where this is
  577. -- found, the function will return after 15 seconds returning false
  578. -- ********************************************************************************** --
  579. function moveTurtle(moveFn, detectFn, digFn, attackFn, compareFn, suckFn, maxDigCount, newX, newY, newZ)
  580.  
  581. local moveSuccess = false
  582.  
  583. -- If we are resuming, then don't do anything in this function other than updating the
  584. -- co-ordinates as if the turtle had moved
  585. if (resuming == true) then
  586. -- Set the move success to true (but don't move) - unless this is below bedrock level
  587. -- in which case return false
  588. if (currY <= 0) then
  589. moveSuccess = false
  590. else
  591. moveSuccess = true
  592. end
  593.  
  594. -- Update the co-ordinates to reflect the movement
  595. currX = newX
  596. currY = newY
  597. currZ = newZ
  598.  
  599. else
  600. local prevX, prevY, prevZ
  601. prevX = currX
  602. prevY = currY
  603. prevZ = currZ
  604.  
  605. ensureFuel()
  606.  
  607. -- Flag to determine whether digging has been tried yet. If it has
  608. -- then pause briefly before digging again to allow sand or gravel to
  609. -- drop
  610. local digCount = 0
  611.  
  612. if (lastMoveNeededDig == false) then
  613. -- Didn't need to dig last time the turtle moved, so try moving first
  614.  
  615. currX = newX
  616. currY = newY
  617. currZ = newZ
  618. saveLocation()
  619.  
  620. moveSuccess = moveFn()
  621.  
  622. -- If move failed, update the co-ords back to the previous co-ords
  623. if (moveSuccess == false) then
  624. currX = prevX
  625. currY = prevY
  626. currZ = prevZ
  627. saveLocation()
  628. end
  629.  
  630. -- Don't need to set the last move needed dig. It is already false, if
  631. -- move success is now true, then it won't be changed
  632. else
  633. -- If we are looking for chests, then check that this isn't a chest before trying to dig it
  634. if (lookForChests == true) then
  635. if (isNoiseBlock(compareFn) == false) then
  636. if (detectFn() == true) then
  637. -- Determine if it is a chest before digging it
  638. if (isChestBlock(compareFn) == true) then
  639. -- Have found a chest, empty it before continuing
  640. emptyChest (suckFn)
  641. end
  642. end
  643. end
  644. end
  645.  
  646. -- Try to dig (without doing a detect as it is quicker)
  647. local digSuccess = digFn()
  648. if (digSuccess == true) then
  649. digCount = 1
  650. end
  651.  
  652. currX = newX
  653. currY = newY
  654. currZ = newZ
  655. saveLocation()
  656.  
  657. moveSuccess = moveFn()
  658.  
  659. if (moveSuccess == true) then
  660. lastMoveNeededDig = digSuccess
  661. else
  662. currX = prevX
  663. currY = prevY
  664. currZ = prevZ
  665. saveLocation()
  666. end
  667.  
  668. end
  669.  
  670. -- Loop until we've successfully moved
  671. if (moveSuccess == false) then
  672. while ((moveSuccess == false) and (digCount < maxDigCount)) do
  673.  
  674. -- If there is a block in front, dig it
  675. if (detectFn() == true) then
  676.  
  677. -- If we've already tried digging, then pause before digging again to let
  678. -- any sand or gravel drop, otherwise check for a chest before digging
  679. if(digCount == 0) then
  680. -- Am about to dig a block - check that it is not a chest if necessary
  681. -- If we are looking for chests, then check that this isn't a chest before moving
  682. if (lookForChests == true) then
  683. if (isNoiseBlock(compareFn) == false) then
  684. if (detectFn() == true) then
  685. -- Determine if it is a chest before digging it
  686. if (isChestBlock(compareFn) == true) then
  687. -- Have found a chest, empty it before continuing
  688. emptyChest (suckFn)
  689. end
  690. end
  691. end
  692. end
  693. else
  694. sleep(0.1)
  695. end
  696.  
  697. digFn()
  698. digCount = digCount + 1
  699. else
  700. -- Am being stopped from moving by a mob, attack it
  701. attackFn()
  702. end
  703.  
  704. currX = newX
  705. currY = newY
  706. currZ = newZ
  707. saveLocation()
  708.  
  709. -- Try the move again
  710. moveSuccess = moveFn()
  711.  
  712. if (moveSuccess == false) then
  713. currX = prevX
  714. currY = prevY
  715. currZ = prevZ
  716. saveLocation()
  717. end
  718. end
  719.  
  720. if (digCount == 0) then
  721. lastMoveNeededDig = false
  722. else
  723. lastMoveNeededDig = true
  724. end
  725. end
  726. end
  727.  
  728. -- If we are resuming and the current co-ordinates and orientation are the resume point
  729. -- then are no longer resuming
  730. if (moveSuccess == true) then
  731. updateResumingFlag()
  732. end
  733.  
  734. -- Return the move success
  735. return moveSuccess
  736.  
  737. end
  738.  
  739. -- ********************************************************************************** --
  740. -- Move the turtle forward one block (updating the turtle's position)
  741. -- ********************************************************************************** --
  742. function turtleForward()
  743.  
  744. -- Determine the new co-ordinate that the turtle will be moving to
  745. local newX, newZ
  746.  
  747. -- Update the current co-ordinates
  748. if (currOrient == direction.FORWARD) then
  749. newZ = currZ + 1
  750. newX = currX
  751. elseif (currOrient == direction.LEFT) then
  752. newX = currX - 1
  753. newZ = currZ
  754. elseif (currOrient == direction.BACK) then
  755. newZ = currZ - 1
  756. newX = currX
  757. elseif (currOrient == direction.RIGHT) then
  758. newX = currX + 1
  759. newZ = currZ
  760. else
  761. writeMessage ("Invalid currOrient in turtleForward function", messageLevel.ERROR)
  762. end
  763.  
  764. local returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  765.  
  766. if (returnVal == true) then
  767. -- Check that there is sufficient inventory space as may have picked up a block
  768. ensureInventorySpace()
  769. end
  770.  
  771. return returnVal
  772. end
  773.  
  774. -- ********************************************************************************** --
  775. -- Move the turtle up one block (updating the turtle's position)
  776. -- ********************************************************************************** --
  777. function turtleUp()
  778.  
  779. local returnVal = moveTurtle(turtle.up, turtle.detectUp, turtle.digUp, turtle.attackUp, turtle.compareUp, turtle.suckUp, maximumGravelStackSupported, currX, currY + 1, currZ)
  780.  
  781. if (returnVal == true) then
  782. -- Check that there is sufficient inventory space as may have picked up a block
  783. ensureInventorySpace()
  784. end
  785.  
  786. return returnVal
  787. end
  788.  
  789. -- ********************************************************************************** --
  790. -- Move the turtle down one block (updating the turtle's position)
  791. -- ********************************************************************************** --
  792. function turtleDown()
  793.  
  794. local returnVal = moveTurtle(turtle.down, turtle.detectDown, turtle.digDown, turtle.attackDown, turtle.compareDown, turtle.suckDown, 1, currX, currY - 1, currZ)
  795.  
  796. if (returnVal == true) then
  797. -- Check that there is sufficient inventory space as may have picked up a block
  798. ensureInventorySpace()
  799. end
  800.  
  801. return returnVal
  802.  
  803. end
  804.  
  805. -- ********************************************************************************** --
  806. -- Move the turtle back one block (updating the turtle's position)
  807. -- ********************************************************************************** --
  808. function turtleBack()
  809.  
  810. -- Assume that the turtle will move, and switch the co-ords back if it doesn't
  811. -- (do this so that we can write the co-ords to a file before moving)
  812. local newX, newZ
  813. local prevX, prevZ
  814. prevX = currX
  815. prevZ = currZ
  816.  
  817. -- Update the current co-ordinates
  818. if (currOrient == direction.FORWARD) then
  819. newZ = currZ - 1
  820. newX = currX
  821. elseif (currOrient == direction.LEFT) then
  822. newX = currX + 1
  823. newZ = currZ
  824. elseif (currOrient == direction.BACK) then
  825. newZ = currZ + 1
  826. newX = currX
  827. elseif (currOrient == direction.RIGHT) then
  828. newX = currX - 1
  829. newZ = currZ
  830. else
  831. writeMessage ("Invalid currOrient in turtleBack function", messageLevel.ERROR)
  832. end
  833.  
  834. -- First try to move back using the standard function
  835.  
  836. currX = newX
  837. currZ = newZ
  838. saveLocation()
  839. local returnVal = turtle.back()
  840.  
  841. if (returnVal == false) then
  842. -- Didn't move. Reset the co-ordinates to the previous value
  843. currX = prevX
  844. currZ = prevZ
  845.  
  846. -- Reset the location back to the previous location (because the turn takes 0.8 of a second
  847. -- so could be stopped before getting to the forward function)
  848. saveLocation()
  849.  
  850. turtle.turnRight()
  851. turtle.turnRight()
  852.  
  853. -- Try to move by using the forward function (note, the orientation will be set as
  854. -- the same way as this function started because if the function stops, that is the
  855. -- direction that we want to consider the turtle to be pointing)
  856.  
  857. returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  858.  
  859. turtle.turnRight()
  860. turtle.turnRight()
  861. end
  862.  
  863. if (returnVal == true) then
  864. -- Check that there is sufficient inventory space as may have picked up a block
  865. ensureInventorySpace()
  866. end
  867.  
  868. return returnVal
  869. end
  870.  
  871. -- ********************************************************************************** --
  872. -- Turns the turtle (updating the current orientation at the same time)
  873. -- ********************************************************************************** --
  874. function turtleTurn(turnDir)
  875.  
  876. if (turnDir == direction.LEFT) then
  877. if (currOrient == direction.FORWARD) then
  878. currOrient = direction.LEFT
  879. elseif (currOrient == direction.LEFT) then
  880. currOrient = direction.BACK
  881. elseif (currOrient == direction.BACK) then
  882. currOrient = direction.RIGHT
  883. elseif (currOrient == direction.RIGHT) then
  884. currOrient = direction.FORWARD
  885. else
  886. writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  887. end
  888.  
  889. -- If we are resuming, just check to see whether have reached the resume point, otherwise
  890. -- turn
  891. if (resuming == true) then
  892. updateResumingFlag()
  893. else
  894. -- Write the new orientation and turn
  895. saveLocation()
  896. turtle.turnLeft()
  897. end
  898.  
  899. elseif (turnDir == direction.RIGHT) then
  900. if (currOrient == direction.FORWARD) then
  901. currOrient = direction.RIGHT
  902. elseif (currOrient == direction.LEFT) then
  903. currOrient = direction.FORWARD
  904. elseif (currOrient == direction.BACK) then
  905. currOrient = direction.LEFT
  906. elseif (currOrient == direction.RIGHT) then
  907. currOrient = direction.BACK
  908. else
  909. writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  910. end
  911.  
  912. -- If we are resuming, just check to see whether have reached the resume point, otherwise
  913. -- turn
  914. if (resuming == true) then
  915. updateResumingFlag()
  916.  
  917. writeMessage("["..currMiningState..", "..currX..", "..currY..", "..currZ..", "..currOrient.."]", messageLevel.DEBUG)
  918. else
  919. -- Write the new orientation and turn
  920. saveLocation()
  921. turtle.turnRight()
  922. end
  923. else
  924. writeMessage ("Invalid turnDir in turtleTurn function", messageLevel.ERROR)
  925. end
  926. end
  927.  
  928. -- ********************************************************************************** --
  929. -- Sets the turtle to a specific orientation, irrespective of its current orientation
  930. -- ********************************************************************************** --
  931. function turtleSetOrientation(newOrient)
  932.  
  933. if (currOrient ~= newOrient) then
  934. if (currOrient == direction.FORWARD) then
  935. if (newOrient == direction.RIGHT) then
  936. currOrient = newOrient
  937.  
  938. -- If resuming, check whether the resume point has been reached, otherwise turn
  939. if (resuming == true) then
  940. updateResumingFlag()
  941. else
  942. -- Write the new orientation and turn
  943. saveLocation()
  944. turtle.turnRight()
  945. end
  946. elseif (newOrient == direction.BACK) then
  947. currOrient = newOrient
  948.  
  949. -- If resuming, check whether the resume point has been reached, otherwise turn
  950. if (resuming == true) then
  951. updateResumingFlag()
  952. else
  953. -- Write the new orientation and turn
  954. saveLocation()
  955. turtle.turnRight()
  956. turtle.turnRight()
  957. end
  958. elseif (newOrient == direction.LEFT) then
  959. currOrient = newOrient
  960.  
  961. -- If resuming, check whether the resume point has been reached, otherwise turn
  962. if (resuming == true) then
  963. updateResumingFlag()
  964. else
  965. -- Write the new orientation and turn
  966. saveLocation()
  967. turtle.turnLeft()
  968. end
  969. else
  970. writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  971. end
  972. elseif (currOrient == direction.RIGHT) then
  973. if (newOrient == direction.BACK) then
  974. currOrient = newOrient
  975.  
  976. -- If resuming, check whether the resume point has been reached, otherwise turn
  977. if (resuming == true) then
  978. updateResumingFlag()
  979. else
  980. -- Write the new orientation and turn
  981. saveLocation()
  982. turtle.turnRight()
  983. end
  984. elseif (newOrient == direction.LEFT) then
  985. currOrient = newOrient
  986.  
  987. -- If resuming, check whether the resume point has been reached, otherwise turn
  988. if (resuming == true) then
  989. updateResumingFlag()
  990. else
  991. -- Write the new orientation and turn
  992. saveLocation()
  993. turtle.turnRight()
  994. turtle.turnRight()
  995. end
  996. elseif (newOrient == direction.FORWARD) then
  997. currOrient = newOrient
  998.  
  999. -- If resuming, check whether the resume point has been reached, otherwise turn
  1000. if (resuming == true) then
  1001. updateResumingFlag()
  1002. else
  1003. -- Write the new orientation and turn
  1004. saveLocation()
  1005. turtle.turnLeft()
  1006. end
  1007. else
  1008. writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1009. end
  1010. elseif (currOrient == direction.BACK) then
  1011. if (newOrient == direction.LEFT) then
  1012. currOrient = newOrient
  1013.  
  1014. -- If resuming, check whether the resume point has been reached, otherwise turn
  1015. if (resuming == true) then
  1016. updateResumingFlag()
  1017. else
  1018. -- Write the new orientation and turn
  1019. saveLocation()
  1020. turtle.turnRight()
  1021. end
  1022. elseif (newOrient == direction.FORWARD) then
  1023. currOrient = newOrient
  1024.  
  1025. -- If resuming, check whether the resume point has been reached, otherwise turn
  1026. if (resuming == true) then
  1027. updateResumingFlag()
  1028. else
  1029. -- Write the new orientation and turn
  1030. saveLocation()
  1031. turtle.turnRight()
  1032. turtle.turnRight()
  1033. end
  1034. elseif (newOrient == direction.RIGHT) then
  1035. currOrient = newOrient
  1036.  
  1037. -- If resuming, check whether the resume point has been reached, otherwise turn
  1038. if (resuming == true) then
  1039. updateResumingFlag()
  1040. else
  1041. -- Write the new orientation and turn
  1042. saveLocation()
  1043. turtle.turnLeft()
  1044. end
  1045. else
  1046. writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1047. end
  1048. elseif (currOrient == direction.LEFT) then
  1049. if (newOrient == direction.FORWARD) then
  1050. currOrient = newOrient
  1051.  
  1052. -- If resuming, check whether the resume point has been reached, otherwise turn
  1053. if (resuming == true) then
  1054. updateResumingFlag()
  1055. else
  1056. -- Write the new orientation and turn
  1057. saveLocation()
  1058. turtle.turnRight()
  1059. end
  1060. elseif (newOrient == direction.RIGHT) then
  1061. currOrient = newOrient
  1062.  
  1063. -- If resuming, check whether the resume point has been reached, otherwise turn
  1064. if (resuming == true) then
  1065. updateResumingFlag()
  1066. else
  1067. -- Write the new orientation and turn
  1068. saveLocation()
  1069. turtle.turnRight()
  1070. turtle.turnRight()
  1071. end
  1072. elseif (newOrient == direction.BACK) then
  1073. currOrient = newOrient
  1074.  
  1075. -- If resuming, check whether the resume point has been reached, otherwise turn
  1076. if (resuming == true) then
  1077. updateResumingFlag()
  1078. else
  1079. -- Write the new orientation and turn
  1080. saveLocation()
  1081. turtle.turnLeft()
  1082. end
  1083. else
  1084. writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1085. end
  1086. else
  1087. writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  1088. end
  1089. end
  1090. end
  1091.  
  1092. -- ********************************************************************************** --
  1093. -- Determines if a particular block is considered a noise block or not. A noise
  1094. -- block is one that is a standard block in the game (stone, dirt, gravel etc.) and
  1095. -- is one to ignore as not being an ore. Function works by comparing the block
  1096. -- in question against a set of blocks in the turtle's inventory which are known not to
  1097. -- be noise blocks. Param is the function to use to compare the block for a noise block
  1098. -- ********************************************************************************** --
  1099. function isNoiseBlock(compareFn)
  1100.  
  1101. -- Consider air to be a noise block
  1102. local returnVal = false
  1103.  
  1104. if (resuming == true) then
  1105. returnVal = true
  1106. else
  1107. local seamLoop = 1
  1108. local prevSelectedSlot
  1109.  
  1110. -- If the currently selected slot is a noise block, then compare against this first
  1111. -- so that the slot doesn't need to be selected again (there is a 0.05s cost to do
  1112. -- this even if it is the currently selected slot)
  1113. if (currentlySelectedSlot <= noiseBlocksCount) then
  1114. returnVal = compareFn()
  1115. end
  1116.  
  1117. if (returnVal == false) then
  1118. prevSelectedSlot = currentlySelectedSlot
  1119. while((returnVal == false) and (seamLoop <= noiseBlocksCount)) do
  1120. if (seamLoop ~= prevSelectedSlot) then
  1121. turtle.select(seamLoop)
  1122. currentlySelectedSlot = seamLoop
  1123. returnVal = compareFn()
  1124. end
  1125. seamLoop = seamLoop + 1
  1126. end
  1127. end
  1128. end
  1129.  
  1130. -- Return the calculated value
  1131. return returnVal
  1132.  
  1133. end
  1134.  
  1135. -- ********************************************************************************** --
  1136. -- Determines if a particular block is a chest. Returns false if it is not a chest
  1137. -- or chests are not being detected
  1138. -- ********************************************************************************** --
  1139. function isChestBlock(compareFn)
  1140.  
  1141. -- Check the block in the appropriate direction to see whether it is a chest. Only
  1142. -- do this if we are looking for chests
  1143. local returnVal = false
  1144. if (lookForChests == true) then
  1145. turtle.select(15)
  1146. currentlySelectedSlot = 15
  1147. returnVal = compareFn()
  1148. end
  1149.  
  1150. -- Return the calculated value
  1151. return returnVal
  1152.  
  1153. end
  1154.  
  1155. -- ********************************************************************************** --
  1156. -- Function to calculate the number of non seam blocks in the turtle's inventory. This
  1157. -- is all of the blocks at the start of the inventory (before the first empty slot is
  1158. -- found
  1159. -- ********************************************************************************** --
  1160. function determineNoiseBlocksCountCount()
  1161. -- Determine the location of the first empty inventory slot. All items before this represent
  1162. -- noise items.
  1163. local foundFirstBlankInventorySlot = false
  1164. noiseBlocksCount = 1
  1165. while ((noiseBlocksCount < 16) and (foundFirstBlankInventorySlot == false)) do
  1166. if (turtle.getItemCount(noiseBlocksCount) > 0) then
  1167. noiseBlocksCount = noiseBlocksCount + 1
  1168. else
  1169. foundFirstBlankInventorySlot = true
  1170. end
  1171. end
  1172. noiseBlocksCount = noiseBlocksCount - 1
  1173.  
  1174. -- Determine whether a chest was provided, and hence whether we should support
  1175. -- looking for chests
  1176. if (turtle.getItemCount(15) > 0) then
  1177. lookForChests = true
  1178. lastEmptySlot = 14
  1179. miningOffset = 0
  1180. writeMessage("Looking for chests...", messageLevel.DEBUG)
  1181. else
  1182. lastEmptySlot = 15
  1183. miningOffset = 1
  1184. writeMessage("Ignoring chests...", messageLevel.DEBUG)
  1185. end
  1186. end
  1187.  
  1188. -- ********************************************************************************** --
  1189. -- Creates a quarry mining out only ores and leaving behind any noise blocks
  1190. -- ********************************************************************************** --
  1191. function createQuarry()
  1192.  
  1193. -- Determine the top mining layer layer. The turtle mines in layers of 3, and the bottom layer
  1194. -- is the layer directly above bedrock.
  1195. --
  1196. -- The actual layer that the turtle operates in is the middle of these three layers,
  1197. -- so determine the top layer
  1198. local topMiningLayer = startHeight + ((bottomLayer - startHeight - 2) % 3) - 1 + miningOffset
  1199.  
  1200. -- If the top layer is up, then ignore it and move to the next layer
  1201. if (topMiningLayer > currY) then
  1202. topMiningLayer = topMiningLayer - 3
  1203. end
  1204.  
  1205. local startedLayerToRight = true -- Only used where the quarry is of an odd width
  1206.  
  1207. -- Loop over each mining row
  1208. local miningLevel
  1209. for miningLevel = (bottomLayer + miningOffset), topMiningLayer, 3 do
  1210. writeMessage("Mining Layer: "..miningLevel, messageLevel.INFO)
  1211. haveBeenAtZeroZeroOnLayer = false
  1212.  
  1213. -- While the initial shaft is being dug out, set the level to return to in order to unload
  1214. -- to the just take the turtle straight back up
  1215. if (miningLevel == (bottomLayer + miningOffset)) then
  1216. levelToReturnTo = startHeight
  1217. end
  1218.  
  1219. -- Move to the correct level to start mining
  1220. if (currY > miningLevel) then
  1221. while (currY > miningLevel) do
  1222. turtleDown()
  1223. end
  1224. elseif (currY < miningLevel) then
  1225. while (currY < miningLevel) do
  1226. turtleUp()
  1227. end
  1228. end
  1229.  
  1230. -- Am now mining the levels (update the mining state to reflect that fact)
  1231. currMiningState = miningState.LAYER
  1232.  
  1233. -- Set the layer to return via when returning to the surface as the one below the currently
  1234. -- mined one
  1235. if (miningLevel == (bottomLayer + miningOffset)) then
  1236. levelToReturnTo = (bottomLayer + miningOffset)
  1237. else
  1238. levelToReturnTo = miningLevel - 3
  1239. end
  1240.  
  1241. -- Move turtle into the correct orientation to start mining (if this is the
  1242. -- first row to be mined, then don't need to turn, otherwise turn towards the next
  1243. -- mining section)
  1244.  
  1245. writeMessage("Mining Level: "..miningLevel..", Bottom Layer: "..bottomLayer..", Mining Offset: "..miningOffset, messageLevel.DEBUG)
  1246.  
  1247. if (miningLevel > (bottomLayer + miningOffset)) then
  1248. -- Turn towards the next mining layer
  1249. if (quarryWidth % 2 == 0) then
  1250. -- An even width quarry, always turn right
  1251. turtleTurn(direction.RIGHT)
  1252. else
  1253. -- Turn the opposite direction to that which we turned before
  1254. if (startedLayerToRight == true) then
  1255. turtleTurn(direction.LEFT)
  1256. startedLayerToRight = false
  1257. else
  1258. turtleTurn(direction.RIGHT)
  1259. startedLayerToRight = true
  1260. end
  1261. end
  1262. end
  1263.  
  1264. local mineRows
  1265. local onNearSideOfQuarry = true
  1266. local diggingAway = true
  1267. for mineRows = 1, quarryWidth do
  1268.  
  1269. -- If this is not the first row, then get into position to mine the next row
  1270. if ((mineRows == 1) and (lookForChests == false)) then
  1271. -- Not looking for chests, check the block below for being an ore. Only do this
  1272. -- if we're not looking for chests since the program doesn't support chests in
  1273. -- bedrock
  1274. if (isNoiseBlock(turtle.compareDown) == false) then
  1275. turtle.digDown()
  1276. ensureInventorySpace()
  1277. end
  1278. elseif (mineRows > 1) then
  1279. -- Move into position for mining the next row
  1280. if (onNearSideOfQuarry == diggingAway) then
  1281. if (startedLayerToRight == true) then
  1282. turtleTurn(direction.LEFT)
  1283. else
  1284. turtleTurn(direction.RIGHT)
  1285. end
  1286. else
  1287. if (startedLayerToRight == true) then
  1288. turtleTurn(direction.RIGHT)
  1289. else
  1290. turtleTurn(direction.LEFT)
  1291. end
  1292. end
  1293.  
  1294. turtleForward()
  1295.  
  1296. -- Before making the final turn, check the block below. Do this
  1297. -- now because if it is a chest, then we want to back up and
  1298. -- approach it from the side (so that we don't lose items if we
  1299. -- have to return to the start through it).
  1300. --
  1301. -- This is the point at which it is safe to back up without moving
  1302. -- out of the quarry area (unless at bedrock in which case don't bother
  1303. -- as we'll be digging down anyway)
  1304. if (miningLevel ~= bottomLayer) then
  1305. if (isNoiseBlock(turtle.compareDown) == false) then
  1306. -- If we are not looking for chests, then just dig it (it takes
  1307. -- less time to try to dig and fail as it does to do detect and
  1308. -- only dig if there is a block there)
  1309. if (lookForChests == false) then
  1310. turtle.digDown()
  1311. ensureInventorySpace()
  1312. elseif (turtle.detectDown() == true) then
  1313. if (isChestBlock(turtle.compareDown) == true) then
  1314. -- There is a chest block below. Move back and approach
  1315. -- from the side to ensure that we don't need to return to
  1316. -- start through the chest itself (potentially losing items)
  1317. turtleBack()
  1318. turtleDown()
  1319. currMiningState = miningState.EMPTYCHESTDOWN
  1320. emptyChest(turtle.suck)
  1321. currMiningState = miningState.LAYER
  1322. turtleUp()
  1323. turtleForward()
  1324. turtle.digDown()
  1325. ensureInventorySpace()
  1326. else
  1327. turtle.digDown()
  1328. ensureInventorySpace()
  1329. end
  1330. end
  1331. end
  1332. end
  1333.  
  1334. -- Move into final position for mining the next row
  1335. if (onNearSideOfQuarry == diggingAway) then
  1336. if (startedLayerToRight == true) then
  1337. turtleTurn(direction.LEFT)
  1338. else
  1339. turtleTurn(direction.RIGHT)
  1340. end
  1341. else
  1342. if (startedLayerToRight == true) then
  1343. turtleTurn(direction.RIGHT)
  1344. else
  1345. turtleTurn(direction.LEFT)
  1346. end
  1347. end
  1348. end
  1349.  
  1350. -- Dig to the other side of the quarry
  1351. local blocksMined
  1352. for blocksMined = 0, (quarryWidth - 1) do
  1353. if (blocksMined > 0) then
  1354. -- Only move forward if this is not the first space
  1355. turtleForward()
  1356. end
  1357.  
  1358. -- If the current block is (0,0), then record the fact that the
  1359. -- turtle has been through this block and what it's orientation was and update the layer
  1360. -- that it should return via to get back to the surface (it no longer needs to go down
  1361. -- a level to prevent losing ores).
  1362. if ((currX == 0) and (currZ == 0)) then
  1363. -- Am at (0, 0). Remember this, and what direction I was facing so that the quickest route
  1364. -- to the surface can be taken
  1365. levelToReturnTo = miningLevel
  1366. haveBeenAtZeroZeroOnLayer = true
  1367. orientationAtZeroZero = currOrient
  1368. end
  1369.  
  1370. -- If currently at bedrock, just move down until the turtle can't go any
  1371. -- further. This allows the blocks within the bedrock to be mined
  1372. if (miningLevel == bottomLayer) then
  1373. -- Temporarily turn off looking for chests to increase bedrock mining speed (this
  1374. -- means that the program doesn't support chests below level 5 - but I think
  1375. -- they they don't exist anyway)
  1376. local lookForChestsPrev = lookForChests
  1377. lookForChests = false
  1378.  
  1379. -- Manually set the flag to determine whether the turtle should try to move first or
  1380. -- dig first. At bedrock, is very rarely any space
  1381.  
  1382. -- Just above bedrock layer, dig down until can't dig any lower, and then
  1383. -- come back up. This replicates how the quarry functions
  1384. lastMoveNeededDig = true
  1385. local moveDownSuccess = turtleDown()
  1386. while (moveDownSuccess == true) do
  1387. moveDownSuccess = turtleDown()
  1388. end
  1389.  
  1390. -- Know that we are moving back up through air, therefore set the flag to force the
  1391. -- turtle to try moving first
  1392. lastMoveNeededDig = false
  1393.  
  1394. -- Have now hit bedrock, move back to the mining layer
  1395. while (currY < bottomLayer) do
  1396. turtleUp()
  1397. end
  1398.  
  1399. -- Now back at the level above bedrock, again reset the flag to tell the turtle to
  1400. -- try digging again (because it is rare to find air at bedrock level)
  1401. lastMoveNeededDig = false
  1402.  
  1403. -- Reset the look for chests value
  1404. lookForChests = lookForChestsPrev
  1405. elseif ((blocksMined > 0) and ((currX ~= 0) or (currZ ~= 0))) then
  1406. -- This isn't the first block of the row, nor are we at (0, 0) so we need to check the
  1407. -- block below
  1408.  
  1409. -- Check the block down for being a noise block (don't need to check the first
  1410. -- block as it has already been checked in the outer loop)
  1411. if (isNoiseBlock(turtle.compareDown) == false) then
  1412. -- If we are not looking for chests, then just dig it (it takes
  1413. -- less time to try to dig and fail as it does to do detect and
  1414. -- only dig if there is a block there)
  1415. if (lookForChests == false) then
  1416. turtle.digDown()
  1417. ensureInventorySpace()
  1418. elseif (turtle.detectDown() == true) then
  1419. if (isChestBlock(turtle.compareDown) == true) then
  1420. -- There is a chest block below. Move back and approach
  1421. -- from the side to ensure that we don't need to return to
  1422. -- start through the chest itself (potentially losing items)
  1423. turtleBack()
  1424. currMiningState = miningState.EMPTYCHESTDOWN
  1425. turtleDown()
  1426. emptyChest(turtle.suck)
  1427. currMiningState = miningState.LAYER
  1428. turtleUp()
  1429. turtleForward()
  1430. turtle.digDown()
  1431. ensureInventorySpace()
  1432. else
  1433. turtle.digDown()
  1434. ensureInventorySpace()
  1435. end
  1436. end
  1437. end
  1438. end
  1439.  
  1440. -- Check the block above for ores (if we're not a (0, 0) in which case
  1441. -- we know it's air)
  1442. if ((currX ~= 0) or (currZ ~= 0)) then
  1443. if (isNoiseBlock(turtle.compareUp) == false) then
  1444. -- If we are not looking for chests, then just dig it (it takes
  1445. -- less time to try to dig and fail as it does to do detect and
  1446. -- only dig if there is a block there)
  1447. if (lookForChests == false) then
  1448. turtle.digUp()
  1449. ensureInventorySpace()
  1450. elseif (turtle.detectUp() == true) then
  1451. -- Determine if it is a chest before digging it
  1452. if (isChestBlock(turtle.compareUp) == true) then
  1453. -- There is a chest block above. Empty it before digging it
  1454. emptyChest(turtle.suckUp)
  1455. turtle.digUp()
  1456. ensureInventorySpace()
  1457. else
  1458. turtle.digUp()
  1459. ensureInventorySpace()
  1460. end
  1461. end
  1462. end
  1463. end
  1464. end
  1465.  
  1466. -- Am now at the other side of the quarry
  1467. onNearSideOfQuarry = not onNearSideOfQuarry
  1468. end
  1469.  
  1470. -- If we were digging away from the starting point, will be digging
  1471. -- back towards it on the next layer
  1472. diggingAway = not diggingAway
  1473. end
  1474.  
  1475. -- Return to the start
  1476. returnToStartAndUnload(false)
  1477. writeMessage("Mining process Complete!", messageLevel.INFO)
  1478.  
  1479. -- Face forward
  1480. turtleSetOrientation(direction.FORWARD)
  1481. end
  1482.  
  1483. -- ********************************************************************************** --
  1484. -- Reads the next number from a given file
  1485. -- ********************************************************************************** --
  1486. function readNumber(inputFile)
  1487.  
  1488. local returnVal
  1489. local nextLine = inputFile.readLine()
  1490. if (nextLine ~= nil) then
  1491. returnVal = tonumber(nextLine)
  1492. end
  1493.  
  1494. return returnVal
  1495. end
  1496.  
  1497. -- ********************************************************************************** --
  1498. -- Startup function to support resuming mining turtle
  1499. -- ********************************************************************************** --
  1500. function isResume()
  1501.  
  1502. local returnVal = false
  1503.  
  1504. -- Try to open the resume file
  1505. local resumeFile = fs.open(startupParamsFile, "r")
  1506. if (resumeFile == nil) then
  1507. -- No resume file (presume that we are not supporting it)
  1508. supportResume = false
  1509. else
  1510. writeMessage("Found startup params file", messageLevel.DEBUG)
  1511.  
  1512. -- Read in the startup params
  1513. quarryWidth = readNumber(resumeFile)
  1514. startHeight = readNumber(resumeFile)
  1515. noiseBlocksCount = readNumber(resumeFile)
  1516. lastEmptySlot = readNumber(resumeFile)
  1517. resumeFile.close()
  1518.  
  1519. -- If the parameters were successfully read, then set the resuming flag to true
  1520. if ((quarryWidth ~= nil) and (startHeight ~= nil) and (noiseBlocksCount ~= nil) and (lastEmptySlot ~= nil)) then
  1521.  
  1522. resuming = true
  1523. writeMessage("Read params", messageLevel.DEBUG)
  1524.  
  1525. -- Determine the look for chest and mining offset
  1526. if (lastEmptySlot == 14) then
  1527. lookForChests = true
  1528. miningOffset = 0
  1529. else
  1530. lookForChests = false
  1531. miningOffset = 1
  1532. end
  1533.  
  1534. -- Get the turtle resume location
  1535. resumeFile = fs.open(oreQuarryLocation, "r")
  1536. if (resumeFile ~= nil) then
  1537.  
  1538. resumeMiningState = readNumber(resumeFile)
  1539. resumeX = readNumber(resumeFile)
  1540. resumeY = readNumber(resumeFile)
  1541. resumeZ = readNumber(resumeFile)
  1542. resumeOrient = readNumber(resumeFile)
  1543. resumeFile.close()
  1544.  
  1545. -- Ensure that the resume location has been found
  1546. if ((resumeMiningState ~= nil) and (resumeX ~= nil) and (resumeY ~= nil) and (resumeZ ~= nil) and (resumeOrient ~= nil)) then
  1547. returnVal = true
  1548. local emptiedInventory = false
  1549.  
  1550. -- Perform any mining state specific startup
  1551. if (resumeMiningState == miningState.EMPTYINVENTORY) then
  1552. -- Am mid way through an empty inventory cycle. Complete it before
  1553. -- starting the main Quarry function
  1554. returnToStartAndUnload(true)
  1555. resuming = true
  1556.  
  1557. -- Continue from the current position
  1558. resumeX = currX
  1559. resumeY = currY
  1560. levelToReturnTo = resumeY
  1561. resumeZ = currZ
  1562. resumeOrient = currOrient
  1563.  
  1564. writeMessage("Resuming with state of "..currMiningState, messageLevel.DEBUG)
  1565. resumeMiningState = currMiningState
  1566. emptiedInventory = true
  1567. end
  1568.  
  1569. -- If was emptying a chest when the program stopped, then move back
  1570. -- to a point which the Quarry
  1571. if (resumeMiningState == miningState.EMPTYCHESTDOWN) then
  1572.  
  1573. -- Set the current X, Y, Z and orientation to the true position that
  1574. -- the turtle is at
  1575. if (emptiedInventory == false) then
  1576. currX = resumeX
  1577. currY = resumeY
  1578. currZ = resumeZ
  1579. currOrient = resumeOrient
  1580. end
  1581.  
  1582. -- Set the mining state as layer, assume haven't been through zero
  1583. -- zero and set the level to return to as the one below the current one
  1584. currMiningState = miningState.LAYER
  1585. levelToReturnTo = currY - 2
  1586. haveBeenAtZeroZeroOnLayer = false
  1587.  
  1588. -- Temporarily disable resuming (so that the new location is written to the file
  1589. -- in case the program stops again)
  1590. resuming = false
  1591. turtleUp()
  1592. resuming = true
  1593.  
  1594. resumeY = currY
  1595. resumeMiningState = miningState.LAYER
  1596. end
  1597. end
  1598. end
  1599. end
  1600.  
  1601. if (returnVal == false) then
  1602. writeMessage("Failed to resume", messageLevel.ERROR)
  1603. end
  1604. end
  1605.  
  1606. return returnVal
  1607. end
  1608.  
  1609. -- ********************************************************************************** --
  1610. -- Main Function
  1611. -- ********************************************************************************** --
  1612. -- Process the input arguments - storing them to global variables
  1613. local args = { ... }
  1614. local paramsOK = true
  1615.  
  1616. -- Detect whether this is a wireless turtle, and if so, open the modem
  1617. local peripheralConnected = peripheral.getType("right")
  1618. if (peripheralConnected == "modem") then
  1619. isWirelessTurtle = true
  1620. end
  1621.  
  1622. -- If a wireless turtle, open the modem
  1623. if (isWirelessTurtle == true) then
  1624. turtleId = os.getComputerLabel()
  1625. rednet.open("right")
  1626. end
  1627.  
  1628. if (#args == 0) then
  1629. -- Is this a resume?
  1630. if (isResume() == false) then
  1631. paramsOK = false
  1632. end
  1633. elseif (#args == 1) then
  1634. quarryWidth = tonumber(args[1])
  1635. local x, y, z = gps.locate(5)
  1636. startHeight = y
  1637. if (startHeight == nil) then
  1638. writeMessage("Can't locate GPS", messageLevel.FATAL)
  1639. paramsOK = false
  1640. end
  1641. elseif (#args == 2) then
  1642. if (args[2] == "/r") then
  1643. quarryWidth = tonumber(args[1])
  1644. supportResume = false
  1645. else
  1646. quarryWidth = tonumber(args[1])
  1647. startHeight = tonumber(args[2])
  1648. end
  1649. elseif (#args == 3) then
  1650. quarryWidth = tonumber(args[1])
  1651. startHeight = tonumber(args[2])
  1652. if (args[3] == "/r") then
  1653. supportResume = false
  1654. else
  1655. paramsOK = false
  1656. end
  1657. end
  1658.  
  1659. if ((paramsOK == false) and (resuming == false)) then
  1660. writeMessage("Usage: "..shell.getRunningProgram().." <diameter> [turtleY] [/r]", messageLevel.FATAL)
  1661. paramsOK = false
  1662. end
  1663.  
  1664. if (paramsOK == true) then
  1665. if ((startHeight < 6) or (startHeight > 256)) then
  1666. writeMessage("turtleY must be between 6 and 256", messageLevel.FATAL)
  1667. paramsOK = false
  1668. end
  1669.  
  1670. if ((quarryWidth < 2) or (quarryWidth > 100)) then
  1671. writeMessage("diameter must be between 2 and 100", messageLevel.FATAL)
  1672. paramsOK = false
  1673. end
  1674. end
  1675.  
  1676. if (paramsOK == true) then
  1677. if (resuming == true) then
  1678. writeMessage("Resuming Ore Quarry...", messageLevel.INFO)
  1679. else
  1680. writeMessage("----------------------------------", messageLevel.INFO)
  1681. writeMessage("** Ore Quarry v0.71 by AustinKK **", messageLevel.INFO)
  1682. writeMessage("----------------------------------", messageLevel.INFO)
  1683. end
  1684.  
  1685. -- Set the turtle's starting position
  1686. currX = 0
  1687. currY = startHeight
  1688. currZ = 0
  1689. currOrient = direction.FORWARD
  1690.  
  1691. -- Calculate which blocks in the inventory signify noise blocks
  1692. if (resuming == false) then
  1693. determineNoiseBlocksCountCount()
  1694. end
  1695.  
  1696. if ((noiseBlocksCount == 0) or (noiseBlocksCount > 13)) then
  1697. writeMessage("No noise blocks have been been added. Please place blocks that the turtle should not mine (e.g. Stone, Dirt, Gravel etc.) in the first few slots of the turtle\'s inventory. The first empty slot signifies the end of the noise blocks.", messageLevel.FATAL)
  1698. else
  1699. -- If we are supporting resume (and are not currently in the process of resuming)
  1700. -- then store startup parameters in appropriate files
  1701. if ((supportResume == true) and (resuming == false)) then
  1702. -- Write the startup parameters to file
  1703. local outputFile = io.open(startupParamsFile, "w")
  1704. outputFile:write(quarryWidth)
  1705. outputFile:write("\n")
  1706. outputFile:write(startHeight)
  1707. outputFile:write("\n")
  1708. outputFile:write(noiseBlocksCount)
  1709. outputFile:write("\n")
  1710. outputFile:write(lastEmptySlot)
  1711. outputFile:write("\n")
  1712. outputFile:close()
  1713.  
  1714. -- Setup the startup file
  1715.  
  1716. -- Take a backup of the current startup file
  1717. if (fs.exists("startup") == true) then
  1718. fs.copy("startup", startupBackup)
  1719. outputFile = io.open("startup", "a")
  1720. else
  1721. outputFile = io.open("startup", "w")
  1722. end
  1723.  
  1724. -- Write an info message so that people know how to get out of auto-resume
  1725. outputFile:write("\nprint(\"Running auto-restart...\")\n")
  1726. outputFile:write("print(\"If you want to stop auto-resume and restore original state:\")\n")
  1727. outputFile:write("print(\"1) Hold Ctrl-T until the program terminates\")\n")
  1728. outputFile:write("print(\"2) Type \\\"rm startup\\\" (without quotes) and hit Enter\")\n")
  1729. outputFile:write("print(\"\")\n\n")
  1730.  
  1731. -- Write the code required to restart the turtle
  1732. outputFile:write("shell.run(\"")
  1733. outputFile:write(shell.getRunningProgram())
  1734. outputFile:write("\")\n")
  1735. outputFile:close()
  1736.  
  1737. end
  1738.  
  1739. -- Create a Quarry
  1740. turtle.select(1)
  1741. currentlySelectedSlot = 1
  1742. createQuarry()
  1743.  
  1744. -- Restore the file system to its original configuration
  1745. if (supportResume == true) then
  1746. fs.delete("startup")
  1747. if (fs.exists(startupBackup) == true) then
  1748. fs.move(startupBackup, "startup")
  1749. end
  1750.  
  1751. if (fs.exists(startupParamsFile) == true) then
  1752. fs.delete(startupParamsFile)
  1753. end
  1754.  
  1755. if (fs.exists(oreQuarryLocation) == true) then
  1756. fs.delete(oreQuarryLocation)
  1757. end
  1758.  
  1759. if (fs.exists(returnToStartFile) == true) then
  1760. fs.delete(returnToStartFile)
  1761. end
  1762. end
  1763. end
  1764. end
Add Comment
Please, Sign In to add comment