Le_JuiceBOX

[App] mine.lua

Mar 29th, 2024 (edited)
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.65 KB | None | 0 0
  1. -- 0DAspFKK
  2.  
  3. local cmdArgs = table.pack(...)
  4.  
  5. local Params = {
  6.     Width = nil,
  7.     Height = nil,
  8.     Depth = nil,
  9.     StartX = nil,
  10.     StartDepth = nil,
  11.     DepositMode = nil,
  12. }
  13.  
  14. local DepoMode = {
  15.     RunHome = 1,
  16.     LeaveChest = 2,
  17.     EnderChest = 3,
  18.     Discard = 4
  19. }
  20.  
  21. local Dir = {
  22.     N = 1,
  23.     E = 2,
  24.     S = 3,
  25.     W = 4
  26. }
  27.  
  28. local FILE_PARAMS_DATA = "/temp/current_mine_params.txt"
  29. local FILE_NAV_DATA = "/temp/mine_nav_data.txt"
  30.  
  31. local Brain = require("/turtleBrain"):new(FILE_NAV_DATA)
  32. local Terminal = require("/terminal"):new()
  33. local mineVolume = 0
  34. local isResuming = false
  35. local depositedResources = {}
  36.  
  37. --=====================================================================================
  38.  
  39. function Main()
  40.     if #cmdArgs > 0 then
  41.         Params.Width = tonumber(cmdArgs[1])
  42.         Params.Height = tonumber(cmdArgs[2])
  43.         Params.Depth = tonumber(cmdArgs[3])
  44.         Params.StartX = tonumber(cmdArgs[4])
  45.         Params.StartDepth = tonumber(cmdArgs[5])
  46.         Params.DepositMode = tonumber(cmdArgs[6])
  47.     else
  48.         local success = GetParams()
  49.         if success == false then return; end
  50.     end
  51.     Brain.X = Params.StartX
  52.     Terminal:reset()
  53.     Terminal:print("Starting work!")
  54.     local start = 1
  55.     if isResuming then
  56.         Brain:moveTo(Params.StartX,0,Brain.Z-1)
  57.         Brain:turnToFace(Dir.N)
  58.     else
  59.         Brain:forceForward(Params.StartDepth)
  60.     end
  61.     print("starting now!!!")
  62.     --// Mining
  63.     for i = start, Params.Depth do
  64.         local success, msg = mineLayer()
  65.         if success == false then
  66.             Terminal:reset()
  67.             Terminal:print(msg)
  68.             break
  69.         end
  70.     end
  71.     depositItems()
  72.     --// Finish
  73.     Brain:moveTo(Params.StartX,1,0,{1,2,3})
  74.     repeat
  75.         Brain:deleteNav()
  76.         Terminal:reset()
  77.         Terminal:print("Turtle finished job.")
  78.         Terminal:print()  
  79.         local resName, resInd = Terminal:promptOptions("&1What do you want to do?",false,{
  80.             "Exit",
  81.             "View Info",
  82.             "View Mined Resources"
  83.         })
  84.         if resInd == 3 then
  85.             local yPos = 4
  86.             local sorted = {}
  87.             for name,ct in pairs(depositedResources) do
  88.                 table.insert(sorted,{name,ct})
  89.             end
  90.             table.sort(sorted, function(a, b) return a[2] > b[2] end)
  91.             repeat  
  92.                 Terminal:reset()
  93.                 Terminal.output.setCursorPos(1,yPos)
  94.                 for i, data in pairs(sorted) do
  95.                     local dispName = Terminal:getItemDisplayName(data[1])
  96.                     local halfScreen = math.ceil(Terminal.size.x/2)
  97.                     local str = dispName.."&8"
  98.                     for i = 1, halfScreen-#dispName do
  99.                         str = str.."."
  100.                     end
  101.                     Terminal:print(str.."&8x&4"..tostring(data[2]))
  102.                 end
  103.                 Terminal:writeLine(1,"&1[Backspace] - exit.")
  104.                 Terminal:writeLine(2,"&1[ArrowKeys] - scroll.")
  105.                 Terminal:writeLine(3,"")
  106.                 local key = Terminal:waitForKey()
  107.                 if key == 265 then -- up
  108.                     yPos = yPos + 1
  109.                 elseif key == 264 then -- down
  110.                     yPos = yPos - 1
  111.                 end
  112.             until key == 259 -- backspace
  113.             Terminal:reset()
  114.         end
  115.     until resInd == 1
  116.     Terminal:reset()
  117.     -- clean up
  118.     if fs.exists(FILE_PARAMS_DATA) then
  119.         fs.delete(FILE_PARAMS_DATA)
  120.     end
  121. end
  122.  
  123. function GetParams()
  124.     if fs.exists(FILE_NAV_DATA) then
  125.         Terminal:reset()
  126.         Terminal:print("&eAlert!")
  127.         Terminal:print("This turtle shutdown half-way through")
  128.         Terminal:print("most recent job.")
  129.         Terminal:print()
  130.         Terminal:print("&8This is possibly due to the turtle:")
  131.         Terminal:print("&8breaking, shutting down, exploring an")
  132.         Terminal:print("&8unloaded chunk, or the server shutdown.")
  133.         Terminal:print()
  134.         local res = Terminal:promptConf("&1Do you want to resume?",true)
  135.         if res then
  136.             Brain:loadNav(Brain:getHasMoved())
  137.             Params.Width = tonumber(w)
  138.             Params.Height = tonumber(h)
  139.             Params.Depth = tonumber(d)
  140.             Params.StartX = tonumber(startX)
  141.             Params.StartDepth = tonumber(start)
  142.             Params.DepositMode = tonumber(mode)
  143.             isResuming = true
  144.             return true -- continue
  145.         else
  146.             Brain:deleteNav()
  147.             if fs.exists(FILE_PARAMS_DATA) then
  148.                 fs.delete(FILE_PARAMS_DATA)
  149.             end
  150.         end
  151.     end
  152.     repeat
  153.         Params = {
  154.             Width = nil,
  155.             Height = nil,
  156.             Depth = nil,
  157.             StartX = nil,
  158.             StartDepth = nil,
  159.             DepositMode = nil,
  160.         }
  161.         Terminal:reset()
  162.         Params.Width = Terminal:promptNum("Input block width:")
  163.         Params.Height = Terminal:promptNum("Input block height:")
  164.         Params.Depth = Terminal:promptNum("Input block depth:")
  165.         Params.StartX = Terminal:promptNum("Input starting X: (leave blank for none)") or 0
  166.         Params.StartDepth = Terminal:promptNum("Input starting Z: (leave blank for none)") or 0
  167.     until Terminal:promptConf("Continue with these parameters?",true)
  168.     repeat
  169.         Terminal:reset()
  170.         local menu = {
  171.             "Return Home",
  172.             "Leave Chests",
  173.             "Enderchest",
  174.             "Discard",
  175.         }
  176.         local modeName,mode = Terminal:promptOptions("Select a deposit mode:",false,menu)
  177.         Terminal:reset()
  178.         if mode == DepoMode.RunHome then
  179.             Terminal:display(nil,
  180.                 "Return Home:",
  181.                 "Turtle will return to origin to",
  182.                 "deposit its items.",
  183.                 ""
  184.             )    
  185.         elseif mode == DepoMode.LeaveChest then
  186.             Terminal:display(nil,
  187.                 "Leave Chests:",
  188.                 "Turtle will place chests when its inventory",
  189.                 "fills up and deposits the items into it.",
  190.                 "NOTE: Uses multiple chests."
  191.             )  
  192.         elseif mode == DepoMode.EnderChest then
  193.             Terminal:display(nil,
  194.                 "Enderchest:",
  195.                 "Turtle will place an ender chest and deposit",
  196.                 "its inventory into it. Turtle will break the EC",
  197.                 "and continue forth when inventory is deposited.",
  198.                 "NOTE: Ender chest must always be empty.",
  199.                 ""
  200.             )  
  201.         elseif mode == DepoMode.Discard then
  202.             Terminal:display(nil,
  203.                 "Discard:",
  204.                 "Throw any items mined on to the ground.",
  205.                 ""
  206.             )
  207.         end
  208.         --Terminal:pressAnyKeyToContinue()
  209.         local res = Terminal:promptConf("&1Confirm selection? &8('"..menu[mode].."')",true)
  210.         if res then Params.DepositMode = mode end
  211.     until res
  212.     Terminal:reset()
  213.     mineVolume = Params.Width * Params.Height * Params.Depth
  214.     --// Check if we have enough fuel for this job
  215.     if Brain:hasEnoughFuel(mineVolume) then
  216.         reset()
  217.         print("Preparing to mine "..mineVolume.." blocks.")
  218.         os.sleep(0.5)        
  219.     else
  220.         Terminal:print("There isn't enough fuel to complete")
  221.         Terminal:print("this job.")
  222.         Terminal:print("")
  223.         Terminal:print("Current Fuel: &e"..turtle.getFuelLevel())
  224.         Terminal:print("Required Fuel: &d"..mineVolume)
  225.         Terminal:print("")
  226.         local res = Terminal:promptConf("Continue anyway?",true)
  227.         if res == false then return false; end
  228.     end
  229.     --// Confirm certain requirments for desired mode
  230.     if Params.DepositMode == DepoMode.LeaveChest then
  231.         Terminal:reset()
  232.         local predChests = math.ceil(mineVolume/1728)
  233.  
  234.         print(
  235.             "Make sure a container block is placed in slot 1 of the turtle.\n"..
  236.             "Without it, you will lose all your items.\n"..
  237.             "(You'll need about "..predChests.." containers [ADD x2, POOR ESITIMATE])\n\n"
  238.         )
  239.         Terminal:pressAnyKeyToContinue()
  240.         Terminal:reset()
  241.     elseif Params.DepositMode == DepoMode.EnderChest then
  242.         Terminal:reset()
  243.         print(
  244.             "Make sure an EnderChest, or something of the sort is placed in slot 1 of the turtle.\n"..
  245.             "Without it, you will lose all your items.\n\n"
  246.         )
  247.         Terminal:pressAnyKeyToContinue()
  248.         Terminal:reset()
  249.     end
  250.     Terminal:reset()
  251.     -- save data to file
  252.     local paramLines = {
  253.         Params.Width,
  254.         Params.Height,
  255.         Params.Depth,
  256.         Params.StartX,
  257.         Params.StartDepth,
  258.         Params.DepositMode
  259.     }
  260.     return true;
  261. end
  262.  
  263. --=====================================================================================
  264.  
  265. function mineLayer()
  266.     --// check if we have fuel for this layer
  267.     local roundTrip = getRoundTripCost()
  268.     local homeTrip = Brain:predictFuelUsageTo(0,0,0)
  269.     if Brain:hasEnoughFuel(getLayerFuelCost()) == false then return false,"Not enough fuel to mine the next layer.\n(has: "..turtle.getFuelLevel()..", needed: "..homeTrip + getLayerFuelCost()..")"; end
  270.     --// Move into layer to mine
  271.     Brain:turnToFace(Dir.N)
  272.     Brain:forceForward()
  273.     if Params.Height == 1 and Params.Width == 1 then return true; end
  274.     --// Mine rows until finished
  275.     while Brain.Y <= Params.Height-1 do
  276.         local mod = Brain.Y % 2
  277.         if mod <= 0 then -- if we odd
  278.             Brain:turnToFace(Dir.E)
  279.             Brain:forceForward(Params.Width-1)
  280.             if Brain:isInvFull() then depositItems(true) end
  281.         elseif mod > 0  then -- if we even
  282.             Brain:turnToFace(Dir.W)
  283.             Brain:forceForward(Params.Width-1)
  284.             if Brain:isInvFull() then depositItems(true) end
  285.         end
  286.         if Brain.Y == Params.Height-1 then break; end
  287.         Brain:forceUp()
  288.     end
  289.     moveToGroundY()
  290.     --// Reorientate afterwards
  291.     if Brain.X == Params.Width-1 then -- if we are on the far end of X
  292.         Brain:turnToFace(Dir.W)
  293.         Brain:forceForward(Params.Width-1)
  294.     end
  295.     Terminal:reset()
  296.     Terminal:print("Current Progress:")
  297.     Terminal:print(Brain.Z.." out of "..Params.Depth.." layers completed.")
  298.     return true
  299. end
  300.  
  301. function depositItems(doReturn)
  302.     doReturn = doReturn or false
  303.     local lastPos = Brain:getPos()
  304.     local lastDir = Brain.CurrentDir
  305.  
  306.     if Params.DepositMode == DepoMode.RunHome then        
  307.         Brain:moveTo(0,0,0)
  308.         logDepositItems()
  309.         Brain:emptyInventoryDown()
  310.         if doReturn then
  311.             if Brain:hasEnoughFuel(table.unpack(lastPos)) == false then
  312.                 print("Not enough fuel to continue mining, staying at home.")
  313.                 return
  314.             end
  315.             Brain:moveTo(table.unpack(lastPos))
  316.             Brain:turnToFace(lastDir)
  317.         end
  318.  
  319.     elseif Params.DepositMode == DepoMode.LeaveChest then
  320.         -- leave chest
  321.         moveToGroundY()
  322.         turtle.digDown()
  323.         turtle.select(1)
  324.         turtle.placeDown()
  325.         logDepositItems(1)
  326.         Brain:emptyInventoryDown(1)
  327.         -- go back
  328.         Brain:moveTo(table.unpack(lastPos))
  329.         Brain:turnToFace(lastDir)
  330.     elseif Params.DepositMode == DepoMode.EnderChest then
  331.         -- leave ender chest
  332.         turtle.digDown()
  333.         turtle.select(1)
  334.         turtle.placeDown()
  335.         logDepositItems(1)
  336.         Brain:emptyInventoryDown(1)
  337.         turtle.select(1)
  338.         turtle.digDown()
  339.     elseif Params.DepositMode == DepoMode.Discard then
  340.         logDepositItems()
  341.         Brain:emptyInventoryDown()
  342.     end
  343. end
  344.  
  345. --=====================================================================================
  346.  
  347. function logDepositItems(ignoreSlot)
  348.     ignoreSlot = ignoreSlot or -1
  349.     for i = 1, 16 do
  350.         if i ~= ignoreSlot then
  351.             --turtle.select(i)
  352.             local itemData = turtle.getItemDetail(i)
  353.             if itemData then
  354.                 local added = false
  355.                 for name,val in pairs(depositedResources) do
  356.                     if name == itemData.name then
  357.                         depositedResources[name] = depositedResources[name] + itemData.count
  358.                         added = true
  359.                     end
  360.                 end
  361.                 if added == false then
  362.                     depositedResources[itemData.name] = itemData.count
  363.                 end
  364.             end
  365.         end
  366.     end
  367. end
  368.  
  369. function moveToGroundY()
  370.     Brain:moveTo(nil,0,nil)
  371. end
  372.  
  373. function promtBool(text)
  374.     local res = promtNum(text)
  375.     return (res == 1)
  376. end
  377.  
  378. function promtNum(text)
  379.     local res = promt(text)
  380.     return tonumber(res)
  381. end
  382.  
  383. function promt(text)
  384.     reset()
  385.     print(tostring(text))
  386.     term.write("> ")
  387.     return io.read()
  388. end
  389.  
  390. function repeatFunc(times,func)
  391.     for i = 1, times do
  392.         func()
  393.     end
  394. end
  395.  
  396. function reset()
  397.     term.clear()
  398.     term.setCursorPos(1,1)
  399. end
  400.  
  401. function getRoundTripCost()
  402.     local home = {0,0,0}
  403.     local current = Brain:getPos()
  404.     return Brain:predictFuelUsageTo(0,0,0)
  405.     + Brain:predictFuelUsage(0,0,0,current[1],current[2],current[3])
  406. end
  407.  
  408. function getLayerFuelCost()
  409.     return (Params.Width*Params.Height)
  410. end
  411.  
  412. function writeParams(...)
  413.     local p = {...}
  414.     return "W: "..(p[1] or "?")..", H: "..(p[2] or "?")..", D: "..(p[3] or "?")
  415. end
  416.  
  417. function clamp(num,min,max)
  418.     if num > max then
  419.         return max;
  420.     elseif num < min then
  421.         return min
  422.     end
  423.     return num
  424. end
  425. --=====================================================================================
  426.  
  427. Main()
Advertisement
Add Comment
Please, Sign In to add comment