Advertisement
SomeoneNew666

Minecraft ComputerCraft Room Mining Program2

Feb 17th, 2025 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Position tracking
  2. local currentX = 0
  3. local currentY = 0
  4. local currentZ = 0
  5. local facing = 0 -- 0=forward(away from chest), 1=right, 2=back(toward chest), 3=left
  6. local startRow = true -- Track if we're starting from the front or back of the row
  7. local miningLength = 0  -- Store length as a module-level variable
  8. local forward = true -- Moved to module-level to preserve state between layers
  9. local resumePos = {x=0, y=0, z=0, facing=0}
  10.  
  11. local ESSENTIAL_ITEMS = {
  12.     ["minecraft:torch"] = true  -- or a very high number like 9999
  13. }
  14.  
  15. local function setMiningLength(len)
  16.   miningLength = len
  17. end
  18.  
  19. -- Utility functions
  20. local function findItem(itemName)
  21.   for slot = 1, 16 do
  22.     local item = turtle.getItemDetail(slot)
  23.     if item and item.name == itemName then
  24.       turtle.select(slot)
  25.       return true
  26.     end
  27.   end
  28.   return false
  29. end
  30.  
  31. local function hasInventorySpace()
  32.   for slot = 1, 16 do
  33.     if turtle.getItemCount(slot) == 0 then
  34.       return true
  35.     end
  36.   end
  37.   return false
  38. end
  39.  
  40. local function turnToFacing(targetFacing)
  41.   while facing ~= targetFacing do
  42.     turtle.turnRight()
  43.     facing = (facing + 1) % 4
  44.   end
  45. end
  46.  
  47. -- Optimized turning function that takes shortest path
  48. local function turnToFacingOptimal(targetFacing)
  49.   local currentFacing = facing
  50.   local rightTurns = (targetFacing - currentFacing) % 4
  51.   local leftTurns = (currentFacing - targetFacing) % 4
  52.  
  53.   if rightTurns <= leftTurns then
  54.       -- Turn right is shorter or equal
  55.       for i = 1, rightTurns do
  56.           turtle.turnRight()
  57.           facing = (facing + 1) % 4
  58.       end
  59.   else
  60.       -- Turn left is shorter
  61.       for i = 1, leftTurns do
  62.           turtle.turnLeft()
  63.           facing = (facing - 1) % 4
  64.       end
  65.   end
  66. end
  67.  
  68. local function tryMove(moveFunc, digFunc, direction)
  69.     -- Maximum attempts to handle falling blocks
  70.     local maxAttempts = 10
  71.     local attempts = 0
  72.  
  73.     while attempts < maxAttempts do
  74.         attempts = attempts + 1
  75.        
  76.         -- Check if there's a block in the way
  77.         local detectFunc
  78.         if direction == "up" then
  79.             detectFunc = turtle.detectUp
  80.         elseif direction == "down" then
  81.             detectFunc = turtle.detectDown
  82.         else
  83.             detectFunc = turtle.detect
  84.         end
  85.        
  86.         if detectFunc() then
  87.             -- There's a block, dig it
  88.             digFunc()
  89.             if moveFunc() then
  90.                 break
  91.             end
  92.         else
  93.             -- No block, try to move
  94.             if moveFunc() then
  95.                 break
  96.             end
  97.         end
  98.  
  99.         -- If we're still here after an attempt, brief pause
  100.         sleep(0.2)
  101.        
  102.         if attempts == maxAttempts then
  103.             print("Warning: Unable to move after multiple attempts")
  104.             return false
  105.         end
  106.     end
  107.    
  108.     -- Update position after successful move
  109.     if attempts < maxAttempts then
  110.         if moveFunc == turtle.forward then
  111.             if facing == 0 then currentY = currentY - 1
  112.             elseif facing == 1 then currentX = currentX + 1
  113.             elseif facing == 2 then currentY = currentY + 1
  114.             else currentX = currentX - 1 end
  115.         elseif moveFunc == turtle.up then
  116.             currentZ = currentZ + 1
  117.         elseif moveFunc == turtle.down then
  118.             currentZ = currentZ - 1
  119.         end
  120.         return true
  121.     end
  122.    
  123.     return false
  124. end
  125.  
  126. -- Optimized turning function that takes shortest path
  127. local function turnToFacingOptimal(targetFacing)
  128.   local currentFacing = facing
  129.   local rightTurns = (targetFacing - currentFacing) % 4
  130.   local leftTurns = (currentFacing - targetFacing) % 4
  131.  
  132.   if rightTurns <= leftTurns then
  133.       -- Turn right is shorter or equal
  134.       for i = 1, rightTurns do
  135.           turtle.turnRight()
  136.           facing = (facing + 1) % 4
  137.       end
  138.   else
  139.       -- Turn left is shorter
  140.       for i = 1, leftTurns do
  141.           turtle.turnLeft()
  142.           facing = (facing - 1) % 4
  143.       end
  144.   end
  145. end
  146.  
  147. local function returnToChest()
  148.   local returnFacing = facing
  149.   local pathFound = false
  150.  
  151.   -- Try multiple vertical levels to find an open path
  152.   local function tryPathAtLevel(targetZ)
  153.       -- Move to target Z level first
  154.       while currentZ > targetZ do
  155.           if not turtle.down() then return false end
  156.           currentZ = currentZ - 1
  157.       end
  158.       while currentZ < targetZ do
  159.           if not turtle.up() then return false end
  160.           currentZ = currentZ + 1
  161.       end
  162.      
  163.       -- Face toward chest (facing 2)
  164.       turnToFacingOptimal(2)
  165.      
  166.       -- Try Y movement without digging
  167.       local initialY = currentY
  168.       while currentY < 0 do
  169.           if not turtle.forward() then
  170.               -- If blocked, restore position and return false
  171.               while currentY < initialY do
  172.                   turtle.back()
  173.                   currentY = currentY + 1
  174.               end
  175.               return false
  176.           end
  177.           currentY = currentY + 1
  178.       end
  179.      
  180.       -- Try X movement without digging
  181.       if currentX ~= 0 then
  182.           if currentX > 0 then
  183.               turnToFacingOptimal(3) -- face left
  184.           else
  185.               turnToFacingOptimal(1) -- face right
  186.           end
  187.          
  188.           local initialX = currentX
  189.           while currentX ~= 0 do
  190.               if not turtle.forward() then
  191.                   -- If blocked, restore position and return false
  192.                   while currentX ~= initialX do
  193.                       turtle.back()
  194.                       currentX = currentX + (currentX > 0 and 1 or -1)
  195.                   end
  196.                   return false
  197.               end
  198.               currentX = currentX + (currentX > 0 and -1 or 1)
  199.           end
  200.       end
  201.      
  202.       return true
  203.   end
  204.  
  205.   -- Try paths at different levels, starting with levels we expect to be clear
  206.   local levelsToTry = {
  207.       0,           -- Ground level (where chest is)
  208.       -1,          -- One below ground
  209.       1,           -- One above ground
  210.       currentZ,    -- Current level
  211.   }
  212.  
  213.   -- Add intermediate levels if we're far from 0
  214.   if math.abs(currentZ) > 1 then
  215.       table.insert(levelsToTry, math.floor(currentZ/2))
  216.   end
  217.  
  218.   -- Try each level until we find a clear path
  219.   for _, targetZ in ipairs(levelsToTry) do
  220.       if tryPathAtLevel(targetZ) then
  221.           pathFound = true
  222.           break
  223.       end
  224.   end
  225.  
  226.   -- If no clear path found, fall back to original digging behavior
  227.   if not pathFound then
  228.       -- Original digging behavior
  229.       while currentZ > 0 do
  230.           if not tryMove(turtle.down, turtle.digDown, "down") then
  231.               print("Can't move down to Z=0")
  232.               return false
  233.           end
  234.       end
  235.       while currentZ < 0 do
  236.           if not tryMove(turtle.up, turtle.digUp, "up") then
  237.               print("Can't move up to Z=0")
  238.               return false
  239.           end
  240.       end
  241.      
  242.       turnToFacingOptimal(2)
  243.       while currentY < 0 do
  244.           if not tryMove(turtle.forward, turtle.dig, "forward") then
  245.               print("Obstruction while returning on Y axis")
  246.               return false
  247.           end
  248.       end
  249.      
  250.       if currentX ~= 0 then
  251.           if currentX > 0 then
  252.               turnToFacingOptimal(3)
  253.           else
  254.               turnToFacingOptimal(1)
  255.           end
  256.          
  257.           while currentX ~= 0 do
  258.               if not tryMove(turtle.forward, turtle.dig, "forward") then
  259.                   print("Obstruction while returning on X axis")
  260.                   return false
  261.               end
  262.           end
  263.       end
  264.   end
  265.  
  266.   -- Final position verification and facing correction
  267.   if currentX ~= 0 or currentY ~= 0 or currentZ ~= 0 then
  268.       print("Failed to reach chest position!")
  269.       return false
  270.   end
  271.  
  272.   -- Ensure we're facing the chest (facing 2) at the end
  273.   turnToFacingOptimal(2)
  274.  
  275.   return true
  276. end
  277.  
  278. local function hasEssentialItems()
  279.     local hasTorches = false
  280.    
  281.     for slot = 1, 16 do
  282.         local item = turtle.getItemDetail(slot)
  283.         if item and item.name == "minecraft:torch" then
  284.             hasTorches = true
  285.             break
  286.         end
  287.     end
  288.    
  289.     return hasTorches
  290. end
  291.  
  292. local function hasOperationalInventory()
  293.     -- Check if we have at least 1 free slot AND torches
  294.     local hasSpace = false
  295.     local hasTorches = false
  296.    
  297.     for slot = 1, 16 do
  298.         if turtle.getItemCount(slot) == 0 then
  299.             hasSpace = true
  300.         else
  301.             local item = turtle.getItemDetail(slot)
  302.             if item and item.name == "minecraft:torch" then
  303.                 hasTorches = true
  304.             end
  305.         end
  306.     end
  307.    
  308.     return hasSpace and hasTorches
  309. end
  310.  
  311.  
  312. local function dumpInventory()
  313.     -- Store current position
  314.     resumePos.x = currentX
  315.     resumePos.y = currentY
  316.     resumePos.z = currentZ
  317.     resumePos.facing = facing
  318.  
  319.     -- Return to chest
  320.     print("Inventory full! Returning to chest...")
  321.     if not returnToChest() then return false end
  322.  
  323.     -- Simply drop all non-torch items
  324.     for slot = 1, 16 do
  325.         turtle.select(slot)
  326.         local item = turtle.getItemDetail(slot)
  327.        
  328.         if item and item.name ~= "minecraft:torch" then
  329.             -- Drop all non-torch items
  330.             turtle.drop()
  331.         end
  332.     end
  333.  
  334.     -- Return to mining position with optimized movement
  335.     -- Move vertically first
  336.     while currentZ ~= resumePos.z do
  337.         if currentZ < resumePos.z then
  338.             tryMove(turtle.up, turtle.digUp, "up")
  339.         else
  340.             tryMove(turtle.down, turtle.digDown, "down")
  341.         end
  342.     end
  343.  
  344.     -- Optimize Y movement
  345.     if currentY ~= resumePos.y then
  346.         if currentY > resumePos.y then
  347.             turnToFacingOptimal(0)  -- Face mining direction
  348.         else
  349.             turnToFacingOptimal(2)  -- Face chest direction
  350.         end
  351.         while currentY ~= resumePos.y do
  352.             tryMove(turtle.forward, turtle.dig, "forward")
  353.         end
  354.     end
  355.  
  356.     -- Optimize X movement
  357.     if currentX ~= resumePos.x then
  358.         if currentX < resumePos.x then
  359.             turnToFacingOptimal(1)  -- Face right
  360.         else
  361.             turnToFacingOptimal(3)  -- Face left
  362.         end
  363.         while currentX ~= resumePos.x do
  364.             tryMove(turtle.forward, turtle.dig, "forward")
  365.         end
  366.     end
  367.  
  368.     -- Return to original facing
  369.     turnToFacingOptimal(resumePos.facing)
  370.     return true
  371. end
  372.  
  373. local function dumpAllInventory()
  374.     -- Return to chest if not already there
  375.     if currentX ~= 0 or currentY ~= 0 or currentZ ~= 0 then
  376.         if not returnToChest() then
  377.             print("Failed to return to chest!")
  378.             return false
  379.         end
  380.     end
  381.    
  382.     -- Ensure facing chest
  383.     turnToFacingOptimal(2)
  384.    
  385.     -- Small delay to ensure stable chest interaction
  386.     sleep(0.5)
  387.    
  388.     -- Dump everything from inventory
  389.     for slot = 1, 16 do
  390.         turtle.select(slot)
  391.         -- Drop entire stack, regardless of item type
  392.         turtle.drop()
  393.     end
  394.    
  395.     return true
  396. end
  397.  
  398. -- Calculate torch positions for symmetric placement
  399. local function calculateTorchPositions(length, width)
  400.   local positions = {}
  401.  
  402.   -- For very small rooms (less than 7x7), just place a torch in the center
  403.   if length <= 7 and width <= 7 then
  404.     table.insert(positions, {x = math.ceil(length/2), z = math.ceil(width/2)})
  405.     return positions
  406.   end
  407.  
  408.   -- For larger rooms, create a grid of torches with optimal spacing
  409.   -- In newer versions (1.18+), we can use spacing up to 13 blocks
  410.   -- But we'll adjust for symmetry based on room dimensions
  411.  
  412.   -- Calculate spacing for symmetrical pattern
  413.   local xSpacing = math.min(13, length)
  414.   local zSpacing = math.min(13, width)
  415.  
  416.   -- Adjust spacing for larger rooms to maintain symmetry
  417.   if length > 13 then
  418.     -- Find the number of torches needed along length
  419.     local numTorchesX = math.ceil(length / 13)
  420.     -- Distribute evenly
  421.     xSpacing = length / numTorchesX
  422.   end
  423.  
  424.   if width > 13 then
  425.     -- Find the number of torches needed along width
  426.     local numTorchesZ = math.ceil(width / 13)
  427.     -- Distribute evenly
  428.     zSpacing = width / numTorchesZ
  429.   end
  430.  
  431.   -- Calculate offsets to center the grid
  432.   local xOffset = xSpacing / 2
  433.   local zOffset = zSpacing / 2
  434.  
  435.   -- Create the grid of torch positions
  436.   for x = xOffset, length, xSpacing do
  437.     for z = zOffset, width, zSpacing do
  438.       table.insert(positions, {x = math.floor(x), z = math.floor(z)})
  439.     end
  440.   end
  441.  
  442.   return positions
  443. end
  444.  
  445. -- Calculate the total number of torches needed
  446. local function calculateTorches(length, width)
  447.   local positions = calculateTorchPositions(length, width)
  448.   return #positions
  449. end
  450.  
  451. -- Main Program
  452. local args = {...}
  453. if #args < 3 then
  454.   print("Usage: digRoom <length> <width> <height> [horizontal] [vertical]")
  455.   print("horizontal: left/right (default: right)")
  456.   print("vertical: up/down (default: up)")
  457.   return
  458. end
  459.  
  460. local length = tonumber(args[1])
  461. local width = tonumber(args[2])
  462. local height = tonumber(args[3])
  463. local horizontalDir = args[4] or "right"
  464. local verticalDir = args[5] or "up"
  465.  
  466. setMiningLength(length)
  467.  
  468. if not (length and width and height) or length < 1 or width < 1 or height < 1 then
  469.   print("Invalid dimensions!")
  470.   return
  471. end
  472.  
  473. if horizontalDir ~= "left" and horizontalDir ~= "right" then
  474.   print("Invalid horizontal direction! Use 'left' or 'right'")
  475.   return
  476. end
  477.  
  478. if verticalDir ~= "up" and verticalDir ~= "down" then
  479.   print("Invalid vertical direction! Use 'up' or 'down'")
  480.   return
  481. end
  482.  
  483. -- Calculate required resources
  484. local totalBlocks = length * width * height
  485. local fuelNeeded = totalBlocks + height + math.ceil(width/2) * 2
  486. local requiredTorches = height > 1 and calculateTorches(length, width) or 0
  487.  
  488. -- Check fuel
  489. if turtle.getFuelLevel() < fuelNeeded then
  490.   print(string.format("Need %d fuel, have %d", fuelNeeded, turtle.getFuelLevel()))
  491.   return
  492. end
  493.  
  494. -- Check torches if needed
  495. if requiredTorches > 0 then
  496.   local torchCount = 0
  497.   for slot = 1, 16 do
  498.     local item = turtle.getItemDetail(slot)
  499.     if item and item.name == "minecraft:torch" then
  500.       torchCount = torchCount + turtle.getItemCount(slot)
  501.     end
  502.   end
  503.   if torchCount < requiredTorches then
  504.     print(string.format("Need %d torches, have %d", requiredTorches, torchCount))
  505.     return
  506.   end
  507. end
  508.  
  509. local function turnToDir(targetDir)
  510.   if horizontalDir == "left" then
  511.     if targetDir == "right" then
  512.       turtle.turnLeft()
  513.       facing = (facing - 1) % 4
  514.     else
  515.       turtle.turnRight()
  516.       facing = (facing + 1) % 4
  517.     end
  518.   else
  519.     if targetDir == "right" then
  520.       turtle.turnRight()
  521.       facing = (facing + 1) % 4
  522.     else
  523.       turtle.turnLeft()
  524.       facing = (facing - 1) % 4
  525.     end
  526.   end
  527. end
  528.  
  529. local function moveVertical()
  530.   if verticalDir == "up" then
  531.     return turtle.up, turtle.digUp, "up"
  532.   else
  533.     return turtle.down, turtle.digDown, "down"
  534.   end
  535. end
  536.  
  537. local function mineLayer()
  538.   -- Calculate torch positions for this layer
  539.   local torchPositions = calculateTorchPositions(length, width)
  540.  
  541.   -- Initialize room-relative coordinates
  542.   local roomX = 0
  543.   local roomZ = 0
  544.  
  545.   for row = 1, width do
  546.     roomZ = row - 1  -- Z coordinate is the row (0-indexed)
  547.    
  548.     for col = 1, length - 1 do
  549.       -- Update room X based on direction (serpentine pattern)
  550.       if forward then
  551.         roomX = col - 1  -- When mining forward, X increases
  552.       else
  553.         roomX = length - col  -- When mining backward, X decreases
  554.       end
  555.      
  556.       -- Check if current room position should have a torch with exact matching
  557.       for _, pos in ipairs(torchPositions) do
  558.         if pos.x - 1 == roomX and pos.z - 1 == roomZ then
  559.           if findItem("minecraft:torch") then
  560.             print("Placing torch at room position: " .. roomX .. "," .. roomZ)
  561.             turtle.placeDown()
  562.             break
  563.           end
  564.         end
  565.       end
  566.      
  567.       -- Continue with inventory check and movement
  568.       local hasSpace = false
  569.       for slot = 1, 16 do
  570.         if turtle.getItemCount(slot) == 0 then
  571.           hasSpace = true
  572.           break
  573.         end
  574.       end
  575.      
  576.       if not hasSpace then
  577.         if not dumpInventory() then
  578.           print("Aborting mining operation")
  579.           return false
  580.         end
  581.       end
  582.      
  583.       -- Move forward
  584.       if not tryMove(turtle.forward, turtle.dig, "forward") then
  585.         print("Obstruction detected")
  586.         return false
  587.       end
  588.     end
  589.    
  590.     -- Handle row changes
  591.     if row < width then
  592.       if forward then
  593.         turnToDir("right")
  594.         if not tryMove(turtle.forward, turtle.dig, "forward") then return false end
  595.         turnToDir("right")
  596.       else
  597.         turnToDir("left")
  598.         if not tryMove(turtle.forward, turtle.dig, "forward") then return false end
  599.         turnToDir("left")
  600.       end
  601.       forward = not forward
  602.     end
  603.   end
  604.  
  605.   return true
  606. end
  607.  
  608. -- Modified end of main program
  609. for layer = 1, height do
  610.     if width % 2 == 0 then
  611.         forward = (layer % 2 == 1)
  612.     else
  613.         forward = true
  614.     end
  615.  
  616.     if not mineLayer() then break end
  617.  
  618.     if layer < height then
  619.         -- Move up/down
  620.         local moveFunc, digFunc, direction = moveVertical()
  621.         if not tryMove(moveFunc, digFunc, direction) then
  622.             print("Warning: Unable to move " .. verticalDir .. " (possible liquid)")
  623.             print("Try again? (y/n)")
  624.             local response = read():lower()
  625.             if response ~= "y" then
  626.                 break
  627.             end
  628.         end
  629.  
  630.         -- Turn around for next layer
  631.         turtle.turnRight()
  632.         turtle.turnRight()
  633.         facing = (facing + 2) % 4
  634.     end
  635. end
  636.  
  637. -- Final return and dump all inventory
  638. print("Mining complete! Returning to chest...")
  639. if dumpAllInventory() then
  640.     print("All items deposited in chest.")
  641.     turnToFacingOptimal(0)
  642. else
  643.     print("Failed to deposit all items!")
  644. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement