Mavis Minecraft Teaches Coding – Part 3

The man with wires in his brain, Duncan Geere, is here with the third part of our guide for learning programming with Minecraft. You can catch up with the whole series here.

Welcome to part three of the RPS guide to learning how to code in Minecraft. If you’ve been following the tutorials so far, you should have a decent grasp of the basics of coding – how to put programs together and what several different commands do.

This week, we’re going to introduce something new to get your head around. The turtle. Turtles are autonomous moving computers with an inventory, basically the Minecraft equivalent of a robot helper. With their help, we’ll be automating some of the duller functions of the game – chopping down trees and mining a dropshaft.

In the process, you’re going to learn a few neat little coding tricks, including how to edit your programs outside of Minecraft itself. So what are we waiting for? Let’s get started.

You’ll need some more advanced resources in your inventory today. Twenty or so iron bars, a stack of coal, a chest, an unused diamond pick, and a stack of ladders and torches.

Once you’ve got all that, let’s put a turtle together. Put a computer in the centre, a chest directly below it, and then fill out the rest of the spaces with iron bars. Something that looks a bit like this:

Plonk it down on the ground somewhere, and right-click to bring up the interface. You’ll notice that it isn’t quite running the same operating system as your regular computers, but don’t worry – pretty much everything you’ve learned so far about operating computers in ComputerCraft will work.

The first thing you’ll need to do is put some fuel in it. Drop a single bit of coal in the right hand side and type “refuel” in the command window. If you’ve done it right, it should return “Fuel level is 80”. Turtles can mine and turn without fuel, but they need one unit of fuel for every block they move.

Now type “dance”, hit enter, and then esc to dismiss the interface, and watch as your turtle gets on down. It’ll carry on going until you right-click it and press a key, or it runs out of fuel.

Now, what can we usefully do with a turtle? Not a whole lot until we give it some tools, to be honest, except maybe automatically building a hut. But the code for that is a bit tedious, so let’s skip that and go straight to mining turtles.

First, stick your turtle in the crafting space in your inventory with the diamond pick to turn it into a mining turtle. We’re going to write a program that automatically fells trees for us.

Before I tell you how to code it, though, I’m going to share a quick secret that’ll make your life much easier. You don’t have to type every single character out into the interface manually – you can actually create the files in a text editor and save them in a specific directory – .minecraft/mods/ComputerCraft/lua/rom/programs.

If you do this, then it’ll be treated as part of the memory of every computer and automatically present on every computer you make from that point onwards, without having to use in-game disks (which are a pain with turtles). You can also edit it in a standard text editor, though if you make any changes and save them, you’ll have to reboot the (in-game) computer before they take effect.

Now, using either that method or the old type-it-all-out variant, you’ll want to create the following program, which looks for a block in front of it, mines it out if it exists, and then moves up and does the same thing again. If it runs out of things to hit, it descends back to the ground.

while turtle.detect() do
print(“Digging the block”)
while turtle.detectUp() do
print(“Moving up”)
while not turtle.detect() and not turtle.detectDown() do
print(“Moving down”)
print(“Job done!”)

Like last week, let’s run down each line of code and what it does:

while turtle.detect() do – If there’s a block in front of the turtle…
turtle.dig() – Mine it out
turtle.refuel(1) – Then refuel the turtle with that block (as in this case, it’s wood)
print(“Digging the block”) – Print status text
while turtle.detectUp() do – If there’s a block above
turtle.digUp() – Break it so there’s space
end – Ends the block-above loop
turtle.up() – Move up
print(“Moving up”) – Print status text
end – Ends the block-in-front loop
while not turtle.detect() and not turtle.detectDown() do – If there isn’t a block in front, and there’s nothing below (i.e. the tree is fully chopped down)
turtle.down() – move down
print(“Moving down”) – print status text
end – end the if-no-block loop
print(“Job done!”) – Print status text

That’s the basics of moving a turtle around and getting it to DESTROY. How about we take a look at how to get a turtle to create? Let’s dig a dropshaft down to the bottom of the world, placing a ladder as we go and dropping torches at 10-block intervals.

For that, we need to learn a couple of new commands: and The first command lets you choose a slot in a turtle’s inventory, and the second one places whatever’s in that slot

In this program, we want to dig downwards then across, place a ladder, and then repeat. Every 10 repeats, we want the turtle to place a torch, too. Here’s the code:

print(“Turtle Miner 1.0 initiated”)
print(“Place fuel in 16, torches in 15 and ladders in 14”)
print(“Press any key when ready”)

while turtle.detectDown() do
if turtle.getFuelLevel() < = 5 then turtle.refuel(1) end turtle.digDown() turtle.down() turtle.dig() n=n+1 if n==10 then turtle.turnRight() turtle.dig() turtle.turnLeft() n=0 end if not turtle.digDown then break end end

It’s a bit longer than our other programs, but let’s go through it line-by-line.

n=0 – start counting at zero
print(“Turtle Miner 1.0 initiated”) – print status text
print(“Place fuel in 16, torches in 15 and ladders in 14”) – give the user some instructions
print(“Press any key when ready”) – more instructions
os.pullEvent(“char”) – waits for input
while turtle.detectDown() do – while there’s ground beneath the turtle, do the following…
if turtle.getFuelLevel() < = 5 then – if fuel gets low – select the fuel slot
turtle.refuel(1) – and refuel with it
end – end the refuelling if block
if not turtle.digDown() then – dig a block out below the turtle, and if the turtle can’t dig down for any reason
break – end the program
end – ends the dig-down if block
turtle.down() – move into that space
turtle.dig() – dig forwards – select the ladder slot – place a ladder
n=n+1 – add 1 to the counter
if n==10 then – if the counter gets to ten
turtle.turnRight() – turn the turtle right
turtle.dig() – dig a hole – select the torch slot – place a torch
turtle.turnLeft() – turn back again
n=0 – reset the counter
end – ends the torch if block
end – ends the while-ground-below loop

There you go. With a bit of imagination and what you learnt last week about taking inputs from the user, it should be simple enough to program a turtle to automatically built out networks of mining tunnels for you to roam along, pulling out the juicy ore from the walls – much quicker than mining manually. Turtles are lava-proof, which you can use to your benefit – particularly in the Nether.

If you want a challenge, how about building a new turtle, equipping it with a diamond hoe, and making an automatic farm? You can use turtle.dig() to till soil with a hoe equipped, and turtle.drop() to put items in the turtle’s inventory into a chest when it’s next to one.

That’s it for this week. In the final instalment in this series, due next week, we’ll be looking at a few useful tools at your disposal in programming, including the use of functions to simplify your code, basic wireless communication, and where to go next. See you then!


  1. AmateurScience says:

    That’s it, I give in, I’m dusting off minecraft when I get home and giving this a shot. The thought of having an army of robots to do my bidding is too alluring.

  2. Clavus says:

    The code snippets could really use some proper indentation. It’s hard to oversee.

    • Chalky says:

      Agreed – an attempt has actually been made to indent the code but the HTML has eaten it. The author should try using “pre” tags to avoid this.

      • Torn says:

        <pre> and <code> tags, noless.

        • RvLeshrac says:

          It looks like you’re trying to
          [write enterprise HTML]

          Would you like some help with that?

          • Duncan says:

            I’ll give that a shot next week – though I’m submitting in Google Docs to RPS and they’re uploading it to the site so might be a bit fiddly :)

  3. P7uen says:

    This series is a great read. Not sure I’ll ever use it (I never even got around to basic redstone during my Minecraft addiction), but both learning what Minecraft can do and reading the tutorials here are ace.

  4. Morten242 says:

    In the second code the “dig-down if block” is close to the bottom while in the explanation part it’s far up (it’s also far up in the screenshot.)

  5. Jhoosier says:

    I’m valiantly resisting the urge to dive in. Job-hunting and finishing the semester are NOT the time to get intrigued by turtles and code.

  6. whollyrandom says:

    I’m probably being dense, but I don’t seem able to save a program in the suggested location (.minecraft etc). I’m assuming that this is in the appsdata file but when I go into mods there is no existing ComputerCraft mods directory, I have to create one and all of the sub-directories. Is this a side-effect of using Technic or is it normal that the mod directory not exist?

    Also, I’m assuming that I save the file under a particular name (eg ‘bighole’ for the digging program) without any file extension and that to run this I should only need to type the program name in the in-game turtle. When I do so, however, having created ‘bighole’ in what I believe to be the right directory, nothing happens. If they had pandas in Minecraft, I’d be a sad Minecraft-panda.

    • whollyrandom says:

      Also, it really doesn’t like line 8 of the digging program (“if turtle.getFuelLevel() < = 5 then") – if I take out the spaces between "<", "=" and "5" then the program runs but doesn't work ("bighole:8: attempt to call nil") and if I leave the spaces in then it doesn't even start (unexpected symbol in line 8).

      The computercraft wiki tells me that slot 16 is bottom right (though not why), so I've put the fuel there, the torches in bottom middle and the ladders in bottom left.

      I is sad and frustrated. Also re the game.

      • DrScuttles says:

        Yeah, the space between then < and = in line 8 need to be taken out to work, but apart from that the program worked for me without any other problems.

        • Duncan says:

          That looks like a bug in the formatting of the site here – you’re absolutely right, shouldn’t be a space there.

    • RvLeshrac says:

      Should go in %appdata%\.minecraft\etcetcetcetc.

      Also, “line 8” depends on a lot of things here. It sounds like you don’t have an item in the slot.

      If you can, fill each slot with a different item, then get and print the contents of each slot. That way, you won’t have to rely on what is usually dodgy documentation written by developers.

    • Duncan says:

      Yep, you need to create those directories yourself. And the second thing should work – it worked for me pretty much as you describe. Don’t forget to reboot your (ingame) computer to find the programs.

  7. Tacroy says:

    It looks like you forgot to close an <i> tag just after “dance”?

  8. Gap Gen says:

    I wonder if there’s a mod that turns villagers into your minions, a bit like Age of Empires or whatnot. I guess this is effectively that, but it’d be nice to get an economy of scale by building tons of these things with complex behaviour. What would be awesome would be a robot factory, so that a machine crafts one of these things and loads it with code, then sends it out into the world to do your bidding. I wonder if a Total Annihilation / Supreme Commander-like game would work in Minecraft…

  9. markb10101 says:

    I just want to know one thing before I reinstall Minecraft and get lost in blocks again… Is it possible to use a Turtle to build another Computer? In other words, can I build self-replicating Turtle-bots?

  10. appropriate touching says:

    Is that an off-by-one error in the last bit? You wanted torches every 10th block, but I think the code gives you every 11th.

    I like these articles.

  11. ghoststalker194 says:

    Argh, I’m lagging behind already. So busy!