NicolaosGreene

Untitled

Dec 18th, 2014
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 87.76 KB | None | 0 0
  1.  
  2.  
  3. --Civilwargeeky's Quarry Program--
  4. VERSION = "3.6.0"
  5. --[[
  6. Recent Changes:
  7. New Ore Quarry System
  8. Added New Rednet Support
  9. Quarry no longer goes to start at end of row!
  10. Turtle can go left!
  11. New Arguments!
  12. -flatBedrock [t/f]: The turtle will initially dig down to bedrock (or possibly a mob) and set startDown from that
  13. -left [t/f]: The turtle will quarry to the left instead of the right
  14. -maxFuel [number]: The number the turtle will stop fueling at. Basically just sets checkFuelLimit to this number
  15. -fuelChest [nothing or slot number]: Prompts for a chest with fuel it. This will be used if the turtle runs out of fuel. Recommended with maxfuel and doCheckFuel false
  16. ]]
  17. --Defining things
  18. civilTable = nil; _G.civilTable = {}; setmetatable(civilTable, {__index = getfenv()}); setfenv(1,civilTable)
  19. originalDay = os.day() --Used in logging
  20. numResumed = 0 --Number of times turtle has been resumed
  21. -------Defaults for Arguments----------
  22. --Arguments assignable by text
  23. x,y,z = 3,3,3 --These are just in case tonumber fails
  24. inverted = false --False goes from top down, true goes from bottom up [Default false]
  25. rednetEnabled = false --Default rednet on or off [Default false]
  26. --Arguments assignable by tArgs
  27. dropSide = "front" --Side it will eject to when full or done [Default "front"]
  28. careAboutResources = true --Will not stop mining once inventory full if false [Default true]
  29. doCheckFuel = true --Perform fuel check [Default true]
  30. doRefuel = false --Whenever it comes to start location will attempt to refuel from inventory [Default false]
  31. keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1]
  32. fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate]
  33. excessFuelAmount = math.huge --How much fuel the turtle will get maximum. Limited by turtle.getFuelLimit in recent CC [Default math.huge]
  34. saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"]
  35. autoResume = true --If true, turtle will auto-restart when loaded. [Default true]
  36. startupRename = "oldStartup.quarry" --What the startup is temporarily renamed to [Default "oldStartup.quarry"]
  37. startupName = "startup" --What the turtle auto-resumes with [Default "startup"]
  38. doBackup = true --If it will keep backups for session persistence [Default true]
  39. uniqueExtras = 8 --How many different items (besides cobble) the turtle expects. [Default 8]
  40. maxTries = 50 --How many times turtle will try to dig a block before it "counts" bedrock [Default 50]
  41. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  42. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  43. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  44. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  45. logExtension = "" --The extension of the file (e.g. ".txt") [Default ""]
  46. flatBedrock = false --If true, will go down to bedrock to set startDown [Default false]
  47. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  48. enderChestEnabled = false --Whether or not to use an ender chest [Default false]
  49. enderChestSlot = 16 --What slot to put the ender chest in [Default 16]
  50. fuelChestEnabled = false --Whether or not to use a fuel chest [Default false]
  51. fuelChestSlot = 15 --What slot to put the fuel chest in [Default 15]
  52. goLeftNotRight = false --Quarry to left, not right (parameter is "left") [Default false]
  53. oreQuarry = false --Enables ore quarry functionality [Default false]
  54. oreQuarryBlacklistName = "oreQuarryBlacklist.txt" --This is the file that will be parsed for item names [Default "oreQuarryBlacklist"]
  55. dumpCompareItems = true --If ore quarry, the turtle will dump items compared to (like cobblestone) [Default true]
  56. p=peripheral.wrap("left") -- Wraps the Miny Chunky module
  57. inventoryMax = 16 --The max number of slots in the turtle inventory [Default 16] (Not assignable by parameter)
  58. --Standard number slots for fuel (you shouldn't care)
  59. fuelTable = { --Will add in this amount of fuel to requirement.
  60. safe = 1000,
  61. moderate = 200,
  62. loose = 0 } --Default 1000, 200, 0
  63. --Standard rednet channels
  64. channels = {
  65. send = os.getComputerID() + 1 ,
  66. receive = os.getComputerID() + 101 ,
  67. confirm = "Turtle Quarry Receiver",
  68. message = "Civil's Quarry",
  69. fingerprint = "quarry"
  70. }
  71.  
  72. --AVERAGE USER: YOU DON'T CARE BELOW THIS POINT
  73.  
  74. local help_paragraph = [[
  75. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  76. -default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  77. -dim: [length] [width] [height] This sets the dimensions for the quarry
  78. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  79. -rednet: [t/f] If true and you have a wireless modem on the turtle, will attempt to make a rednet connection for sending important information to a screen
  80. -restore / -resume: If your quarry stopped in the middle of its run, use this to resume at the point where the turtle was. Not guarenteed to work properly. For more accurate location finding, check out the -GPS parameter
  81. -autoResume / autoRestore: Turtle will automatically resume if stopped. Replaces startup
  82. -oreQuarry: [t/f] If true, the turtle will use ore quarry mode. It will not mine the blocks that are placed in the turtle initially. So if you put in stone, it will ignore stone blocks and only mine ores.
  83. -oreQuarry: [t/f] If you are using a newer version of CC, you won't have to put in any compare blocks. (CC 1.64+)
  84. -blacklist: [file name] If using oreQuarry, this is the blacklist file it will read. Example --
  85. minecraft:stone
  86. minecraft:sand
  87. ThermalExpansion:Sponge
  88. ThermalFoundation:Storage
  89.  
  90. If you have bspkrsCore, look for "UniqueNames.txt" in your config
  91. -atChest: [force] This is for use with "-restore," this will tell the restarting turtle that it is at its home chest, so that if it had gotten lost, it now knows where it is.
  92. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  93. -doCheckFuel: [t/f] If you for some reason don't want the program to check fuel usage, set to false. This is honestly a hold-over from when the refueling algorithm was awful...
  94. -uniqueExtras: [number] The expected number of slots filled with low-stacking items like ore. Higher numbers request more fuel.
  95. -maxFuel: [number] How much the turtle will fuel to max (limited by turtle in most cases)
  96. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  97. -enderChest: This one is special. If you use "-enderChest true" then it will use an enderChest in the default slot. However, you can also do "-enderChest [slot]" then it will take the ender chest from whatever slot you tell it to. Like 7... or 14... or whatever.
  98. -fuelChest: See the above, but for a fueling chest. Reccommend use with -maxFuel and -doCheckFuel false
  99. -GPS: [force] If you use "-GPS" and there is a GPS network, then the turtle will record its first two positions to precisly calculate its position if it has to restart. This will only take two GPS readings
  100. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  101. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  102. -startY: [current Y coord] Randomly encountering bedrock? This is the parameter for you! Just give it what y coordinate you are at right now. If it is not within bedrock range, it will never say it found bedrock
  103. -startupRename: [file name] What to rename any existing startup to.
  104. -startupName: [file name] What the turtle will save its startup file to.
  105. -extraDropItems: [force] If oreQuarry then this will prompt the user for extra items to drop, but not compare to (like cobblestone)
  106. -dumpCompareItems: [t/f] If oreQuarry and this is true, the turtle will dump off compare blocks instead of storing them in a chest
  107. -oldOreQuarry: [t/f] If you are using new CC versions, you can use this to use the old oreQuarry.
  108. -left: [t/f] If true, turtle will quarry to the left instead of the right
  109. -maxTries: [number] This is the number of times the turtle will try to dig before deciding its run into bedrock.
  110. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  111. -doBackup: [t/f] If false, will not back up important information and cannot restore, but will not make an annoying file (Actually I don't really know why anyone would use this...)
  112. -saveFile: [word] This is what the backup file will be called
  113. -logFolder: [word] The folder that quarry logs will be stored in
  114. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  115. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every time it mines
  116. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  117. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  118. =
  119. C _ |
  120. |
  121. |
  122. |
  123. |_ _ _ _ >
  124. -promptAll: This is the opposite of -Default, it prompts for everything
  125. -manualPos: [xPos] [zPos] [yPos] [facing] This is for advanced use. If the server reset when the turtle was in the middle of a 100x100x100 quarry, fear not, you can now manually set the position of the turtle. yPos is always positive. The turtle's starting position is 0, 1, 1, 0. Facing is measured 0 - 3. 0 is forward, and it progresses clockwise. Example- "-manualPos 65 30 30 2"
  126. -help: Thats what this is :D
  127. Examples: Everything below is examples and tips for use
  128. Important Note:
  129. None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  130. Examples [1]:
  131. Want to just start a quarry from the interface, without going through menus? It's easy! Just use some parameters. Assume you called the program "quarry." To start a 10x6x3 quarry, you just type in "quarry -dim 10 6 3 -default".
  132. You just told it to start a quarry with dimensions 10x6x3, and "-default" means it won't prompt you about invert or rednet. Wasn't that easy?
  133. Examples [2]:
  134. Okay, so you've got the basics of this now, so if you want, you can type in really long strings of stuff to make the quarry do exactly what you want. Now, say you want a 40x20x9, but you want it to go down to diamond level, and you're on the surface (at y = 64). You also want it to send rednet messages to your computer so you can see how its doing.
  135. Examples [2] [cont.]:
  136. Oh yeah! You also want it to use an ender chest in slot 12 and restart if the server crashes. Yeah, you can do that. You would type
  137. "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  138. BAM. Now you can just let that turtle do it's thing
  139. Tips:
  140. The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  141.  
  142. Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  143. Tips [cont.]:
  144. For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  145.  
  146. For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  147. Tips [cont.]:
  148. If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  149.  
  150. If you want, you can load this program onto a computer, and use "quarry -help" so you can have help with the parameters whenever you want.
  151. Internal Config:
  152. At the top of this program is an internal configuration file. If there is some setup that you use all the time, you can just change the config value at the top and run "quarry -default" for a quick setup.
  153.  
  154. You can also use this if there are settings that you don't like the default value of.
  155. ]]
  156.  
  157. --Parsing help for display
  158. --[[The way the help table works:
  159. All help indexes are numbered. There is a help[i].title that contains the title,
  160. and the other lines are in help[i][1] - help[i][#help[i] ]
  161. Different lines (e.g. other than first) start with a space.
  162. As of now, the words are not wrapped, fix that later]]
  163. local help = {}
  164. local i = 0
  165. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  166. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  167. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  168. local current = string.sub(a,1,-2).."" --Concatenate Trick
  169. if string.sub(current,1,1) ~= " " then
  170. i = i + 1
  171. help[i] = {}
  172. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  173. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  174. elseif string.sub(current,1,1) == " " then
  175. table.insert(help[i], string.sub(current,2, -1).."")
  176. end
  177. end
  178.  
  179. local supportsRednet
  180. if peripheral.find then
  181. supportsRednet = peripheral.find("modem") or false
  182. else
  183. supportsRednet = (peripheral.getType("right") == "modem") or false
  184. end
  185.  
  186. local tArgs = {...}
  187. --Pre-defining variables that need to be saved
  188. xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, startY, chestFull, gotoDest, atChest, fuelLevel, numDropOffs, allowedItems, compareSlots, dumpSlots, selectedSlot, extraDropItems, oldOreQuarry, specialSlots, relzPos
  189. = 0, 1, 1, 0, 0, 0, 0, 1, true , false, true, 1, 0, 0, false, "", false, 0, 0, {}, {}, {}, 1, false, false, {}, 0
  190.  
  191. local statusString
  192.  
  193. --Initializing various inventory management tables
  194. for i=1, inventoryMax do
  195. allowedItems[i] = 0 --Number of items allowed in slot when dropping items
  196. dumpSlots[i] = false --Does this slot contain junk items?
  197. end --compareSlots is a table of the compare slots, not all slots with a condition
  198. totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function), this goes up here because many functions use it
  199.  
  200. local function newSpecialSlot(index, value)
  201. value = tonumber(value) or 0 --We only want numerical indexes
  202. if specialSlots[value] then return false end --Can't overwrite other slots
  203. specialSlots[index] = value
  204. specialSlots[value] = index
  205. return true
  206. end
  207.  
  208. function resetDumpSlots()
  209. for i=1, inventoryMax do
  210. if oldOreQuarry then
  211. if turtle.getItemCount(i) > 0 and i~= specialSlots.enderChest then
  212. dumpSlots[i] = true
  213. else
  214. dumpSlots[i] = false
  215. end
  216. else
  217. dumpSlots[i] = false
  218. end
  219. end
  220. if not oldOreQuarry and specialSlots.enderChest == 1 then
  221. dumpSlots[2] = true
  222. elseif not oldOreQuarry then
  223. dumpSlots[1] = true
  224. end
  225. end
  226.  
  227.  
  228. local function copyTable(tab) local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end --This goes up here because it is a basic utility
  229.  
  230. --NOTE: rowCheck is a bit. true = "right", false = "left"
  231.  
  232. local foundBedrock = false
  233.  
  234. local checkFuel, checkFuelLimit
  235. if turtle then --Function inits
  236. checkFuel = turtle.getFuelLevel
  237. if turtle.getFuelLevel() == "unlimited" then --Fuel is disabled --Unlimited screws up my calculations
  238. checkFuel = function() return math.huge end --Infinite Fuel
  239. end --There is no "else" because it will already return the regular getFuel
  240. if turtle.getFuelLimit then
  241. checkFuelLimit = function() return math.min(turtle.getFuelLimit(), excessFuelAmount) end --Return the limiting one
  242. if turtle.getFuelLimit() == "unlimited" then
  243. checkFuelLimit = function() return math.huge end
  244. end
  245. else
  246. checkFuelLimit = function() return excessFuelAmount end --If the function doesn't exist
  247. end
  248.  
  249.  
  250. turtle.select(1) --To ensure this is correct
  251. end
  252.  
  253.  
  254. function select(slot)
  255. if slot ~= selectedSlot and slot > 0 and slot <= inventoryMax then
  256. selectedSlot = slot
  257. return turtle.select(slot), selectedSlot
  258. end
  259. end
  260.  
  261.  
  262. -----------------------------------------------------------------
  263. --Input Phase
  264. local function screen(xPos,yPos)
  265. xPos, yPos = xPos or 1, yPos or 1
  266. term.setCursorPos(xPos,yPos); term.clear(); end
  267. local function screenLine(xPos,yPos)
  268. term.setCursorPos(xPos,yPos); term.clearLine(); end
  269.  
  270. screen(1,1)
  271. print("----- Welcome to Quarry! -----")
  272. print("")
  273.  
  274. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  275. local changedT, tArgsWithUpper = {}, {}
  276. changedT.new = function(key, value) table.insert(changedT,{key, value}) end --Numeric list of lists
  277. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  278. for i=1, #tArgs do tArgsWithUpper[i] = tArgs[i]; tArgsWithUpper[tArgsWithUpper[i]] = i; tArgs[i] = tArgs[i]:lower(); tArgs[tArgs[i]] = i end --My signature key-value pair system, now with upper
  279.  
  280. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  281. function addParam(name, displayText, formatString, forcePrompt, trigger, variableOverride) --To anyone that doesn't understand this very well, probably not your best idea to go in here.
  282. if trigger == nil then trigger = true end --Defaults to being able to run
  283. if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  284. if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these. Default is no variable because resuming
  285. if not restoreFoundSwitch and tArgs["-promptall"] then forcePrompt = true end
  286. local toGetText = name:lower() --Because all params are now lowered
  287. local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  288. local args = formatString:sub(({formatString:find(formatType)})[2] + 2).."" --Everything in formatString but the type and space
  289. local variable = variableOverride or name --Goes first to the override for name
  290. local func = loadstring("return "..variable)
  291. setfenv(func,getfenv(1))
  292. local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  293. if originalValue == nil then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  294. local givenValue, toRet --Initializing for use
  295. if tArgs["-"..toGetText] then
  296. givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  297. elseif forcePrompt then
  298. write(displayText.."? ")
  299. givenValue = io.read()
  300. end
  301. if formatType == "force" then --This is the one exception. Should return true if givenValue is nothing
  302. toRet = (tArgs["-"..toGetText] and true) or false --Will return true if param exists, otherwise false
  303. end
  304. if not (givenValue or toRet) then return end --Don't do anything if you aren't given anything. Leave it as default, except for "force"
  305. if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  306. toRet = givenValue:sub(1,1):lower() == "y" or givenValue:sub(1,1):lower() == "t" --Accepts true or yes
  307. if formatString == "boolean special" then
  308. toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  309. end
  310. elseif formatType == "string" then
  311. toRet = givenValue:match("^[%w%.]+") --Basically anything not a space or control character etc
  312. elseif formatType == "number" then
  313. toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  314. if not toRet then return end --We need a number... Otherwise compare errors
  315. toRet = math.abs(math.floor(toRet)) --Get proper integers
  316. local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  317. startNum, endNum = tonumber(startNum), tonumber(endNum)
  318. if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  319. elseif formatType == "side" then
  320. local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  321. for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  322. if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  323. elseif formatType == "list" then
  324. toRet = {}
  325. for a in args:gmatch("[^,]") do
  326. table.insert(toRet,a)
  327. end
  328. elseif formatType == "force" then --Do nothing, everything is already done
  329. else error("Improper formatType",2)
  330. end
  331. if toRet == nil then return end --Don't want to set variables to nil... That's bad
  332. tempParam = toRet --This is what loadstring will see :D
  333. local func = loadstring(variable.." = tempParam")
  334. setfenv(func, getfenv(1))
  335. func()
  336. tempParam = nil --Cleanup of global
  337. if toRet ~= originalValue and displayText ~= "" then
  338. changedT.new(displayText, tostring(toRet))
  339. end
  340. return toRet
  341. end
  342.  
  343. --Check if it is a turtle
  344. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then --If all of these are false then
  345. print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  346. print("Press 'q' to quit, or any other key to start help ")
  347. if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  348. end
  349.  
  350. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  351. print("You have selected help, press any key to continue"); print("Use arrow keys to navigate, q to quit"); os.pullEvent("key")
  352. local pos = 1
  353. local key = 0
  354. while pos <= #help and key ~= keys.q do
  355. if pos < 1 then pos = 1 end
  356. screen(1,1)
  357. print(help[pos].title)
  358. for a=1, #help[pos] do print(help[pos][a]) end
  359. repeat
  360. _, key = os.pullEvent("key")
  361. until key == 200 or key == 208 or key == keys.q
  362. if key == 200 then pos = pos - 1 end
  363. if key == 208 then pos = pos + 1 end
  364. end
  365. error("",0)
  366. end
  367.  
  368. --Saving
  369. addParam("doBackup", "Backup Save File", "boolean")
  370. addParam("saveFile", "Save File Name", "string")
  371.  
  372. restoreFound = fs.exists(saveFile)
  373. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound and doBackup
  374. if restoreFoundSwitch then
  375. local file = fs.open(saveFile,"r")
  376. local test = file.readAll() ~= ""
  377. file.close()
  378. if test then
  379. os.run(getfenv(1),saveFile) --This is where the actual magic happens
  380. numResumed = numResumed + 1
  381. if checkFuel() ~= math.huge then --If turtle uses fuel
  382. if fuelLevel - checkFuel() == 1 then
  383. if facing == 0 then xPos = xPos + 1
  384. elseif facing == 2 then xPos = xPos - 1
  385. elseif facing == 1 then zPos = zPos + 1
  386. elseif facing == 3 then zPos = zPos - 1 end
  387. elseif fuelLevel - checkFuel() ~= 0 then
  388. print("Very Strange Fuel in Restore Section...")
  389. print("Current: ",checkFuel())
  390. print("Saved: ",fuelLevel)
  391. print("Difference: ",fuelLevel - checkFuel())
  392. os.pullEvent("char")
  393. end
  394. end
  395. if gpsEnabled then --If it had saved gps coordinates
  396. print("Found GPS Start Coordinates")
  397. local currLoc = {gps.locate(gpsTimeout)} or {}
  398. local backupPos = {xPos, yPos, zPos} --This is for comparing to later
  399. if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  400. print("GPS Position Successfully Read")
  401. if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  402. xPos, yPos, zPos = 0,1,1
  403. if facing ~= 0 then turnTo(0) end
  404. print("Is at start")
  405. else
  406. if inverted then --yPos setting
  407. ------------------------------------------------FIX THIS
  408. end
  409. local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  410. local flag = true --So we can account for left quarry
  411. if b[3] - a[3] == -1 then--If went north (-Z)
  412. a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  413. xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  414. elseif b[1] - a[1] == 1 then--If went east (+X)
  415. a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  416. xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  417. elseif b[3] - a[3] == 1 then--If went south (+Z)
  418. a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  419. xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  420. elseif b[1] - a[1] == -1 then--If went west (-X)
  421. a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  422. xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  423. else
  424. flag = false
  425. print("Improper Coordinates")
  426. print("GPS Locate Failed, Using Standard Methods") ----Maybe clean this up a bit to use flags instead.
  427. end
  428. if flag and goLeftNotRight then --This accounts for left quarry (barred to left only because there might be errors in a regular, causing neg/0
  429. zPos = math.abs(zPos-1) + 1
  430. end
  431. end
  432. print("X Pos: ",xPos)
  433. print("Y Pos: ",yPos)
  434. print("Z Pos: ",zPos)
  435. print("Facing: ",facing)
  436. for i=1, 3, 2 do --We want 1 and 3, but 2 could be coming back to start.
  437. if backupPos[i] ~= currLoc[i] then
  438. events = {} --We want to remove event queue if not in proper place, so won't turn at end of row or things.
  439. end
  440. end
  441. else
  442. print("GPS Locate Failed, Using Standard Methods")
  443. end
  444. print("Restore File read successfully. Starting in 3"); sleep(3)
  445. end
  446. else
  447. fs.delete(saveFile)
  448. print("Restore file was empty, sorry, aborting")
  449. error("",0)
  450. end
  451. else --If turtle is just starting
  452. events = {} --This is the event queue :D
  453. originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  454. end
  455.  
  456. --Dimensions
  457. if tArgs["-dim"] then
  458. local a,b,c = x,y,z
  459. local num = tArgs["-dim"]
  460. x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  461. if a ~= x then changedT.new("Length", x) end
  462. if c ~= z then changedT.new("Width", z) end
  463. if b ~= y then changedT.new("Height", y) end
  464. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  465. print("What dimensions?")
  466. print("")
  467. --This will protect from negatives, letters, and decimals
  468. term.write("Length? ")
  469. x = math.floor(math.abs(tonumber(io.read()) or x))
  470. term.write("Width? ")
  471. z = math.floor(math.abs(tonumber(io.read()) or z))
  472. term.write("Height? ")
  473. y = math.floor(math.abs(tonumber(io.read()) or y))
  474. changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  475. end
  476. --Params: parameter/variable name, display name, type, force prompt, boolean condition, variable name override
  477. --Invert
  478. addParam("flatBedrock","Go to bedrock", "boolean") --Not done before GPS because GPS only runs on restart
  479. addParam("invert", "Inverted","boolean", true, not flatBedrock, "inverted") --Not flat bedrock, because invert will be set to false
  480. addParam("startDown","Start Down","number 1-256", nil, not flatBedrock)
  481. addParam("left","Left Quarry","boolean", nil, nil, "goLeftNotRight")
  482. --Inventory
  483. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  484. addParam("enderChest","Ender Chest Enabled","boolean special", nil, nil, "enderChestEnabled") --This will accept anything (including numbers) thats not "f" or "n"
  485. addParam("enderChest", "Ender Chest Slot", "number 1-16", nil, nil, "enderChestSlot") --This will get the number slot if given
  486. newSpecialSlot("enderChest",enderChestEnabled and enderChestSlot or 0) --This allows for easy checking and getting --This makes everything better (0)
  487. addParam("fuelChest","Fuel Chest Enabled","boolean special", nil, nil, "fuelChestEnabled") --See above notes
  488. addParam("fuelChest", "Fuel Chest Slot", "number 1-16", nil, nil, "fuelChestSlot")
  489. newSpecialSlot("fuelChest", fuelChestEnabled and fuelChestSlot or 0)
  490. if (enderChestEnabled and fuelChestEnabled) and (enderChestSlot == fuelChestSlot) then
  491. error("Warning: Ender Chest Slot and Fuel Chest Slot cannot be the same",0)
  492. end
  493. --Rednet
  494. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
  495. addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  496. if gpsEnabled and not restoreFoundSwitch then
  497. gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  498. gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  499. end
  500. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  501. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  502. addParam("fingerprint","Sending Fingerprint", "string", false, supportsRednet, "channels.fingerprint")
  503. --Fuel
  504. addParam("uniqueExtras","Unique Items", "number 0-15")
  505. addParam("doRefuel", "Refuel from Inventory","boolean", nil, checkFuel() ~= math.huge) --math.huge due to my changes
  506. addParam("doCheckFuel", "Check Fuel", "boolean", nil, checkFuel() ~= math.huge)
  507. excessFuelAmount = excessFuelAmount or math.huge --Math.huge apparently doesn't save properly
  508. addParam("maxFuel", "Max Fuel", "number 1-999999999", nil, checkFuel() ~= math.huge, "excessFuelAmount")
  509. --Logging
  510. addParam("logging", "Logging", "boolean")
  511. addParam("logFolder", "Log Folder", "string")
  512. addParam("logExtension","Log Extension", "string")
  513. --Misc
  514. addParam("startY", "Start Y","number 1-256")
  515. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  516. addParam("careAboutResources", "Care About Resources","boolean")
  517. addParam("maxTries","Tries Before Bedrock", "number 1-9001")
  518. --Auto Startup
  519. addParam("autoResume", "Auto Resume", "boolean", nil, doBackup)
  520. addParam("autoRestart", "Auto Restart", "boolean", nil, doBackup, "autoResume")
  521. addParam("startupRename", "Startup Rename","string", nil, autoResume)
  522. addParam("startupName", "Startup File", "string", nil, autoResume)
  523. --Ore Quarry
  524. addParam("oreQuarry", "Ore Quarry", "boolean" )
  525. if oreQuarry and not turtle.inspect then
  526. oldOreQuarry = true
  527. oreQuarry = false
  528. end
  529. --Old Ore
  530. addParam("oldOreQuarry", "Old Ore Quarry", "boolean")
  531. addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oldOreQuarry) --Do not dump compare items if not oreQuarry
  532. addParam("extraDropItems", "", "force", nil, oldOreQuarry) --Prompt for extra dropItems
  533. addParam("extraDumpItems", "", "force", nil, oldOreQuarry, "extraDropItems") --changed to Dump
  534. --New Ore
  535. addParam("blacklist","Ore Blacklist", "string", nil, oreQuarry, "oreQuarryBlacklistName")
  536.  
  537.  
  538. --for flatBedrock
  539. if flatBedrock then
  540. inverted = false
  541. end
  542.  
  543. --Auto Startup functions
  544. local function doAutoResumeStuff()
  545. if fs.exists(startupName) then
  546. if fs.exists(startupRename) then fs.delete(startupRename) end
  547. fs.move(startupName, startupRename)
  548. end
  549. local file = fs.open(startupName,"w") --Startup File
  550. file.writeLine( --The below is on the left because spacing
  551. [[
  552. --This is an auto-generated startup
  553. --Made by civilwargeeky's Variable Size Quarry
  554. print("Now Resuming Quarry")
  555. print("Press any key to quit. You have 5 seconds.")
  556. sleep(1)
  557. function deleteStuff()
  558. fs.delete("]]..startupName..[[")
  559. if fs.exists("]]..startupRename..[[") then
  560. fs.move("]]..startupRename.."\",\""..startupName..[[")
  561. end
  562. end
  563. local event
  564. if fs.exists("]]..saveFile..[[") then
  565. for i=5,1,-1 do
  566. print(i)
  567. os.startTimer(1)
  568. event = os.pullEvent()
  569. if event == "key" then break end
  570. end
  571. if event == "timer" then
  572. os.run({},"]]..shell.getRunningProgram()..[[","-resume")
  573. else
  574.  
  575. deleteStuff()
  576. end
  577. else
  578. print("Never mind, no save file found")
  579. deleteStuff()
  580. end
  581. ]])
  582. file.close()
  583. end
  584. if autoResume and not restoreFoundSwitch then --Don't do for restore because would overwrite renamed thing. Can't edit mid-run because no shell in restarted
  585. doAutoResumeStuff()
  586. end
  587. --oreQuarry blacklist
  588. local blacklist = { "minecraft:air", "minecraft:bedrock", "minecraft:cobblestone", "minecraft:dirt", "minecraft:ice", "minecraft:ladder", "minecraft:netherrack", "minecraft:sand", "minecraft:sandstone",
  589. "minecraft:snow", "minecraft:snow_layer", "minecraft:stone", "minecraft:gravel", "minecraft:grass", "minecraft:torch" }
  590. for a,b in pairs(blacklist) do
  591. blacklist[b], blacklist[b] = true, nil --Switch
  592. end
  593. if fs.exists(oreQuarryBlacklistName) then --Loading user-defined blacklist
  594. local file = fs.open(oreQuarryBlacklistName, "r")
  595. blacklist = {}
  596. for a in file:readAll():gmatch("[^,]+") do
  597. blacklist[a:match("%S+:%S+")] = true --Grab only the actual characters, not whitespaces
  598. end
  599. file:close()
  600. end
  601.  
  602. --Manual Position
  603. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  604. local a = tArgs["-manualpos"]
  605. xPos, zPos, yPos, facing = tonumber(tArgs[a+1]) or xPos, tonumber(tArgs[a+2]) or zPos, tonumber(tArgs[a+3]) or yPos, tonumber(tArgs[a+4]) or facing
  606. changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  607. restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  608. for i=0,4 do tArgs[a+i] = "" end --Get rid of this argument from future restores
  609. end
  610. if addParam("atChest", "Is at Chest", "force") then --This sets position to 0,1,1, facing forward, and queues the turtle to go back to proper row.
  611. local neededLayer = math.floor((yPos+1)/3)*3-1 --Make it a proper layer, +- because mining rows are 2, 5, etc.
  612. if neededLayer > 2 and neededLayer%3 ~= 2 then --If turtle was not on a proper mining layer
  613. print("Last known pos was not in proper layer, restarting quarry")
  614. sleep(4)
  615. neededLayer = 2
  616. end
  617. if ((neededLayer-2)/3) % 2 == 1 then neededLayer = neededLayer - 3 end --Because with weird end of row, just go to last basic row
  618. xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
  619. doAutoResumeStuff() --This was probably deleted when they hit a key to launch with -atChest
  620. events = {{"goto",1,1,neededLayer, 0}}
  621. end
  622.  
  623.  
  624. local function saveProgress(extras) --Session persistence
  625. exclusions = { modem = true, }
  626. if doBackup then
  627. local toWrite = ""
  628. for a,b in pairs(getfenv(1)) do
  629. if not exclusions[a] then
  630. --print(a ," ", b, " ", type(b)) --Debug
  631. if type(b) == "string" then b = "\""..b.."\"" end
  632. if type(b) == "table" then b = textutils.serialize(b) end
  633. if type(b) ~= "function" then
  634. toWrite = toWrite..a.." = "..tostring(b).."\n"
  635. end
  636. end
  637. end
  638. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnecessary
  639. local file
  640. repeat
  641. file = fs.open(saveFile,"w")
  642. until file
  643. file.write(toWrite)
  644. if type(extras) == "table" then
  645. for a, b in pairs(extras) do
  646. file.write(a.." = "..tostring(b).."\n")
  647. end
  648. end
  649. if checkFuel() ~= math.huge then --Used for location comparing
  650. file.write("fuelLevel = "..tostring(checkFuel()).."\n")
  651. end
  652. file.close()
  653. end
  654. end
  655.  
  656. local area = x*z
  657. local volume = x*y*z
  658. local lastHeight = y%3
  659. layers = math.ceil(y/3)
  660. local yMult = layers --This is basically a smart y/3 for movement
  661. local moveVolume = (area * yMult) --Kept for display percent
  662. --Calculating Needed Fuel--
  663. do --Because many local variables unneeded elsewhere
  664. local changeYFuel = 2*(y + startDown)
  665. local dropOffSupplies = 2*(x + z + y + startDown) --Assumes turtle as far away as possible, and coming back
  666. local frequency = math.ceil(((moveVolume/(64*(15-uniqueExtras) + uniqueExtras)) ) ) --This is complicated: volume / inventory space of turtle, defined as 64*full stacks + 1 * unique stacks.
  667. --max of 15 full stacks because once one item is picked up, slot is "full". Ceil to count for initial back and forth
  668. if enderChestEnabled then frequency = 0 end --Never goes back to start
  669. neededFuel = moveVolume + changeYFuel + (frequency * dropOffSupplies) + ((x + z) * layers) --x + z *layers because turtle has to come back from far corner every layer
  670. neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  671. end
  672.  
  673. if neededFuel+checkFuel() > checkFuelLimit() and doCheckFuel then--Checks for if refueling goes over turtle fuel limit
  674. if not (doRefuel or fuelChestEnabled) then
  675. screen()
  676. print("Turtle cannot hold enough fuel\n")
  677. print("Options: \n1. Select a smaller size (press q) \n2. Enable Mid-Run Refueling (any other key)")
  678. if ({os.pullEvent("char")})[2] == "q" then
  679. screen(); print("Okay"); error("",0)
  680. else
  681. doRefuel = true
  682. end
  683. end
  684. neededFuel = checkFuelLimit()-checkFuel()-1
  685. end
  686.  
  687.  
  688. --Getting Fuel
  689. local hasRefueled --This is for oreQuarry prompting
  690. if doCheckFuel and checkFuel() < neededFuel then
  691. hasRefueled = true
  692. print("Not enough fuel")
  693. print("Current: ",checkFuel()," Needed: ",neededFuel)
  694. print("Starting SmartFuel...")
  695. sleep(2) --So they can read everything.
  696. term.clear()
  697. local oneFuel, neededFuelItems = 0,0 --Initializing Variables
  698. local currSlot = 0
  699. local function output(text, x, y) --For displaying fuel statistics
  700. local currX, currY = term.getCursorPos()
  701. term.setCursorPos(x,y)
  702. term.clearLine()
  703. term.write(text)
  704. term.setCursorPos(currX,currY)
  705. end
  706. local function roundTo(num, target) --For stacks of fuel and turtle slots when undergoing addition/subtraction
  707. if num >= target then return target elseif num < 0 then return 0 else return num end
  708. end
  709. local function updateScreen()
  710. output("Welcome to SmartFuel! Now Refueling...", 1,1)
  711. output("Currently taking fuel from slot "..currSlot,1,2)
  712. output("Current single fuel: "..tostring(oneFuel or 0),1,3)
  713. output("Current estimate of needed fuel: ",1,4)
  714. output("Single Items: "..math.ceil(neededFuelItems),4,5)
  715. output("Stacks: "..math.ceil(neededFuelItems / 64),4,6)
  716. output("Needed Fuel: "..tostring(neededFuel),1,12)
  717. output("Current Fuel: "..tostring(checkFuel()),1,13)
  718. end
  719. while checkFuel() <= neededFuel do
  720. currSlot = currSlot + 1
  721. select(currSlot)
  722. if currSlot ~= 1 and not turtle.refuel(0) then --If it's not the first slot, and not fuel, go back to start
  723. currSlot = 1; select(currSlot)
  724. end
  725. updateScreen()
  726. while turtle.getItemCount(currSlot) == 0 do
  727. sleep(1.5)
  728. end
  729. repeat --TODO: Probably unnecessary loop, remove later
  730. local previous = checkFuel()
  731. turtle.refuel(1)
  732. oneFuel = checkFuel() - previous
  733. updateScreen()
  734. until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  735. neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel)
  736. turtle.refuel(roundTo(neededFuelItems, 64)) --Change because can only think about 64 at once.
  737. if turtle.getItemCount(roundTo(currSlot + 1, inventoryMax)) == 0 then --Resets if no more fuel
  738. currSlot = 0
  739. end
  740. neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel) --This line is not repeated uselessly, it's for the display function
  741. end
  742. select(1)
  743. end
  744. --Ender Chest Obtaining
  745. function promptSpecialSlot(specialSlot, name)
  746. while turtle.getItemCount(specialSlots[specialSlot]) ~= 1 do
  747. screen(1,1)
  748. print("You have decided to use a ",name,"!")
  749. print("Please place one ",name," in slot ",specialSlots[specialSlot])
  750. sleep(1)
  751. end
  752. print(name," in slot ",specialSlots[specialSlot], " checks out")
  753. end
  754. function checkSpecialSlot(specialSlot, name)
  755. if restoreFoundSwitch and turtle.getItemCount(specialSlots[specialSlot]) == 0 then --If the turtle was stopped while dropping off items.
  756. select(specialSlots[specialSlot])
  757. p.dig()
  758. select(1)
  759. end
  760. promptSpecialSlot(specialSlot, name)
  761. allowedItems[specialSlots[specialSlot]] = 1
  762. sleep(2)
  763. end
  764. if enderChestEnabled then
  765. checkSpecialSlot("enderChest","Ender Chest")
  766. end
  767. if fuelChestEnabled then
  768. checkSpecialSlot("fuelChest","Fuel Chest")
  769. end
  770. --Fuel Chest Obtaining
  771.  
  772. --Setting which slots are marked as compare slots
  773. if oldOreQuarry then
  774. if not restoreFoundSwitch then --We don't want to reset compare blocks every restart
  775. local counter = 0
  776. for i=1, inventoryMax do if turtle.getItemCount(i) > 0 and i ~= specialSlots.enderChest then counter = counter+1 end end --If the slot has items, but isn't enderChest slot if it is enabled
  777.  
  778. screen(1,1)
  779. print("You have selected an Ore Quarry!")
  780. if counter == 0 or hasRefueled then --If there are no compare slots, or the turtle has refueled, and probably has fuel in inventory
  781. print("Please place your compare blocks in the first slots\n")
  782.  
  783. print("Press Enter when done")
  784. repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  785. else
  786. print("Registering slots as compare slots")
  787. sleep(1)
  788. end
  789. for i=1, inventoryMax do
  790. if turtle.getItemCount(i) > 0 then
  791. if i ~= specialSlots.enderChest then
  792. table.insert(compareSlots, i) --Compare slots are ones compared to while mining. Conditions are because we Don't want to compare to enderChest
  793. allowedItems[i] = 1 --Blacklist is for dropping off items. The number is maximum items allowed in slot when dropping off
  794. dumpSlots[i] = true --We also want to ignore all excess of these items, like dirt
  795. end
  796. end
  797. end
  798. if extraDropItems then
  799. screen(1,1)
  800. print("Put in extra drop items now\n")
  801. print("Press Enter when done")
  802. repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  803. for i=1,inventoryMax do
  804. if not dumpSlots[i] and turtle.getItemCount(i) > 0 then --I don't want to modify from above, so I check it hasn't been assigned.
  805. dumpSlots[i] = true
  806. allowedItems[i] = 1
  807. end
  808. end
  809. end
  810. --This is could go very wrong if this isn't here
  811. if #compareSlots >= inventoryMax-keepOpen then screen(1,1); error("You have more quarry compare items than keep open slots, the turtle will continuously come back to start. Please fix.",0) end
  812. end
  813. local counter = 0
  814. for a, b in pairs(compareSlots) do if turtle.getItemCount(b) > 0 then counter = counter + 1 end end
  815. if counter == 0 then
  816. screen(1,1)
  817. print("You have an ore quarry without any compare slots. Continue? y/n")
  818. if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
  819. end
  820. elseif not oreQuarry then --This was screwing up dumpCompareItems
  821. dumpCompareItems = false --If not an ore quarry, this should definitely be false
  822. if specialSlots.enderChest == 1 then
  823. dumpSlots[2] = true
  824. else
  825. dumpSlots[1] = true
  826. end
  827. end
  828.  
  829. --Rednet Handshake
  830. function newMessageID()
  831. return math.random(1,2000000000)
  832. end
  833. function sendMessage(send, receive, message)
  834. return modem.transmit(send , receive, {fingerprint = channels.fingerprint, id = newMessageID(), message = message})
  835. end
  836. if rednetEnabled then
  837. screen(1,1)
  838. print("Rednet is Enabled")
  839. print("The Channel to open is "..channels.send)
  840. if peripheral.find then
  841. modem = peripheral.find("modem")
  842. else
  843. modem = peripheral.wrap("right")
  844. end
  845. modem.open(channels.receive)
  846. local i = 0
  847. repeat
  848. local id = os.startTimer(3)
  849. i=i+1
  850. print("Sending Initial Message "..i)
  851. sendMessage(channels.send, channels.receive, channels.message)
  852. local message = {} --Have to initialize as table to prevent index nil
  853. repeat
  854. local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  855. if locMessage then message = locMessage end
  856. until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and type(message) == "table")
  857. until message.message == channels.confirm
  858. connected = true
  859. print("Connection Confirmed!")
  860. sleep(1.5)
  861. end
  862. function biometrics(isAtBedrock)
  863. if not rednetEnabled then return end --This function won't work if rednet not enabled :P
  864. local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
  865. percent = percent, zPos = relzPos, xPos = relxPos, yPos = yPos,
  866. layersDone = layersDone, x = x, z = z, layers = layers,
  867. openSlots = getNumOpenSlots(), mined = mined, moved = moved,
  868. chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
  869. isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
  870. fuel = checkFuel(), volume = volume, status = statusString,
  871. }
  872. sendMessage(channels.send, channels.receive, toSend)
  873. id = os.startTimer(0.1)
  874. local event, received
  875. repeat
  876. local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  877. event, received = locEvent, locMessage or {message = ""}
  878. until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive and type(received) == "table")
  879. if event == "modem_message" then connected = true else connected = false end
  880. local message = received.message:lower()
  881. if message == "stop" or message == "quit" or message == "kill" then error("Rednet said to stop...",0) end
  882. if message == "return" then
  883. endingProcedure()
  884. error('Rednet said go back to start...',0)
  885. end
  886. if message == "drop" then
  887. dropOff()
  888. end
  889. if message == "pause" then
  890. print("\nTurtle is paused. Send 'resume' or press any character to resume")
  891. statusString = "Paused"
  892. repeat
  893. sleep(1) --The turtle sends out periodic messages, which will clear the receiver's queue and send a message (if it exists)
  894. sendMessage(channels.send, channels.receive, toSend) --This may be a bit overkill, sending the whole message again, but whatever.
  895. local event, idCheck, confirm, _, message, distance = os.pullEvent()
  896. until (event == "modem_message" and confirm == channels.receive and (message.message == "resume" or message.message == "unpause" or message.message == "pause")) or (event == "char")
  897. statusString = nil
  898. end
  899.  
  900. end
  901. --Showing changes to settings
  902. screen(1,1)
  903. print("Your selected settings:")
  904. if #changedT == 0 then
  905. print("Completely Default")
  906. else
  907. for i=1, #changedT do
  908. print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  909. end
  910. end
  911. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  912.  
  913.  
  914.  
  915. ----------------------------------------------------------------
  916. --Define ALL THE FUNCTIONS
  917. --Event System Functions
  918. function eventAddAt(pos, ...)
  919. return table.insert(events,pos, {...}) or true
  920. end
  921. function eventAdd(...) --Just a wrapper
  922. return eventAddAt(1, ...)
  923. end
  924. function eventGet(pos)
  925. return events[tonumber(pos) or #events]
  926. end
  927. function eventPop(pos)
  928. return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  929. end
  930. function eventRun(value, ...)
  931. local argsList = {...}
  932. if type(value) == "string" then
  933. if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  934. value = value .. "("
  935. for a, b in pairs(argsList) do --Appending arguments
  936. local toAppend
  937. if type(b) == "table" then toAppend = textutils.serialize(b)
  938. elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  939. else toAppend = tostring(b) end
  940. value = value .. (toAppend or "true") .. ", "
  941. end
  942. if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  943. value = value:sub(1,-3)..""
  944. end
  945. value = value .. ")"
  946. end
  947. --print(value) --Debug
  948. local func = loadstring(value)
  949. setfenv(func, getfenv(1))
  950. return func()
  951. end
  952. end
  953. function eventClear(pos)
  954. if pos then events[pos] = nil else events = {} end
  955. end
  956. function runAllEvents()
  957. while #events > 0 do
  958. local toRun = eventGet()
  959. --print(toRun[1]) --Debug
  960. eventRun(unpack(toRun))
  961. eventPop()
  962. end
  963. end
  964.  
  965. --Display Related Functions
  966. function display() --This is just the last screen that displays at the end
  967. screen(1,1)
  968. print("Total Blocks Mined: "..mined)
  969. print("Current Fuel Level: "..checkFuel())
  970. print("Cobble: "..totals.cobble)
  971. print("Usable Fuel: "..totals.fuel)
  972. print("Other: "..totals.other)
  973. if rednetEnabled then
  974. print("")
  975. print("Sent Stop Message")
  976. local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
  977. other = totals.other, fuel = checkFuel(), isDone = true }
  978. sendMessage(channels.send,channels.receive, finalTable)
  979. modem.close(channels.receive)
  980. end
  981. if doBackup then
  982. fs.delete(saveFile)
  983. if autoResume then --Getting rid of the original startup files and replacing
  984. fs.delete(startupName)
  985. if fs.exists(startupRename) then
  986. fs.move(startupRename, startupName)
  987. end
  988. end
  989. end
  990. end
  991. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  992. screen(1,1)
  993. print("Blocks Mined")
  994. print(mined)
  995. print("Percent Complete")
  996. print(percent.."%")
  997. print("Fuel")
  998. print(checkFuel())
  999. -- screen(1,1)
  1000. -- print("Xpos: ")
  1001. -- print(xPos)
  1002. -- print("RelXPos: ")
  1003. -- print(relxPos)
  1004. -- print("Z Pos: ")
  1005. -- print(zPos)
  1006. -- print("Y pos: ")
  1007. -- print(yPos)
  1008. if rednetEnabled then
  1009. screenLine(1,7)
  1010. print("Connected: "..tostring(connected))
  1011. end
  1012. end
  1013. --Utility functions
  1014. function logMiningRun(textExtension, extras) --Logging mining runs
  1015. if not logging then return end
  1016. local number, name = 0
  1017. if not fs.isDir(logFolder) then
  1018. fs.delete(logFolder)
  1019. fs.makeDir(logFolder)
  1020. end
  1021. repeat
  1022. number = number + 1 --Number will be at least 2
  1023. name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
  1024. until not fs.exists(name)
  1025. local handle = fs.open(name,"w")
  1026. local function write(...)
  1027. for a, b in ipairs({...}) do
  1028. handle.write(tostring(b))
  1029. end
  1030. handle.write("\n")
  1031. end
  1032. local function boolToText(bool) if bool then return "Yes" else return "No" end end
  1033. write("Welcome to the Quarry Logs!")
  1034. write("Entry Number: ",number)
  1035. write("Quarry Version: ",VERSION)
  1036. write("Dimensions (X Z Y): ",x," ",z," ", y)
  1037. write("Blocks Mined: ", mined)
  1038. write(" Cobble: ", totals.cobble)
  1039. write(" Usable Fuel: ", totals.fuel)
  1040. write(" Other: ",totals.other)
  1041. write("Total Fuel Used: ", (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  1042. write("Expected Fuel Use: ", neededFuel)
  1043. write("Days to complete mining run: ",os.day()-originalDay)
  1044. write("Day Started: ", originalDay)
  1045. write("Number of times resumed: ", numResumed)
  1046. write("Was an ore quarry? ",boolToText(oreQuarry or oldOreQuarry))
  1047. write("Was inverted? ",boolToText(invert))
  1048. write("Was using rednet? ",boolToText(rednetEnabled))
  1049. write("Chest was on the ",dropSide," side")
  1050. if startDown > 0 then write("Started ",startDown," blocks down") end
  1051. handle.close()
  1052. end
  1053. --Inventory related functions
  1054. function isFull(slots) --Checks if there are more than "slots" used inventory slots.
  1055. slots = slots or inventoryMax
  1056. local numUsed = 0
  1057. sleep(0)
  1058. for i=1, inventoryMax do
  1059. if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  1060. end
  1061. if numUsed > slots then
  1062. return true
  1063. end
  1064. return false
  1065. end
  1066. function countUsedSlots() --Returns number of slots with items in them, as well as a table of item counts
  1067. local toRet, toRetTab = 0, {}
  1068. for i=1, inventoryMax do
  1069. local a = turtle.getItemCount(i)
  1070. if a > 0 then toRet = toRet + 1 end
  1071. table.insert(toRetTab, a)
  1072. end
  1073. return toRet, toRetTab
  1074. end
  1075. function getSlotsTable() --Just get the table from above
  1076. local _, toRet = countUsedSlots()
  1077. return toRet
  1078. end
  1079. function getChangedSlots(tab1, tab2) --Returns a table of changed slots. Format is {slotNumber, numberChanged}
  1080. local toRet = {}
  1081. for i=1, min(#tab1, #tab2) do
  1082. diff = math.abs(tab2[i]-tab1[i])
  1083. if diff > 0 then
  1084. table.insert(toRet, {i, diff})
  1085. end
  1086. end
  1087. return toRet
  1088. end
  1089. function getFirstChanged(tab1, tab2) --Just a wrapper. Probably not needed
  1090. local a = getChangedSlots(tab1,tab2)
  1091. return (a[1] or {"none"})[1]
  1092. end
  1093.  
  1094. function getRep(which, list) --Gets a representative slot of a type. Expectation is a sequential table of types
  1095. for a,b in pairs(list) do
  1096. if b == which then return a end
  1097. end
  1098. return false
  1099. end
  1100. function assignTypes(types, count) --The parameters allow a preexisting table to be used, like a table from the original compareSlots...
  1101. types, count = types or {1}, count or 1 --Table of types and current highest type
  1102. for i=1, inventoryMax do
  1103. if turtle.getItemCount(i) > 0 and not specialSlots[i] then --Not special slots so we don't count ender chests
  1104. select(i)
  1105. for k=1, count do
  1106. if turtle.compareTo(getRep(k, types)) then types[i] = k end
  1107. end
  1108. if not types[i] then
  1109. count = count + 1
  1110. types[i] = count
  1111. end
  1112. if oreQuarry then
  1113. if blacklist[turtle.getItemDetail().name] then
  1114. dumpSlots[i] = true
  1115. else
  1116. dumpSlots[i] = false
  1117. end
  1118. end
  1119. end
  1120. end
  1121. select(1)
  1122. return types, count
  1123. end
  1124. function getTableOfType(which, list) --Returns a table of all the slots of which type
  1125. local toRet = {}
  1126. for a, b in pairs(list) do
  1127. if b == which then
  1128. table.insert(toRet, a)
  1129. end
  1130. end
  1131. return toRet
  1132. end
  1133.  
  1134. --This is so the turtle will properly get types, otherwise getRep of a type might not be a dumpSlot, even though it should be.
  1135. if not restoreFoundSwitch then --We only want this to happen once
  1136. if oldOreQuarry then --If its not ore quarry, this screws up type assigning
  1137. initialTypes, initialCount = assignTypes()
  1138. else
  1139. initialTypes, initialCount = {1}, 1
  1140. end
  1141. end
  1142.  
  1143. function count(add) --Done any time inventory dropped and at end, true=add, false=nothing, nil=subtract
  1144. local mod = -1
  1145. if add then mod = 1 end
  1146. if add == false then mod = 0 end
  1147. slot = {} --1: Filler 2: Fuel 3:Other --[1] is type, [2] is number
  1148. for i=1, inventoryMax do
  1149. slot[i] = {}
  1150. slot[i][2] = turtle.getItemCount(i)
  1151. end
  1152.  
  1153. local function iterate(toSet , rawTypes, set)
  1154. for _, a in pairs(getTableOfType(toSet, rawTypes)) do --Get all slots matching type
  1155. slot[a][1] = set --Set official type to "set"
  1156. end
  1157. end
  1158.  
  1159. --This assigns "dumb" types to all slots based on comparing, then based on knowledge of dump type slots, changes all slots matching a dump type to one. Otherwise, if the slot contains fuel, it is 2, else 3
  1160. local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount) --This gets increasingly numbered types, copyTable because assignTypes will modify it
  1161.  
  1162. for i=1, numTypes do
  1163. if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then --Selects the rep slot, checks if it is fuel
  1164. iterate(i, rawTypes, 2) --This type is fuel
  1165. elseif dumpSlots[getRep(i,(oreQuarry and rawTypes) or initialTypes)] then --If the rep of this slot is a dump item. This is initial types so that the rep is in dump slots. rawTypes if oreQuarry to get newly assigned dumps
  1166. iterate(i, rawTypes, 1) --This type is cobble/filler
  1167. else
  1168. iterate(i, rawTypes, 3) --This type is other
  1169. end
  1170. end
  1171.  
  1172. for i=1,inventoryMax do
  1173. if specialSlots[i] then --Do nothing!
  1174. elseif slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
  1175. elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
  1176. elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
  1177. end
  1178.  
  1179. select(1)
  1180. end
  1181.  
  1182. --Mining functions
  1183. function dig(doAdd, mineFunc, inspectFunc) --Note, turtle will not bother comparing if not given an inspectFunc
  1184. if doAdd == nil then doAdd = true end
  1185. mineFunc = mineFunc or p.dig
  1186. local function retTab(tab) if type(tab) == "table" then return tab end end --Please ignore the stupid one-line trickery. I felt special writing that. (Unless it breaks, then its cool)
  1187. --Mine if not in blacklist. inspectFunc returns success and (table or string) so retTab filters out the string and the extra table prevents errors.
  1188. if not oreQuarry or not inspectFunc or not blacklist[(retTab(({inspectFunc()})[2]) or {name = "none"}).name] then --Will stop at first false, last part won't run if one of first are false
  1189. if mineFunc() then
  1190. if doAdd then
  1191. mined = mined + 1
  1192. end
  1193. return true
  1194. else
  1195. return false
  1196. end
  1197. end
  1198. return true --This only runs if oreQuarry but item not in blacklist
  1199. end
  1200.  
  1201.  
  1202.  
  1203. function digUp(doAdd, ignoreInspect)--Regular functions :) I switch definitions for optimization (I think)
  1204. return dig(doAdd, p.digUp, (not ignoreInspect and turtle.inspectUp) or nil)
  1205. end
  1206. function digDown(doAdd, ignoreInspect)
  1207. return dig(doAdd, p.digDown, (not ignoreInspect and turtle.inspectDown) or nil)
  1208. end
  1209. if inverted then --If inverted, switch the options
  1210. digUp, digDown = digDown, digUp
  1211. end
  1212.  
  1213. function smartDig(doDigUp, doDigDown) --This function is used only in mine when oldOreQuarry
  1214. if inverted then doDigUp, doDigDown = doDigDown, doDigUp end --Switching for invert
  1215. local blockAbove, blockBelow = doDigUp and turtle.detectUp(), doDigDown and turtle.detectDown() --These control whether or not the turtle digs
  1216. local index = 1
  1217. for i=1, #compareSlots do
  1218. if not (blockAbove or blockBelow) then break end --We don't want to go selecting if there is nothing to dig
  1219. index = i --To access out of scope
  1220. select(compareSlots[i])
  1221. if blockAbove and turtle.compareUp() then blockAbove = false end
  1222. if blockBelow and turtle.compareDown() then blockBelow = false end
  1223. end
  1224. table.insert(compareSlots, 1, table.remove(compareSlots, index)) --This is so the last selected slot is the first slot checked, saving a select call
  1225. if blockAbove then dig(true, p.digUp) end
  1226. if blockBelow then dig(true, p.digDown) end
  1227. end
  1228.  
  1229. function relxCalc()
  1230. if layersDone % 2 == 1 then
  1231. relzPos = zPos
  1232. else
  1233. relzPos = (z-zPos) + 1
  1234. end
  1235. if relzPos % 2 == 1 then
  1236. relxPos = xPos
  1237. else
  1238. relxPos = (x-xPos)+1
  1239. end
  1240. if layersDone % 2 == 0 and z % 2 == 1 then
  1241. relxPos = (x-relxPos)+1
  1242. end
  1243. end
  1244. function forward(doAdd)
  1245. if doAdd == nil then doAdd = true end
  1246. if turtle.forward() then
  1247. if doAdd then
  1248. moved = moved + 1
  1249. end
  1250. if facing == 0 then
  1251. xPos = xPos + 1
  1252. elseif facing == 1 then
  1253. zPos = zPos + 1
  1254. elseif facing == 2 then
  1255. xPos = xPos - 1
  1256. elseif facing == 3 then
  1257. zPos = zPos - 1
  1258. else
  1259. error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  1260. end
  1261. relxCalc()
  1262. return true
  1263. end
  1264. return false
  1265. end
  1266. function verticalMove(moveFunc, yDiff, digFunc, attackFunc)
  1267. local count = 0
  1268. while not moveFunc() do
  1269. if not digFunc(true, true) then --True True is doAdd, and ignoreInspect
  1270. attackFunc()
  1271. sleep(0.5)
  1272. count = count + 1
  1273. if count > maxTries then bedrock() end
  1274. end
  1275. end
  1276. yPos = yDiff + yPos
  1277. saveProgress()
  1278. biometrics()
  1279. return true
  1280. end
  1281. function up() --Uses other function if inverted
  1282. verticalMove(inverted and turtle.down or turtle.up, -1, digUp, attackUp) --Other functions deal with invert already
  1283. end
  1284. function down()
  1285. verticalMove(inverted and turtle.up or turtle.down, 1, digDown, attackDown)
  1286. end
  1287.  
  1288.  
  1289. function right(num)
  1290. num = num or 1
  1291. for i=1, num do
  1292. facing = coterminal(facing+1)
  1293. saveProgress()
  1294. if not goLeftNotRight then turtle.turnRight() --Normally
  1295. else turtle.turnLeft() end --Left Quarry
  1296. end
  1297. end
  1298. function left(num)
  1299. num = num or 1
  1300. for i=1, num do
  1301. facing = coterminal(facing-1)
  1302. saveProgress()
  1303. if not goLeftNotRight then turtle.turnLeft() --Normally
  1304. else turtle.turnRight() end --Left Quarry
  1305. end
  1306. end
  1307.  
  1308. function attack(doAdd, func)
  1309. doAdd = doAdd or true
  1310. func = func or turtle.attack
  1311. if func() then
  1312. if doAdd then
  1313. attacked = attacked + 1
  1314. end
  1315. return true
  1316. end
  1317. return false
  1318. end
  1319. function attackUp(doAdd)
  1320. if inverted then
  1321. return attack(doAdd, turtle.attackDown)
  1322. else
  1323. return attack(doAdd, turtle.attackUp)
  1324. end
  1325. end
  1326. function attackDown(doAdd)
  1327. if inverted then
  1328. return attack(doAdd, turtle.attackUp)
  1329. else
  1330. return attack(doAdd, turtle.attackDown)
  1331. end
  1332. end
  1333.  
  1334. function detect(func)
  1335. func = func or turtle.detect
  1336. return func()
  1337. end
  1338. function detectUp(ignoreInvert)
  1339. if inverted and not ignoreInvert then return detect(turtle.detectDown)
  1340. else return detect(turtle.detectUp) end
  1341. end
  1342. function detectDown(ignoreInvert)
  1343. if inverted and not ignoreInvert then return detect(turtle.detectUp)
  1344. else return detect(turtle.detectDown) end
  1345. end
  1346.  
  1347.  
  1348.  
  1349. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  1350. if doCheckInv == nil then doCheckInv = true end
  1351. if doDigDown == nil then doDigDown = true end
  1352. if doDigUp == nil then doDigUp = true end
  1353. if outOfPath == nil then outOfPath = false end
  1354. isInPath = (not outOfPath) --For rednet
  1355. if not outOfPath and (checkFuel() <= xPos + zPos + yPos + 5) then --If the turtle can just barely get back to the start, we need to get it there. We don't want this to activate coming back though...
  1356. local continueEvac = true --This turns false if more fuel is acquired
  1357. if fuelChestEnabled then --This is pretty much the only place that this will be used
  1358. if not fuelChestPhase then --Since I want to do things with return of enderRefuel, I will just make a special system
  1359. fuelChestPhase = 0 --Global variable will be saved
  1360. fuelChestProperFacing = facing
  1361. end
  1362. if fuelChestPhase == 0 then
  1363. turnTo(coterminal(fuelChestProperFacing+2))
  1364. dig(false)
  1365. fuelChestPhase = 1
  1366. saveProgress()
  1367. end
  1368. if fuelChestPhase == 1 then
  1369. select(specialSlots.fuelChest)
  1370. turtle.place()
  1371. fuelChestPhase = 2
  1372. saveProgress()
  1373. end
  1374. if fuelChestPhase == 2 then
  1375. if not enderRefuel() then --Returns false if slots are full
  1376. select(specialSlots.fuelChest)
  1377. turtle.drop() --Somehow stuff got in here...
  1378. end
  1379. fuelChestPhase = 3
  1380. saveProgress()
  1381. end
  1382. if fuelChestPhase == 3 then
  1383. select(specialSlots.fuelChest)
  1384. dig(false)
  1385. select(1)
  1386. fuelChestPhase = 4
  1387. saveProgress()
  1388. end
  1389. if fuelChestPhase == 4 then
  1390. turnTo(fuelChestProperFacing)
  1391. fuelChestProperFacing = nil --Getting rid of saved values
  1392. fuelChestPhase = nil
  1393. continueEvac = false
  1394. end
  1395. elseif doRefuel then --Attempt an emergency refueling
  1396. screen()
  1397. print("Attempting an emergency refuel")
  1398. print("Fuel Level: ",checkFuel())
  1399. print("Distance Back: ",(xPos+zPos+yPos+1))
  1400. print("Categorizing Items")
  1401. count(false) --Do not add count, but categorize
  1402. local fuelSwitch, initialFuel = false, checkFuel() --Fuel switch so we don't go over limit (in emergency...)
  1403. print("Going through available fuel slots")
  1404. for i=1, inventoryMax do
  1405. if fuelSwitch then break end
  1406. if turtle.getItemCount(i) > 0 and slot[i][1] == 2 then --If there are items and type 2 (fuel)
  1407. select(i)
  1408. fuelSwitch = midRunRefuel(i) --See above "function drop" for usage
  1409. end
  1410. end
  1411. select(1) --Cleanup
  1412. print("Done fueling")
  1413. if checkFuel() > initialFuel then
  1414. continueEvac = false
  1415. print("Evac Aborted")
  1416. else
  1417. print("Evac is a go, returning to base")
  1418. sleep(1.5) --Pause for reading
  1419. end
  1420. end
  1421. if continueEvac then
  1422. eventClear() --Clear any annoying events for evac
  1423. endingProcedure() --End the program
  1424. print("Turtle ran low on fuel so was brought back to start for you :)\n\nTo resume where you left off, use '-startDown "..tostring(yPos-1).."' when you start")
  1425. error("",0)
  1426. end
  1427. end
  1428. local count = 0
  1429. if not outOfPath then dig() end --This speeds up the quarry by a decent amount if there are more mineable blocks than air
  1430. while not forward(not outOfPath) do
  1431. sleep(0) --Calls coroutine.yield to prevent errors
  1432. count = count + 1
  1433. if not dig() then
  1434. attack()
  1435. end
  1436. if count > 10 then
  1437. attack()
  1438. sleep(0.2)
  1439. end
  1440. if count > maxTries then
  1441. if checkFuel() == 0 then --Don't worry about inf fuel because I modified this function
  1442. saveProgress({doCheckFuel = true})
  1443. error("No more fuel",0)
  1444. elseif yPos > (startY-7) and turtle.detect() then --If it is near bedrock
  1445. bedrock()
  1446. else --Otherwise just sleep for a bit to avoid sheeps
  1447. sleep(1)
  1448. end
  1449. end
  1450. end
  1451. checkSanity() --Not kidding... This is necessary
  1452. saveProgress(tab)
  1453.  
  1454. if not oldOreQuarry then
  1455. if doDigUp then--The digging up and down part
  1456. sleep(0) --Calls coroutine.yield
  1457. if not digUp(true) and detectUp() then --This is relative: will dig down first on invert
  1458. if not attackUp() then
  1459. if yPos > (startY-7) then bedrock() end --Checking for bedrock, but respecting user wishes
  1460. end
  1461. end
  1462. end
  1463. if doDigDown then
  1464. digDown(true) --This needs to be absolute as well
  1465. end
  1466. else --If oldQuarry
  1467. smartDig(doDigUp,doDigDown)
  1468. end
  1469. percent = math.ceil(moved/moveVolume*100)
  1470. updateDisplay()
  1471. if doCheckInv and careAboutResources then
  1472. if isFull(inventoryMax-keepOpen) then dropOff() end
  1473. end
  1474. biometrics()
  1475. end
  1476. --Insanity Checking
  1477. function checkSanity()
  1478. if not isInPath then --I don't really care if its not in the path.
  1479. return true
  1480. end
  1481. if not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  1482. turnTo(0)
  1483. rowCheck = true
  1484. end
  1485. if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  1486. saveProgress()
  1487. print("I have gone outside boundaries, attempting to fix (maybe)")
  1488. if xPos > x then goto(x, zPos, yPos, 2) end --I could do this with some fancy math, but this is much easier
  1489. if xPos < 0 then goto(1, zPos, yPos, 0) end
  1490. if zPos > z then goto(xPos, z, yPos, 3) end
  1491. if zPos < 0 then goto(xPos, 1, yPos, 1) end
  1492. relxCalc() --Get relxPos properly
  1493. eventClear()
  1494.  
  1495. --[[
  1496. print("Oops. Detected that quarry was outside of predefined boundaries.")
  1497. print("Please go to my forum thread and report this with a short description of what happened")
  1498. print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  1499. error("",0)]]
  1500. end
  1501. end
  1502.  
  1503. local function fromBoolean(input) --Like a calculator
  1504. if input then return 1 end
  1505. return 0
  1506. end
  1507. local function multBoolean(first,second) --Boolean multiplication
  1508. return (fromBoolean(first) * fromBoolean(second)) == 1
  1509. end
  1510. function coterminal(num, limit) --I knew this would come in handy :D
  1511. limit = limit or 4 --This is for facing
  1512. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  1513. end
  1514. if tArgs["-manualpos"] then
  1515. facing = coterminal(facing) --Done to improve support for "-manualPos"
  1516. if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end --Ditto
  1517. relxCalc() --Ditto
  1518. end
  1519.  
  1520. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  1521. function turnTo(num)
  1522. num = num or facing
  1523. num = coterminal(num) --Prevent errors
  1524. local turnRight = true
  1525. if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  1526. while facing ~= num do --The above is used to smartly turn
  1527. if turnRight then
  1528. right()
  1529. else
  1530. left()
  1531. end
  1532. end
  1533. end
  1534. function goto(x,z,y, toFace, destination)
  1535. --Will first go to desired z pos, then x pos, y pos varies
  1536. x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  1537. gotoDest = destination or "" --This is used by biometrics.
  1538. statusString = "Going somewhere"
  1539. --Possible destinations: layerStart, quarryStart
  1540. if yPos > y then --Will go up first if below position
  1541. while yPos~=y do up() end
  1542. end
  1543. if zPos > z then
  1544. turnTo(3)
  1545. elseif zPos < z then
  1546. turnTo(1)
  1547. end
  1548. while zPos ~= z do mine(false,false,true,false) end
  1549. if xPos > x then
  1550. turnTo(2)
  1551. elseif xPos < x then
  1552. turnTo(0)
  1553. end
  1554. while xPos ~= x do mine(false,false,true,false) end
  1555. if yPos < y then --Will go down after if above position
  1556. while yPos~=y do down() end
  1557. end
  1558. turnTo(toFace)
  1559. saveProgress()
  1560. gotoDest = ""
  1561. statusString = nil
  1562. end
  1563. function getNumOpenSlots()
  1564. local toRet = 0
  1565. for i=1, inventoryMax do
  1566. if turtle.getItemCount(i) == 0 then
  1567. toRet = toRet + 1
  1568. end
  1569. end
  1570. return toRet
  1571. end
  1572.  
  1573. --Ideas: Bring in inventory change-checking functions, count blocks that have been put in, so it will wait until all blocks have been put in.
  1574. local function waitDrop(slot, allowed, whereDrop) --This will just drop, but wait if it can't
  1575. allowed = allowed or 0
  1576. while turtle.getItemCount(slot) > allowed do --No more half items stuck in slot!
  1577. local tries = 1
  1578. while not whereDrop(turtle.getItemCount(slot)-allowed) do --Drop off only the amount needed
  1579. screen(1,1)
  1580. print("Chest Full, Try "..tries)
  1581. chestFull = true
  1582. biometrics()--To send that the chest is full
  1583. tries = tries + 1
  1584. sleep(2)
  1585. end
  1586. chestFull = false
  1587. end
  1588. end
  1589.  
  1590. function midRunRefuel(i, allowed)
  1591. allowed = allowed or allowedItems[i]
  1592. local numToRefuel = turtle.getItemCount(i)-allowed
  1593. if checkFuel() >= checkFuelLimit() then return true end --If it doesn't need fuel, then signal to not take more
  1594. local firstCheck = checkFuel()
  1595. if numToRefuel > 0 then turtle.refuel(1) end --This is so we can see how many fuel we need.
  1596. local singleFuel
  1597. if checkFuel() - firstCheck > 0 then singleFuel = checkFuel() - firstCheck else singleFuel = math.huge end --If fuel is 0, we want it to be huge so the below will result in 0 being taken
  1598. --Refuel The lesser of max allowable or remaining fuel space / either inf or a single fuel (which can be 0)
  1599. turtle.refuel(math.min(numToRefuel-1, math.ceil((checkFuelLimit()-checkFuel()) / singleFuel))) --The refueling part of the the doRefuel option
  1600. if checkFuel() >= checkFuelLimit() then return true end --Do not need any more fuel
  1601. return false --Turtle can still be fueled
  1602. end
  1603.  
  1604. function enderRefuel() --Assumes a) An enderchest is in front of it b) It needs fuel
  1605. local slot
  1606. for a,b in ipairs(getSlotsTable()) do
  1607. if b == 0 then slot = a; break end
  1608. end
  1609. if not slot then return false end --No room for fueling
  1610. select(slot)
  1611. repeat
  1612. print("Required Fuel: ",excessFuelAmount)
  1613. print("Current Fuel: ",checkFuel())
  1614. local tries = 0
  1615. while not turtle.suck() do
  1616. sleep(1)
  1617. statusString = "No Fuel in Ender Chest"
  1618. biometrics() --Let user know that fuel chest is empty
  1619. print(statusString,". Try: ",tries)
  1620. tries = tries + 1
  1621. end
  1622. statusString = nil
  1623. until midRunRefuel(slot, 0) --Returns true when should not refuel any more
  1624. if not turtle.drop() then turtle.dropDown() end --If cannot put fuel back, just drop it, full fuel chest = user has too much fuel already
  1625. return true -- :D
  1626. end
  1627.  
  1628.  
  1629. function drop(side, final)
  1630. side = sides[side] or "front"
  1631. local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
  1632. if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
  1633. if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
  1634. if side == "right" then turnTo(1); dropFacing = 0 end
  1635. if side == "left" then turnTo(3); dropFacing = 0 end
  1636. local properFacing = facing --Capture the proper direction to be facing
  1637.  
  1638. count(true) --Count number of items before drop. True means add. This is before chest detect, because could be final
  1639.  
  1640. while not detectFunc() do
  1641. if final then return end --If final, we don't need a chest to be placed, but there can be
  1642. chestFull = true
  1643. biometrics() --Let the user know there is a problem with chest
  1644. screen(1,1) --Clear screen
  1645. print("Waiting for chest placement on ",side," side (when facing quarry)")
  1646. sleep(2)
  1647. end
  1648. chestFull = false
  1649.  
  1650. local fuelSwitch = false --If doRefuel, this can switch so it won't overfuel
  1651. for i=1,inventoryMax do
  1652. --if final then allowedItems[i] = 0 end --0 items allowed in all slots if final ----It is already set to 1, so just remove comment if want change
  1653. if turtle.getItemCount(i) > 0 then --Saves time, stops bugs
  1654. if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing) --Turn around to drop junk, not store it. dumpComapareItems is global config
  1655. else turnTo(properFacing) --Turn back to proper position... or do nothing if already there
  1656. end
  1657. select(i)
  1658. if doRefuel and slot[i][1] == 2 then --Intelligently refuels to fuel limit
  1659. if not fuelSwitch then --Not in the conditional because we don't want to waitDrop excess fuel. Not a break so we can drop junk
  1660. fuelSwitch = midRunRefuel(i)
  1661. end
  1662. else
  1663. waitDrop(i, allowedItems[i], dropFunc)
  1664. end
  1665. end
  1666. end
  1667.  
  1668. if oldOreQuarry then count(nil) end--Subtract the items still there if oreQuarry
  1669. resetDumpSlots() --So that slots gone aren't counted as dump slots next
  1670.  
  1671. select(1) --For fanciness sake
  1672.  
  1673. end
  1674.  
  1675. function dropOff() --Not local because called in mine()
  1676. local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  1677. if careAboutResources then
  1678. if not enderChestEnabled then --Regularly
  1679. eventAdd("goto", 1,1,currY,2) --Need this step for "-startDown"
  1680. eventAdd("goto(0,1,1,2)")
  1681. eventAdd("drop", dropSide,false)
  1682. eventAdd("turnTo(0)")
  1683. eventAdd("mine",false,false,true,false)
  1684. eventAdd("goto(1,1,1, 0)")
  1685. eventAdd("goto", 1, 1, currY, 0)
  1686. eventAdd("goto", currX,currZ,currY,currFacing)
  1687. else --If using an enderChest
  1688. if turtle.getItemCount(specialSlots.enderChest) ~= 1 then eventAdd("promptSpecialSlot('enderChest','Ender Chest')") end
  1689. eventAdd("turnTo",currFacing-2)
  1690. eventAdd("dig",false)
  1691. eventAdd("select",specialSlots.enderChest)
  1692. eventAdd("turtle.place")
  1693. eventAdd("drop","front",false)
  1694. eventAdd("turnTo",currFacing-2)
  1695. eventAdd("select", specialSlots.enderChest)
  1696. eventAdd("dig",false)
  1697. eventAdd("turnTo",currFacing)
  1698. eventAdd("select(1)")
  1699. end
  1700. runAllEvents()
  1701. numDropOffs = numDropOffs + 1 --Analytics tracking
  1702. end
  1703. return true
  1704. end
  1705. function endingProcedure() --Used both at the end and in "biometrics"
  1706. eventAdd("goto",1,1,yPos,2,"quarryStart") --Allows for startDown variable
  1707. eventAdd("goto",0,1,1,2, "quarryStart") --Go back to base
  1708. runAllEvents()
  1709. --Output to a chest or sit there
  1710. if enderChestEnabled then
  1711. if dropSide == "right" then eventAdd("turnTo(1)") end --Turn to proper drop side
  1712. if dropSide == "left" then eventAdd("turnTo(3)") end
  1713. eventAdd("dig(false)") --This gets rid of a block in front of the turtle.
  1714. eventAdd("select",specialSlots.enderChest)
  1715. eventAdd("turtle.place")
  1716. eventAdd("select(1)")
  1717. end
  1718. eventAdd("drop",dropSide, true)
  1719. eventAdd("turnTo(0)")
  1720.  
  1721. --Display was moved above to be used in bedrock function
  1722. eventAdd("display")
  1723. --Log current mining run
  1724. eventAdd("logMiningRun",logExtension)
  1725. toQuit = true --I'll use this flag to clean up (legacy)
  1726. runAllEvents()
  1727. end
  1728. function bedrock()
  1729. foundBedrock = true --Let everyone know
  1730. if rednetEnabled then biometrics() end
  1731. if checkFuel() == 0 then error("No Fuel",0) end
  1732. local origin = {x = xPos, y = yPos, z = zPos}
  1733. print("Bedrock Detected")
  1734. if turtle.detectUp() and not p.digUp() then
  1735. print("Block Above")
  1736. local var
  1737. if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end
  1738. goto(xPos,zPos,yPos,var)
  1739. for i=1, relxPos do mine(false, false); end
  1740. else
  1741. up() --Go up two to avoid any bedrock.
  1742. up()
  1743. end
  1744. eventClear() --Get rid of any excess events that may be run. Don't want that.
  1745. endingProcedure()
  1746. print("\nFound bedrock at these coordinates: ")
  1747. print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  1748. error("",0)
  1749. end
  1750.  
  1751. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  1752. local halfFacing = ((layersDone % 2 == 1) and 1) or 3
  1753. local toFace = coterminal(wasFacing + 2) --Opposite side
  1754. if zPos == startZ then
  1755. if facing ~= halfFacing then turnTo(halfFacing) end
  1756. mine(unpack(mineFunctionTable or {}))
  1757. end
  1758. if facing ~= toFace then
  1759. turnTo(toFace)
  1760. end
  1761. end
  1762.  
  1763.  
  1764. -------------------------------------------------------------------------------------
  1765. --Pre-Mining Stuff dealing with session persistence
  1766. runAllEvents()
  1767. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  1768.  
  1769. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  1770. if not restoreFoundSwitch then --Regularly
  1771. --Check if it is a mining turtle
  1772. if not isMiningTurtle then
  1773. local a, b = p.dig()
  1774. if a then
  1775. mined = mined + 1
  1776. isMiningTurtle = true
  1777. elseif b == "Nothing to dig with" or b == "No tool to dig with" then
  1778. print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  1779. error("",0)
  1780. end
  1781. end
  1782. mine(false,false,true) --Get into quarry by going forward one
  1783. if gpsEnabled and not restoreFoundSwitch then --The initial locate is done in the arguments. This is so I can figure out what quadrant the turtle is in.
  1784. gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  1785. end
  1786. for i = 1, startDown do
  1787. eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  1788. end
  1789. runAllEvents()
  1790. if flatBedrock then
  1791. while (detectDown() and digDown(false)) or not detectDown() do --None of these functions are non-invert protected because inverse always false here
  1792. down()
  1793. startDown = startDown + 1
  1794. end
  1795. startDown = startDown - y + 1
  1796. for i=1, y-2 do
  1797. up() --It has hit bedrock, now go back up for proper 3 wide mining
  1798. end
  1799. elseif not(y == 1 or y == 2) then
  1800. down() --Go down to align properly. If y is one or two, it doesn't need to do this.
  1801. end
  1802. else --restore found
  1803. if not(layersDone == layers and not doDigDown) then digDown() end
  1804. if not(layersDone == layers and not doDigUp) then digUp() end --Get blocks missed before stopped
  1805. end
  1806. --Mining Loops--------------------------------------------------------------------------
  1807. select(1)
  1808. while layersDone <= layers do -------------Height---------
  1809. local lastLayer = layersDone == layers --If this is the last layer
  1810. local secondToLastLayer = (layersDone + 1) == layers --This is a check for going down at the end of a layer.
  1811. moved = moved + 1 --To account for the first position in row as "moved"
  1812. if not(layersDone == layers and not doDigDown) then digDown() end --This is because it doesn't mine first block in layer
  1813. if not restoreFoundSwitch and layersDone % 2 == 1 then rowCheck = true end
  1814. relxCalc()
  1815. while relzPos <= z do -------------Width----------
  1816. while relxPos < x do ------------Length---------
  1817. mine(not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)) --This will be the idiom that I use for the mine function
  1818. end ---------------Length End-------
  1819. if relzPos ~= z then --If not on last row of section
  1820. local func
  1821. if rowCheck == true then --Switching to next row
  1822. func = "right"; rowCheck = false; else func = false; rowCheck = true end --Which way to turn
  1823. eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  1824. runAllEvents()
  1825. else break
  1826. end
  1827. end ---------------Width End--------
  1828. if layersDone % 2 == 0 then --Will only go back to start on non-even layers
  1829. eventAdd("goto",1,1,yPos,0, "layerStart") --Goto start of layer
  1830. else
  1831. eventAdd("turnTo",coterminal(facing-2))
  1832. end
  1833. if not lastLayer then --If there is another layer
  1834. for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do eventAdd("down()") end --The fromBoolean stuff means that if lastheight is 1 and last and layer, will only go down two
  1835. end
  1836. eventAdd("relxCalc")
  1837. layersDone = layersDone + 1
  1838. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  1839. runAllEvents()
  1840. end ---------------Height End-------
  1841.  
  1842. endingProcedure() --This takes care of getting to start, dropping in chest, and displaying ending screen
Advertisement
Add Comment
Please, Sign In to add comment