Guest User

quarry

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