Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --Civilwargeeky's Quarry Program
- VERSION = "3.6.3 TurtleScripts"
- civilTable = nil; _G.civilTable = {}; setmetatable(civilTable, {__index = getfenv()}); setfenv(1,civilTable)
- originalDay = os.day()
- numResumed = 0
- x,y,z = 3,3,3
- inverted = false
- rednetEnabled = false
- dropSide = "front"
- careAboutResources = true
- doCheckFuel = true
- doRefuel = false
- keepOpen = 1
- fuelSafety = "moderate"
- excessFuelAmount = math.huge
- fuelMultiplier = 1
- saveFile = "Civil_Quarry_Restore"
- autoResume = true
- startupRename = "oldStartup.quarry"
- startupName = "startup"
- doBackup = true
- uniqueExtras = 8
- maxTries = 200
- gpsEnabled = false
- gpsTimeout = 3
- legacyRednet = false
- logging = true
- logFolder = "Quarry_Logs"
- logExtension = ""
- flatBedrock = false
- startDown = 0
- enderChestEnabled = false
- enderChestSlot = 16
- fuelChestEnabled = false
- fuelChestSlot = 15
- preciseTotals = false
- goLeftNotRight = false
- oreQuarry = false
- oreQuarryBlacklistName = "oreQuarryBlacklist.txt"
- dumpCompareItems = true
- inventoryMax = 16
- quadEnabled = false
- quadTimeout = 60 * 5
- fuelTable = {
- safe = 1000,
- moderate = 200,
- loose = 0 }
- channels = {
- send = os.getComputerID() + 1 ,
- receive = os.getComputerID() + 101 ,
- confirm = "Turtle Quarry Receiver",
- message = "Civil's Quarry",
- fingerprint = "quarry"
- }
- local help_paragraph = [[
- Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
- Unfortunately: I had to remove the help section to upload to turtle scripts. So sorry :( Please download from my forum thread instead.
- Thread: http://www.computercraft.info/forums2/index.php?/topic/5681-variable-size-quarry-now-with-super-ore-quarry%e2%84%a2/
- ]]
- local help = {}
- local i = 0
- local titlePattern = ".-%:"
- local textPattern = "%:.+"
- for a in help_paragraph:gmatch("\n?.-\n") do
- local current = string.sub(a,1,-2)..""
- if string.sub(current,1,1) ~= " " then
- i = i + 1
- help[i] = {}
- help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
- help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
- elseif string.sub(current,1,1) == " " then
- table.insert(help[i], string.sub(current,2, -1).."")
- end
- end
- local supportsRednet
- if peripheral.find then
- supportsRednet = peripheral.find("modem") or false
- else
- supportsRednet = (peripheral.getType("right") == "modem") or false
- end
- 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
- = 0, 1, 1, 0, 0, 0, 0, 1, true , false, true, 1, 0, 0, false, "", false, 0, 0, {}, {}, {}, 1, false, false, {}, 0
- local statusString
- for i=1, inventoryMax do
- allowedItems[i] = 0
- dumpSlots[i] = false
- end
- totals = {cobble = 0, fuel = 0, other = 0}
- local function newSpecialSlot(index, value)
- value = tonumber(value) or 0
- if value ~= 0 and specialSlots[value] then error("Failed making special slot: "..index.."\nSlot "..tonumber(value).." already taken",2) end
- specialSlots[index] = value
- specialSlots[value] = index
- return true
- end
- function resetDumpSlots()
- for i=1, inventoryMax do
- if oldOreQuarry then
- if turtle.getItemCount(i) > 0 and i~= specialSlots.enderChest then
- dumpSlots[i] = true
- else
- dumpSlots[i] = false
- end
- else
- dumpSlots[i] = false
- end
- end
- if not oldOreQuarry and specialSlots.enderChest == 1 then
- dumpSlots[2] = true
- elseif not oldOreQuarry then
- dumpSlots[1] = true
- end
- end
- local function copyTable(tab) local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end
- local foundBedrock = false
- local checkFuel, checkFuelLimit
- if turtle then
- checkFuel = turtle.getFuelLevel
- if turtle.getFuelLevel() == "unlimited" then
- checkFuel = function() return math.huge end
- end
- if turtle.getFuelLimit then
- checkFuelLimit = function() return math.min(turtle.getFuelLimit(), excessFuelAmount) end
- if turtle.getFuelLimit() == "unlimited" then
- checkFuelLimit = function() return math.huge end
- end
- else
- checkFuelLimit = function() return excessFuelAmount end
- end
- turtle.select(1)
- end
- function select(slot)
- if slot ~= selectedSlot and slot > 0 and slot <= inventoryMax then
- selectedSlot = slot
- return turtle.select(slot), selectedSlot
- end
- end
- local function screen(xPos,yPos)
- xPos, yPos = xPos or 1, yPos or 1
- term.setCursorPos(xPos,yPos); term.clear(); end
- local function screenLine(xPos,yPos)
- term.setCursorPos(xPos,yPos); term.clearLine(); end
- screen(1,1)
- print("")
- print("")
- local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"}
- local tArgs
- local originalArgs = {...}
- local changedT, tArgsWithUpper, forcePrompts = {}, {}, {}
- changedT.new = function(key, value) table.insert(changedT,{key, value}) end
- changedT.remove = function() table.remove(changedT) end
- local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
- local function initializeArgs()
- tArgs = copyTable(originalArgs)
- for i=1, #tArgs do
- tArgsWithUpper[i] = tArgs[i]
- tArgsWithUpper[tArgsWithUpper[i]] = i
- tArgs[i] = tArgs[i]:lower()
- tArgs[tArgs[i]] = i
- if tArgs[i] == "-forceprompt" and i ~= #tArgs then
- forcePrompts[tArgs[i+1]:lower()] = true
- end
- end
- end
- initializeArgs()
- local restoreFound, restoreFoundSwitch = false
- function parseParam(name, displayText, formatString, forcePrompt, trigger, variableOverride, variableExists)
- if variableExists ~= false then variableExists = true end
- if trigger == nil then trigger = true end
- if not trigger then return end
- if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end
- if not restoreFoundSwitch and (tArgs["-promptall"] or forcePrompts[name:lower()]) then forcePrompt = true end
- local toGetText = name:lower()
- local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString)
- local args = formatString:sub(({formatString:find(formatType)})[2] + 2)..""
- local variable = variableOverride or name
- local func = loadstring("return "..variable)
- setfenv(func,getfenv(1))
- local originalValue = assert(func)()
- if originalValue == nil and variableExists then error("From addParam, \""..variable.."\" returned nil",2) end
- local givenValue, toRet
- if tArgs["-"..toGetText] then
- givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1]
- elseif forcePrompt then
- write(displayText.."? ")
- givenValue = io.read()
- end
- if formatType == "force" then
- toRet = (tArgs["-"..toGetText] and true) or false
- end
- if not (givenValue or toRet) or (type(givenValue) == "string" and #givenValue == 0) then return end
- if formatType == "boolean" then
- toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f"
- elseif formatType == "string" then
- toRet = givenValue:match("^[%w%./]+")
- elseif formatType == "number" or formatType == "float" then
- toRet = tonumber(givenValue)
- if not toRet then return end
- if formatType == "number" then toRet = math.floor(toRet) end
- local startNum, endNum = formatString:match("(%d+)%-(%d+)")
- startNum, endNum = tonumber(startNum), tonumber(endNum)
- if not ((toRet >= startNum) and (toRet <= endNum)) then return end
- elseif formatType == "side" then
- local exclusionTab = {}
- for a in args:gmatch("%S+") do exclusionTab[a] = true end
- if not exclusionTab[givenValue] then toRet = sides[givenValue] end
- elseif formatType == "list" then
- toRet = {}
- for a in args:gmatch("[^,]") do
- table.insert(toRet,a)
- end
- elseif formatType == "force" then
- else error("Improper formatType",2)
- end
- if toRet == nil then return end
- tempParam = toRet
- local func = loadstring(variable.." = tempParam")
- setfenv(func, getfenv(1))
- func()
- tempParam = nil
- if toRet ~= originalValue and displayText ~= "" then
- changedT.new(displayText, tostring(toRet))
- end
- return toRet
- end
- local paramLookup = {}
- local function addParam(...)
- local args = {...}
- if not paramLookup[args[1]] then
- local toRet = copyTable(args)
- for i=2, table.maxn(toRet) do
- toRet[i-1] = toRet[i]
- end
- table.remove(toRet)
- paramLookup[args[1]] = toRet
- end
- return parseParam(unpack(args, 1, table.maxn(args)))
- end
- local function paramAlias(original, alias)
- local a = paramLookup[original]
- if a then
- if a[5] == nil then a[5] = original end
- parseParam(alias, unpack(a, 1, table.maxn(a)))
- else
- error("In paramAlias: '"..original.."' did not exist",2)
- end
- end
- if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then
- print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
- print("Press 'q' to quit, or any other key to start help ")
- if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
- end
- if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
- print("You have selected help, press any key to continue"); print("Use arrow keys to navigate, q to quit"); os.pullEvent("key")
- local pos = 1
- local key = 0
- while pos <= #help and key ~= keys.q do
- if pos < 1 then pos = 1 end
- screen(1,1)
- print(help[pos].title)
- for a=1, #help[pos] do print(help[pos][a]) end
- repeat
- _, key = os.pullEvent("key")
- until key == 200 or key == 208 or key == keys.q
- if key == 200 then pos = pos - 1 end
- if key == 208 then pos = pos + 1 end
- end
- error("",0)
- end
- if tArgs["-version"] or tArgs["version"] then
- print("QUARRY VERSION: ",VERSION)
- error("",0)
- end
- local function split(str, sep)
- assert(#sep == 1, "Split seperator too long. Got '"..sep.."'")
- if not str:match(sep) then return {str} end
- local toRet = {}
- toRet[1] = str:match("^([^"..sep.."]-)"..sep)
- for i in str:gmatch(sep.."([^"..sep.."]*)") do
- toRet[#toRet+1] = i
- end
- return toRet
- end
- if addParam("file","Custom Parameters","string", false, nil, "parameterFile", false) and parameterFile then
- if not fs.exists(parameterFile) then
- print("WARNING: '"..parameterFile.."' DOES NOT EXIST. FILE NOT LOADED")
- sleep(3)
- changedT.remove()
- else
- local file = fs.open(parameterFile, "r")
- local text = file.readAll()
- file.close()
- text = text.."\n"
- text = text:gsub("#[^\n]-\n","")
- local commands = {}
- local append = table.insert
- for _, a in pairs(split(text,"\n")) do
- local words = split(a," ")
- if not a:match("-") then
- append(originalArgs,"-"..words[1])
- for i=2, #words do
- append(originalArgs, words[i])
- end
- else
- for i=1, #words do
- append(originalArgs, words[i])
- end
- end
- end
- initializeArgs()
- print("Finished loading file: ",tArgs[tArgs["-file"]+1])
- sleep(0.5)
- end
- end
- addParam("doBackup", "Backup Save File", "boolean")
- addParam("saveFile", "Save File Name", "string")
- restoreFound = fs.exists(saveFile)
- restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound and doBackup
- if restoreFoundSwitch then
- local file = fs.open(saveFile,"r")
- local test = file.readAll() ~= ""
- file.close()
- if test then
- os.run(getfenv(1),saveFile)
- numResumed = numResumed + 1
- if checkFuel() ~= math.huge then
- if fuelLevel - checkFuel() == 1 then
- if facing == 0 then xPos = xPos + 1
- elseif facing == 2 then xPos = xPos - 1
- elseif facing == 1 then zPos = zPos + 1
- elseif facing == 3 then zPos = zPos - 1 end
- elseif fuelLevel - checkFuel() ~= 0 then
- print("Very Strange Fuel in Restore Section...")
- print("Current: ",checkFuel())
- print("Saved: ",fuelLevel)
- print("Difference: ",fuelLevel - checkFuel())
- os.pullEvent("char")
- end
- end
- if gpsEnabled then
- print("Found GPS Start Coordinates")
- local currLoc = {gps.locate(gpsTimeout)} or {}
- local backupPos = {xPos, yPos, zPos}
- if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then
- print("GPS Position Successfully Read")
- if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then
- xPos, yPos, zPos = 0,1,1
- if facing ~= 0 then turnTo(0) end
- print("Is at start")
- else
- if inverted then
- end
- local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos)
- local flag = true
- if b[3] - a[3] == -1 then
- a[1] = a[1] - 1
- xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
- elseif b[1] - a[1] == 1 then
- a[3] = a[3] - 1
- xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
- elseif b[3] - a[3] == 1 then
- a[1] = a[1] + 1
- xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
- elseif b[1] - a[1] == -1 then
- a[3] = a[3] + 1
- xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
- else
- flag = false
- print("Improper Coordinates")
- print("GPS Locate Failed, Using Standard Methods")
- end
- if flag and goLeftNotRight then
- zPos = math.abs(zPos-1) + 1
- end
- end
- print("X Pos: ",xPos)
- print("Y Pos: ",yPos)
- print("Z Pos: ",zPos)
- print("Facing: ",facing)
- for i=1, 3, 2 do
- if backupPos[i] ~= currLoc[i] then
- events = {}
- end
- end
- else
- print("GPS Locate Failed, Using Standard Methods")
- end
- print("Restore File read successfully. Starting in 3"); sleep(3)
- end
- else
- fs.delete(saveFile)
- print("Restore file was empty, sorry, aborting")
- error("",0)
- end
- else
- events = {}
- originalFuel = checkFuel()
- end
- if tArgs["-dim"] then
- local a,b,c = x,y,z
- local num = tArgs["-dim"]
- x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
- if a ~= x then changedT.new("Length", x) end
- if c ~= z then changedT.new("Width", z) end
- if b ~= y then changedT.new("Height", y) end
- elseif not (tArgs["-default"] or restoreFoundSwitch) then
- print("What dimensions?")
- print("")
- term.write("Length? ")
- x = math.floor(math.abs(tonumber(io.read()) or x))
- term.write("Width? ")
- z = math.floor(math.abs(tonumber(io.read()) or z))
- term.write("Height? ")
- y = math.floor(math.abs(tonumber(io.read()) or y))
- changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
- end
- addParam("flatBedrock","Go to bedrock", "boolean")
- addParam("invert", "Inverted","boolean", true, not flatBedrock, "inverted")
- addParam("startDown","Start Down","number 1-256", nil, not flatBedrock)
- addParam("left","Left Quarry","boolean", nil, nil, "goLeftNotRight")
- addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
- addParam("enderChest","Ender Chest Enabled","boolean special", nil, nil, "enderChestEnabled")
- addParam("enderChest", "Ender Chest Slot", "number 1-16", nil, nil, "enderChestSlot")
- newSpecialSlot("enderChest",enderChestEnabled and enderChestSlot or 0)
- addParam("fuelChest","Fuel Chest Enabled","boolean special", nil, nil, "fuelChestEnabled")
- addParam("fuelChest", "Fuel Chest Slot", "number 1-16", nil, nil, "fuelChestSlot")
- newSpecialSlot("fuelChest", fuelChestEnabled and fuelChestSlot or 0)
- addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
- addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
- addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
- addParam("fingerprint","Sending Fingerprint", "string", false, supportsRednet, "channels.fingerprint")
- addParam("legacyRednet","Legacy Rednet","boolean", false, supportsRednet)
- if addParam("quad", "Quad Rotor Enabled","boolean",nil, rednetEnabled, "quadEnabled") then
- gpsEnabled = true
- end
- addParam("quadTimeout","Quad Rotor Timeout","number 1-1000000", nil, quadEnabled)
- addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet and not quadEnabled, "gpsEnabled" )
- if gpsEnabled and not restoreFoundSwitch then
- gpsStartPos = {gps.locate(gpsTimeout)}
- gpsEnabled = #gpsStartPos > 0
- if quadEnabled and not gpsEnabled then
- error("You have no GPS network. You may not use Quad Rotors",0)
- end
- end
- addParam("uniqueExtras","Unique Items", "number 0-15")
- addParam("doRefuel", "Refuel from Inventory","boolean", nil, checkFuel() ~= math.huge)
- addParam("doCheckFuel", "Check Fuel", "boolean", nil, checkFuel() ~= math.huge)
- excessFuelAmount = excessFuelAmount or math.huge
- addParam("maxFuel", "Max Fuel", "number 1-999999999", nil, checkFuel() ~= math.huge, "excessFuelAmount")
- addParam("fuelMultiplier", "Fuel Multiplier", "float 1-9001", nil, checkFuel() ~= math.huge)
- paramAlias("fuelMultiplier","fuelRequestMultiplier")
- paramAlias("fuelMultiplier","overFuel")
- addParam("logging", "Logging", "boolean")
- addParam("logFolder", "Log Folder", "string")
- addParam("logExtension","Log Extension", "string")
- addParam("startY", "Start Y","number 1-256")
- addParam("maxTries","Tries Before Bedrock", "number 1-9001")
- addParam("keepOpen", "Slots to Keep Open", "number 1-15")
- addParam("careAboutResources", "Care About Resources","boolean")
- addParam("preciseTotals","Precise Totals","boolean", nil, turtle.getItemDetail ~= nil)
- if preciseTotals and not restoreFoundSwitch then
- exactTotals = {}
- end
- addParam("autoResume", "Auto Resume", "boolean", nil, doBackup)
- paramAlias("autoResume","autoRestart")
- addParam("startupRename", "Startup Rename","string", nil, autoResume)
- addParam("startupName", "Startup File", "string", nil, autoResume)
- addParam("oreQuarry", "Ore Quarry", "boolean" )
- if oreQuarry and not turtle.inspect then
- oldOreQuarry = true
- oreQuarry = false
- end
- addParam("oldOreQuarry", "Old Ore Quarry", "boolean")
- addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oldOreQuarry)
- addParam("extraDropItems", "", "force", nil, oldOreQuarry)
- paramAlias("extraDropItems","extraDumpItems")
- addParam("blacklist","Ore Blacklist", "string", nil, oreQuarry, "oreQuarryBlacklistName")
- paramAlias("blacklist","blacklistFile")
- if flatBedrock then
- inverted = false
- end
- local function doAutoResumeStuff()
- if fs.exists(startupName) then
- if fs.exists(startupRename) then fs.delete(startupRename) end
- fs.move(startupName, startupRename)
- end
- local file = fs.open(startupName,"w")
- file.writeLine(
- [[
- print("Now Resuming Quarry")
- print("Press any key to quit. You have 5 seconds.")
- function deleteStuff()
- fs.delete("]]..startupName..[[")
- if fs.exists("]]..startupRename..[[") then
- fs.move("]]..startupRename.."\",\""..startupName..[[")
- end
- end
- local event
- if fs.exists("]]..saveFile..[[") then
- for i=5,1,-1 do
- print(i)
- os.startTimer(1)
- event = os.pullEvent()
- if event == "key" then break end
- end
- if event == "timer" then
- os.run({},"]]..shell.getRunningProgram()..[[","-resume")
- else
- deleteStuff()
- end
- else
- print("Never mind, no save file found")
- deleteStuff()
- end
- ]])
- file.close()
- end
- if autoResume and not restoreFoundSwitch then
- doAutoResumeStuff()
- end
- local blacklist = { "minecraft:air", "minecraft:bedrock", "minecraft:cobblestone", "minecraft:dirt", "minecraft:ice", "minecraft:ladder", "minecraft:netherrack", "minecraft:sand", "minecraft:sandstone",
- "minecraft:snow", "minecraft:snow_layer", "minecraft:stone", "minecraft:gravel", "minecraft:grass", "minecraft:torch" }
- for a,b in pairs(blacklist) do
- blacklist[b], blacklist[b] = true, nil
- end
- if fs.exists(oreQuarryBlacklistName) then
- local file = fs.open(oreQuarryBlacklistName, "r")
- blacklist = {}
- for a in file:readAll():gmatch("[^,]+") do
- blacklist[a:match("%S+:%S+")] = true
- end
- file:close()
- end
- if tArgs["-manualpos"] then
- local a = tArgs["-manualpos"]
- 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
- changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
- restoreFoundSwitch = true
- for i=0,4 do tArgs[a+i] = "" end
- end
- if addParam("atChest", "Is at Chest", "force") then
- local neededLayer = math.floor((yPos+1)/3)*3-1
- if neededLayer > 2 and neededLayer%3 ~= 2 then
- print("Last known pos was not in proper layer, restarting quarry")
- sleep(4)
- neededLayer = 2
- end
- if ((neededLayer-2)/3) % 2 == 1 then neededLayer = neededLayer - 3 end
- xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
- doAutoResumeStuff()
- events = {{"goto",1,1,neededLayer, 0}}
- end
- local function saveProgress(extras)
- exclusions = { modem = true, }
- if doBackup then
- local toWrite = ""
- for a,b in pairs(getfenv(1)) do
- if not exclusions[a] then
- if type(b) == "string" then b = "\""..b.."\"" end
- if type(b) == "table" then b = textutils.serialize(b) end
- if type(b) ~= "function" then
- toWrite = toWrite..a.." = "..tostring(b).."\n"
- end
- end
- end
- toWrite = toWrite.."doCheckFuel = false\n"
- local file
- repeat
- file = fs.open(saveFile,"w")
- until file
- file.write(toWrite)
- if type(extras) == "table" then
- for a, b in pairs(extras) do
- file.write(a.." = "..tostring(b).."\n")
- end
- end
- if checkFuel() ~= math.huge then
- file.write("fuelLevel = "..tostring(checkFuel()).."\n")
- end
- file.close()
- end
- end
- local area = x*z
- local volume = x*y*z
- local lastHeight = y%3
- layers = math.ceil(y/3)
- local yMult = layers
- local moveVolume = (area * yMult)
- do
- local changeYFuel = 2*(y + startDown)
- local dropOffSupplies = 2*(x + z + y + startDown)
- local frequency = math.ceil(((moveVolume/(64*(15-uniqueExtras) + uniqueExtras)) ) )
- if enderChestEnabled then frequency = 0 end
- neededFuel = moveVolume + changeYFuel + (frequency * dropOffSupplies) + ((x + z) * layers)
- neededFuel = neededFuel + fuelTable[fuelSafety]
- end
- if neededFuel > checkFuelLimit() and doCheckFuel then
- if not (doRefuel or fuelChestEnabled) then
- screen()
- print("Turtle cannot hold enough fuel\n")
- 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")
- local _, key = os.pullEvent("char")
- if key == "1" then
- screen(); print("Okay"); error("",0)
- elseif key == "3" then
- doCheckFuel = false
- elseif key == "4" then
- else
- doRefuel = true
- end
- end
- neededFuel = checkFuelLimit()-checkFuel()-1
- end
- local hasRefueled
- if doCheckFuel and checkFuel() < neededFuel then
- neededFuel = math.min(math.floor(neededFuel * fuelMultiplier), checkFuelLimit()-checkFuel()-1)
- hasRefueled = true
- print("Not enough fuel")
- print("Current: ",checkFuel()," Needed: ",neededFuel)
- print("Starting SmartFuel...")
- sleep(2)
- term.clear()
- local oneFuel, neededFuelItems = 0,0
- local currSlot = 0
- local function output(text, x, y)
- local currX, currY = term.getCursorPos()
- term.setCursorPos(x,y)
- term.clearLine()
- term.write(text)
- term.setCursorPos(currX,currY)
- end
- local function roundTo(num, target)
- if num >= target then return target elseif num < 0 then return 0 else return num end
- end
- local function updateScreen()
- output("Welcome to SmartFuel! Now Refueling...", 1,1)
- output("Fuel Request Multiplier: "..tostring(fuelMultiplier).."x",1,2)
- output("Currently taking fuel from slot "..currSlot,1,3)
- output("Current single fuel: "..tostring(oneFuel or 0),1,4)
- output("Current estimate of needed fuel: ",1,4)
- output("Single Items: "..math.ceil(neededFuelItems),4,6)
- output("Stacks: "..math.ceil(neededFuelItems / 64),4,7)
- output("Needed Fuel: "..tostring(neededFuel),1,12)
- output("Current Fuel: "..tostring(checkFuel()),1,13)
- end
- while checkFuel() < neededFuel do
- currSlot = currSlot + 1
- select(currSlot)
- if currSlot ~= 1 and not turtle.refuel(0) then
- currSlot = 1; select(currSlot)
- end
- updateScreen()
- while turtle.getItemCount(currSlot) == 0 do
- sleep(1.5)
- end
- repeat
- local previous = checkFuel()
- turtle.refuel(1)
- oneFuel = checkFuel() - previous
- updateScreen()
- until (oneFuel or 0) > 0
- neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel)
- turtle.refuel(roundTo(neededFuelItems, 64))
- if turtle.getItemCount(roundTo(currSlot + 1, inventoryMax)) == 0 then
- currSlot = 0
- end
- neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel)
- end
- select(1)
- end
- function promptSpecialSlot(specialSlot, name)
- while turtle.getItemCount(specialSlots[specialSlot]) ~= 1 do
- screen(1,1)
- print("You have decided to use a ",name,"!")
- print("Please place one ",name," in slot ",specialSlots[specialSlot])
- sleep(1)
- end
- print(name," in slot ",specialSlots[specialSlot], " checks out")
- end
- function checkSpecialSlot(specialSlot, name)
- if restoreFoundSwitch and turtle.getItemCount(specialSlots[specialSlot]) == 0 then
- select(specialSlots[specialSlot])
- turtle.dig()
- select(1)
- end
- promptSpecialSlot(specialSlot, name)
- allowedItems[specialSlots[specialSlot]] = 1
- sleep(2)
- end
- if enderChestEnabled then
- checkSpecialSlot("enderChest","Ender Chest")
- end
- if fuelChestEnabled then
- checkSpecialSlot("fuelChest","Fuel Chest")
- end
- if oldOreQuarry then
- if not restoreFoundSwitch then
- local counter = 0
- for i=1, inventoryMax do if turtle.getItemCount(i) > 0 and i ~= specialSlots.enderChest then counter = counter+1 end end
- screen(1,1)
- print("You have selected an Ore Quarry!")
- if counter == 0 or hasRefueled then
- print("Please place your compare blocks in the first slots\n")
- print("Press Enter when done")
- repeat until ({os.pullEvent("key")})[2] == 28
- else
- print("Registering slots as compare slots")
- sleep(1)
- end
- for i=1, inventoryMax do
- if turtle.getItemCount(i) > 0 then
- if i ~= specialSlots.enderChest then
- table.insert(compareSlots, i)
- allowedItems[i] = 1
- dumpSlots[i] = true
- end
- end
- end
- if extraDropItems then
- screen(1,1)
- print("Put in extra drop items now\n")
- print("Press Enter when done")
- repeat until ({os.pullEvent("key")})[2] == 28
- for i=1,inventoryMax do
- if not dumpSlots[i] and turtle.getItemCount(i) > 0 then
- dumpSlots[i] = true
- allowedItems[i] = 1
- end
- end
- end
- 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
- end
- local counter = 0
- for a, b in pairs(compareSlots) do if turtle.getItemCount(b) > 0 then counter = counter + 1 end end
- if counter == 0 then
- screen(1,1)
- print("You have an ore quarry without any compare slots. Continue? y/n")
- if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
- end
- elseif not oreQuarry then
- dumpCompareItems = false
- if specialSlots.enderChest == 1 then
- dumpSlots[2] = true
- else
- dumpSlots[1] = true
- end
- end
- function newMessageID()
- return math.random(1,2000000000)
- end
- function sendMessage(send, receive, message)
- if legacyRednet then
- if type(message) == "table" then message = textutils.serialize(message) end
- return modem.transmit(send, receive, message)
- end
- return modem.transmit(send , receive, {fingerprint = channels.fingerprint, id = newMessageID(), message = message})
- end
- if rednetEnabled then
- screen(1,1)
- print("Rednet is Enabled")
- print("The Channel to open is "..channels.send)
- if peripheral.find then
- modem = peripheral.find("modem")
- else
- modem = peripheral.wrap("right")
- end
- modem.open(channels.receive)
- local i = 0
- repeat
- local id = os.startTimer(3)
- i=i+1
- print("Sending Initial Message "..i)
- sendMessage(channels.send, channels.receive, channels.message)
- local message = {}
- repeat
- local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
- if locMessage then message = locMessage end
- if legacyRednet then
- message = {message = message}
- end
- until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and type(message) == "table")
- until message.message == channels.confirm
- connected = true
- print("Connection Confirmed!")
- sleep(1.5)
- end
- function biometrics(isAtBedrock, requestQuad)
- if not rednetEnabled then return end
- local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
- percent = percent, zPos = relzPos, xPos = relxPos, yPos = yPos,
- layersDone = layersDone, x = x, z = z, layers = layers,
- openSlots = getNumOpenSlots(), mined = mined, moved = moved,
- chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
- isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
- fuel = checkFuel(), volume = volume, status = statusString,
- }
- if requestQuad and isInPath then
- if not gps.locate(gpsTimeout) then
- print("\nOH NOES! Trying to reach quadrotor, but can't get GPS position!")
- sleep(1)
- else
- toSend.firstPos = gpsStartPos
- toSend.secondPos = gpsSecondPos
- toSend.emergencyLocation = {gps.locate(gpsTimeout)}
- end
- end
- sendMessage(channels.send, channels.receive, toSend)
- id = os.startTimer(0.1)
- local event, received
- repeat
- local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
- event, received = locEvent, locMessage or {message = ""}
- if legacyRednet and type(received) == "string" then
- received = {message = received}
- end
- until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive and type(received) == "table")
- if event == "modem_message" then connected = true else connected = false end
- local message = received.message:lower()
- if message == "stop" or message == "quit" or message == "kill" then error("Rednet said to stop...",0) end
- if message == "return" then
- endingProcedure()
- error('Rednet said go back to start...',0)
- end
- if message == "drop" then
- dropOff()
- end
- if message == "pause" then
- print("\nTurtle is paused. Send 'resume' or press any character to resume")
- statusString = "Paused"
- repeat
- sleep(1)
- sendMessage(channels.send, channels.receive, toSend)
- local event, idCheck, confirm, _, message, distance = os.pullEvent()
- until (event == "modem_message" and confirm == channels.receive and (message.message == "resume" or message.message == "unpause" or message.message == "pause")) or (event == "char")
- statusString = nil
- end
- if message == "refuel" then
- print("\nEngaging in emergency refueling")
- emergencyRefuel()
- end
- end
- screen(1,1)
- print("Your selected settings:")
- if #changedT == 0 then
- print("Completely Default")
- else
- for i=1, #changedT do
- print(changedT[i][1],": ",changedT[i][2])
- end
- end
- print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5)
- function eventAddAt(pos, ...)
- return table.insert(events,pos, {...}) or true
- end
- function eventAdd(...)
- return eventAddAt(1, ...)
- end
- function eventGet(pos)
- return events[tonumber(pos) or #events]
- end
- function eventPop(pos)
- return table.remove(events,tonumber(pos) or #events) or false
- end
- function eventRun(value, ...)
- local argsList = {...}
- if type(value) == "string" then
- if value:sub(-1) ~= ")" then
- value = value .. "("
- for a, b in pairs(argsList) do
- local toAppend
- if type(b) == "table" then toAppend = textutils.serialize(b)
- elseif type(b) == "string" then toAppend = "\""..tostring(b).."\""
- else toAppend = tostring(b) end
- value = value .. (toAppend or "true") .. ", "
- end
- if value:sub(-1) ~= "(" then
- value = value:sub(1,-3)..""
- end
- value = value .. ")"
- end
- local func = loadstring(value)
- setfenv(func, getfenv(1))
- return func()
- end
- end
- function eventClear(pos)
- if pos then events[pos] = nil else events = {} end
- end
- function runAllEvents()
- while #events > 0 do
- local toRun = eventGet()
- eventRun(unpack(toRun))
- eventPop()
- end
- end
- function display()
- screen(1,1)
- print("Total Blocks Mined: "..mined)
- print("Current Fuel Level: "..checkFuel())
- print("Cobble: "..totals.cobble)
- print("Usable Fuel: "..totals.fuel)
- print("Other: "..totals.other)
- if rednetEnabled then
- print("")
- print("Sent Stop Message")
- if legacyRednet then
- print("Sent Legacy Stop")
- sendMessage(channels.send, channels.receive, "stop")
- end
- local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
- other = totals.other, fuel = checkFuel(), isDone = true }
- sendMessage(channels.send,channels.receive, finalTable)
- modem.close(channels.receive)
- end
- if doBackup then
- fs.delete(saveFile)
- if autoResume then
- fs.delete(startupName)
- if fs.exists(startupRename) then
- fs.move(startupRename, startupName)
- end
- end
- end
- end
- function updateDisplay()
- screen(1,1)
- print("Blocks Mined")
- print(mined)
- print("Percent Complete")
- print(percent.."%")
- print("Fuel")
- print(checkFuel())
- if rednetEnabled then
- screenLine(1,7)
- print("Connected: "..tostring(connected))
- end
- end
- local function pad(str, length, side)
- toRet = ""
- if side == "right" then
- toRet = str
- end
- for i=1, length do
- toRet = toRet.." "
- end
- if side == "left" then
- toRet = toRet..str
- end
- return toRet
- end
- function logMiningRun(textExtension, extras)
- if not logging then return end
- local number, name = 0
- if not fs.isDir(logFolder) then
- fs.delete(logFolder)
- fs.makeDir(logFolder)
- end
- repeat
- number = number + 1
- name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
- until not fs.exists(name)
- local handle = fs.open(name,"w")
- local function write(...)
- for a, b in ipairs({...}) do
- handle.write(tostring(b))
- end
- handle.write("\n")
- end
- local function boolToText(bool) if bool then return "Yes" else return "No" end end
- write("Welcome to the Quarry Logs!")
- write("Entry Number: ",number)
- write("Quarry Version: ",VERSION)
- write("Dimensions (X Z Y): ",x," ",z," ", y)
- write("Blocks Mined: ", mined)
- write(" Cobble: ", totals.cobble)
- write(" Usable Fuel: ", totals.fuel)
- write(" Other: ",totals.other)
- write("Total Fuel Used: ", (originalFuel or (neededFuel + checkFuel()))- checkFuel())
- write("Expected Fuel Use: ", neededFuel)
- write("Days to complete mining run: ",os.day()-originalDay)
- write("Day Started: ", originalDay)
- write("Number of times resumed: ", numResumed)
- write("Was an ore quarry? ",boolToText(oreQuarry or oldOreQuarry))
- write("Was inverted? ",boolToText(invert))
- write("Was using rednet? ",boolToText(rednetEnabled))
- write("Chest was on the ",dropSide," side")
- if startDown > 0 then write("Started ",startDown," blocks down") end
- if exactTotals then
- write("\n==DETAILED TOTALS==")
- for a,b in pairs(exactTotals) do
- write(pad(a, 15, "right"),":",pad(tostring(b),({term.getSize()})[1]-15-1, "left"))
- end
- end
- handle.close()
- end
- function isFull(slots)
- slots = slots or inventoryMax
- local numUsed = 0
- sleep(0)
- for i=1, inventoryMax do
- if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
- end
- if numUsed > slots then
- return true
- end
- return false
- end
- function countUsedSlots()
- local toRet, toRetTab = 0, {}
- for i=1, inventoryMax do
- local a = turtle.getItemCount(i)
- if a > 0 then toRet = toRet + 1 end
- table.insert(toRetTab, a)
- end
- return toRet, toRetTab
- end
- function getSlotsTable()
- local _, toRet = countUsedSlots()
- return toRet
- end
- function getChangedSlots(tab1, tab2)
- local toRet = {}
- for i=1, math.min(#tab1, #tab2) do
- diff = math.abs(tab2[i]-tab1[i])
- if diff > 0 then
- table.insert(toRet, {i, diff})
- end
- end
- return toRet
- end
- function getFirstChanged(tab1, tab2)
- local a = getChangedSlots(tab1,tab2)
- return (a[1] or {"none"})[1]
- end
- function getRep(which, list)
- for a,b in pairs(list) do
- if b == which then return a end
- end
- return false
- end
- function assignTypes(types, count)
- types, count = types or {1}, count or 1
- for i=1, inventoryMax do
- if turtle.getItemCount(i) > 0 and not specialSlots[i] then
- select(i)
- for k=1, count do
- if turtle.compareTo(getRep(k, types)) then types[i] = k end
- end
- if not types[i] then
- count = count + 1
- types[i] = count
- end
- if oreQuarry then
- if blacklist[turtle.getItemDetail().name] then
- dumpSlots[i] = true
- else
- dumpSlots[i] = false
- end
- end
- end
- end
- select(1)
- return types, count
- end
- function getTableOfType(which, list)
- local toRet = {}
- for a, b in pairs(list) do
- if b == which then
- table.insert(toRet, a)
- end
- end
- return toRet
- end
- if not restoreFoundSwitch then
- if oldOreQuarry then
- initialTypes, initialCount = assignTypes()
- else
- initialTypes, initialCount = {1}, 1
- end
- end
- function count(add)
- local mod = -1
- if add then mod = 1 end
- if add == false then mod = 0 end
- slot = {}
- for i=1, inventoryMax do
- slot[i] = {}
- slot[i][2] = turtle.getItemCount(i)
- end
- local function iterate(toSet , rawTypes, set)
- for _, a in pairs(getTableOfType(toSet, rawTypes)) do
- slot[a][1] = set
- end
- end
- local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount)
- for i=1, numTypes do
- if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then
- iterate(i, rawTypes, 2)
- elseif dumpSlots[getRep(i,(oreQuarry and rawTypes) or initialTypes)] then
- iterate(i, rawTypes, 1)
- else
- iterate(i, rawTypes, 3)
- end
- end
- for i=1,inventoryMax do
- if not specialSlots[i] then
- if exactTotals then
- local data = turtle.getItemDetail()
- exactTotals[data.name] = (exactTotals[data.name] or 0) + data.count
- end
- if slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
- elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
- elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
- end
- end
- select(1)
- end
- function dig(doAdd, mineFunc, inspectFunc)
- if doAdd == nil then doAdd = true end
- mineFunc = mineFunc or turtle.dig
- local function retTab(tab) if type(tab) == "table" then return tab end end
- if not oreQuarry or not inspectFunc or not blacklist[(retTab(({inspectFunc()})[2]) or {name = "none"}).name] then
- if mineFunc() then
- if doAdd then
- mined = mined + 1
- end
- return true
- else
- return false
- end
- end
- return true
- end
- function emergencyRefuel()
- local continueEvac = true
- if fuelChestEnabled then
- if not fuelChestPhase then
- fuelChestPhase = 0
- fuelChestProperFacing = facing
- end
- if fuelChestPhase == 0 then
- turnTo(coterminal(fuelChestProperFacing+2))
- dig(false)
- fuelChestPhase = 1
- saveProgress()
- end
- if fuelChestPhase == 1 then
- select(specialSlots.fuelChest)
- turtle.place()
- fuelChestPhase = 2
- saveProgress()
- end
- if fuelChestPhase == 2 then
- if not enderRefuel() then
- select(specialSlots.fuelChest)
- turtle.drop()
- end
- fuelChestPhase = 3
- saveProgress()
- end
- if fuelChestPhase == 3 then
- select(specialSlots.fuelChest)
- dig(false)
- select(1)
- fuelChestPhase = 4
- saveProgress()
- end
- if fuelChestPhase == 4 then
- turnTo(fuelChestProperFacing)
- fuelChestProperFacing = nil
- fuelChestPhase = nil
- continueEvac = false
- end
- elseif quadEnabled then
- screen()
- print("Attempting an emergency Quad Rotor refuel")
- print("The turtle will soon send a message, then wait ",quadTimeout," seconds before moving on")
- print("Press any key to break timer")
- biometrics(nil, true)
- local timer, counter, counterID, event, id = os.startTimer(quadTimeout), 0, os.startTimer(1)
- local startInventory = getSlotsTable()
- repeat
- if id == counterID then counter = counter + 1; counterID = os.startTimer(1) end
- screenLine(1,6)
- print("Seconds elapsed: ",counter)
- event, id = os.pullEvent()
- until (event == "timer" and id == timer) or event == "key" or event == "turtle_inventory"
- if event == "turtle_inventory" then
- local slot = getFirstChanged(startInventory, getSlotsTable())
- select(slot)
- local initialFuel = checkFuel()
- midRunRefuel(slot)
- if checkFuel() > initialFuel then
- print("Fuel delivered! Evac aborted")
- continueEvac = false
- else
- print("What did you send the turtle? Not fuel >:(")
- print("Continuing evac")
- end
- sleep(1)
- end
- elseif doRefuel then
- screen()
- print("Attempting an emergency refuel")
- print("Fuel Level: ",checkFuel())
- print("Distance Back: ",(xPos+zPos+yPos+1))
- print("Categorizing Items")
- count(false)
- local fuelSwitch, initialFuel = false, checkFuel()
- print("Going through available fuel slots")
- for i=1, inventoryMax do
- if fuelSwitch then break end
- if turtle.getItemCount(i) > 0 and slot[i][1] == 2 then
- select(i)
- fuelSwitch = midRunRefuel(i)
- end
- end
- select(1)
- print("Done fueling")
- if checkFuel() > initialFuel then
- continueEvac = false
- print("Evac Aborted")
- else
- print("Evac is a go, returning to base")
- sleep(1.5)
- end
- end
- return continueEvac
- end
- function digUp(doAdd, ignoreInspect)
- return dig(doAdd, turtle.digUp, (not ignoreInspect and turtle.inspectUp) or nil)
- end
- function digDown(doAdd, ignoreInspect)
- return dig(doAdd, turtle.digDown, (not ignoreInspect and turtle.inspectDown) or nil)
- end
- if inverted then
- digUp, digDown = digDown, digUp
- end
- function smartDig(doDigUp, doDigDown)
- if inverted then doDigUp, doDigDown = doDigDown, doDigUp end
- local blockAbove, blockBelow = doDigUp and turtle.detectUp(), doDigDown and turtle.detectDown()
- local index = 1
- for i=1, #compareSlots do
- if not (blockAbove or blockBelow) then break end
- index = i
- select(compareSlots[i])
- if blockAbove and turtle.compareUp() then blockAbove = false end
- if blockBelow and turtle.compareDown() then blockBelow = false end
- end
- table.insert(compareSlots, 1, table.remove(compareSlots, index))
- if blockAbove then dig(true, turtle.digUp) end
- if blockBelow then dig(true, turtle.digDown) end
- end
- function relxCalc()
- if layersDone % 2 == 1 then
- relzPos = zPos
- else
- relzPos = (z-zPos) + 1
- end
- if relzPos % 2 == 1 then
- relxPos = xPos
- else
- relxPos = (x-xPos)+1
- end
- if layersDone % 2 == 0 and z % 2 == 1 then
- relxPos = (x-relxPos)+1
- end
- end
- function horizontalMove(movement, posAdd, doAdd)
- if doAdd == nil then doAdd = true end
- if movement() then
- if doAdd then
- moved = moved + 1
- end
- if facing == 0 then
- xPos = xPos + 1
- elseif facing == 1 then
- zPos = zPos + 1
- elseif facing == 2 then
- xPos = xPos - 1
- elseif facing == 3 then
- zPos = zPos - 1
- else
- error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
- end
- relxCalc()
- return true
- end
- return false
- end
- function forward(doAdd)
- return horizontalMove(turtle.forward, 1, doAdd)
- end
- function back(doAdd)
- return horizontalMove(turtle.back, -1, doAdd)
- end
- function verticalMove(moveFunc, yDiff, digFunc, attackFunc)
- local count = 0
- while not moveFunc() do
- if not digFunc(true, true) then
- attackFunc()
- sleep(0.5)
- count = count + 1
- if count > maxTries and yPos > (startY-7) then bedrock() end
- end
- end
- yPos = yDiff + yPos
- saveProgress()
- biometrics()
- return true
- end
- function up()
- verticalMove(inverted and turtle.down or turtle.up, -1, digUp, attackUp)
- end
- function down()
- verticalMove(inverted and turtle.up or turtle.down, 1, digDown, attackDown)
- end
- function right(num)
- num = num or 1
- for i=1, num do
- facing = coterminal(facing+1)
- saveProgress()
- if not goLeftNotRight then turtle.turnRight()
- else turtle.turnLeft() end
- end
- end
- function left(num)
- num = num or 1
- for i=1, num do
- facing = coterminal(facing-1)
- saveProgress()
- if not goLeftNotRight then turtle.turnLeft()
- else turtle.turnRight() end
- end
- end
- function attack(doAdd, func)
- doAdd = doAdd or true
- func = func or turtle.attack
- if func() then
- if doAdd then
- attacked = attacked + 1
- end
- return true
- end
- return false
- end
- function attackUp(doAdd)
- if inverted then
- return attack(doAdd, turtle.attackDown)
- else
- return attack(doAdd, turtle.attackUp)
- end
- end
- function attackDown(doAdd)
- if inverted then
- return attack(doAdd, turtle.attackUp)
- else
- return attack(doAdd, turtle.attackDown)
- end
- end
- function detect(func)
- func = func or turtle.detect
- return func()
- end
- function detectUp(ignoreInvert)
- if inverted and not ignoreInvert then return detect(turtle.detectDown)
- else return detect(turtle.detectUp) end
- end
- function detectDown(ignoreInvert)
- if inverted and not ignoreInvert then return detect(turtle.detectUp)
- else return detect(turtle.detectDown) end
- end
- function mine(doDigDown, doDigUp, outOfPath,doCheckInv)
- if doCheckInv == nil then doCheckInv = true end
- if doDigDown == nil then doDigDown = true end
- if doDigUp == nil then doDigUp = true end
- if outOfPath == nil then outOfPath = false end
- isInPath = (not outOfPath)
- if not outOfPath and (checkFuel() <= xPos + zPos + yPos + 5) then
- local continueEvac = false
- if xPos ~= 0 then
- continueEvac = emergencyRefuel()
- end
- if continueEvac then
- eventClear()
- local currPos = yPos
- endingProcedure()
- 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")
- error("",0)
- end
- end
- local count = 0
- if not outOfPath then dig() end
- while not forward(not outOfPath) do
- sleep(0)
- count = count + 1
- if not dig() then
- attack()
- end
- if count > 10 then
- attack()
- sleep(0.2)
- end
- if count > maxTries then
- if checkFuel() == 0 then
- saveProgress({doCheckFuel = true, doRefuel = true})
- os.reboot()
- elseif yPos > (startY-7) and turtle.detect() then
- bedrock()
- else
- sleep(1)
- end
- end
- end
- checkSanity()
- saveProgress(tab)
- if not oldOreQuarry then
- if doDigUp then
- sleep(0)
- if not digUp(true) and detectUp() then
- if not attackUp() then
- if yPos > (startY-7) then bedrock() end
- end
- end
- end
- if doDigDown then
- digDown(true)
- end
- else
- smartDig(doDigUp,doDigDown)
- end
- percent = math.ceil(moved/moveVolume*100)
- updateDisplay()
- if doCheckInv and careAboutResources then
- if isFull(inventoryMax-keepOpen) then
- if not ((oreQuarry or oldOreQuarry) and dumpCompareItems) then
- dropOff()
- else
- local currInv = getSlotsTable()
- drop(nil, false, true)
- if #getChangedSlots(currInv, getSlotsTable()) <= 2 then
- dropOff()
- end
- end
- end
- end
- biometrics()
- end
- function checkSanity()
- if not isInPath then
- return true
- end
- if not (facing == 0 or facing == 2) and #events == 0 then
- turnTo(0)
- rowCheck = true
- end
- if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
- saveProgress()
- print("I have gone outside boundaries, attempting to fix (maybe)")
- if xPos > x then goto(x, zPos, yPos, 2) end
- if xPos < 0 then goto(1, zPos, yPos, 0) end
- if zPos > z then goto(xPos, z, yPos, 3) end
- if zPos < 0 then goto(xPos, 1, yPos, 1) end
- relxCalc()
- eventClear()
- end
- end
- local function fromBoolean(input)
- if input then return 1 end
- return 0
- end
- local function multBoolean(first,second)
- return (fromBoolean(first) * fromBoolean(second)) == 1
- end
- function coterminal(num, limit)
- limit = limit or 4
- return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
- end
- if tArgs["-manualpos"] then
- facing = coterminal(facing)
- if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end
- relxCalc()
- end
- function turnTo(num)
- num = num or facing
- num = coterminal(num)
- local turnRight = true
- if facing-num == 1 or facing-num == -3 then turnRight = false end
- while facing ~= num do
- if turnRight then
- right()
- else
- left()
- end
- end
- end
- function goto(x,z,y, toFace, destination, updateStatus)
- x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
- gotoDest = destination or ""
- statusString = "Going somewhere"
- if yPos > y then
- while yPos~=y do up() end
- end
- if zPos > z then
- turnTo(3)
- elseif zPos < z then
- turnTo(1)
- end
- while zPos ~= z do mine(false,false,true,false) end
- if xPos > x then
- turnTo(2)
- elseif xPos < x then
- turnTo(0)
- end
- while xPos ~= x do mine(false,false,true,false) end
- if yPos < y then
- while yPos~=y do down() end
- end
- turnTo(toFace)
- saveProgress()
- gotoDest = ""
- statusString = nil
- end
- function getNumOpenSlots()
- local toRet = 0
- for i=1, inventoryMax do
- if turtle.getItemCount(i) == 0 then
- toRet = toRet + 1
- end
- end
- return toRet
- end
- local function waitDrop(slot, allowed, whereDrop)
- allowed = allowed or 0
- while turtle.getItemCount(slot) > allowed do
- local tries = 1
- while not whereDrop(turtle.getItemCount(slot)-allowed) do
- screen(1,1)
- print("Chest Full, Try "..tries)
- chestFull = true
- biometrics()
- tries = tries + 1
- sleep(2)
- end
- chestFull = false
- end
- end
- function midRunRefuel(i, allowed)
- allowed = allowed or allowedItems[i]
- local numToRefuel = turtle.getItemCount(i)-allowed
- if checkFuel() >= checkFuelLimit() then return true end
- local firstCheck = checkFuel()
- if numToRefuel > 0 then turtle.refuel(1) else return false end
- local singleFuel
- if checkFuel() - firstCheck > 0 then singleFuel = checkFuel() - firstCheck else singleFuel = math.huge end
- turtle.refuel(math.min(numToRefuel-1, math.ceil((checkFuelLimit()-checkFuel()) / singleFuel)))
- if checkFuel() >= checkFuelLimit() then return true end
- return false
- end
- function enderRefuel()
- local slot
- for a,b in ipairs(getSlotsTable()) do
- if b == 0 then slot = a; break end
- end
- if not slot then return false end
- select(slot)
- repeat
- print("Required Fuel: ",excessFuelAmount)
- print("Current Fuel: ",checkFuel())
- local tries = 0
- while not turtle.suck() do
- sleep(1)
- statusString = "No Fuel in Ender Chest"
- biometrics()
- print(statusString,". Try: ",tries)
- tries = tries + 1
- end
- statusString = nil
- until midRunRefuel(slot, 0)
- if not turtle.drop() then turtle.dropDown() end
- return true
- end
- function drop(side, final, compareDump)
- side = sides[side] or "front"
- local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
- if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
- if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
- if side == "right" then turnTo(1); dropFacing = 0 end
- if side == "left" then turnTo(3); dropFacing = 0 end
- local properFacing = facing
- count(true)
- while not compareDump and not detectFunc() do
- if final then return end
- chestFull = true
- biometrics()
- screen(1,1)
- print("Waiting for chest placement on ",side," side (when facing quarry)")
- sleep(2)
- end
- chestFull = false
- local fuelSwitch = false
- for i=1,inventoryMax do
- if turtle.getItemCount(i) > 0 then
- if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing)
- else turnTo(properFacing)
- end
- select(i)
- if doRefuel and slot[i][1] == 2 then
- if not fuelSwitch then
- fuelSwitch = midRunRefuel(i)
- end
- elseif not compareDump or (compareDump and slot[i][1] == 1) then
- waitDrop(i, allowedItems[i], dropFunc)
- end
- end
- end
- if oldOreQuarry or compareDump then count(nil) end
- resetDumpSlots()
- select(1)
- end
- function dropOff()
- local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
- if careAboutResources then
- if not enderChestEnabled then
- eventAdd("goto", 1,1,currY,2)
- eventAdd("goto(0,1,1,2)")
- eventAdd("drop", dropSide,false)
- eventAdd("turnTo(0)")
- eventAdd("mine",false,false,true,false)
- eventAdd("goto(1,1,1, 0)")
- eventAdd("goto", 1, 1, currY, 0)
- eventAdd("goto", currX,currZ,currY,currFacing)
- else
- if turtle.getItemCount(specialSlots.enderChest) ~= 1 then eventAdd("promptSpecialSlot('enderChest','Ender Chest')") end
- eventAdd("turnTo",currFacing-2)
- eventAdd("dig",false)
- eventAdd("select",specialSlots.enderChest)
- eventAdd("turtle.place")
- eventAdd("drop","front",false)
- eventAdd("turnTo",currFacing-2)
- eventAdd("select", specialSlots.enderChest)
- eventAdd("dig",false)
- eventAdd("turnTo",currFacing)
- eventAdd("select(1)")
- end
- runAllEvents()
- numDropOffs = numDropOffs + 1
- end
- return true
- end
- function endingProcedure()
- eventAdd("goto",1,1,yPos,2,"quarryStart")
- eventAdd("goto",0,1,1,2, "quarryStart")
- runAllEvents()
- if enderChestEnabled then
- if dropSide == "right" then eventAdd("turnTo(1)") end
- if dropSide == "left" then eventAdd("turnTo(3)") end
- eventAdd("dig(false)")
- eventAdd("select",specialSlots.enderChest)
- eventAdd("turtle.place")
- eventAdd("select(1)")
- end
- eventAdd("drop",dropSide, true)
- eventAdd("turnTo(0)")
- eventAdd("display")
- eventAdd("logMiningRun",logExtension)
- toQuit = true
- runAllEvents()
- end
- function bedrock()
- foundBedrock = true
- if rednetEnabled then biometrics() end
- if checkFuel() == 0 then error("No Fuel",0) end
- local origin = {x = xPos, y = yPos, z = zPos}
- print("Bedrock Detected")
- if turtle.detectUp() and not turtle.digUp() then
- print("Block Above")
- turnTo(facing+2)
- repeat
- if not forward(false) then
- if not attck() then
- if not dig() then
- turnTo(facing+1)
- end
- end
- end
- until not turtle.detectUp() or turtle.digUp()
- end
- up()
- up()
- eventClear()
- endingProcedure()
- print("\nFound bedrock at these coordinates: ")
- print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
- error("",0)
- end
- function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
- local halfFacing = ((layersDone % 2 == 1) and 1) or 3
- local toFace = coterminal(wasFacing + 2)
- if zPos == startZ then
- if facing ~= halfFacing then turnTo(halfFacing) end
- mine(unpack(mineFunctionTable or {}))
- end
- if facing ~= toFace then
- turnTo(toFace)
- end
- end
- runAllEvents()
- if toQuit then error("",0) end
- local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0)
- if not restoreFoundSwitch then
- if not isMiningTurtle then
- local a, b = turtle.dig()
- if a then
- mined = mined + 1
- isMiningTurtle = true
- elseif b == "Nothing to dig with" or b == "No tool to dig with" then
- print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
- error("",0)
- end
- end
- mine(false,false,true)
- if gpsEnabled and not restoreFoundSwitch then
- gpsSecondPos = {gps.locate(gpsTimeout)}
- end
- for i = 1, startDown do
- eventAdd("down")
- end
- runAllEvents()
- if flatBedrock then
- while (detectDown() and digDown(false, true)) or not detectDown() do
- down()
- startDown = startDown + 1
- end
- startDown = startDown - y + 1
- for i=1, y-2 do
- up()
- end
- elseif not(y == 1 or y == 2) then
- down()
- end
- else
- if not(layersDone == layers and not doDigDown) then digDown() end
- if not(layersDone == layers and not doDigUp) then digUp() end
- end
- select(1)
- while layersDone <= layers do
- local lastLayer = layersDone == layers
- local secondToLastLayer = (layersDone + 1) == layers
- moved = moved + 1
- if not(layersDone == layers and not doDigDown) then digDown() end
- if not restoreFoundSwitch and layersDone % 2 == 1 then rowCheck = true end
- relxCalc()
- while relzPos <= z do
- while relxPos < x do
- mine(not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer))
- end
- if relzPos ~= z then
- local func
- if rowCheck == true then
- func = "right"; rowCheck = false; else func = false; rowCheck = true end
- eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)})
- runAllEvents()
- else break
- end
- end
- if layersDone % 2 == 0 then
- eventAdd("goto",1,1,yPos,0, "layerStart")
- else
- eventAdd("turnTo",coterminal(facing-2))
- end
- if not lastLayer then
- for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do eventAdd("down()") end
- end
- eventAdd("relxCalc")
- layersDone = layersDone + 1
- restoreFoundSwitch = false
- runAllEvents()
- end
- endingProcedure()
Add Comment
Please, Sign In to add comment