Justiik

Quarry Turtle Left

Sep 27th, 2021 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 100.00 KB | None | 0 0
  1. --Civilwargeeky's Quarry Program--
  2. VERSION = "3.6.4.5"
  3. --[[
  4. Recent Changes:
  5. Parameter Files! Create a file of parameters, and use -file to load it!
  6. Works will with -forcePrompt
  7. Quarry no longer goes to start at end of row!
  8. Turtle can go left!
  9. QuadCopters! Check Lyqyd's thread
  10. New Parameters:
  11. -overfuel/fuelMultiplier [number]: This number is is what neededFuel is multiplied by when fuel is low.
  12. -version: This will display the current version number and end the program
  13. -file [fileName]: This will load a custom configuration file (basically a list of parameters). "##" starts comment lines. In the future "#" will start programs to run (but only through shell)
  14. -preciseTotals [t/f]: If true, turtle will write exactly what it mined to the logs. It may also transmit it over rednet.
  15. -forcePrompt [param]: This will add to a list of parameters to force prompt for. So if you say "-forcePrompt doRefuel" it will prompt you "Length","Width","Height","Invert","Do Refuel" etc.
  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 = 16,30,16 --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. fuelMultiplier = 1 --How much extra fuel turtle will ask for when it does need fuel [Default 1]
  35. saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"]
  36. autoResume = true --If true, turtle will auto-restart when loaded. [Default true]
  37. startupRename = "oldStartup.quarry" --What the startup is temporarily renamed to [Default "oldStartup.quarry"]
  38. startupName = "startup" --What the turtle auto-resumes with [Default "startup"]
  39. doBackup = true --If it will keep backups for session persistence [Default true]
  40. uniqueExtras = 8 --How many different items (besides cobble) the turtle expects. [Default 8]
  41. maxTries = 200 --How many times turtle will try to dig a block before it "counts" bedrock [Default 200]
  42. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  43. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  44. legacyRednet = false --Use this if playing 1.4.7
  45. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  46. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  47. logExtension = "" --The extension of the file (e.g. ".txt") [Default ""]
  48. flatBedrock = false --If true, will go down to bedrock to set startDown [Default false]
  49. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  50. preciseTotals = false --If true, will record exact totals and names for all materials [Default false]
  51. goLeftNotRight = false --Quarry to left, not right (parameter is "left") [Default false]
  52. oreQuarry = false --Enables ore quarry functionality [Default false]
  53. oreQuarryBlacklistName = "oreQuarryBlacklist.txt" --This is the file that will be parsed for item names [Default "oreQuarryBlacklist"]
  54. dumpCompareItems = true --If ore quarry, the turtle will dump items compared to (like cobblestone) [Default true]
  55. frontChest = false --If oreQuarry and chest checking, you can turn this on to make turtle check in front of itself for chests as well [Default false]
  56. lavaBuffer = 500 --If using a lava bucket, this is the buffer it will wait for before checking for lava [Default 500]
  57. inventoryMax = 16 --The max number of slots in the turtle inventory [Default 16] (Not assignable by parameter)
  58. quadEnabled = false --Whether or not to request a quadRotor when out of fuel [Default false]
  59. quadTimeout = 60 * 5 --How long the turtle will wait for a quadRotor [Default 5 minutes]
  60. --Standard number slots for fuel (you shouldn't care)
  61. fuelTable = { --Will add in this amount of fuel to requirement.
  62. safe = 1000,
  63. moderate = 200,
  64. loose = 0 } --Default 1000, 200, 0
  65. --Standard rednet channels
  66. channels = {
  67. send = os.getComputerID() + 1 ,
  68. receive = os.getComputerID() + 101 ,
  69. confirm = "Turtle Quarry Receiver",
  70. message = "Civil's Quarry",
  71. fingerprint = "quarry"
  72. }
  73. ID = os.getComputerID()
  74.  
  75. --AVERAGE USER: YOU DON'T CARE BELOW THIS POINT
  76.  
  77. local help_paragraph = [[
  78. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  79. -default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  80. -dim: [length] [width] [height] This sets the dimensions for the quarry
  81. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  82. -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
  83. -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
  84. -autoResume / autoRestore: Turtle will automatically resume if stopped. Replaces startup
  85. -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.
  86. -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+)
  87. -blacklist: [file name] If using oreQuarry, this is the blacklist file it will read. Example --
  88. minecraft:stone
  89. minecraft:sand
  90. ThermalExpansion:Sponge
  91. ThermalFoundation:Storage
  92.  
  93. Note: If you have bspkrsCore, look
  94. for "UniqueNames.txt" in your config
  95. -file: [file name] Will load a file of parameters. One parameter per line. # is a comment line (See the forum thread for more detailed directions)
  96. -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.
  97. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  98. -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...
  99. -overfuel: [number] When fuel is below required, fuel usage is multiplied by this. Large numbers permit more quarries without refueling
  100. -fuelMultiplier: [number] See overfuel
  101. -uniqueExtras: [number] The expected number of slots filled with low-stacking items like ore. Higher numbers request more fuel.
  102. -maxFuel: [number] How much the turtle will fuel to max (limited by turtle in most cases)
  103. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  104. -enderChest: [slot] 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.
  105. -fuelChest: [slot] See the above, but for a fueling chest. Reccommend use with -maxFuel and -doCheckFuel false
  106. -lava: [slot] If using an oreQuarry, will fill itself with lava it finds to maxFuel
  107. -lavaBuffer: [number] The amount of fuel below maxFuel the turtle will wait for before using lava again
  108. -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
  109. -quad: [t/f] This forces the use of GPS. Make sure you have a network set up. This will request to be refueled by a quadrotor from Lyqyd's mod if the turtle is out of fuel
  110. -quadTimeout: [number] The amount of time the turtle will wait for a quadRotor
  111. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  112. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  113. -legacyRednet: [t/f] Check true if using 1.4.7
  114. -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
  115. -startupRename: [file name] What to rename any existing startup to.
  116. -startupName: [file name] What the turtle will save its startup file to.
  117. -extraDropItems: [force] If oreQuarry then this will prompt the user for extra items to drop, but not compare to (like cobblestone)
  118. -dumpCompareItems: [t/f] If oreQuarry and this is true, the turtle will dump off compare blocks instead of storing them in a chest
  119. -oldOreQuarry: [t/f] If you are using new CC versions, you can use this to use the old oreQuarry.
  120. -compareChest: [slot] If using oldOreQuarry, this will allow you to check for dungeon chests and suck from them.
  121. -frontChest: [t/f] If using oreQuarry/oldOreQuarry, this will check in front of itself for chests as well.
  122. -left: [t/f] If true, turtle will quarry to the left instead of the right
  123. -maxTries: [number] This is the number of times the turtle will try to dig before deciding its run into bedrock.
  124. -forcePrompt: [parameter] Whatever parameter you specify, it will always prompt you, like it does now for invert and dim.
  125. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  126. -preciseTotals: [t/f] If true (and turtle.inspect exists), it will log a detailed record of every block the turtle mines and send it over rednet
  127. -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...)
  128. -saveFile: [word] This is what the backup file will be called
  129. -logFolder: [word] The folder that quarry logs will be stored in
  130. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  131. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every time it mines
  132. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  133. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  134. =
  135. C _ |
  136. |
  137. |
  138. |
  139. |_ _ _ _ >
  140. -flatBedrock: [t/f] If true, turtle will find bedrock and "zero" itself so it ends on bedrock level
  141. -promptAll: This is the opposite of -Default, it prompts for everything
  142. -listParams: This will list out all your selected parameters and end quarry. Good for testing
  143. -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"
  144. -version: Displays the current quarry version and stops the program
  145. -help: Thats what this is :D
  146. Examples: Everything below is examples and tips for use
  147. Important Note:
  148. None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  149. Examples [1]:
  150. 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".
  151. 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?
  152. Examples [2]:
  153. 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.
  154. Examples [2] [cont.]:
  155. 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
  156. "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  157. BAM. Now you can just let that turtle do it's thing
  158. Tips:
  159. The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  160.  
  161. Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  162. Tips [cont.]:
  163. For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  164.  
  165. For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  166. Tips [cont.]:
  167. If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  168.  
  169. 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.
  170. Internal Config:
  171. 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.
  172.  
  173. You can also use this if there are settings that you don't like the default value of.
  174. ]]
  175. --NOTE: BIOS 114 MEANS YOU FORGOT A COLON
  176. --NOTE: THIS ALSO BREAKS IF YOU REMOVE "REDUNDANT" WHITESPACE
  177. --Parsing help for display
  178. --[[The way the help table works:
  179. All help indexes are numbered. There is a help[i].title that contains the title,
  180. and the other lines are in help[i][1] - help[i][#help[i] ]
  181. Different lines (e.g. other than first) start with a space.
  182. As of now, the words are not wrapped, fix that later]]
  183. local help = {}
  184. local i = 0
  185. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  186. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  187. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  188. local current = string.sub(a,1,-2).."" --Concatenate Trick
  189. if string.sub(current,1,1) ~= " " then
  190. i = i + 1
  191. help[i] = {}
  192. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  193. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  194. elseif string.sub(current,1,1) == " " then
  195. table.insert(help[i], string.sub(current,2, -1).."")
  196. end
  197. end
  198.  
  199. local supportsRednet
  200. if peripheral.find then
  201. supportsRednet = peripheral.find("modem") or false
  202. else
  203. supportsRednet = (peripheral.getType("right") == "modem") or false
  204. end
  205.  
  206. --Pre-defining variables that need to be saved
  207. 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, eventInsertionPoint
  208. = 0, 1, 1, 0, 0, 0, 0, 1, true , false, true, 1, 0, 0, false, "", false, 0, 0, {}, {}, {}, 1, false, false, {explicit = {}}, 0, 1
  209.  
  210. --These are slot options that need to exist as variables for parameters to work.
  211. enderChest, fuelChest, lavaBucket, compareChest
  212. = false, false, false, false
  213.  
  214. local chestID, lavaID, lavaMeta = "minecraft:chest", "minecraft:flowing_lava", 0
  215.  
  216. local statusString
  217.  
  218. --Initializing various inventory management tables
  219. for i=1, inventoryMax do
  220. allowedItems[i] = 0 --Number of items allowed in slot when dropping items
  221. dumpSlots[i] = false --Does this slot contain junk items?
  222. end --compareSlots is a table of the compare slots, not all slots with a condition
  223. totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function), this goes up here because many functions use it
  224.  
  225. local function newSpecialSlot(index, value, explicit) --If isn't explicit, it will move whatever is already in the slot around to make room.
  226. value = tonumber(value) or 0 --We only want numerical indexes
  227. local flag = false --Used in slot moving, moved slot is returned for ease of use
  228. local function check(num) return num >= 1 and num <= inventoryMax end
  229. if not check(value) then error("from newSpecialSlot: number "..value.." out of range",2) end
  230. local function getFirstFree(start)
  231. for i=1, math.max(inventoryMax-value,value-1) do
  232. for a=-1,1,2 do
  233. local num = value + (a*i)
  234. if check(num) and not specialSlots[num] then return num end
  235. end
  236. end
  237. return false
  238. end
  239. if specialSlots[value] and specialSlots[value] ~= index then --If we aren't trying to override the same slot :P
  240. if not explicit then
  241. value = getFirstFree(value) or error("from newSpecialSlots: all slots full, could not add")
  242. elseif explicit and not specialSlots.explicit[value] then --Moving around other slots
  243. flag = getFirstFree(value)
  244. if not flag then error("from newSpecialSlots: could not add explicit in slot: "..index.." "..value.." Taken by "..specialSlots[value],2) end
  245. specialSlots[flag] = specialSlots[value]
  246. specialSlots[specialSlots[value]] = flag --These will get set to the new thing later
  247. else
  248. error('You cannot put a "'..index..'" in the same slot as a "'..specialSlots.explicit[value]..'" (Slot '..value..")",0) --Show the user an understandable error :)
  249. end
  250. end
  251. specialSlots[index] = value
  252. specialSlots[value] = index
  253. if explicit then
  254. specialSlots.explicit[value] = index
  255. end
  256. return value, flag
  257. end
  258.  
  259. function resetDumpSlots()
  260. for i=1, inventoryMax do
  261. if oldOreQuarry then
  262. if turtle.getItemCount(i) > 0 and i~= specialSlots.enderChest then
  263. dumpSlots[i] = true
  264. else
  265. dumpSlots[i] = false
  266. end
  267. else
  268. dumpSlots[i] = false
  269. end
  270. end
  271. if not oldOreQuarry and specialSlots.enderChest == 1 then
  272. dumpSlots[2] = true
  273. elseif not oldOreQuarry then
  274. dumpSlots[1] = true
  275. end
  276. end
  277.  
  278. local function copyTable(tab) if type(tab) ~= "table" then error("copyTable received "..type(tab)..", expected table",2) end 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
  279.  
  280. --NOTE: rowCheck is a bit. true = "right", false = "left"
  281.  
  282. local foundBedrock = false
  283.  
  284. local checkFuel, checkFuelLimit
  285. if turtle then --Function inits
  286. checkFuel = turtle.getFuelLevel
  287. if turtle.getFuelLevel() == "unlimited" then --Fuel is disabled --Unlimited screws up my calculations
  288. checkFuel = function() return math.huge end --Infinite Fuel
  289. end --There is no "else" because it will already return the regular getFuel
  290. if turtle.getFuelLimit then
  291. checkFuelLimit = function() return math.min(turtle.getFuelLimit(), excessFuelAmount) end --Return the limiting one
  292. if turtle.getFuelLimit() == "unlimited" then
  293. checkFuelLimit = function() return math.huge end
  294. end
  295. else
  296. checkFuelLimit = function() return excessFuelAmount end --If the function doesn't exist
  297. end
  298.  
  299.  
  300. turtle.select(1) --To ensure this is correct
  301. end
  302.  
  303.  
  304. function select(slot)
  305. if slot ~= selectedSlot and slot > 0 and slot <= inventoryMax then
  306. selectedSlot = slot
  307. return turtle.select(slot), selectedSlot
  308. end
  309. end
  310.  
  311.  
  312. -----------------------------------------------------------------
  313. --Input Phase
  314. local function screen(xPos,yPos)
  315. xPos, yPos = xPos or 1, yPos or 1
  316. term.setCursorPos(xPos,yPos); term.clear(); end
  317. local function screenLine(xPos,yPos)
  318. term.setCursorPos(xPos,yPos); term.clearLine(); end
  319.  
  320. screen(1,1)
  321. print("----- Welcome to Quarry! -----")
  322. print("")
  323.  
  324. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  325. local tArgs --Will be set in initializeArgs
  326. local originalArgs = {...}
  327. local changedT, tArgsWithUpper, forcePrompts = {}, {}, {}
  328. changedT.new = function(key, value, name) table.insert(changedT,{key, value, name}); if name then changedT[name] = #changedT end end --Numeric list of lists
  329. changedT.remove = function(num) changedT[num or #changedT].hidden = true end --Note actually remove, just hide :)
  330. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  331. local function initializeArgs()
  332. tArgs = copyTable(originalArgs) --"Reset" tArgs
  333. for i=1, #tArgs do --My signature key-value pair system, now with upper
  334. tArgsWithUpper[i] = tArgs[i]
  335. tArgsWithUpper[tArgsWithUpper[i]] = i
  336. tArgs[i] = tArgs[i]:lower()
  337. tArgs[tArgs[i]] = i
  338. if tArgs[i] == "-forceprompt" and i ~= #tArgs then --If the prompt exists then add it to the list of prompts
  339. forcePrompts[tArgs[i+1]:lower()] = true
  340. end
  341. end
  342. end
  343. initializeArgs()
  344.  
  345. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  346. function parseParam(name, displayText, formatString, forcePrompt, trigger, variableOverride, variableExists) --Beware confusion, all ye who enter here
  347. --[[ Guide to Variables
  348. originalValue: what the variable was before the function
  349. givenValue: This is the value after the parameter. So -invert fAlSe, givenValue is "fAlSe"
  350. ]]
  351. if variableExists ~= false then variableExists = true end --Almost all params should have the variable exist. Some don't exist unless invoked
  352. if trigger == nil then trigger = true end --Defaults to being able to run
  353. if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  354. if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these. Default is no variable because resuming
  355. if not restoreFoundSwitch and (tArgs["-promptall"] or forcePrompts[name:lower()]) then forcePrompt = true end --Won't prompt if resuming, can prompt all or checks list of prompts
  356. local toGetText = name:lower() --Because all params are now lowered
  357. local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  358. local args = formatString:match(" (.+)") or "".."" --Everything in formatString after the type
  359. local variable = variableOverride or name --Goes first to the override for name
  360. local func = loadstring("return "..variable) --Note to future self: If you want to remove loadstring, this breaks on tables. You will have to remove tables or figure something else out
  361. setfenv(func,getfenv(1))
  362. local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  363. if originalValue == nil and variableExists then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  364. local givenValue, toRet, values --Initializing for use
  365. if tArgs["-"..toGetText] then
  366. givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  367. elseif forcePrompt then
  368. write(displayText.."? ")
  369. givenValue = io.read()
  370. end
  371. if formatType == "force" then --This is the one exception. Should return true if givenValue is nothing
  372. toRet = (tArgs["-"..toGetText] and true) or false --Will return true if param exists, otherwise false
  373. end
  374. if not (givenValue or toRet) or (type(givenValue) == "string" and #givenValue == 0) then return end --Don't do anything if you aren't given anything. Leave it as default, except for "force". Also don't want empty strings
  375. if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  376. toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  377. elseif formatType == "string" then
  378. toRet = givenValue:match("^[%w%./]+") --Basically anything not a space or control character etc
  379. elseif formatType == "number" or formatType == "float" then
  380. toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  381. if not toRet then return end --We need a number... Otherwise compare errors
  382. if formatType == "number" then toRet = math.floor(toRet) end --Get proper integers
  383. local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  384. startNum, endNum = tonumber(startNum), tonumber(endNum)
  385. if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  386. elseif formatType == "side" then
  387. local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  388. for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  389. if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  390. elseif formatType == "list" then
  391. toRet = {}
  392. for a in args:gmatch("[^,]") do
  393. table.insert(toRet,a)
  394. end
  395. elseif formatType == "slot" then
  396. if givenValue:sub(1,1):lower() == "n" or givenValue:sub(1,1):lower() == "f" then --Copied from boolean
  397. toRet = false
  398. else
  399. local userNumber, correction = givenValue:match("^%d+$") --This makes sure the value is a number | Locally initialize correction
  400. toRet, correction = newSpecialSlot(variable, tonumber(userNumber or args), userNumber) --If givenValue was "true", it won't be explicit and will use default number
  401. if correction then changedT[changedT[specialSlots[correction]]][2] = tostring(correction) end --This changes the value field of the changedT index taken from the named pointer (which is the value in specialSlots under correction)
  402. end
  403. elseif formatType == "force" then --Do nothing, everything is already done
  404. else error("Improper formatType",2)
  405. end
  406. if toRet == nil then return end --Don't want to set variables to nil... That's bad
  407. tempParam = toRet --This is what loadstring will see :D
  408. local func = loadstring(variable.." = tempParam")
  409. setfenv(func, getfenv(1)) --Note to future self: If you want to remove loadstring, this breaks on tables. You will have to remove tables or figure something else out
  410. func()
  411. tempParam = nil --Cleanup of global
  412. if toRet ~= originalValue and displayText ~= "" then
  413. changedT.new(displayText, tostring(toRet), variable)
  414. end
  415. return toRet
  416. end
  417.  
  418. local paramLookup = {}
  419. local function addParam(...)
  420. local args = {...}
  421. if not paramLookup[args[1]] then
  422. local toRet = copyTable(args)
  423. for i=2, table.maxn(toRet) do --Have to do this because table.remove breaks on nil
  424. toRet[i-1] = toRet[i]
  425. end
  426. table.remove(toRet)
  427. paramLookup[args[1]] = toRet
  428. end
  429. return parseParam(unpack(args, 1, table.maxn(args)))
  430. end
  431.  
  432. local function paramAlias(original, alias)
  433. local a = paramLookup[original]
  434. if a then
  435. if a[5] == nil then a[5] = original end --This is variableOverride because the originals won't put a variable override
  436. return parseParam(alias, unpack(a, 1, table.maxn(a)))
  437. else
  438. error("In paramAlias: '"..original.."' did not exist",2)
  439. end
  440. end
  441.  
  442. --Check if it is a turtle
  443. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then --If all of these are false then
  444. print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  445. print("Press 'q' to quit, or any other key to start help ")
  446. if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  447. end
  448.  
  449. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  450. print("You have selected help, press any key to continue"); print("Use arrow keys to navigate, q to quit"); os.pullEvent("key")
  451. local pos = 1
  452. local key = 0
  453. while pos <= #help and key ~= keys.q do
  454. if pos < 1 then pos = 1 end
  455. screen(1,1)
  456. print(help[pos].title)
  457. for a=1, #help[pos] do print(help[pos][a]) end
  458. repeat
  459. _, key = os.pullEvent("key")
  460. until key == 200 or key == 208 or key == keys.q
  461. if key == 200 then pos = pos - 1 end
  462. if key == 208 then pos = pos + 1 end
  463. end
  464. error("",0)
  465. end
  466.  
  467. if tArgs["-version"] or tArgs["version"] then
  468. print("QUARRY VERSION: ",VERSION)
  469. error("",0) --Exit not so gracefully
  470. end
  471.  
  472. --Loading custom parameter lists
  473. local function split(str, sep)
  474. assert(#sep == 1, "Split seperator too long. Got '"..sep.."'")
  475. if not str:match(sep) then return {str} end --So everything else isn't pointless
  476. local toRet = {}
  477. toRet[1] = str:match("^([^"..sep.."]-)"..sep)
  478. for i in str:gmatch(sep.."([^"..sep.."]*)") do --Matches not seperator chars
  479. toRet[#toRet+1] = i
  480. end
  481. return toRet
  482. end
  483.  
  484. if addParam("file","Custom Parameters","string", false, nil, "parameterFile", false) and parameterFile then --This will not load when resuming because there is no "file" parameter when resuming.
  485. if not fs.exists(parameterFile) then
  486. print("WARNING: '"..parameterFile.."' DOES NOT EXIST. FILE NOT LOADED")
  487. sleep(3)
  488. changedT.remove()
  489. else
  490. local file = fs.open(parameterFile, "r")
  491. local text = file.readAll()
  492. file.close()
  493. text = text.."\n" --So that all replacements work properly
  494. text = text:gsub("#[^\n]-\n","") --Replace program codes/comment lines+
  495. local commands = {} --Contains all the parameters
  496. local append = table.insert
  497. for _, a in pairs(split(text,"\n")) do
  498. local words = split(a," ")
  499. if not a:match("-") then --This means only one command per line
  500. append(originalArgs,"-"..words[1])
  501. for i=2, #words do
  502. append(originalArgs, words[i])
  503. end
  504. else --Otherwise the dashes are already ordered where we want!
  505. for i=1, #words do
  506. append(originalArgs, words[i])
  507. end
  508. end
  509. end
  510. initializeArgs() --Manipulate the args again, because we modified them
  511. print("Finished loading file: ",tArgs[tArgs["-file"]+1])
  512. sleep(0.5) --Give em a sec
  513. end
  514. end
  515.  
  516.  
  517.  
  518. --Saving
  519. addParam("doBackup", "Backup Save File", "boolean")
  520. addParam("saveFile", "Save File Name", "string")
  521.  
  522. restoreFound = fs.exists(saveFile)
  523. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound and doBackup
  524. if restoreFoundSwitch then
  525. local file = fs.open(saveFile,"r")
  526. local test = file.readAll() ~= ""
  527. file.close()
  528. if test then
  529. local temp = shell and copyTable(shell) --For whatever reason, the shell table doesn't survive resuming. shell and ... so that copyTable doesn't error
  530. os.run(getfenv(1),saveFile) --This is where the actual magic happens
  531. shell = temp
  532. numResumed = numResumed + 1
  533. if checkFuel() ~= math.huge then --If turtle uses fuel
  534. if fuelLevel - checkFuel() == 1 then
  535. if facing == 0 then xPos = xPos + 1
  536. elseif facing == 2 then xPos = xPos - 1
  537. elseif facing == 1 then zPos = zPos + 1
  538. elseif facing == 3 then zPos = zPos - 1 end
  539. elseif fuelLevel - checkFuel() ~= 0 then
  540. print("Very Strange Fuel in Restore Section...")
  541. print("Current: ",checkFuel())
  542. print("Saved: ",fuelLevel)
  543. print("Difference: ",fuelLevel - checkFuel())
  544. os.pullEvent("char")
  545. end
  546. end
  547. if gpsEnabled then --If it had saved gps coordinates
  548. print("Found GPS Start Coordinates")
  549. local currLoc = {gps.locate(gpsTimeout)} or {}
  550. local backupPos = {xPos, yPos, zPos} --This is for comparing to later
  551. if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  552. print("GPS Position Successfully Read")
  553. if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  554. xPos, yPos, zPos = 0,1,1
  555. if facing ~= 0 then turnTo(0) end
  556. print("Is at start")
  557. else
  558. if inverted then --yPos setting
  559. ------------------------------------------------FIX THIS
  560. end
  561. local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  562. local flag = true --So we can account for left quarry
  563. if b[3] - a[3] == -1 then--If went north (-Z)
  564. a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  565. xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  566. elseif b[1] - a[1] == 1 then--If went east (+X)
  567. a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  568. xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  569. elseif b[3] - a[3] == 1 then--If went south (+Z)
  570. a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  571. xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  572. elseif b[1] - a[1] == -1 then--If went west (-X)
  573. a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  574. xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  575. else
  576. flag = false
  577. print("Improper Coordinates")
  578. print("GPS Locate Failed, Using Standard Methods") ----Maybe clean this up a bit to use flags instead.
  579. end
  580. 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
  581. zPos = math.abs(zPos-1) + 1
  582. end
  583. end
  584. print("X Pos: ",xPos)
  585. print("Y Pos: ",yPos)
  586. print("Z Pos: ",zPos)
  587. print("Facing: ",facing)
  588. for i=1, 3, 2 do --We want 1 and 3, but 2 could be coming back to start.
  589. if backupPos[i] ~= currLoc[i] then
  590. events = {} --We want to remove event queue if not in proper place, so won't turn at end of row or things.
  591. end
  592. end
  593. else
  594. print("GPS Locate Failed, Using Standard Methods")
  595. end
  596. print("Restore File read successfully. Starting in 3"); sleep(3)
  597. end
  598. else
  599. fs.delete(saveFile)
  600. print("Restore file was empty, sorry, aborting")
  601. error("",0)
  602. end
  603. else --If turtle is just starting
  604. events = {} --This is the event queue :D
  605. originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  606. end
  607.  
  608. --Dimensions
  609. if tArgs["-dim"] then
  610. local a,b,c = x,y,z
  611. local num = tArgs["-dim"]
  612. x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  613. if a ~= x then changedT.new("Length", x) end
  614. if c ~= z then changedT.new("Width", z) end
  615. if b ~= y then changedT.new("Height", y) end
  616. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  617. print("What dimensions?")
  618. print("")
  619. --This will protect from negatives, letters, and decimals
  620. term.write("Length? ")
  621. x = math.floor(math.abs(tonumber(io.read()) or x))
  622. term.write("Width? ")
  623. z = math.floor(math.abs(tonumber(io.read()) or z))
  624. term.write("Height? ")
  625. y = math.floor(math.abs(tonumber(io.read()) or y))
  626. changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  627. end
  628. --Params: parameter/variable name, display name, type, force prompt, boolean condition, variable name override
  629. --Invert
  630. addParam("flatBedrock","Go to bedrock", "boolean") --Not done before GPS because GPS only runs on restart
  631. addParam("invert", "Inverted","boolean", true, not flatBedrock, "inverted") --Not flat bedrock, because invert will be set to false
  632. addParam("startDown","Start Down","number 1-256", nil, not flatBedrock)
  633. addParam("left","Left Quarry","boolean", nil, nil, "goLeftNotRight")
  634. --Inventory
  635. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  636. addParam("enderChest","Ender Chest Slot","slot 16") --Note: All slots can be 16 and they will auto-assign, but I feel it is less confusing if they are always the same
  637. addParam("fuelChest","Fuel Chest Slot","slot 15")
  638. --Rednet
  639. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
  640. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  641. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  642. addParam("fingerprint","Sending Fingerprint", "string", false, supportsRednet, "channels.fingerprint")
  643. addParam("legacyRednet","Legacy Rednet","boolean", false, supportsRednet)
  644. --Quad Rotor --Must be before GPS
  645. if addParam("quad", "Quad Rotor Enabled","boolean",nil, rednetEnabled, "quadEnabled") then --This returns true if param found :3
  646. gpsEnabled = true
  647. end
  648. addParam("quadTimeout","Quad Rotor Timeout","number 1-1000000", nil, quadEnabled) --The amount of time to wait for a quadRotor
  649. --GPS
  650. addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet and not quadEnabled, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  651. if gpsEnabled and not restoreFoundSwitch then
  652. gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  653. gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  654. if quadEnabled and not gpsEnabled then
  655. error("You have no GPS network. You may not use Quad Rotors",0)
  656. end
  657. end
  658. --Fuel
  659. addParam("uniqueExtras","Unique Items", "number 0-15")
  660. addParam("doRefuel", "Refuel from Inventory","boolean", nil, checkFuel() ~= math.huge) --math.huge due to my changes
  661. addParam("doCheckFuel", "Check Fuel", "boolean", doCheckFuel and fuelChest, checkFuel() ~= math.huge) --Will prompt if doCheckFuel and fuelChest are on. Probably don't want
  662. excessFuelAmount = excessFuelAmount or math.huge --Math.huge apparently doesn't save properly (Without saving, this is the config, on save it is actually set to nil if math.huge)
  663. addParam("maxFuel", "Max Fuel", "number 1-999999999", maxFuel == checkFuelLimit() and fuelChest, checkFuel() ~= math.huge, "excessFuelAmount") --Will prompt if fuel chest and the limit isn't changed
  664. addParam("fuelMultiplier", "Fuel Multiplier", "float 1-9001", nil, checkFuel() ~= math.huge)
  665. paramAlias("fuelMultiplier","fuelRequestMultiplier")
  666. paramAlias("fuelMultiplier","overFuel")
  667. --Logging
  668. addParam("logging", "Logging", "boolean")
  669. addParam("logFolder", "Log Folder", "string")
  670. addParam("logExtension","Log Extension", "string")
  671. --Misc
  672. addParam("startY", "Start Y","number 1-256")
  673. addParam("maxTries","Tries Before Bedrock", "number 1-9001")
  674. --Inventory
  675. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  676. addParam("careAboutResources", "Care About Resources","boolean")
  677. addParam("preciseTotals","Precise Totals","boolean", rednetEnabled and turtle.inspect, turtle.getItemDetail ~= nil)
  678. if preciseTotals and not restoreFoundSwitch then
  679. exactTotals = {} --Don't want to initialize if we aren't using this
  680. end
  681. --Auto Startup
  682. addParam("autoResume", "Auto Resume", "boolean", nil, doBackup)
  683. paramAlias("autoResume","autoRestart")
  684. addParam("startupRename", "Startup Rename","string", nil, autoResume)
  685. addParam("startupName", "Startup File", "string", nil, autoResume)
  686. --Ore Quarry
  687. addParam("oreQuarry", "Ore Quarry", "boolean" )
  688. if oreQuarry and not turtle.inspect then
  689. oldOreQuarry = true
  690. oreQuarry = false
  691. end
  692. addParam("lavaBucket","Lava Bucket Slot", "slot 14", nil, oreQuarry)
  693. paramAlias("lavaBucket","lava")
  694. paramAlias("lavaBucket","lavaRefuel")
  695. addParam("lavaBuffer","Lava Buffer","number 1-19999", nil, lavaBucket)
  696. --Old Ore
  697. addParam("oldOreQuarry", "Old Ore Quarry", "boolean")
  698. addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oldOreQuarry) --Do not dump compare items if not oreQuarry
  699. addParam("extraDropItems", "", "force", nil, oldOreQuarry) --Prompt for extra dropItems
  700. paramAlias("extraDropItems","extraDumpItems") --changed to Dump
  701. addParam("compareChest","Compare Chest Slot","slot 13", nil, oldOreQuarry)
  702. addParam("frontChest","Front Chest Check","boolean", nil, compareChest or turtle.insepect) --Does not need oreQuarry, but is similar (does need inspect if not compareChest)
  703. --New Ore
  704. addParam("blacklist","Ore Blacklist", "string", nil, oreQuarry, "oreQuarryBlacklistName")
  705. paramAlias("blacklist","blacklistFile")
  706. --Mod Related
  707.  
  708. --Extra
  709. if tArgs["-testparams"] then
  710. screen()
  711. print("KEY: VALUE (VARIABLE)")
  712. for key, val in ipairs(changedT) do
  713. if not val.hidden then
  714. print(val[1],": ",val[2]," (",val[3] or "",")")
  715. end
  716. end
  717. error("Done",0)
  718. end
  719.  
  720.  
  721. --for flatBedrock
  722. if flatBedrock then
  723. inverted = false
  724. end
  725.  
  726. --Auto Startup functions
  727. local function doAutoResumeStuff()
  728. if fs.exists(startupName) then
  729. if fs.exists(startupRename) then fs.delete(startupRename) end
  730. fs.move(startupName, startupRename)
  731. end
  732. local file = fs.open(startupName,"w") --Startup File
  733. file.writeLine( --The below is on the left because spacing
  734. [[
  735. --This is an auto-generated startup
  736. --Made by civilwargeeky's Variable Size Quarry
  737. print("Now Resuming Quarry")
  738. print("Press any key to quit. You have 5 seconds.")
  739. function deleteStuff()
  740. fs.delete("]]..startupName..[[")
  741. if fs.exists("]]..startupRename..[[") then
  742. fs.move("]]..startupRename.."\",\""..startupName..[[")
  743. end
  744. end
  745. local event
  746. if fs.exists("]]..saveFile..[[") then
  747. for i=5,1,-1 do
  748. print(i)
  749. os.startTimer(1)
  750. event = os.pullEvent()
  751. if event == "key" then break end
  752. end
  753. if event == "timer" then
  754. os.run({},"]]..shell.getRunningProgram()..[[","-resume")
  755. else
  756.  
  757. deleteStuff()
  758. end
  759. else
  760. print("Never mind, no save file found")
  761. deleteStuff()
  762. end
  763. ]])
  764. file.close()
  765. end
  766. 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
  767. doAutoResumeStuff()
  768. end
  769. --oreQuarry blacklist
  770. local blacklist = { "minecraft:air", "minecraft:bedrock", "minecraft:cobblestone", "minecraft:dirt", "minecraft:ice", "minecraft:ladder", "minecraft:netherrack", "minecraft:sand", "minecraft:sandstone",
  771. "minecraft:snow", "minecraft:snow_layer", "minecraft:stone", "minecraft:gravel", "minecraft:grass", "minecraft:torch" }
  772. for a,b in pairs(copyTable(blacklist)) do
  773. blacklist[b], blacklist[a] = true, nil --Switch
  774. end
  775. if fs.exists(oreQuarryBlacklistName) then --Loading user-defined blacklist
  776. local file = fs.open(oreQuarryBlacklistName, "r")
  777. blacklist = {}
  778. for a in file:readAll():gmatch("[^,\n]+") do
  779. blacklist[a:match("[%w_.]+:[%w_.]+")] = true --Grab only the actual characters, not whitespaces
  780. end
  781. file:close()
  782. end
  783.  
  784. --Manual Position
  785. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  786. local a = tArgs["-manualpos"]
  787. 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
  788. changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  789. restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  790. for i=0,4 do tArgs[a+i] = "" end --Get rid of this argument from future restores
  791. end
  792. 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.
  793. local neededLayer = math.floor((yPos+1)/3)*3-1 --Make it a proper layer, +- because mining rows are 2, 5, etc.
  794. if neededLayer > 2 and neededLayer%3 ~= 2 then --If turtle was not on a proper mining layer
  795. print("Last known pos was not in proper layer, restarting quarry")
  796. sleep(4)
  797. neededLayer = 2
  798. end
  799. xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
  800. doAutoResumeStuff() --This was probably deleted when they hit a key to launch with -atChest
  801. events = {{"goto",1,1,neededLayer, 0}}
  802. end
  803.  
  804.  
  805. local function saveProgress(extras) --Session persistence
  806. exclusions = { modem = true, shell = true, _ENV = true}
  807. if doBackup then
  808. local toWrite = ""
  809. for a,b in pairs(getfenv(1)) do
  810. if not exclusions[a] then
  811. --print(a ," ", b, " ", type(b)) --Debug
  812. if type(b) == "string" then b = "\""..b.."\"" end
  813. if type(b) == "table" then b = textutils.serialize(b) end
  814. if type(b) ~= "function" then
  815. toWrite = toWrite..a.." = "..tostring(b).."\n"
  816. end
  817. end
  818. end
  819. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnecessary
  820. local file
  821. repeat
  822. file = fs.open(saveFile,"w")
  823. until file
  824. file.write(toWrite)
  825. if type(extras) == "table" then
  826. for a, b in pairs(extras) do
  827. file.write(a.." = "..tostring(b).."\n")
  828. end
  829. end
  830. if checkFuel() ~= math.huge then --Used for location comparing
  831. file.write("fuelLevel = "..tostring(checkFuel()).."\n")
  832. end
  833. file.close()
  834. end
  835. end
  836.  
  837. local area = x*z
  838. local volume = x*y*z
  839. local lastHeight = y%3
  840. layers = math.ceil(y/3)
  841. local yMult = layers --This is basically a smart y/3 for movement
  842. local moveVolume = (area * yMult) --Kept for display percent
  843. --Calculating Needed Fuel--
  844. do --Because many local variables unneeded elsewhere
  845. local changeYFuel = 2*(y + startDown)
  846. local dropOffSupplies = 2*(x + z + y + startDown) --Assumes turtle as far away as possible, and coming back
  847. 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.
  848. --max of 15 full stacks because once one item is picked up, slot is "full". Ceil to count for initial back and forth
  849. if enderChest then frequency = 0 end --Never goes back to start
  850. neededFuel = moveVolume + changeYFuel + (frequency * dropOffSupplies) + ((x + z) * layers) --x + z *layers because turtle has to come back from far corner every layer
  851. neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  852. end
  853.  
  854. if neededFuel > checkFuelLimit() and doCheckFuel then--Checks for if refueling goes over turtle fuel limit
  855. if not (doRefuel or fuelChest) then
  856. screen()
  857. print("Turtle cannot hold enough fuel\n")
  858. print("Options: \n1. Select a smaller size \n2. Enable Mid-Run Refueling (RECOMMENDED) \n3. Turn fuel checking off (only if fuel chest) \n4. Do nothing")
  859. local _, key = os.pullEvent("char")
  860. if key == "1" then
  861. screen(); print("Okay"); error("",0)
  862. elseif key == "3" then
  863. doCheckFuel = false
  864. elseif key == "4" then
  865. --pass
  866. else --Not for number two because this is default
  867. doRefuel = true
  868. end
  869. end
  870. neededFuel = checkFuelLimit()-checkFuel()-1
  871. end
  872.  
  873.  
  874. --Getting Fuel
  875. local hasRefueled --This is for oldOreQuarry prompting
  876. if doCheckFuel and checkFuel() < neededFuel then
  877. neededFuel = math.min(math.floor(neededFuel * fuelMultiplier), checkFuelLimit()-checkFuel()-1) --Does the same as above, but not verbose because optional
  878. hasRefueled = true
  879. print("Not enough fuel")
  880. print("Current: ",checkFuel()," Needed: ",neededFuel)
  881. print("Starting SmartFuel...")
  882. sleep(2) --So they can read everything.
  883. term.clear()
  884. local oneFuel, neededFuelItems = 0,0 --Initializing Variables
  885. local currSlot = 0
  886. local function output(text, x, y) --For displaying fuel statistics
  887. local currX, currY = term.getCursorPos()
  888. term.setCursorPos(x,y)
  889. term.clearLine()
  890. term.write(text)
  891. term.setCursorPos(currX,currY)
  892. end
  893. local function roundTo(num, target) --For stacks of fuel and turtle slots when undergoing addition/subtraction
  894. if num >= target then return target elseif num < 0 then return 0 else return num end
  895. end
  896. local function updateScreen()
  897. output("Welcome to SmartFuel! Now Refueling...", 1,1)
  898. output("Fuel Request Multiplier: "..tostring(fuelMultiplier).."x",1,2)
  899. output("Currently taking fuel from slot "..currSlot,1,3)
  900. output("Current single fuel: "..tostring(oneFuel or 0),1,4)
  901. output("Current estimate of needed fuel: ",1,4)
  902. output("Single Items: "..math.ceil(neededFuelItems),4,6)
  903. output("Stacks: "..math.ceil(neededFuelItems / 64),4,7)
  904. output("Needed Fuel: "..tostring(neededFuel),1,12)
  905. output("Current Fuel: "..tostring(checkFuel()),1,13)
  906. end
  907. while checkFuel() < neededFuel do
  908. currSlot = currSlot + 1
  909. select(currSlot)
  910. if currSlot ~= 1 and not turtle.refuel(0) then --If it's not the first slot, and not fuel, go back to start
  911. currSlot = 1; select(currSlot)
  912. end
  913. updateScreen()
  914. while turtle.getItemCount(currSlot) == 0 do
  915. sleep(1.5)
  916. end
  917. repeat --TODO: Probably unnecessary loop, remove later
  918. local previous = checkFuel()
  919. turtle.refuel(1)
  920. oneFuel = checkFuel() - previous
  921. updateScreen()
  922. until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  923. neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel)
  924. turtle.refuel(roundTo(neededFuelItems, 64)) --Change because can only think about 64 at once.
  925. if turtle.getItemCount(roundTo(currSlot + 1, inventoryMax)) == 0 then --Resets if no more fuel
  926. currSlot = 0
  927. end
  928. neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel) --This line is not repeated uselessly, it's for the display function
  929. end
  930. select(1)
  931. end
  932. --Ender Chest Obtaining
  933. function promptSpecialSlot(specialSlot, name, limit)
  934. local function isInRange(toCheck, lower, upper) return toCheck <= upper and toCheck >= lower end
  935. while not isInRange(turtle.getItemCount(specialSlots[specialSlot]), 1, limit or 1) do
  936. screen(1,1)
  937. print("You have decided to use a ",name,"!")
  938. print("Please place one ",name," in slot ",specialSlots[specialSlot])
  939. sleep(1)
  940. end
  941. print(name," in slot ",specialSlots[specialSlot], " checks out")
  942. end
  943. function checkSpecialSlot(specialSlot, name, allowed)
  944. if restoreFoundSwitch and turtle.getItemCount(specialSlots[specialSlot]) == 0 then --If the turtle was stopped while dropping off items.
  945. select(specialSlots[specialSlot])
  946. turtle.dig()
  947. select(1)
  948. end
  949. promptSpecialSlot(specialSlot, name, allowed)
  950. allowedItems[specialSlots[specialSlot]] = 1
  951. sleep(1)
  952. end
  953. if enderChest then
  954. checkSpecialSlot("enderChest","Ender Chest")
  955. end
  956. if fuelChest then
  957. checkSpecialSlot("fuelChest","Fuel Chest")
  958. end
  959. if lavaBucket then
  960. checkSpecialSlot("lavaBucket","Empty Bucket")
  961. select(specialSlots.lavaBucket)
  962. if turtle.refuel(1) then --Just in case they actually put in a lava bucket >:(
  963. print("No! You're supposed to put in an empty bucket") --This doubles as emptying the lava bucket if mid-run
  964. sleep(2)
  965. end
  966. select(1)
  967. end
  968. if compareChest then
  969. checkSpecialSlot("compareChest","Chest", 64)
  970. end
  971.  
  972. --Setting which slots are marked as compare slots
  973. if oldOreQuarry then
  974. if not restoreFoundSwitch then --We don't want to reset compare blocks every restart
  975. local counter = 0
  976. for i=1, inventoryMax do if turtle.getItemCount(i) > 0 and not specialSlots[i] then counter = counter+1 end end --If the slot has items, but isn't enderChest slot if it is enabled
  977.  
  978. screen(1,1)
  979. print("You have selected an Ore Quarry!")
  980. if counter == 0 or hasRefueled then --If there are no compare slots, or the turtle has refueled, and probably has fuel in inventory
  981. print("Please place your compare blocks in the first slots\n")
  982.  
  983. print("Press Enter when done")
  984. repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  985. else
  986. print("Registering slots as compare slots")
  987. sleep(1)
  988. end
  989. for i=1, inventoryMax do
  990. if turtle.getItemCount(i) > 0 then
  991. if not specialSlots[i] then
  992. table.insert(compareSlots, i) --Compare slots are ones compared to while mining. Conditions are because we Don't want to compare to enderChest
  993. allowedItems[i] = 1 --Blacklist is for dropping off items. The number is maximum items allowed in slot when dropping off
  994. dumpSlots[i] = true --We also want to ignore all excess of these items, like dirt
  995. end
  996. end
  997. end
  998. if extraDropItems then
  999. screen(1,1)
  1000. print("Put in extra drop items now\n")
  1001. print("Press Enter when done")
  1002. repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  1003. for i=1,inventoryMax do
  1004. 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.
  1005. dumpSlots[i] = true
  1006. allowedItems[i] = 1
  1007. end
  1008. end
  1009. end
  1010. --This is could go very wrong if this isn't here
  1011. 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
  1012. end
  1013. local counter = 0
  1014. for a, b in pairs(compareSlots) do if turtle.getItemCount(b) > 0 then counter = counter + 1 end end
  1015. if counter == 0 then
  1016. screen(1,1)
  1017. print("You have an ore quarry without any compare slots. Continue? y/n")
  1018. if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
  1019. end
  1020. elseif not oreQuarry then --This was screwing up dumpCompareItems
  1021. dumpCompareItems = false --If not an ore quarry, this should definitely be false
  1022. if specialSlots.enderChest == 1 then
  1023. dumpSlots[2] = true
  1024. else
  1025. dumpSlots[1] = true
  1026. end
  1027. end
  1028.  
  1029. --Rednet Handshake
  1030. function newMessageID()
  1031. return math.random(1,2000000000)
  1032. end
  1033. function sendMessage(send, receive, message)
  1034. if legacyRednet then
  1035. if type(message) == "table" then message = textutils.serialize(message) end
  1036. return modem.transmit(send, receive, message)
  1037. end
  1038. return modem.transmit(send , receive, {fingerprint = channels.fingerprint, id = newMessageID(), message = message})
  1039. end
  1040. if rednetEnabled then
  1041. screen(1,1)
  1042. print("Rednet is Enabled")
  1043. print("The Channel to open is "..channels.send)
  1044. if peripheral.find then
  1045. modem = peripheral.find("modem")
  1046. else
  1047. modem = peripheral.wrap("right")
  1048. end
  1049. modem.open(channels.receive)
  1050. local i = 0
  1051. repeat
  1052. local id = os.startTimer(3)
  1053. i=i+1
  1054. print("Sending Initial Message "..i)
  1055. sendMessage(channels.send, channels.receive, channels.message)
  1056. local message = {} --Have to initialize as table to prevent index nil
  1057. repeat
  1058. local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  1059. if locMessage then message = locMessage end
  1060. if legacyRednet then --For that one guy that uses 1.4.7
  1061. message = {message = message}
  1062. end
  1063. until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and type(message) == "table")
  1064. until message.message == channels.confirm
  1065. connected = true
  1066. print("Connection Confirmed!")
  1067. sleep(1.5)
  1068. end
  1069. function biometrics(isAtBedrock, requestQuad)
  1070. if not rednetEnabled then return end --This function won't work if rednet not enabled :P
  1071. local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
  1072. percent = percent, zPos = relzPos, xPos = relxPos, yPos = yPos,
  1073. layersDone = layersDone, x = x, z = z, layers = layers,
  1074. openSlots = getNumOpenSlots(), mined = mined, moved = moved,
  1075. chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
  1076. isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
  1077. fuel = checkFuel(), volume = volume, status = statusString,
  1078. }
  1079. if requestQuad and isInPath then --If we are requesting a quadRotor to send help
  1080. if not gps.locate(gpsTimeout) then
  1081. print("\nOH NOES! Trying to reach quadrotor, but can't get GPS position!")
  1082. sleep(1)
  1083. else
  1084. toSend.firstPos = gpsStartPos
  1085. toSend.secondPos = gpsSecondPos
  1086. toSend.emergencyLocation = {gps.locate(gpsTimeout)}
  1087. end
  1088. end
  1089. sendMessage(channels.send, channels.receive, toSend)
  1090. id = os.startTimer(0.1)
  1091. local event, received
  1092. repeat
  1093. local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  1094. event, received = locEvent, locMessage or {message = ""}
  1095. if legacyRednet and type(received) == "string" then
  1096. received = {message = received}
  1097. end
  1098. until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive and type(received) == "table")
  1099. if event == "modem_message" then connected = true else connected = false end
  1100. local message = received.message:lower()
  1101. if message == "stop" or message == "quit" or message == "kill" then
  1102. count(true)
  1103. display()
  1104. error("Rednet said to stop...",0)
  1105. end
  1106. if message == "return" then
  1107. endingProcedure()
  1108. error('Rednet said go back to start...',0)
  1109. end
  1110. if message == "drop" then
  1111. dropOff()
  1112. end
  1113. if message == "pause" then
  1114. print("\nTurtle is paused. Send 'resume' or press any character to resume")
  1115. statusString = "Paused"
  1116. toSend.status = statusString
  1117. os.startTimer(3)
  1118. repeat --The turtle sends out periodic messages, which will clear the receiver's queue and send a message (if it exists)
  1119. --This may be a bit overkill, sending the whole message again, but whatever.
  1120. local event, idCheck, confirm, _, message, distance = os.pullEvent()
  1121. if event == "timer" then os.startTimer(3); sendMessage(channels.send, channels.receive, toSend) end --Only send messages on the timer. This prevents ridiculous spam
  1122. until (event == "modem_message" and confirm == channels.receive and (message.message == "resume" or message.message == "unpause" or message.message == "pause")) or (event == "char")
  1123. statusString = nil
  1124. end
  1125. if message == "refuel" then
  1126. print("\nEngaging in emergency refueling")
  1127. emergencyRefuel(true)
  1128. end
  1129.  
  1130. end
  1131. --Showing changes to settings
  1132. screen(1,1)
  1133. print("Your selected settings:")
  1134. if #changedT == 0 then
  1135. print("Completely Default")
  1136. else
  1137. for i=1, #changedT do
  1138. if not changedT[i].hidden then
  1139. print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  1140. end
  1141. end
  1142. end
  1143. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  1144.  
  1145.  
  1146.  
  1147. ----------------------------------------------------------------
  1148. --Define ALL THE FUNCTIONS
  1149. --Event System Functions
  1150. function eventSetInsertionPoint(num)
  1151. eventInsertionPoint = num or 1
  1152. end
  1153. function eventAddAt(pos, ...)
  1154. return table.insert(events,pos, {...}) or true
  1155. end
  1156. function eventAdd(...) --Just a wrapper
  1157. return eventAddAt(eventInsertionPoint, ...)
  1158. end
  1159. function eventGet(pos)
  1160. return events[tonumber(pos) or #events]
  1161. end
  1162. function eventPop(pos)
  1163. return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  1164. end
  1165. function eventRun(value, ...)
  1166. local argsList = {...}
  1167. if type(value) == "string" then
  1168. if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  1169. value = value .. "("
  1170. for a, b in pairs(argsList) do --Appending arguments
  1171. local toAppend
  1172. if type(b) == "table" then toAppend = textutils.serialize(b)
  1173. elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  1174. else toAppend = tostring(b) end
  1175. value = value .. (toAppend or "true") .. ", "
  1176. end
  1177. if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  1178. value = value:sub(1,-3)..""
  1179. end
  1180. value = value .. ")"
  1181. end
  1182. --print(value) --Debug
  1183. local func = loadstring(value)
  1184. setfenv(func, getfenv(1))
  1185. return func()
  1186. end
  1187. end
  1188. function eventClear(pos)
  1189. if pos then events[pos] = nil else events = {} end
  1190. end
  1191. function runAllEvents()
  1192. while #events > 0 do
  1193. local toRun = eventGet()
  1194. --print(toRun[1]) --Debug
  1195. eventRun(unpack(toRun))
  1196. eventPop()
  1197. end
  1198. end
  1199.  
  1200. --Display Related Functions
  1201. function display() --This is just the last screen that displays at the end
  1202. screen(1,1)
  1203.  
  1204.  
  1205.  
  1206.  
  1207. modem = peripheral.wrap("left")
  1208. modem.open(ID)
  1209. bob = os.getComputerLabel()
  1210.  
  1211.  
  1212.  
  1213.  
  1214.  
  1215. modem.transmit(ID,1," "..bob.." Complete")
  1216. print("Total Blocks Mined: "..mined)
  1217. print("Current Fuel Level: "..checkFuel())
  1218. print("Cobble: "..totals.cobble)
  1219. print("Usable Fuel: "..totals.fuel)
  1220. print("Other: "..totals.other)
  1221. if rednetEnabled then
  1222. print("")
  1223. print("Sent Stop Message")
  1224. if legacyRednet then --This was the traditional stopping signal
  1225. print("Sent Legacy Stop")
  1226. sendMessage(channels.send, channels.receive, "stop")
  1227. end
  1228. local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
  1229. other = totals.other, fuel = checkFuel(), isDone = true }
  1230. if preciseTotals then
  1231. finalTable.preciseTotals = exactTotals --This table doubles as a flag.
  1232. end
  1233. sendMessage(channels.send,channels.receive, finalTable)
  1234. modem.close(channels.receive)
  1235. end
  1236. if doBackup then
  1237. fs.delete(saveFile)
  1238. if autoResume then --Getting rid of the original startup files and replacing
  1239. fs.delete(startupName)
  1240. if fs.exists(startupRename) then
  1241. fs.move(startupRename, startupName)
  1242. end
  1243. end
  1244. end
  1245. end
  1246. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  1247. screen(1,1)
  1248. bob = os.getComputerLabel()
  1249. print("Blocks Mined")
  1250. print(mined)
  1251. print("Percent Complete")
  1252. print(percent.."%")
  1253. modem = peripheral.wrap("left")
  1254. modem.open(ID)
  1255. print("Fuel")
  1256. print(checkFuel())
  1257.  
  1258. if percent<10
  1259. then padding = " "
  1260. elseif percent<99
  1261. then padding = " "
  1262. else padding = " "
  1263. end
  1264. fuel = checkFuel()
  1265.  
  1266. if fuel>99999 then
  1267. padding2 = " "
  1268. elseif fuel>9999 then
  1269. padding2 = " "
  1270. elseif fuel>999 then
  1271. padding2 = " "
  1272. elseif fuel>99 then
  1273. padding2 = " "
  1274. else
  1275. padding2 = " "
  1276. end
  1277.  
  1278. modem.transmit(ID,1,percent.."%"..padding..checkFuel()..padding2..bob)
  1279. -- screen(1,1)
  1280. -- print("Xpos: ")
  1281. -- print(xPos)
  1282. -- print("RelXPos: ")
  1283. -- print(relxPos)
  1284. -- print("Z Pos: ")
  1285. -- print(zPos)
  1286. -- print("Y pos: ")
  1287. -- print(yPos)
  1288. if rednetEnabled then
  1289. screenLine(1,7)
  1290. print("Connected: "..tostring(connected))
  1291. end
  1292. end
  1293. --Utility functions
  1294. local function pad(str, length, side)
  1295. toRet = ""
  1296. if side == "right" then
  1297. toRet = str
  1298. end
  1299. for i=1, length-#str do
  1300. toRet = toRet.." "
  1301. end
  1302. if side == "left" then
  1303. toRet = toRet..str
  1304. end
  1305. return toRet
  1306. end
  1307. function logMiningRun(textExtension, extras) --Logging mining runs
  1308. if not logging then return end
  1309. local number, name = 0
  1310. if not fs.isDir(logFolder) then
  1311. fs.delete(logFolder)
  1312. fs.makeDir(logFolder)
  1313. end
  1314. repeat
  1315. number = number + 1 --Number will be at least 2
  1316. name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
  1317. until not fs.exists(name)
  1318. local handle = fs.open(name,"w")
  1319. local function write(...)
  1320. for a, b in ipairs({...}) do
  1321. handle.write(tostring(b))
  1322. end
  1323. handle.write("\n")
  1324. end
  1325. local function boolToText(bool) if bool then return "Yes" else return "No" end end
  1326. write("Welcome to the Quarry Logs!")
  1327. write("Entry Number: ",number)
  1328. write("Quarry Version: ",VERSION)
  1329. write("Dimensions (X Z Y): ",x," ",z," ", y)
  1330. write("Blocks Mined: ", mined)
  1331. write(" Cobble: ", totals.cobble)
  1332. write(" Usable Fuel: ", totals.fuel)
  1333. write(" Other: ",totals.other)
  1334. write("Total Fuel Used: ", (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  1335. write("Expected Fuel Use: ", neededFuel)
  1336. write("Days to complete mining run: ",os.day()-originalDay)
  1337. write("Day Started: ", originalDay)
  1338. write("Number of times resumed: ", numResumed)
  1339. write("Was an ore quarry? ",boolToText(oreQuarry or oldOreQuarry))
  1340. write("Was inverted? ",boolToText(invert))
  1341. write("Was using rednet? ",boolToText(rednetEnabled))
  1342. write("Chest was on the ",dropSide," side")
  1343. if startDown > 0 then write("Started ",startDown," blocks down") end
  1344. if exactTotals then
  1345. write("\n==DETAILED TOTALS==")
  1346. for a,b in pairs(exactTotals) do
  1347. write(pad(a, 15, "right"),":",pad(tostring(b),({term.getSize()})[1]-15-1, "left"))
  1348. end
  1349. end
  1350. handle.close()
  1351. end
  1352. --Inventory related functions
  1353. function isFull(slots) --Checks if there are more than "slots" used inventory slots.
  1354. slots = slots or inventoryMax
  1355. local numUsed = 0
  1356. sleep(0)
  1357. for i=1, inventoryMax do
  1358. if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  1359. end
  1360. if numUsed > slots then
  1361. return true
  1362. end
  1363. return false
  1364. end
  1365. function countUsedSlots() --Returns number of slots with items in them, as well as a table of item counts
  1366. local toRet, toRetTab = 0, {}
  1367. for i=1, inventoryMax do
  1368. local a = turtle.getItemCount(i)
  1369. if a > 0 then toRet = toRet + 1 end
  1370. table.insert(toRetTab, a)
  1371. end
  1372. return toRet, toRetTab
  1373. end
  1374. function getSlotsTable() --Just get the table from above
  1375. local _, toRet = countUsedSlots()
  1376. return toRet
  1377. end
  1378. function getChangedSlots(tab1, tab2) --Returns a table of changed slots. Format is {slotNumber, numberChanged}
  1379. local toRet = {}
  1380. for i=1, math.min(#tab1, #tab2) do
  1381. diff = math.abs(tab2[i]-tab1[i])
  1382. if diff > 0 then
  1383. table.insert(toRet, {i, diff})
  1384. end
  1385. end
  1386. return toRet
  1387. end
  1388. function getFirstChanged(tab1, tab2) --Just a wrapper. Probably not needed
  1389. local a = getChangedSlots(tab1,tab2)
  1390. return (a[1] or {"none"})[1]
  1391. end
  1392.  
  1393. function getRep(which, list) --Gets a representative slot of a type. Expectation is a sequential table of types
  1394. for a,b in pairs(list) do
  1395. if b == which then return a end
  1396. end
  1397. return false
  1398. end
  1399. function assignTypes(types, count) --The parameters allow a preexisting table to be used, like a table from the original compareSlots...
  1400. types, count = types or {1}, count or 1 --Table of types and current highest type
  1401. for i=1, inventoryMax do
  1402. if turtle.getItemCount(i) > 0 and not specialSlots[i] then --Not special slots so we don't count ender chests
  1403. select(i)
  1404. for k=1, count do
  1405. if turtle.compareTo(getRep(k, types)) then types[i] = k end
  1406. end
  1407. if not types[i] then
  1408. count = count + 1
  1409. types[i] = count
  1410. end
  1411. if oreQuarry then
  1412. if blacklist[turtle.getItemDetail().name] then
  1413. dumpSlots[i] = true
  1414. else
  1415. dumpSlots[i] = false
  1416. end
  1417. end
  1418. end
  1419. end
  1420. select(1)
  1421. return types, count
  1422. end
  1423. function getTableOfType(which, list) --Returns a table of all the slots of which type
  1424. local toRet = {}
  1425. for a, b in pairs(list) do
  1426. if b == which then
  1427. table.insert(toRet, a)
  1428. end
  1429. end
  1430. return toRet
  1431. end
  1432.  
  1433. --This is so the turtle will properly get types, otherwise getRep of a type might not be a dumpSlot, even though it should be.
  1434. if not restoreFoundSwitch then --We only want this to happen once
  1435. if oldOreQuarry then --If its not ore quarry, this screws up type assigning
  1436. initialTypes, initialCount = assignTypes()
  1437. else
  1438. initialTypes, initialCount = {1}, 1
  1439. end
  1440. end
  1441.  
  1442. function count(add) --Done any time inventory dropped and at end, true=add, false=nothing, nil=subtract
  1443. local mod = -1
  1444. if add then mod = 1 end
  1445. if add == false then mod = 0 end
  1446. slot = {} --1: Filler 2: Fuel 3:Other --[1] is type, [2] is number
  1447. for i=1, inventoryMax do
  1448. slot[i] = {}
  1449. slot[i][2] = turtle.getItemCount(i)
  1450. end
  1451.  
  1452. local function iterate(toSet , rawTypes, set)
  1453. for _, a in pairs(getTableOfType(toSet, rawTypes)) do --Get all slots matching type
  1454. slot[a][1] = set --Set official type to "set"
  1455. end
  1456. end
  1457.  
  1458. --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
  1459. local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount) --This gets increasingly numbered types, copyTable because assignTypes will modify it
  1460.  
  1461. for i=1, numTypes do
  1462. if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then --Selects the rep slot, checks if it is fuel
  1463. iterate(i, rawTypes, 2) --This type is fuel
  1464. 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
  1465. iterate(i, rawTypes, 1) --This type is cobble/filler
  1466. else
  1467. iterate(i, rawTypes, 3) --This type is other
  1468. end
  1469. end
  1470.  
  1471. for i=1,inventoryMax do
  1472. if not specialSlots[i] then --Do nothing for specialSlots!
  1473. if exactTotals and slot[i][2] > 0 then
  1474. local data = turtle.getItemDetail(i)
  1475. exactTotals[data.name] = (exactTotals[data.name] or 0) + (data.count * mod)
  1476. end
  1477. if slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
  1478. elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
  1479. elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
  1480. end
  1481. end
  1482.  
  1483. select(1)
  1484. end
  1485.  
  1486. --Refuel Functions
  1487. function emergencyRefuel(forceBasic)
  1488. local continueEvac = true --This turns false if more fuel is acquired
  1489. if fuelChest then --This is pretty much the only place that this will be used
  1490. if not fuelChestPhase then --Since I want to do things with return of enderRefuel, I will just make a special system. All of this is for backup safety.
  1491. fuelChestPhase = 0 --Global variable will be saved
  1492. fuelChestProperFacing = facing
  1493. end
  1494. if fuelChestPhase == 0 then
  1495. turnTo(coterminal(fuelChestProperFacing+2))
  1496. dig(false)
  1497. fuelChestPhase = 1
  1498. saveProgress()
  1499. end
  1500. if fuelChestPhase == 1 then
  1501. select(specialSlots.fuelChest)
  1502. turtle.place()
  1503. fuelChestPhase = 2
  1504. saveProgress()
  1505. end
  1506. if fuelChestPhase == 2 then
  1507. if not enderRefuel() then --Returns false if slots are full
  1508. select(specialSlots.fuelChest)
  1509. turtle.drop() --Somehow stuff got in here...
  1510. end
  1511. fuelChestPhase = 3
  1512. saveProgress()
  1513. end
  1514. if fuelChestPhase == 3 then
  1515. select(specialSlots.fuelChest)
  1516. dig(false)
  1517. select(1)
  1518. fuelChestPhase = 4
  1519. saveProgress()
  1520. end
  1521. if fuelChestPhase == 4 then
  1522. turnTo(fuelChestProperFacing)
  1523. fuelChestProperFacing = nil --Getting rid of saved values
  1524. fuelChestPhase = nil
  1525. continueEvac = false
  1526. end
  1527. elseif quadEnabled then --Ask for a quadRotor
  1528. screen()
  1529. print("Attempting an emergency Quad Rotor refuel")
  1530. print("The turtle will soon send a message, then wait ",quadTimeout," seconds before moving on")
  1531. print("Press any key to break timer")
  1532. biometrics(nil, true)
  1533. local timer, counter, counterID, event, id = os.startTimer(quadTimeout), 0, os.startTimer(1)
  1534. local startInventory = getSlotsTable()
  1535. repeat
  1536. if id == counterID then counter = counter + 1; counterID = os.startTimer(1) end
  1537. screenLine(1,6)
  1538. print("Seconds elapsed: ",counter)
  1539. event, id = os.pullEvent() --Waits for a key or fuel or the timer
  1540. until (event == "timer" and id == timer) or event == "key" or event == "turtle_inventory" --Key event just makes turtle go back to start
  1541. if event == "turtle_inventory" then --If fuel was actually delivered
  1542. local slot = getFirstChanged(startInventory, getSlotsTable())
  1543. select(slot)
  1544. local initialFuel = checkFuel()
  1545. midRunRefuel(slot)
  1546. if checkFuel() > initialFuel then
  1547. print("Fuel delivered! Evac aborted")
  1548. continueEvac = false
  1549. else
  1550. print("What did you send the turtle? Not fuel >:(")
  1551. print("Continuing evac")
  1552. end
  1553. sleep(1)
  1554. end
  1555. elseif doRefuel or forceBasic then --Attempt an emergency refueling
  1556. screen()
  1557. print("Attempting an emergency refuel")
  1558. print("Fuel Level: ",checkFuel())
  1559. print("Distance Back: ",(xPos+zPos+yPos+1))
  1560. print("Categorizing Items")
  1561. count(false) --Do not add count, but categorize
  1562. local fuelSwitch, initialFuel = false, checkFuel() --Fuel switch so we don't go over limit (in emergency...)
  1563. print("Going through available fuel slots")
  1564. for i=1, inventoryMax do
  1565. if fuelSwitch then break end
  1566. if turtle.getItemCount(i) > 0 and slot[i][1] == 2 then --If there are items and type 2 (fuel)
  1567. select(i)
  1568. fuelSwitch = midRunRefuel(i) --See above "function drop" for usage
  1569. end
  1570. end
  1571. select(1) --Cleanup
  1572. print("Done fueling")
  1573. if checkFuel() > initialFuel then
  1574. continueEvac = false
  1575. print("Evac Aborted")
  1576. else
  1577. print("Evac is a go, returning to base")
  1578. sleep(1.5) --Pause for reading
  1579. end
  1580. end
  1581. return continueEvac
  1582. end
  1583.  
  1584. function lavaRefuel(suckDir)
  1585. if checkFuel() + lavaBuffer >= checkFuelLimit() then return false end -- we don't want to constantly over-fuel the turtle.
  1586. local suckFunc
  1587. if suckDir == "up" then suckFunc = turtle.placeUp
  1588. elseif suckDir == "down" then suckFunc = turtle.placeDown
  1589. else suckFunc = turtle.place end
  1590.  
  1591. select(specialSlots.lavaBucket)
  1592. if suckFunc() then
  1593. midRunRefuel(specialSlots.lavaBucket, 0) --0 forces it to refuel, even though allowed items[slot] is 1
  1594. end
  1595. select(1)
  1596. return true
  1597. end
  1598.  
  1599. --Mining functions
  1600. function dig(doAdd, mineFunc, inspectFunc, suckDir) --Note, turtle will not bother comparing if not given an inspectFunc
  1601. if doAdd == nil then doAdd = true end
  1602. mineFunc = mineFunc or turtle.dig
  1603. 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)
  1604. --Mine if not in blacklist. inspectFunc returns success and (table or string) so retTab filters out the string and the extra table prevents errors.
  1605. local mineFlag = false
  1606. if oreQuarry and inspectFunc then
  1607. local worked, data = inspectFunc()
  1608. if data then
  1609. mineFlag = not blacklist[data.name]
  1610. if data.name == chestID then
  1611. emptyChest(suckDir)
  1612. end
  1613. if lavaBucket and data.name == lavaID and data.metadata == lavaMeta then
  1614. lavaRefuel(suckDir)
  1615. end
  1616. end
  1617. end
  1618. if not oreQuarry or not inspectFunc or mineFlag then --Mines if not oreQuarry, or if the inspect passed
  1619. if mineFunc() then
  1620. if doAdd then
  1621. mined = mined + 1
  1622. end
  1623. return true
  1624. else
  1625. return false
  1626. end
  1627. end
  1628. return true --This only runs if oreQuarry but item not in blacklist. true means succeeded in duty, not necessarily dug block
  1629. end
  1630.  
  1631. function digUp(doAdd, ignoreInspect)--Regular functions :) I switch definitions for optimization (I think)
  1632. return dig(doAdd, turtle.digUp, (not ignoreInspect and turtle.inspectUp) or nil, "up")
  1633. end
  1634. function digDown(doAdd, ignoreInspect)
  1635. return dig(doAdd, turtle.digDown, (not ignoreInspect and turtle.inspectDown) or nil, "down")
  1636. end
  1637. if inverted then --If inverted, switch the options
  1638. digUp, digDown = digDown, digUp
  1639. end
  1640.  
  1641. function smartDig(doDigUp, doDigDown) --This function is used only in mine when oldOreQuarry
  1642. if inverted then doDigUp, doDigDown = doDigDown, doDigUp end --Switching for invert
  1643. local blockAbove, blockBelow = doDigUp and turtle.detectUp(), doDigDown and turtle.detectDown() --These control whether or not the turtle digs
  1644. local index = 1
  1645. for i=1, #compareSlots do
  1646. if not (blockAbove or blockBelow) then break end --We don't want to go selecting if there is nothing to dig
  1647. index = i --To access out of scope
  1648. select(compareSlots[i])
  1649. if blockAbove and turtle.compareUp() then blockAbove = false end
  1650. if blockBelow and turtle.compareDown() then blockBelow = false end
  1651. end
  1652. if compareChest then
  1653. local flag = false
  1654. select(specialSlots.compareChest)
  1655. if turtle.compareUp() then emptyChest("up") end --Impressively, this actually works with session persistence. I'm gooood (apparently :P )
  1656. if turtle.compareDown() then emptyChest("down") end --Looking over the code, I see no reason why that works... Oh well.
  1657. end
  1658. table.insert(compareSlots, 1, table.remove(compareSlots, index)) --This is so the last selected slot is the first slot checked, saving a select call
  1659. if blockAbove then dig(true, turtle.digUp) end
  1660. if blockBelow then dig(true, turtle.digDown) end
  1661. end
  1662.  
  1663. function relxCalc()
  1664. if layersDone % 2 == 1 then
  1665. relzPos = zPos
  1666. else
  1667. relzPos = (z-zPos) + 1
  1668. end
  1669. if relzPos % 2 == 1 then
  1670. relxPos = xPos
  1671. else
  1672. relxPos = (x-xPos)+1
  1673. end
  1674. if layersDone % 2 == 0 and z % 2 == 1 then
  1675. relxPos = (x-relxPos)+1
  1676. end
  1677. end
  1678. function horizontalMove(movement, posAdd, doAdd)
  1679. if doAdd == nil then doAdd = true end
  1680. if movement() then
  1681. if doAdd then
  1682. moved = moved + 1
  1683. end
  1684. if facing == 0 then
  1685. xPos = xPos + 1
  1686. elseif facing == 1 then
  1687. zPos = zPos + 1
  1688. elseif facing == 2 then
  1689. xPos = xPos - 1
  1690. elseif facing == 3 then
  1691. zPos = zPos - 1
  1692. else
  1693. error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  1694. end
  1695. relxCalc()
  1696. return true
  1697. end
  1698. return false
  1699. end
  1700. function forward(doAdd)
  1701. return horizontalMove(turtle.forward, 1, doAdd)
  1702. end
  1703. function back(doAdd)
  1704. return horizontalMove(turtle.back, -1, doAdd)
  1705. end
  1706. function verticalMove(moveFunc, yDiff, digFunc, attackFunc)
  1707. local count = 0
  1708. while not moveFunc() do
  1709. if not digFunc(true, true) then --True True is doAdd, and ignoreInspect
  1710. attackFunc()
  1711. sleep(0.5)
  1712. count = count + 1
  1713. if count > maxTries and yPos > (startY-7) then bedrock() end
  1714. end
  1715. end
  1716. yPos = yDiff + yPos
  1717. saveProgress()
  1718. biometrics()
  1719. return true
  1720. end
  1721. function up() --Uses other function if inverted
  1722. verticalMove(inverted and turtle.down or turtle.up, -1, digUp, attackUp) --Other functions deal with invert already
  1723. end
  1724. function down()
  1725. verticalMove(inverted and turtle.up or turtle.down, 1, digDown, attackDown)
  1726. end
  1727.  
  1728.  
  1729. function right(num)
  1730. num = num or 1
  1731. for i=1, num do
  1732. facing = coterminal(facing+1)
  1733. saveProgress()
  1734. if not goLeftNotRight then turtle.turnRight() --Normally
  1735. else turtle.turnLeft() end --Left Quarry
  1736. end
  1737. end
  1738. function left(num)
  1739. num = num or 1
  1740. for i=1, num do
  1741. facing = coterminal(facing-1)
  1742. saveProgress()
  1743. if not goLeftNotRight then turtle.turnLeft() --Normally
  1744. else turtle.turnRight() end --Left Quarry
  1745. end
  1746. end
  1747.  
  1748. function attack(doAdd, func)
  1749. doAdd = doAdd or true
  1750. func = func or turtle.attack
  1751. if func() then
  1752. if doAdd then
  1753. attacked = attacked + 1
  1754. end
  1755. return true
  1756. end
  1757. return false
  1758. end
  1759. function attackUp(doAdd)
  1760. if inverted then
  1761. return attack(doAdd, turtle.attackDown)
  1762. else
  1763. return attack(doAdd, turtle.attackUp)
  1764. end
  1765. end
  1766. function attackDown(doAdd)
  1767. if inverted then
  1768. return attack(doAdd, turtle.attackUp)
  1769. else
  1770. return attack(doAdd, turtle.attackDown)
  1771. end
  1772. end
  1773.  
  1774. function detect(func)
  1775. func = func or turtle.detect
  1776. return func()
  1777. end
  1778. function detectUp(ignoreInvert)
  1779. if inverted and not ignoreInvert then return detect(turtle.detectDown)
  1780. else return detect(turtle.detectUp) end
  1781. end
  1782. function detectDown(ignoreInvert)
  1783. if inverted and not ignoreInvert then return detect(turtle.detectUp)
  1784. else return detect(turtle.detectDown) end
  1785. end
  1786.  
  1787.  
  1788.  
  1789. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  1790. if doCheckInv == nil then doCheckInv = true end
  1791. if doDigDown == nil then doDigDown = true end
  1792. if doDigUp == nil then doDigUp = true end
  1793. if outOfPath == nil then outOfPath = false end
  1794. isInPath = (not outOfPath) --For rednet
  1795. 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...
  1796. local continueEvac = false --It will be set true unless at start
  1797. if xPos ~= 0 then
  1798. continueEvac = emergencyRefuel() --This is a huge list of things to do in an emergency
  1799. end
  1800. if continueEvac then
  1801. eventClear() --Clear any annoying events for evac
  1802. local currPos = yPos
  1803. endingProcedure() --End the program
  1804. print("Turtle ran low on fuel so was brought back to start for you :)\n\nTo resume where you left off, use '-startDown "..tostring(currPos-1).."' when you start")
  1805. error("",0)
  1806. end
  1807. end
  1808. if frontChest and not outOfPath then
  1809. if turtle.inspect then
  1810. local check, data = turtle.inspect()
  1811. if check and data.name == chestID then
  1812. emptyChest("front")
  1813. end
  1814. else
  1815. local flag = false
  1816. select(specialSlots.compareChest)
  1817. if turtle.compare() then flag = true end
  1818. select(1)
  1819. if flag then
  1820. emptyChest("front")
  1821. end
  1822. end
  1823. end
  1824.  
  1825. local count = 0
  1826. if not outOfPath then dig() end --This speeds up the quarry by a decent amount if there are more mineable blocks than air
  1827. while not forward(not outOfPath) do
  1828. sleep(0) --Calls coroutine.yield to prevent errors
  1829. count = count + 1
  1830. if not dig() then
  1831. attack()
  1832. end
  1833. if count > 10 then
  1834. attack()
  1835. sleep(0.2)
  1836. end
  1837. if count > maxTries then
  1838. if checkFuel() == 0 then --Don't worry about inf fuel because I modified this function
  1839. saveProgress({doCheckFuel = true, doRefuel = true}) --This is emergency because this should never really happen.
  1840. os.reboot()
  1841. elseif yPos > (startY-7) and turtle.detect() then --If it is near bedrock
  1842. bedrock()
  1843. else --Otherwise just sleep for a bit to avoid sheeps
  1844. sleep(1)
  1845. end
  1846. end
  1847. end
  1848. checkSanity() --Not kidding... This is necessary
  1849. saveProgress(tab)
  1850.  
  1851. if not oldOreQuarry then
  1852. if doDigUp then--The digging up and down part
  1853. sleep(0) --Calls coroutine.yield
  1854. if not digUp(true) and detectUp() then --This is relative: will dig down first on invert
  1855. if not attackUp() then
  1856. if yPos > (startY-7) then bedrock() end --Checking for bedrock, but respecting user wishes
  1857. end
  1858. end
  1859. end
  1860. if doDigDown then
  1861. digDown(true) --This needs to be absolute as well
  1862. end
  1863. else --If oldQuarry
  1864. smartDig(doDigUp,doDigDown)
  1865. end
  1866. percent = math.ceil(moved/moveVolume*100)
  1867. updateDisplay()
  1868. if doCheckInv and careAboutResources then
  1869. if isFull(inventoryMax-keepOpen) then
  1870. if not ((oreQuarry or oldOreQuarry) and dumpCompareItems) then
  1871. dropOff()
  1872. else
  1873. local currInv = getSlotsTable()
  1874. drop(nil, false, true) --This also takes care of counting.
  1875. if #getChangedSlots(currInv, getSlotsTable()) <= 2 then --This is so if the inventory is full of useful stuff, it still has to drop it
  1876. dropOff()
  1877. end
  1878. end
  1879. end
  1880. end
  1881. biometrics()
  1882. end
  1883. --Insanity Checking
  1884. function checkSanity()
  1885. if not isInPath then --I don't really care if its not in the path.
  1886. return true
  1887. end
  1888. if not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  1889. turnTo(0)
  1890. rowCheck = true
  1891. end
  1892. if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  1893. saveProgress()
  1894. print("I have gone outside boundaries, attempting to fix (maybe)")
  1895. if xPos > x then goto(x, zPos, yPos, 2) end --I could do this with some fancy math, but this is much easier
  1896. if xPos < 0 then goto(1, zPos, yPos, 0) end
  1897. if zPos > z then goto(xPos, z, yPos, 3) end
  1898. if zPos < 0 then goto(xPos, 1, yPos, 1) end
  1899. relxCalc() --Get relxPos properly
  1900. eventClear()
  1901.  
  1902. --[[
  1903. print("Oops. Detected that quarry was outside of predefined boundaries.")
  1904. print("Please go to my forum thread and report this with a short description of what happened")
  1905. print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  1906. error("",0)]]
  1907. end
  1908. end
  1909.  
  1910. local function fromBoolean(input) --Like a calculator
  1911. if input then return 1 end
  1912. return 0
  1913. end
  1914. local function multBoolean(first,second) --Boolean multiplication
  1915. return (fromBoolean(first) * fromBoolean(second)) == 1
  1916. end
  1917. function coterminal(num, limit) --I knew this would come in handy :D
  1918. limit = limit or 4 --This is for facing
  1919. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  1920. end
  1921. if tArgs["-manualpos"] then
  1922. facing = coterminal(facing) --Done to improve support for "-manualPos"
  1923. if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end --Ditto
  1924. relxCalc() --Ditto
  1925. end
  1926.  
  1927. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  1928. function turnTo(num)
  1929. num = num or facing
  1930. num = coterminal(num) --Prevent errors
  1931. local turnRight = true
  1932. if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  1933. while facing ~= num do --The above is used to smartly turn
  1934. if turnRight then
  1935. right()
  1936. else
  1937. left()
  1938. end
  1939. end
  1940. end
  1941. function goto(x,z,y, toFace, destination)
  1942. --Will first go to desired z pos, then x pos, y pos varies
  1943. x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  1944. gotoDest = destination or "" --This is used by biometrics.
  1945. statusString = "Going to ".. (destination or "somewhere")
  1946. --Possible destinations: layerStart, quarryStart
  1947. if yPos > y then --Will go up first if below position
  1948. while yPos~=y do up() end
  1949. end
  1950. if zPos > z then
  1951. turnTo(3)
  1952. elseif zPos < z then
  1953. turnTo(1)
  1954. end
  1955. while zPos ~= z do mine(false,false,true,false) end
  1956. if xPos > x then
  1957. turnTo(2)
  1958. elseif xPos < x then
  1959. turnTo(0)
  1960. end
  1961. while xPos ~= x do mine(false,false,true,false) end
  1962. if yPos < y then --Will go down after if above position
  1963. while yPos~=y do down() end
  1964. end
  1965. turnTo(toFace)
  1966. saveProgress()
  1967. gotoDest = ""
  1968. statusString = nil
  1969. end
  1970. function getNumOpenSlots()
  1971. local toRet = 0
  1972. for i=1, inventoryMax do
  1973. if turtle.getItemCount(i) == 0 then
  1974. toRet = toRet + 1
  1975. end
  1976. end
  1977. return toRet
  1978. end
  1979. function emptyChest(suckDirection)
  1980. eventAdd("emptyChest",suckDirection)
  1981. eventSetInsertionPoint(2) --Because dropOff adds events we want to run first
  1982. local suckFunc
  1983. if suckDirection == "up" then
  1984. suckFunc = turtle.suckUp
  1985. elseif suckDirection == "down" then
  1986. suckFunc = turtle.suckDown
  1987. else
  1988. suckFunc = turtle.suck
  1989. end
  1990. repeat
  1991. if inventoryMax - countUsedSlots() <= 0 then --If there are no slots open, need to empty
  1992. dropOff()
  1993. end
  1994. until not suckFunc()
  1995. eventClear()
  1996. eventSetInsertionPoint()
  1997. end
  1998.  
  1999. --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.
  2000. local function waitDrop(slot, allowed, whereDrop) --This will just drop, but wait if it can't
  2001. allowed = allowed or 0
  2002. while turtle.getItemCount(slot) > allowed do --No more half items stuck in slot!
  2003. local tries = 1
  2004. while not whereDrop(turtle.getItemCount(slot)-allowed) do --Drop off only the amount needed
  2005. screen(1,1)
  2006. print("Chest Full, Try "..tries)
  2007. chestFull = true
  2008. biometrics()--To send that the chest is full
  2009. tries = tries + 1
  2010. sleep(2)
  2011. end
  2012. chestFull = false
  2013. end
  2014. end
  2015.  
  2016. function midRunRefuel(i, allowed)
  2017. allowed = allowed or allowedItems[i]
  2018. local numToRefuel = turtle.getItemCount(i)-allowed
  2019. if checkFuel() >= checkFuelLimit() then return true end --If it doesn't need fuel, then signal to not take more
  2020. local firstCheck = checkFuel()
  2021. if numToRefuel > 0 then turtle.refuel(1) --This is so we can see how many fuel we need.
  2022. else return false end --Bandaid solution: If won't refuel, don't try.
  2023. local singleFuel
  2024. 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
  2025. --Refuel The lesser of max allowable or remaining fuel space / either inf or a single fuel (which can be 0)
  2026. turtle.refuel(math.min(numToRefuel-1, math.ceil((checkFuelLimit()-checkFuel()) / singleFuel))) --The refueling part of the the doRefuel option
  2027. if checkFuel() >= checkFuelLimit() then return true end --Do not need any more fuel
  2028. return false --Turtle can still be fueled
  2029. end
  2030.  
  2031. function enderRefuel() --Assumes a) An enderchest is in front of it b) It needs fuel
  2032. local slot
  2033. for a,b in ipairs(getSlotsTable()) do
  2034. if b == 0 then slot = a; break end
  2035. end
  2036. if not slot then return false end --No room for fueling
  2037. select(slot)
  2038. repeat
  2039. print("Required Fuel: ",checkFuelLimit())
  2040. print("Current Fuel: ",checkFuel())
  2041. local tries = 0
  2042. while not turtle.suck() do
  2043. sleep(1)
  2044. statusString = "No Fuel in Ender Chest"
  2045. biometrics() --Let user know that fuel chest is empty
  2046. print(statusString,". Try: ",tries)
  2047. tries = tries + 1
  2048. end
  2049. statusString = nil
  2050. until midRunRefuel(slot, 0) --Returns true when should not refuel any more
  2051. 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
  2052. return true -- :D
  2053. end
  2054.  
  2055.  
  2056. function drop(side, final, compareDump)
  2057. side = sides[side] or "front"
  2058. local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
  2059. if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
  2060. if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
  2061. if side == "right" then turnTo(1); dropFacing = 0 end
  2062. if side == "left" then turnTo(3); dropFacing = 0 end
  2063. local properFacing = facing --Capture the proper direction to be facing
  2064.  
  2065. count(true) --Count number of items before drop. True means add. This is before chest detect, because could be final
  2066.  
  2067. while not compareDump and not detectFunc() do
  2068. if final then return end --If final, we don't need a chest to be placed, but there can be
  2069. chestFull = true
  2070. biometrics() --Let the user know there is a problem with chest
  2071. screen(1,1) --Clear screen
  2072. print("Waiting for chest placement on ",side," side (when facing quarry)")
  2073. sleep(2)
  2074. end
  2075. chestFull = false
  2076.  
  2077. local fuelSwitch = false --If doRefuel, this can switch so it won't overfuel
  2078. for i=1,inventoryMax do
  2079. --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
  2080. if turtle.getItemCount(i) > 0 then --Saves time, stops bugs
  2081. if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing) --Turn around to drop junk, not store it. dumpComapareItems is global config
  2082. else turnTo(properFacing) --Turn back to proper position... or do nothing if already there
  2083. end
  2084. select(i)
  2085. if slot[i][1] == 2 then --Intelligently refuels to fuel limit
  2086. if doRefuel and not fuelSwitch then --Not in the conditional because we don't want to waitDrop excess fuel. Not a break so we can drop junk
  2087. fuelSwitch = midRunRefuel(i)
  2088. else
  2089. waitDrop(i, allowedItems[i], dropFunc)
  2090. end
  2091. if fuelSwitch then
  2092. waitDrop(i, allowedItems[i], dropFunc)
  2093. end
  2094. elseif not compareDump or (compareDump and slot[i][1] == 1) then --This stops all wanted items from being dropped off in a compareDump
  2095. waitDrop(i, allowedItems[i], dropFunc)
  2096. end
  2097. end
  2098. end
  2099.  
  2100. if compareDump then
  2101. for i=2, inventoryMax do
  2102. if not specialSlots[i] then --We don't want to move buckets and things into earlier slots
  2103. select(i)
  2104. for j=1, i-1 do
  2105. if turtle.getItemCount(i) == 0 then break end
  2106. turtle.transferTo(j)
  2107. end
  2108. end
  2109. end
  2110. select(1)
  2111. end
  2112. if oldOreQuarry or compareDump then count(nil) end--Subtract the items still there if oreQuarry
  2113. resetDumpSlots() --So that slots gone aren't counted as dump slots next
  2114.  
  2115. select(1) --For fanciness sake
  2116.  
  2117. end
  2118.  
  2119. function dropOff() --Not local because called in mine()
  2120. local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  2121. if careAboutResources then
  2122. if not enderChest then --Regularly
  2123. eventAdd("goto", 1,1,currY,2, "drop off") --Need this step for "-startDown"
  2124. eventAdd('goto(0,1,1,2,"drop off")')
  2125. eventAdd("drop", dropSide,false)
  2126. eventAdd("turnTo(0)")
  2127. eventAdd("mine",false,false,true,false)
  2128. eventAdd("goto(1,1,1, 0)")
  2129. eventAdd("goto", 1, 1, currY, 0)
  2130. eventAdd("goto", currX,currZ,currY,currFacing)
  2131. else --If using an enderChest
  2132. if turtle.getItemCount(specialSlots.enderChest) ~= 1 then eventAdd("promptSpecialSlot('enderChest','Ender Chest')") end
  2133. eventAdd("turnTo",currFacing-2)
  2134. eventAdd("dig",false)
  2135. eventAdd("select",specialSlots.enderChest)
  2136. eventAdd("turtle.place")
  2137. eventAdd("drop","front",false)
  2138. eventAdd("turnTo",currFacing-2)
  2139. eventAdd("select", specialSlots.enderChest)
  2140. eventAdd("dig",false)
  2141. eventAdd("turnTo",currFacing)
  2142. eventAdd("select(1)")
  2143. end
  2144. runAllEvents()
  2145. numDropOffs = numDropOffs + 1 --Analytics tracking
  2146. end
  2147. return true
  2148. end
  2149. function endingProcedure() --Used both at the end and in "biometrics"
  2150. eventAdd("goto",1,1,yPos,2,"quarryStart") --Allows for startDown variable
  2151. eventAdd("goto",0,1,1,2, "quarryStart") --Go back to base
  2152. runAllEvents()
  2153. --Output to a chest or sit there
  2154. if enderChest then
  2155. if dropSide == "right" then eventAdd("turnTo(1)") end --Turn to proper drop side
  2156. if dropSide == "left" then eventAdd("turnTo(3)") end
  2157. eventAdd("dig(false)") --This gets rid of a block in front of the turtle.
  2158. eventAdd("select",specialSlots.enderChest)
  2159. eventAdd("turtle.place")
  2160. eventAdd("select(1)")
  2161. end
  2162. eventAdd("drop",dropSide, true)
  2163. eventAdd("turnTo(0)")
  2164.  
  2165. --Display was moved above to be used in bedrock function
  2166. eventAdd("display")
  2167. --Log current mining run
  2168. eventAdd("logMiningRun",logExtension)
  2169. toQuit = true --I'll use this flag to clean up (legacy)
  2170. runAllEvents()
  2171. end
  2172. function bedrock()
  2173. foundBedrock = true --Let everyone know
  2174. if rednetEnabled then biometrics() end
  2175. if checkFuel() == 0 then error("No Fuel",0) end
  2176. local origin = {x = xPos, y = yPos, z = zPos}
  2177. print("Bedrock Detected")
  2178. if turtle.detectUp() and not turtle.digUp() then
  2179. print("Block Above")
  2180. turnTo(facing+2)
  2181. repeat
  2182. if not forward(false) then --Tries to go back out the way it came
  2183. if not attck() then --Just making sure not mob-blocked
  2184. if not dig() then --Now we know its bedrock
  2185. turnTo(facing+1) --Try going a different direction
  2186. end
  2187. end
  2188. end
  2189. until not turtle.detectUp() or turtle.digUp() --These should be absolute and we don't care about about counting resources here.
  2190. end
  2191. up() --Go up two to avoid any bedrock.
  2192. up()
  2193. eventClear() --Get rid of any excess events that may be run. Don't want that.
  2194. endingProcedure()
  2195. print("\nFound bedrock at these coordinates: ")
  2196. print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  2197. error("",0)
  2198. end
  2199.  
  2200. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  2201. local halfFacing = ((layersDone % 2 == 1) and 1) or 3
  2202. local toFace = coterminal(wasFacing + 2) --Opposite side
  2203. if zPos == startZ then
  2204. if facing ~= halfFacing then turnTo(halfFacing) end
  2205. mine(unpack(mineFunctionTable or {}))
  2206. end
  2207. if facing ~= toFace then
  2208. turnTo(toFace)
  2209. end
  2210. end
  2211.  
  2212.  
  2213. -------------------------------------------------------------------------------------
  2214. --Pre-Mining Stuff dealing with session persistence
  2215. runAllEvents()
  2216. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  2217.  
  2218. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  2219. if not restoreFoundSwitch then --Regularly
  2220. --Check if it is a mining turtle
  2221. if not isMiningTurtle then
  2222. local a, b = turtle.dig()
  2223. if a then
  2224. mined = mined + 1
  2225. isMiningTurtle = true
  2226. elseif b == "Nothing to dig with" or b == "No tool to dig with" then
  2227. print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  2228. error("",0)
  2229. end
  2230. end
  2231.  
  2232. if checkFuel() == 0 then --Some people forget to start their turtles with fuel
  2233. screen(1,1)
  2234. print("I have no fuel and doCheckFuel is off!")
  2235. print("Starting emergency fueling procedures!\n")
  2236. emergencyRefuel()
  2237. if checkFuel() == 0 then
  2238. print("I have no fuel and can't get more!")
  2239. print("Try using -doRefuel or -fuelChest")
  2240. print("I have no choice but to quit.")
  2241. error("",0)
  2242. end
  2243. end
  2244.  
  2245. mine(false,false,true) --Get into quarry by going forward one
  2246. 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.
  2247. gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  2248. end
  2249. for i = 1, startDown do
  2250. eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  2251. end
  2252. runAllEvents()
  2253. if flatBedrock then
  2254. while (detectDown() and digDown(false, true)) or not detectDown() do --None of these functions are non-invert protected because inverse always false here
  2255. down()
  2256. startDown = startDown + 1
  2257. end
  2258. startDown = startDown - y + 1
  2259. for i=1, y-2 do
  2260. up() --It has hit bedrock, now go back up for proper 3 wide mining
  2261. end
  2262. elseif not(y == 1 or y == 2) then
  2263. down() --Go down to align properly. If y is one or two, it doesn't need to do this.
  2264. end
  2265. else --restore found
  2266. if not(layersDone == layers and not doDigDown) then digDown() end
  2267. if not(layersDone == layers and not doDigUp) then digUp() end --Get blocks missed before stopped
  2268. end
  2269. --Mining Loops--------------------------------------------------------------------------
  2270. select(1)
  2271. while layersDone <= layers do -------------Height---------
  2272. local lastLayer = layersDone == layers --If this is the last layer
  2273. local secondToLastLayer = (layersDone + 1) == layers --This is a check for going down at the end of a layer.
  2274. moved = moved + 1 --To account for the first position in row as "moved"
  2275. if not(layersDone == layers and not doDigDown) then digDown() end --This is because it doesn't mine first block in layer
  2276. if not restoreFoundSwitch and layersDone % 2 == 1 then rowCheck = true end
  2277. relxCalc()
  2278. while relzPos <= z do -------------Width----------
  2279. while relxPos < x do ------------Length---------
  2280. 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
  2281. end ---------------Length End-------
  2282. if relzPos ~= z then --If not on last row of section
  2283. local func
  2284. if rowCheck == true then --Switching to next row
  2285. func = "right"; rowCheck = false; else func = false; rowCheck = true end --Which way to turn
  2286. eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  2287. runAllEvents()
  2288. else break
  2289. end
  2290. end ---------------Width End--------
  2291. if layersDone % 2 == 0 then --Will only go back to start on non-even layers
  2292. eventAdd("goto",1,1,yPos,0, "layerStart") --Goto start of layer
  2293. else
  2294. eventAdd("turnTo",coterminal(facing-2))
  2295. end
  2296. if not lastLayer then --If there is another layer
  2297. 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
  2298. end
  2299. eventAdd("relxCalc")
  2300. layersDone = layersDone + 1
  2301. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  2302. runAllEvents()
  2303. end ---------------Height End-------
  2304.  
  2305. endingProcedure() --This takes care of getting to start, dropping in chest, and displaying ending screen
Add Comment
Please, Sign In to add comment