Guest User

Untitled

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