daily pastebin goal
11%
SHARE
TWEET

Quarry 3.1.0

a guest Jun 22nd, 2013 229 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. --[[
  3. Version 3.1.0
  4. Recent Changes:
  5. 1. Now has session persistence! Just type "quarry -restore"
  6.    and your turtle will pick up where it left off
  7. 2. Improved Session Persistence
  8. 3. Improved Bedrock detecting logic
  9. 4. Made turtle faster by .5 seconds every 10 blocks
  10. 5. All movement function are now self contained and keep track of position.
  11.    Use civilTable.forward or just forward (environment is civilTable)
  12. 6. Now automatically checks if fuel is off so you don't have to!
  13. 7. Checks if it actually being run on a turtle or not.
  14. 8. Fixed the bug where the turtle would always say connected: false with rednet (I think)
  15. ]]
  16. --[[ToDo:
  17. 1. Actually get the rednet send back and forth to work
  18. 3. Send basic commands from receiver program e.g. Stop
  19. 4. Check on the new session persistence
  20. 5. See if you can consolidate the mining loops.
  21. 6. Add in rednet stuff
  22. 7. GET THE STUPID REDNET PROGRAM UPDATED
  23. ]]
  24. --Defining things
  25. _G.civilTable = {}; civilTable = nil; setmetatable(civilTable, {__index = _G}); setfenv(1,civilTable)
  26. -------Defaults for Arguments----------
  27. --Arguments assignable by text
  28. x,y,z = 3,3,3 --These are just in case tonumber fails
  29. inverted = false --False goes from top down, true goes from bottom up [Default false]
  30. rednetEnabled = false --Default rednet on or off  [Default false]
  31. --Arguments assignable by tArgs
  32. dropSide = "front" --Side it will eject to when full or done [Default "front"]
  33. careAboutResources = true --Will not stop mining once inventory full if false [Default true]
  34. doCheckFuel = true --Perform fuel check [Default true]
  35. doRefuel = false --Whenever it comes to start location will attempt to refuel from inventory [Default false]
  36. invCheckFreq = 10 --Will check for inventory full every <-- moved spaces [Default 10]
  37. keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1]
  38. fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate]
  39. saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"]
  40. doBackup = true --If it will keep backups for session persistence [Default true]
  41. --Standard number slots for fuel (you shouldn't care)
  42. fuelTable = { --Will add in this amount of fuel to requirement.
  43. safe = 1000,
  44. moderate = 200,
  45. loose = 0 } --Default 1000, 200, 0
  46. --Standard rednet channels
  47. channels = {
  48. send = os.getComputerID()  ,
  49. receive = os.getComputerID() + 100 ,
  50. confirm = "Confirm"
  51. }
  52.  
  53. local help_paragraph = [[
  54. -DEFAULT: This will ignore all arguments and prompts and use defaults
  55. -vanilla: This will ignore all arguments except for dimensions
  56. -dim: [num] [num] [num] This sets the dimensions of the quarry
  57. -invert: [t/f] This sets whether invert is true or false
  58. -rednet: [t/f] This sets whether it will attempt to make a rednet connection
  59. -sendChannel: [num] This sets the channel the turtle will attempt to send on
  60. -receiveChannel: [num] This sets the channel the turtle will attempt to receive on
  61. -doRefuel: Changes whether or not the turtle will refuel itself with coal when fuel is low (opposite of written config)
  62. -doCheckFuel: Changes whether or not the turtle will check its fuel level before running (opposite of written config)
  63. -chest: [chest side] Changes what side turtle will output to
  64. -keepOpen: [num] How many slots of the inventory turtle will try to keep open (Will then auto-empty)
  65. -invCheckFreq: [num] How many blocks before full inventory checks
  66. -saveFile: [word] Changes where the turtle saves its backup to.
  67. -doBackup: [t/f] Whether or not the turtle will backup its current position to a file.
  68. -restore: Turtle will check for a save file. If found will ignore all other arguments.
  69. -fuelSafety: [safe/moderate/loose] How much extra fuel the turtle will request at startup
  70. Examples [1]:
  71.  The minimum amount necessary to start a turtle automatically would be one of these two
  72.  ---------
  73.  quarry -dim 3 3 3 -invert false -rednet false
  74.  ---------
  75.  quarry -dim 3 3 3 -vanilla
  76.  ---------
  77.  or, if you actually wanted a 3x3x3 then
  78.  ---------
  79.  quarry -DEFAULT
  80. Examples [2]:
  81.  If you wanted start a quarry that has
  82.  rednet on channels 500 and 501, outputs
  83.  to a chest below itself, is inverted,
  84.  and has the dimesions 5x5x21, then here
  85.  is what you would type: (Remember that
  86.  order does not matter)
  87.  ----------
  88.  quarry -receiveChannel 501 -sendChannel 500 -invert true -dim 5 5 21 -chest bottom -rednet true
  89. Examples [2] (cont.):
  90.  Now, this may be very long, but it is meant for people who want to make automated quarries with
  91.  the same settings every time (or with variable setting)
  92. Examples [3]:
  93.  If you are playing softcore then you
  94.  can do
  95.  ---------
  96.  quarry -doCheckFuel false
  97.  ---------
  98.  Followed by any other arguments
  99. Tips:
  100.  You don't actually have to type out "false" or "true" if you don't want. It actaully just checks if the first
  101.  letter is "t", so you (usually) don't have to put anything at all. Putting the whole word just helps with clarity
  102. Internal Config:
  103.  At the top of the program, right below the changelog is a written config. Anything not specified by arguments
  104.  will be taken from here. If you have a quarry setup you use a lot, you could just edit the config and then
  105.  type in the following:
  106.  ----------
  107.  quarry -DEFAULT
  108. ]]
  109.  
  110. --Parsing help for display
  111. --[[The way the help table works:
  112. All help indexes are numbered. There is a help[i].title that contains the title,
  113. and the other lines are in help[i][1] - help[i][#help[i] ]
  114. Different lines (e.g. other than first) start with a space.
  115. As of now, the words are not wrapped, fix that later]]
  116. local help = {}
  117. local i = 0
  118. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  119. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  120. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  121. local current = string.sub(a,1,-2).."" --Concatenate Trick
  122. if string.sub(current,1,1) ~= " " then
  123. i = i + 1
  124. help[i] = {}
  125. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  126. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  127. elseif string.sub(current,1,1) == " " then
  128. table.insert(help[i], string.sub(current,2, -1).."")
  129. end
  130. end
  131.  
  132.  
  133. local supportsRednet = (peripheral.wrap("right") ~= nil)
  134.  
  135. local tArgs = {...}
  136. --You don't care about these
  137.       xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, endRow
  138.     = 0,   1,   1,   0,     0,      0,    0,    1,       "right",  false,     true,     1,          0,        0
  139.  
  140. local totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function)
  141. local function count() --Done any time inventory dropped and at end
  142. slot = {}        --1: Cobble 2: Fuel 3:Other
  143. for i=1, 16 do   --[1] is type, [2] is number
  144. slot[i] = {}
  145. slot[i][2] = turtle.getItemCount(i)
  146. end
  147. slot[1][1] = 1   -- = Assumes Cobble/Main
  148. for i=1, 16 do   --Cobble Check
  149. turtle.select(i)
  150. if turtle.compareTo(1)  then
  151. slot[i][1] = 1
  152. totals.cobble = totals.cobble + slot[i][2]
  153. elseif turtle.refuel(0) then
  154. slot[i][1] = 2
  155. totals.fuel = totals.fuel + slot[i][2]
  156. else
  157. slot[i][1] = 3
  158. totals.other = totals.other + slot[i][2]
  159. end
  160. end
  161. turtle.select(1)
  162. end
  163. local function checkFuel()
  164. return turtle.getFuelLevel()
  165. end
  166.  
  167.  -----------------------------------------------------------------
  168. --Input Phase
  169. local function screen(xPos,yPos)
  170. xPos, yPos = xPos or 1, yPos or 1
  171. term.setCursorPos(xPos,yPos); term.clear(); end
  172. local function screenLine(xPos,yPos)
  173. term.setCursorPos(xPos,yPos); term.clearLine(); end
  174.  
  175. screen(1,1)
  176. print("----- Welcome to Quarry! -----")
  177. print("")
  178.  
  179. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  180. local errorT = {num = "Numbers not recognized", zero = "Variable is out of range", word = "String failed assertion" }
  181. local changedT = {}
  182. changedT.new = function(key, value) changedT[#changedT+1] = {[key] = value} end
  183. changedT.getPair = function(i) for a, b in pairs(changedT[i]) do return a, b end end
  184. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  185. local function assert(condition, message, section) section = section or "[Blank]"; if condition then return condition else error("Error: "..message.."\nin section "..section, 0) end end
  186. local function checkNum(number, section) return assert(tonumber(number),errorT.num, section) end
  187. tArgs.checkStart = function(num) tArgs[tArgs[num]] = num end
  188. for i=1, #tArgs do tArgs.checkStart(i) end
  189.  
  190. --Check if it is a turtle
  191. if not turtle then
  192.   print("This is not a turtle, you must be looking for the \"Companion Rednet Program\" \nCheck My forum thread at:\nhttp://www.computercraft.info/forums2/index.php?/topic/5681-variable-size-quarry/")
  193.   print("Press 'q' to quit, or any other key to start help ")
  194.   local _, key = os.pullEvent("char")
  195.   if key ~= "q" then tArgs.help = true else error("",0) end
  196. end
  197.  
  198.  
  199. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] then
  200. print("You have selected help, press any key to continue"); print("Use arrow keys to naviate, q to quit"); os.pullEvent("key")
  201. local pos = 1
  202. local key = 0
  203. while pos <= #help and key ~= keys.q do
  204. if pos < 1 then pos = 1 end
  205. screen(1,1)
  206. print(help[pos].title)
  207. for a=1, #help[pos] do print(help[pos][a]) end
  208. repeat
  209. _, key = os.pullEvent("key")
  210. until key == 200 or key == 208 or key == keys.q
  211. if key == 200 then pos = pos - 1 end
  212. if key == 208 then pos = pos + 1 end
  213. end
  214. error("",0)
  215. end
  216.  
  217.  
  218. --Saving
  219. if tArgs["doBackup"] then doBackup = (string.lower(string.sub(tArgs[tArgs["doBackup"]+1],1,1)) ~= "f") end
  220. if tArgs["saveFile"] then saveFile = tArgs[tArgs["saveFile"]+1] or saveFile end
  221.  
  222. local restoreFound = false
  223. if tArgs["-restore"] then
  224. restoreFound = fs.exists(saveFile)
  225. if restoreFound then
  226. os.run(getfenv(1),saveFile)
  227. print("Restore File read successfully. Starting in 3"); sleep(3)
  228. end
  229. end
  230.  
  231. if not (tArgs["-DEFAULT"] or restoreFound) then
  232. local section = "Dimensions"
  233. --Dimesnions
  234. if tArgs["-dim"] then local num = tArgs["-dim"];
  235. x = checkNum(tArgs[num + 1],section); z = checkNum(tArgs[num + 2],section); y = checkNum(tArgs[num + 3],section)
  236. else
  237. print("What dimensions?")
  238. print("")
  239. --This will protect from negatives, letters, and decimals
  240. term.write("Length: ")
  241. x = math.floor(math.abs(tonumber(io.read()) or x))
  242. term.write("Width: ")
  243. z = math.floor(math.abs(tonumber(io.read()) or z))
  244. term.write("Height: ")
  245. y = math.floor(math.abs(tonumber(io.read()) or y))
  246. end
  247. changedT.new("x",x); changedT.new("z",z); changedT.new("y",y)
  248. assert(x~=0, errorT.zero, section); assert(z~=0, errorT.zero, section); assert(y~=0, errorT.zero, section)
  249. assert(not(x == 1 and y == 1 and z == 1) ,"1, 1, 1 dosen't work well at all, try again", section)
  250. if not tArgs["-vanilla"] then
  251. --Invert
  252. if tArgs["-invert"] then
  253. inverted = (string.lower(string.sub(tArgs[tArgs["-invert"]+1] or "",1,1)) == "t") else
  254. term.write("Inverted? ")
  255. inverted = (string.lower(string.sub(io.read(),1,1)) == "y")
  256. end
  257. changedT.new("Inverted", inverted)
  258. --Rednet
  259. if supportsRednet then
  260. if tArgs["-rednet"] then
  261. rednetEnabled = (string.lower(string.sub(tArgs[tArgs["-rednet"]+1] or "",1,1)) == "t")
  262. else term.write("Rednet? "); rednetEnabled = (string.lower(string.sub(io.read(),1,1)) == "y")
  263. end
  264. changedT.new("Rednet Enabled", rednetEnabled)
  265. if tArgs["-sendChannel"] then
  266. channels.send = assert(tonumber(tArgs[tArgs["-sendChannel"]+1]), errorT.num)
  267. assert(channels.send > 0 and channels.send < 65535, errorT.zero)
  268. changedT.new("Send Channel",channels.send) end
  269. if tArgs["-receiveChannel"] then
  270. channels.receive = assert(tonumber(tArgs[tArgs["-receiveChannel"]+1]), errorT.num)
  271. assert(channels.receive > 0 and channels.receive < 65535 and channels.receive ~= channels.send, errorT.zero)
  272. changedT.new("Receive Channel",channels.receive) end
  273. end
  274. --Fuel
  275. if tArgs["-doRefuel"] then doRefuel = not doRefuel; changedT.new("Do Refuel",doRefuel) end
  276. if turtle.getFuelLevel() == "unlimited" then
  277.   doCheckFuel = false
  278. else
  279.   if tArgs["-doCheckFuel"] then
  280.   doCheckFuel = (string.lower(string.sub(tArgs[tArgs["-doCheckFuel"]+1] or "",1,1)) == "t"); changedT.new("Do Check Fuel", doCheckFuel) end
  281. end
  282. if tArgs["-chest"] then
  283. dropSide = sides[tArgs[tArgs["-chest"]+1]] or dropSide; changedT.new("Chest Side",dropSide) end
  284. if tArgs["-fuelSafety"] then local loc = tArgs[tArgs["-fuelSafety"]+1]
  285.   if fuelTable[loc] then
  286.     fuelSafety = loc; changedT.new("Fuel Check Safety", fuelSafety)
  287.   end
  288. end
  289. --Misc
  290. if tArgs["-invCheckFreq"] then
  291. invCheckFreq = math.abs(math.floor(checkNum(tArgs[tArgs["-invCheckFreq"]+1],"Inventory Check Frequency")))
  292. changedT.new("Inventory Check Frequency",invCheckFreq) end
  293. assert(invCheckFreq ~= 0, errorT.zero, "Inventory Check Frequency")
  294. if tArgs["-keepOpen"] then
  295. keepOpen = math.abs(math.floor(checkNum(tArgs[tArgs["-keepOpen"]+1],"Open Slots")))
  296. changedT.new("Slots to keep open", keepOpen) end
  297. assert(keepOpen ~= 0 and keepOpen < 16, errorT.zero, "Open Slots")
  298. if tArgs["-ignoreResources"] then careAboutResources = false; changedT.new("Ignore Resources?", not careAboutResources) end
  299. if tArgs["-saveFile"] then saveFile = tArgs[tArgs["-saveFile"]+1] changedT.new("Save File", saveFile) end
  300. assert(#saveFile >= 2,errorT.word, "Save File")
  301. end; end --First end is for vanilla, second is for DEFAULT
  302.  
  303. local function saveProgress(extras) --Session persistence
  304. local file = fs.open(saveFile,"w")
  305. for a,b in pairs(getfenv(1)) do
  306. if type(b) == "string" then b = "\""..b.."\"" end
  307. if type(b) == "table" and a~="modem" then b = textutils.serialize(b) end
  308. if type(b) ~= "function" then
  309. file.write(a.." = "..tostring(b).."\n")
  310. end
  311. end
  312. file.write("doCheckFuel = false\n") --It has already used fuel, so calculation unnesesary
  313. if type(extras) == "table" then
  314.   for a, b in pairs(extras) do
  315.     file.write(a.." = "..tostring(b))
  316.   end
  317. end
  318. file.close()
  319. end
  320.  
  321. local area = x*z
  322. local volume = x*y*z
  323. local lastHeight = y%3
  324. local dispY = y
  325. y = math.floor(y/3)*3
  326. local yMult = y/3 + math.ceil(lastHeight/2)
  327. local moveVolumeCalc = ((area+x+z)*yMult) + (2 * dispY)
  328. local moveVolume = (area * yMult)
  329.  
  330. --Getting Fuel
  331. if doCheckFuel then --Calculating Needed Fuel
  332. local neededFuel = moveVolume + (math.floor(volume / (64 * 8)) * (x+dispY+z)) --Standard move plus dropping off supplies
  333.                              --How many times come back to start| * If it were at the very far side
  334. neededFuel = neededFuel + fuelTable[fuelSafety]
  335. if neededFuel < 100 then neededFuel = 100; end
  336. if checkFuel() < neededFuel then
  337. screen(1,1)
  338. print("More Fuel Needed")
  339. print("Current Fuel: ",checkFuel()," Needed: ",neededFuel)
  340. print("Place fuel in Bottom Right")
  341. while turtle.getItemCount(16) == 0 do
  342.   sleep(1)
  343. end
  344. turtle.select(16)
  345. while checkFuel() < neededFuel do
  346. if not turtle.refuel(1) then
  347. term.clearLine()
  348. print("Still too little fuel")
  349. term.clearLine()
  350. print("Insert more fuel to resume")
  351. while turtle.getItemCount(16) == 0 do
  352.   sleep(1)
  353. end
  354. end
  355. local x,y = term.getCursorPos()
  356. print(checkFuel().." Fuel")
  357. term.setCursorPos(x,y)
  358. end
  359. print(checkFuel().." Units of Fuel")
  360. sleep(3)
  361. turtle.select(1)
  362. end
  363. end
  364. --Initial Rednet Handshake
  365. if rednetEnabled then
  366. screen(1,1)
  367. print("Rednet is Enabled")
  368. print("The Channel to open is "..channels.send)
  369. modem = peripheral.wrap("right")
  370. modem.open(channels.receive)
  371. local i = 0
  372. repeat
  373. local id = os.startTimer(3)
  374. i=i+1
  375. print("Sending Initial Message "..i)
  376. modem.transmit(channels.send, channels.receive, "{ 'Initial' }")
  377. local message
  378. repeat
  379. local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  380. message = locMessage
  381. until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and message == channels.confirm)
  382. until message == channels.confirm
  383. connected = true
  384. print("Connection Confirmed!")
  385. sleep(1.5)
  386. end
  387. local function biometrics(sendChannel)
  388. local commands = { Confirm = "Confirm" }
  389. local toSend = { ["x"] = x, ["y"] = (y/3 + math.ceil(lastHeight/2)),
  390.      ["z"] = z,                     --The y calc is weird...
  391.     ["xPos"] = xPos, ["yPos"] = yPos, ["zPos"] = zPos,
  392.     ["percent"] = percent, ["mined" ]= mined,
  393.     ["fuel"] = checkFuel(), ["moved"] = moved,
  394.     ["remainingBlocks"] = (volume-mined), ["ID"] = os.getComputerID(),
  395.     ["isInPath"] = isInPath, --Whether it is going back to start
  396.     ["volume"] = volume, ["area"] = area}
  397. modem.transmit(channels.send, channels.receive, textutils.serialize(toSend))
  398. id = os.startTimer(0.1)
  399. local event, message
  400. repeat
  401. local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  402. event, message = locEvent, locMessage
  403. until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive)
  404. if event == "modem_message" then connected = true else connected = false end
  405. --Stuff to do for different commands
  406. end
  407. --Showing changes to settings
  408. screen(1,1)
  409. print("Your selected settings:")
  410. if #changedT == 0 then
  411. print("Completely Default")
  412. else
  413. for i=1, #changedT do
  414. local title, value = changedT.getPair(i)
  415. print(capitalize(title)..": ",value)
  416. end
  417. end
  418. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5)
  419.  
  420.  
  421.  
  422. ----------------------------------------------------------------
  423. --Define ALL THE FUNCTIONS
  424. function display() --This is just the last screen that displays at the end
  425. screen(1,1)
  426. print("Total Blocks Mined: "..mined)
  427. print("Current Fuel Level: "..turtle.getFuelLevel())
  428. print("Cobble: "..totals.cobble)
  429. print("Usable Fuel: "..totals.fuel)
  430. print("Other: "..totals.other)
  431. if rednetEnabled then
  432. print("")
  433. print("Sent Stop Message")
  434. finalTable = {{["Mined: "] = mined}, {["Cobble: "] = totals.cobble}, {["Fuel: "] = totals.fuel},
  435.     {["Other: "] = totals.other}, {["Fuel: "] = checkFuel()} }
  436. modem.transmit(channels.send,channels.receive,"stop")
  437. modem.transmit(channels.send,channels.receive,textutils.serialize(finalTable))
  438. modem.close(channels.receive)
  439. end
  440. if doBackup then fs.delete(saveFile) end
  441. end
  442. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  443. screen(1,1)
  444. print("Blocks Mined")
  445. print(mined)
  446. print("Percent Complete")
  447. print(percent.."%")
  448. print("Fuel")
  449. print(checkFuel())
  450. if rednetEnabled then
  451. screenLine(1,7)
  452. print("Connected: "..tostring(connected))
  453. end
  454. -- print("XPos: ",xPos)
  455. -- print("ZPos: ",zPos)
  456. -- print("YPos: ",yPos)
  457. end
  458. function isFull(slots)
  459.   slots = slots or 16
  460.   local numUsed = 0
  461.   sleep(0)
  462.   for i=1, slots do
  463.     if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  464.   end
  465.   if numUsed >= slots then
  466.     return true
  467.   end
  468.   return false
  469. end
  470. function dig(doAdd, func)
  471.   doAdd = doAdd or true
  472.   func = func or turtle.dig
  473.   if func() then
  474.     if doAdd then
  475.       mined = mined + 1
  476.     end
  477.     return true
  478.   end
  479.   return false
  480. end
  481. function relativeXCalc()
  482.   if rowCheck == "right" then relxPos = xPos else relxPos = (x-xPos)+1 end
  483. end
  484. function digUp(doAdd)
  485.   return dig(doAdd,turtle.digUp)
  486. end
  487. function digDown(doAdd)
  488.   return dig(doAdd,turtle.digDown)
  489. end
  490. function forward(doAdd)
  491.   if doAdd == nil then doAdd = true end
  492.   if turtle.forward() then
  493.     if doAdd then
  494.       moved = moved + 1
  495.     end
  496.    if facing == 0 then
  497.       xPos = xPos + 1
  498.     elseif facing == 1 then
  499.       zPos = zPos + 1
  500.     elseif facing == 2 then
  501.       xPos = xPos - 1
  502.     elseif facing == 3 then
  503.       zPos = zPos - 1
  504.     else
  505.       error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  506.     end
  507.     relativeXCalc()
  508.     return true
  509.   end
  510.   return false
  511. end
  512. function up(sneak)
  513.   sneak = sneak or 1
  514.   if inverted and sneak == 1 then
  515.     down(-1)
  516.   else
  517.     while not turtle.up() do
  518.       while not digUp() do
  519.         attackUp()
  520.         sleep(0.5)
  521.       end
  522.     end
  523.     yPos = yPos - sneak --Oh! I feel so clever
  524.   end                   --This works because inverted :)
  525. end
  526. function down(sneak)
  527.   sneak = sneak or 1
  528.   local count = 0
  529.   if inverted and sneak == 1 then
  530.     up(-1)
  531.   else
  532.     while not turtle.down() do
  533.       count = count + 1
  534.       if not digDown() then
  535.         attackDown()
  536.         sleep(0.2)
  537.       end
  538.       if count > 20 then bedrock() end
  539.     end
  540.     yPos = yPos + sneak
  541.   end
  542. end
  543. function right(num)
  544.   num = num or 1
  545.   for i=1, num do turtle.turnRight(); facingF(1); end
  546.   saveProgress()
  547. end
  548. function left(num)
  549.   num = num or 1
  550.   for i=1, num do turtle.turnLeft(); facingF(-1) end
  551.   saveProgress()
  552. end
  553. function attack(doAdd, func)
  554.   doAdd = doAdd or true
  555.   func = func or turtle.attack
  556.   local didAttack
  557.   if func() then
  558.     if doAdd then
  559.       attacked = attacked + 1
  560.     end
  561.     return true
  562.   end
  563.   return false
  564. end
  565. function attackUp(doAdd)
  566.   return attack(doAdd, turtle.attackUp)
  567. end
  568. function attackDown(doAdd)
  569.   return attack(doAdd, turtle.attackDown)
  570. end
  571.  
  572.  
  573. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  574. if doCheckInv == nil then doCheckInv = true end
  575. if doDigDown == nil then doDigDown = true end
  576. if doDigUp == nil then doDigUp = true end
  577. if outOfPath == nil then outOfPath = false end
  578. if doRefuel and checkFuel() < 100 then
  579.   for i=1, 16 do
  580.   if turtle.getItemCount(i) > 0 then
  581.     turtle.select(i)
  582.     if checkFuel() < 200 + fuelTable[fuelSafety] then
  583.       turtle.refuel()
  584.     end
  585.   end
  586.   end
  587. end
  588. local count = 0
  589. while not forward(not outOfPath) do
  590.   sleep(0) --Calls coroutine.yield to prevent errors
  591.   count = count + 1
  592.   if not dig() then
  593.     attack()
  594.   end
  595.   if count > 10 then
  596.     attack()
  597.     sleep(0.2)
  598.   end
  599.   if count > 50 then
  600.     if turtle.getFuelLevel() > 0 then
  601.       bedrock()
  602.     else
  603.       error("No Fuel",0)
  604.     end
  605.   end
  606. end
  607. if doDigUp then
  608. while turtle.detectUp() do
  609.   sleep(0) --Calls coroutine.yield
  610.   if not digUp() then
  611.     attackUp()
  612.     count = count + 1
  613.   end
  614.   if count > 50 then
  615.     bedrock()
  616.   end
  617.   end
  618. end
  619. if doDigDown then
  620.  digDown()
  621. end
  622. percent = math.ceil(moved/moveVolume*100)
  623. updateDisplay()
  624. local tab = {} --This registers a change in the saveProgress file
  625. if facing == 0 then --I do this because when it restores, it always
  626.   tab.xPos = xPos + 1-- Thinks it is one position back, for some reason
  627. elseif facing == 1 then-- This overwrites that.
  628.   tab.zPos = zPos + 1
  629. elseif facing == 2 then
  630.   tab.xPos = xPos - 1
  631. elseif facing == 3 then
  632.   tab.zPos = zPos - 1
  633. end
  634. saveProgress(tab)
  635. isInPath = (not outOfPath)
  636. if doCheckInv and careAboutResources then
  637. if moved%invCheckFreq == 0 then
  638.  if isFull(16-keepOpen) then dropOff() end
  639. end; end
  640. if rednetEnabled then biometrics() end
  641. end
  642. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  643. function facingF(num)
  644. facing = facing + num
  645. if facing > 3 then facing = 0 end
  646. if facing < 0 then facing = 3 end
  647. end
  648.  
  649. function turnTo(num, dir)
  650.   num = num or facing
  651.   dir = dir or "left"
  652.   while facing ~= num do
  653.     if dir == "left" then
  654.       left()
  655.     elseif dir == "right" then
  656.       right()
  657.     else
  658.       error("TurnTo: Left or Right expected, got "..tosrting(dir))
  659.       end
  660.   end
  661. end
  662. function goto(x,z,y, toFace)
  663. --Will first go to desired z pos, then x pos, y pos varies
  664. x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  665. gotoX,gotoY,gotoZ,gotoFacing = xPos,yPos,zPos,facing --For use in session persistence
  666. if yPos > y then --Will go up first if below position
  667.   while yPos~=y do up() end
  668. end
  669. if zPos > z then
  670.   turnTo(3)
  671. elseif zPos < z then
  672.   turnTo(1)
  673. end
  674. while zPos ~= z do mine(false,false,true,false) end
  675. if xPos > x then
  676.   turnTo(2)
  677. elseif xPos < x then
  678.   turnTo(0)
  679. end
  680. while xPos ~= x do mine(false,false,true,false) end
  681. if yPos < y then --Will go down after if above position
  682.   while yPos~=y do down() end
  683. end
  684. turnTo(toFace,"right")
  685. saveProgress()
  686. gotoX,gotoY,gotoZ,gotoFacing = nil
  687. end
  688. function drop(side, final, allowSkip)
  689. side = sides[side] or "front"    --The final number means that it will
  690. if final then final = 0 else final = 1 end --drop a whole stack at the end
  691. local allowSkip = allowSkip or (final == 0) --This will allow drop(side,t/f, rednetConnected)
  692. count()
  693. if doRefuel then
  694.   for i=1, 16 do
  695.     if slot[i][1] == 2 then
  696.       turtle.select(i); turtle.refuel()
  697.     end
  698.   end
  699.   turtle.select(1)
  700. end
  701. if side == "right" then turnTo(1) end
  702. if side == "left" then turnTo(3) end
  703. local whereDetect, whereDrop1, whereDropAll
  704. local _1 = slot[1][2] - final --All but one if final, all if not final
  705. if side == "top" then
  706. whereDetect = turtle.detectUp ; whereDrop = turtle.dropUp
  707. elseif side == "bottom" then
  708. whereDetect = turtle.detectDown ; whereDrop = turtle.dropDown
  709. else
  710. whereDetect = turtle.detect; whereDrop = turtle.drop
  711. end
  712. local function waitDrop(val) --This will just drop, but wait if it can't
  713.   val = val or 64
  714.   local try = 1
  715.   while not whereDrop(val) do
  716.     print("Chest Full, Try "..try)
  717.     try = try + 1
  718.     sleep(2)
  719.   end
  720. end
  721. repeat
  722. local detected = whereDetect()
  723. if detected then
  724.   waitDrop(_1)
  725.   for i=2, 16 do
  726.     if turtle.getItemCount(i) > 0 then
  727.       turtle.select(i)
  728.       waitDrop()
  729.     end
  730.   end
  731. elseif not allowSkip then
  732.   print("Waiting for chest placement place a chest to continue")
  733.   while not whereDetect() do
  734.     sleep(1)
  735.   end
  736. end
  737. until detected or allowSkip
  738. if not allowSkip then totals.cobble = totals.cobble - 1 end
  739. turtle.select(1)
  740. turnTo(0)
  741. end
  742. function dropOff() --Not local because called in mine()
  743. local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  744. goto(0,1,1,2)
  745. drop(dropSide,false)
  746. mine(false,false,true, false)
  747. goto(1,1,1, 0)
  748. goto(currX,currZ,currY,currFacing)
  749. end
  750. function bedrock()
  751. local origin = {x = xPos, y = yPos, z = zPos}
  752. print("Bedrock Detected")
  753. if turtle.detectUp() then
  754. print("Block Above")
  755. local var
  756. if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end
  757. goto(xPos,zPos,yPos,var)
  758. for i=1, relxPos do mine(true,true); end
  759. end
  760. goto(0,1,1,2)
  761. drop(dropSide, true)
  762. display()
  763. print("\nFound bedrock at these coordinates: ")
  764. print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  765. error("",0)
  766. end
  767. -------------------------------------------------------------------------------------
  768. --Pre-Mining Stuff dealing with session persistence
  769. local doDigDown, doDigUp
  770. if not inverted then doDigDown , doDigUp = (lastHeight ~= 1), false
  771. else doDigUp, doDigDown = (lastHeight ~= 1) , false; end --Used in lastHeight
  772. if not restoreFound then mine(false,false, true) else digUp(); digDown() end --Get it into the quarry
  773. if restoreFound then
  774.   if gotoX then
  775.     goto(gotoX,gotoZ,gotoY,gotoFacing)
  776.   end
  777.   local func
  778.   if rowCheck == "left" then func = right else func = left end
  779.   if endRow == 1 then
  780.     mine()
  781.     func()
  782.   elseif endRow == 2 then
  783.     func()
  784.   end
  785. end
  786. if y ~= 0 and not restoreFound then down() end
  787. --Mining Loops
  788. turtle.select(1)
  789. while layersDone <= y do -------------Height---------
  790. moved = moved + 1 --To account for the first position in row as "moved"
  791. if not restoreFound then rowCheck = "right" end
  792. relativeXCalc()
  793. while zPos <= z do -------------Width----------
  794. while relxPos < x do ------------Length---------
  795. mine()
  796. end ---------------Length End-------
  797. if zPos ~= z then
  798. local func
  799. if rowCheck == "right" and zPos ~= z then --Swithcing to next row
  800.   func = right; rowCheck = "left"; else func = left; rowCheck = "right" end --Which way to turn
  801.   func()
  802.   endRow = 1
  803.   mine()
  804.   endRow = 2
  805.   func()
  806.   endRow = 0
  807. else break
  808. end
  809. end ---------------Width End--------
  810. goto(1,1,yPos,0)
  811. if yPos+1 ~= y then
  812.   for i=1, 3 do down() end
  813. end
  814. layersDone = layersDone + 3
  815. restoreFound = false --This is done so that rowCheck works properly upon restore
  816. end ---------------Height End-------
  817. if lastHeight ~= 0 then ---------LAST ROW--------- (copied from above)
  818. moved = moved + 1 --To account for the first position in row as "moved"
  819. if y ~= 0 then --If the basic y == 2 or 1
  820.   for i=1, 2 do down() end
  821. end
  822. if not restoreFound then rowCheck = "right" end
  823. relativeXCalc()
  824. while zPos <= z do -------------Width----------
  825. while relxPos < x do ------------Length---------
  826. mine(doDigDown,doDigUp)
  827. end ---------------Length End-------
  828. if zPos ~= z then
  829. local func
  830. if rowCheck == "right" and zPos ~= z then --Swithcing to next row
  831.   func = right; rowCheck = "left"; else func = left; rowCheck = "right" end --Which way to turn
  832.   func()
  833.   endRow = 1
  834.   mine(doDigDown,doDigUp)
  835.   endRow = 2
  836.   func()
  837.   endRow = 0
  838. else break
  839. end
  840. end ---------------Width End--------
  841. goto(1,1,yPos,0)
  842. end
  843. if not inverted then
  844.     if doDigDown then digDown() end
  845.   else
  846.     if doDigUp then digUp() end
  847. end
  848. goto(0,1,1,2)
  849.  
  850. --Output to a chest or sit there
  851. drop(dropSide, true)
  852. --Display was moved above to be used in bedrock function
  853. display()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top