This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Jakkor's profile picture

Problem with mining code

Started by Jakkor, 15 December 2013 - 10:47 AM
Jakkor #1
Posted 15 December 2013 - 11:47 AM
I made a simple program to raise the ceiling of an underground room:

function dig()
  for i = 1, 16 do
	if turtle.detectUp() then
	  turtle.digUp()
	else
	  turtle.forward()
	end
  end
  i = 0 -- I added this to see if it would fix it.
end

for l = 1, 17 do
  dig()
  turtle.digUp()
  if l%2 == 1 then
	turtle.turnRight()
	turtle.forward()
	turtle.turnRight()
  else
	turtle.turnLeft()
	turtle.forward()
	turtle.turnLeft()
  end
end

The problem starts when I run the code. It runs fine, except the turtle decided to do things its own way.



The cobblestone in the top left is where the turtle started. It's supposed to dig all the way to the end of the room, go to the next line, and come back. You can see it went about halfway instead. Also, for some reason it decided to dig an extra block after 6 lines and stopped that a little later.

Did I craft a defective turtle or am I missing something in my code?

(Extra: Originally the code was supposed to allow you to define the volume as well as to dig up or down, but that failed miserably. If you could help me do that, I'd really appreciate it.)
Bomb Bloke #2
Posted 15 December 2013 - 06:38 PM
Let's say you call "dig()". The turtle will start a loop of 16 iterations; first time through, it'll likely dig out the block above it. Next time through, it'll go forward one. Assuming there's a block above it for every movement it makes, it'll dig eight times and move forward eight times, as you're only having one or the other action performed each time the loop repeats - not both.

However: What if there was an air bubble - one of the blocks was already missing? If you run through the logic in your mind, you'll see that it'd dig seven times, and try to move forward nine!

Or what if digging out one of the blocks caused sand/gravel to fall? It could potentially dig out ten blocks, and only go ahead six!

Hence it's rather unpredictable as to how far the turtle will go each time dig() is called. Here's another version of the function:

local function dig()
  for i=1,16 do
    while turtle.detectUp() do  -- Until all blocks above the turtle have been cleared (eg falling gravel)...
      turtle.digUp()  -- Note that this won't be performed if the block above was already clear.
    end

    while not turtle.forward() do  -- Until the turtle successfully moves forward...
      turtle.dig()  -- Maybe there was a block in front of it?
      turtle.attack()  -- Maybe a mob flew in front of it?
    end
  end  -- Now both actions have been checked & performed as need be, we can start the next iteration.
end