With ComputerCraft, Your Clever Minecrafter Can Learn to Code

ComputerCraft computer, miner and code in Minecraft
Share this post:
Facebooktwitterredditpinterest

As well as being a fun, creative game for kids, Minecraft offers a huge range of learning opportunities to help your child expand their skills and knowledge. Even with just the basic version of Minecraft — known as vanilla — your kid can pick up reading and maths skills, as well as learn patience, cooperation, concentration and a ton of other useful skills.

However, once you start modding Minecraft, an even bigger world of learning opens up. From the Galacticraft mod, which lets you build a rocket and fly to other planets, to qCraft, which simulates quantum mechanics, the possibilities are enormous!

One fantastic Minecraft mod that’s been around for a while is ComputerCraft. This mod allows you to build fully-functioning computers inside your Minecraft world, then use those computers much like you use a real computer. You can type commands at the computer’s terminal, play games inside the computer and — yes — even write computer programs!

In addition, the computers in ComputerCraft can interact with their “real” world (that is, the Minecraft world in which they’re placed!). They can send redstone signals to control other blocks; they can communicate with each other via wireless networking; and you can even create turtles — computer-controlled robots that you can program to carry out actions, such as mining, farming, crafting and protecting you against monsters.

You program computers and turtles in ComputerCraft using a language called Lua. Lua is easy to learn and use, and it’s perfect for learning essential programming concepts.

ComputerCraft is a great way to help your kid learn coding skills. They’re already playing one of their favourite games — Minecraft — and by learning how to program computers in ComputerCraft, they gain extra control over their Minecraft worlds, and can create new and exciting things. So they’re highly motivated to learn!

How can you and your kid get started with ComputerCraft? This is where this ComputerCraft tutorial comes in! You’ll explore the following topics:

  • How to install the ComputerCraft mod (you’ll need a copy of Minecraft too, of course).
  • Creating computers in ComputerCraft.
  • How to use a computer and run programs.
  • How to write a simple game inside a ComputerCraft computer.

Along the way, your kid will pick up a whole range of programming skills and concepts, including variables, program flow, loops, conditional statements, functions, and lots more.

Ready? Let’s get started on your ComputerCraft adventure!

Installing ComputerCraft

The usual way to install the ComputerCraft mod is to use the Minecraft Forge modloader. The whole process is fairly easy, and takes about five minutes.

To install both Forge and ComputerCraft, follow these steps:

  1. Download Minecraft Forge.
    Visit the Forge download page and download Forge for the appropriate Minecraft version. At the time of writing, ComputerCraft works with Minecraft 1.6.4, so you should download “1.6.4-Recommended”. Click the appropriate “Installer” link to download the forge-x-x-x-installer.jar file to your computer.
  2. Install Minecraft Forge.
    Find the downloaded forge-x-x-x-installer.jar file, and double-click it to open it. When the “Mod system installer” dialog appears, make sure that “Install client” is selected, and that the path to your Minecraft game folder is displayed in the box at the bottom of the dialog. Then click OK to start the installation. After a short while, you should see a message indicating that Forge was installed successfully.
Once Minecraft Forge has installed, you'll see a success message like this.

Once Minecraft Forge has installed, you’ll see a success message like this.

  1. Run Minecraft with the Forge profile.
    Start the Minecraft launcher in the usual way. In the launcher window’s Profile list, you should see a new profile called Forge. Select this profile, then click the Play button to launch Minecraft with that profile. If all goes well, you’ll see a message in the Minecraft title screen indicating that Forge is loaded. Forge should also automatically create a folder called mods in your Minecraft game folder (we’ll get to this in a moment). Now quit Minecraft.
Once Forge is installed, choose the Forge profile from the Profile menu, and click Play.

Once Forge is installed, choose the Forge profile from the Profile menu, and click Play.

The text in the bottom left corner of the Minecraft title screen lets you know that Forge is installed.

The text in the bottom left corner of the Minecraft title screen lets you know that Forge is installed.

  1. Open the Minecraft game folder.
    Open the Minecraft launcher again. Make sure the Forge profile is selected in the launcher, but this time, click Edit Profile instead of Play. In the Profile Editor window that appears, click the Open Game Dir button to open your Minecraft game folder, then click the Cancel button in the Profile Editor window to close it. In the game folder, you should see a folder called mods that Forge created. Open the mods folder (it’s probably empty at this stage).
Once Forge has run once, you should have an empty mods folder inside your Minecraft game folder.

Once Forge has run once, you should have an empty mods folder inside your Minecraft game folder.

  1. Download and install ComputerCraft.
    Visit the ComputerCraft download page and click the Download ComputerCraft link in the page (at the time of writing this is called “Download ComputerCraft 1.63 (for Minecraft 1.6.4)”). This downloads the ComputerCraft .jar file to your computer. Now simply drag this .jar file into the mods folder you opened in Step 4 to install it.
To install ComputerCraft, just drag it into the mods folder.

To install ComputerCraft, just drag it into the mods folder.

  1. Make sure it worked.
    Switch back to the Minecraft launcher, make sure the Forge profile is still selected, and click Play. When the Minecraft title screen comes up, click the Mods button. You should see ComputerCraft in the list of included mods.
Once ComputerCraft is installed, you should see it appear in the list of mods in Minecraft.

Once ComputerCraft is installed, you should see it appear in the list of mods in Minecraft.

All done!

Another way to install ComputerCraft is to use a modpack launcher, along with a modpack that includes the ComputerCraft mod. For example, the Technic platform supports modpacks such as Big Dig, which includes ComputerCraft (as well as some other ComputerCraft-related mods).

Creating your first computer

Now that we have ComputerCraft installed, let’s try making our first virtual computer! Start a new Minecraft world, or open an existing world (I recommend using creative mode). Press ‘E’ to bring up the creative mode inventory, click the compass icon to bring up the Search Items box, and type computer. You’ll see a list of all the computers you can create in ComputerCraft, including the Computer, Advanced Computer, Pocket Computer and so on.

For now, click the basic Computer (the leftmost grey cube) to pick it up, and drop it into your inventory.

Type 'computer' to find all the ComputerCraft computers in the inventory.

Type ‘computer’ to find all the ComputerCraft computers in the inventory.

Now press Esc to exit the inventory, select the Computer in the inventory bar at the bottom of the screen, then right-click on the ground to place the computer, just like any other block.

Placing a computer on the ground. (Don't worry, rain doesn't affect it!)

Placing a computer on the ground.

Using your computer

To access your new computer, right-click it. This brings up a window showing the computer’s white-on-black screen, with a “CraftOS” prompt. No fancy graphics or mouse here — this computer is old-school! Everything you do needs to be typed into the computer, in the form of commands.

To get going, type the command help and press Return. You’ll see a menu of other commands that you can type to learn more.

To stop using the computer at any point, just press the Esc key.

Right-click a computer to access it. Type commands and press Return. Old-school!

Right-click a computer to access it. Type commands and press Return. Old-school!

Running programs

It’s easy to run programs in your virtual computer: just type the program’s name and press Return. CraftOS — ComputerCraft’s operating system — comes with a range of built-in programs and games that you can try. To get a full list of them, type:

programs

and press Return.

For example, to play the game Worm, type:

worm

and press Return.

To stop a program running, hold down both the Control and ’T’ keys for a couple of seconds.

Writing a simple game

One of the best ways to learn any programming language is to create a game in the language, and Lua is no exception.

Let’s build a simple “number guessing” game inside a ComputerCraft computer, that has a nice reward when you win! In the following sections I’ll guide you step by step through the process of building the game. If you’ve never coded before, don’t worry — this tutorial is for absolute beginners!

(By the way, if you don’t want to type in all of this code — which can be quite tedious on a little computer running inside Minecraft! — you’ll find a quicker way to get the program into your ComputerCraft computer at the end of this tutorial.)

In this tutorial you'll learn how to create this simple number-guessing game in ComputerCraft.

In this tutorial you’ll learn how to create this simple number-guessing game in ComputerCraft.

Step 1: Create and access the computer

To begin, open your Minecraft world, or create a new world — I recommend using creative mode — and place a Computer as described earlier in the tutorial. Then right-click the computer to access the CraftOS prompt.

Step 2: Create the program file

Type:

edit numberGuess

and press Return. This creates a new program file called numberGuess and opens the text editor to edit the file. This text editor is quite simple to use: Just type text into it like a word processor. To save the file, press the Control key, then press the ’S’ key. To leave the editor, press Control followed by ‘E’.

Make sure you save your file regularly as you enter your programs!

Step 3: Set up some variables

Let’s start our numberGuess program by creating three variables that we need for the game. A variable is simply an area of the computer’s memory that can store a value. When you create a variable, you give it a name so that you can access it later.

In the editor, type the following lines of code:

-- Set up some variables

local myNumber = math.random(1, 100)
local tries = 0
local maxTries = 5

Here we’ve created three variables, as follows:

  • myNumber, which holds the number that the user needs to guess. We set this variable to the result of the function call math.random(1, 100); this function call returns a random whole number between 1 and 100.
  • tries, which tracks how many guesses the user has made so far. We set this to zero at the start.
  • maxTries, which governs how many tries the user is allowed to have. We set it to 5 tries. (If you find the game to difficult, you can increase this value!)
A variable is a named area of memory that stores a value.

A variable is a named area of memory that stores a value.

By the way, the line:

-- Set up some variables

is a comment. Comments are just for people to read; the computer ignores them. Comments in Lua start with two dashes (--).

Step 4: Display an introduction to the user

It’s always nice to welcome the user and give them some instructions when they start the game. Add the following lines of code to your program:

-- Display the intro

term.clear()
print("I'm thinking of a number between 1 and 100.")
print("You have 5 tries to guess it!")

The first line of code calls the built-in term.clear() function, which clears all text from the screen and moves the cursor to the top left corner of the screen.

The second line of code calls the built-in print() function, passing in a string of text as an argument to the function. An argument is simply a value that you give to a function when you call it.

As you can probably guess, the print() function outputs its argument — in this case, “I’m thinking of a number between 1 and 100.” — to the screen. It also outputs a “newline” character, which means that any future output will start on the next line on the screen.

The third line of code calls print() again, displaying “You have 5 tries to guess it!” on the next line.

Step 5: Create the game loop

Most games contain one central “loop”, or repeating block of code, that runs again and again while the game is played. The game loop’s job is to listen for input from the user, adjust the game’s state, and end the game if certain conditions are met.

Let’s write the game loop for our number guessing game. Type the following into your computer’s text editor:

-- The main game loop

while true do

  -- Read the next guess from the user

  tries = tries + 1
  print("\nTry #" .. tries .. ". What's your guess?")
  local guess = tonumber(read())

  -- Compare the guess to my number

  if guess < myNumber then
    print("Too low!")
  elseif guess > myNumber then
    print("Too high!")
  else
    print("\nYou got it!")
    shootFireworks(5)
    break
  end

  -- Check if the user has used up their tries

  if tries == maxTries then
    print("\nBad luck, you ran out of tries!")
    break
  else
    print("Try again...")
  end

end

This loop contains the “meat” of the game. Let’s work through each line of code:

Create an infinite while loop

The very first and last lines of the game loop code create the actual loop:

while true do
…
end

This uses a looping construct known as a while loop. The more general form of a while loop is:

while condition do
…
end

These two lines of code mean: “While condition is true, keep running the code between the ‘while’ line and the ‘end’ line over and over again.”

With a while loop, the computer keeps running the loop code until condition is no longer true.

With a while loop, the computer keeps running the loop code until condition is no longer true.

The condition can be anything that results in a value of true or false (known as a Boolean value). For example, ‘a == b’ (“a equals b”) and ‘x < y’ (“x is less than y”) are both valid conditions, since they result in either a true (“yes”) or a false (“no”) value.

In our game loop, we’ve used true for the condition. In theory, this makes the loop run forever, because the condition will always be true. This is known as an infinite loop. Don’t worry, though — our loop won’t really run forever! We’ll see how to stop the loop running in a moment.

Read the next guess from the user

The first three lines of code inside our game loop allow the user to guess the number:

tries = tries + 1
print("\nTry #" .. tries .. ". What's your guess?")
local guess = tonumber(read())

The first line increases the value of the tries variable by 1, to track the fact that the user is about to use up one of their tries.

The second line uses print() to prompt the user to type their guess. There are a couple of new things here worth looking at:

  • The \n at the start of the string is the “newline” character. This outputs an extra blank line before the text, to make it easier to read.
  • The string is actually three strings joined together: (a) "\nTry #"; (b) the value of the tries variable; and (c) ". What's your guess?". We join these three strings together using the special .. operator  (that’s two dots). This is called the concatenation operator. (“Concatenation” is just a fancy word that means “joining together.”)

The third line of code calls the read() function, which reads in a line of text typed by the user and returns the result. The code then takes this string of text and converts it to a number by passing it through a built-in function called tonumber(). Finally, the code stores this number — the user’s guess — in a new variable called guess.

Prompting the user for their guess, and reading their input.

Prompting the user for their guess, and reading their input.

Compare the guess to the computer’s number

The next chunk of code checks to see if the user’s guess was too low, too high, or correct:

-- Compare the guess to my number

if guess < myNumber then
  print("Too low!")
elseif guess > myNumber then
  print("Too high!")
else
  print("\nYou got it!")
  shootFireworks(5)
  break
end

This code uses some new Lua statements:

  • if condition then
  • elseif condition then, and
  • else.

These are called conditional statements, because they either run or skip a block of code based on the value of a condition. If condition is true, the code is run; if condition is false, the code is skipped. The following diagram shows how these statements work when put together:

An if...elseif...else...end block. The values of condition1 and condition2 determine which chunk of code the computer runs.

An if…elseif…else…end block. The values of condition1 and condition2 determine which block of code the computer runs.

Here’s how our code works:

  • First the computer runs the if line of code. If guess is less than myNumber, the computer displays the message “Too low!”, then skips to the first line of code after the end statement.
  • If guess is not less than myNumber then the computer skips to the elseif line. This checks to see if guess is greater than myNumber. If it is, the computer displays the message “Too high!”, then skips to the first line of code after the end statement.
  • If guess is not greater than myNumber then the computer skips to the else line. The else statement tells the computer to run the block of code between the else and the end. By this point we know that guess is neither less than nor greater than myNumber, so it must equal myNumber. So we display the message “You got it!” to the user. We also call an intriguing function called shootFireworks(), passing the value 5 as an argument (we’ll get to this function in a moment!).
  • We also add a statement called break to the else code block. This breaks out of the main while game loop, and runs the first line of code (if any) after the while loop’s end statement. In our case, the while loop’s end statement is the last line of runnable code in our program, so the program stops once the user has guessed correctly.

By the way, the elseif and else statements are optional. If you only want to run (or not run) some code based on a single condition, just use:

if condition then
  code
end

If you want to run one block of code if the condition is true or another block of code if the condition is false, use:

if condition then
  code1
else
  code2
end

We’ll use this second type of conditional block in the next section.

Check if the user has used up their tries

The last chunk of code inside our game loop uses an if…else…end block to check if the tries variable equals the value of maxTries:

-- Check if the user has used up their tries

if tries == maxTries then
  print("\nBad luck, you ran out of tries!")
  break
else
  print("Try again...")
end

If tries equals maxTries then the user has used up all their guesses, so the code displays a “Bad luck!” message and uses break to break out of the game loop, ending the game. Otherwise, the user still has one or more guesses left, so the code block simply displays “Try again”.

And do it all again!

Assuming neither of the two break statements described earlier was called, the computer eventually reaches the end statement at the end of the while loop. This tells the computer to go back to the first line of code after the while line, and run the code in the game loop all over again.

Step 6: Shoot some fireworks!

Now let’s take a look at that intriguing function call inside our game loop:

shootFireworks(5)

Can our computer program really shoot fireworks? Yes it can! First, we need to write our shootFireworks() function. Add the following code below the game loop in your program:

-- Shoot some fireworks!

function shootFireworks(numFireworks)

  sleep(1)

  for i=1,numFireworks do
    redstone.setOutput("left", true)
    sleep(.2)
    redstone.setOutput("left", false)
    sleep(.2)
  end

end

This code defines the shootFireworks() function. A function is a reusable block of code that carries out a particular task, and that you can call — that is, run — from anywhere else in your program. In this case, we only call it from one place — within the game loop — but you could, if you wanted, call this function from other places in your program too.

It’s always a good idea to break your programs up into functions as much as possible. Not only does it make it easier to reuse blocks of code, but it also makes your code easier to read.

To define any function, you write:

function functionName(parameters)
  ...
end

The block of code between the function and end lines runs whenever the function is called.

parameters is an optional list of parameters for the function. A parameter is a temporary variable that receives a value — called an argument — that is sent by the code that calls the function. Your function’s code can then read the parameter’s value — just like any other variable — and do stuff with that value as needed.

In our shootFireworks() function, we’ve included one parameter called numFireworks. If you remember, when our game loop called shootFireworks(), it passed the value 5 as an argument. This means that, when shootFireworks() runs, numFireworks equals 5.

The first thing our function does is call the sleep() function, passing in an argument of 1. sleep() is a built-in function that tells the computer to wait for a certain amount of time — in this case, one second.

Then, our function sets up another kind of loop, called a for loop. Unlike a while loop — which loops until a certain condition becomes false — a for loop is designed to run a block of code a set number of times. A general for loop looks like this:

for counter=start,end do
  ...
end

start and end specify the start and end values that the loop should move between. Usually, the loop counts from start to end in whole numbers. For example, if you set start to 1 and end to 3, the loop runs three times, counting 1, 2, 3. If you set start to 5 and end to 8, the loop runs four times, counting 5, 6, 7, 8.

An example of a for loop. The counter variable counts from 1 to 3, running the loop code 3 times.

An example of a for loop. The counter variable counts from 1 to 3, running the loop code 3 times.

counter is a variable that holds the current value that the loop has reached. The letter ‘i‘ is often used for the counter variable’s name, but it can be any name you like. You can use this variable within the block of code inside your loop (although we won’t in this case).

In our shootFireworks() function, we set up the following for loop:

for i=1,numFireworks do
  ...
end

This loop counts from 1 to the value of numFireworks, storing the current counter value in the variable i. Since our game loop calls shootFireworks() with the value of 5 as an argument, our loop will run five times.

Within the for loop, we include the following code:

  redstone.setOutput("left", true)
  sleep(.2)
  redstone.setOutput("left", false)
  sleep(.2)

This code makes two calls to a built-in function called redstone.setOutput(). This function takes two arguments:

  • A “side” of the computer block (which can be "left", "right", "front", "back", "bottom", or "top").
  • A Boolean value (true or false). true turns on a redstone signal on the specified side of the computer, while false turns the signal off.

So this block of code turns on a redstone signal on the left side of our computer block, waits 0.2 seconds, turns it off again, and waits another 0.2 seconds. Since this code is within a for loop that runs 5 times, the result is that the computer generates five quick redstone pulses on its left-hand side, one after the other.

Step 7: Stock up with fireworks

But how does all this code shoot fireworks exactly? To make that happen, we need to back out of computer programming for a minute, and delve into some good old-fashioned crafting! Follow these steps:

  1. Save your program and exit the editor by pressing Control, then ’S’, then Control, then ‘E’.
  2. Press the Esc key to finish using the computer. (Make sure you don’t left-click your computer, or you’ll break it — and lose your program!)
  3. Place a dispenser face-up on the left hand side of the computer block, as you face the computer. (You may need to stand on the computer to do this. Don’t worry, it’s strong!)
  4. Make a crafting table (if you don’t already have one).
  5. Get the following items from the creative mode inventory: two stacks of gunpowder, a stack of dye (any colour), and a stack of paper. (Shift-click an item in the creative mode inventory to pick up a whole stack at once.)
  6. Use your crafting table to make a stack of coloured firework stars from one stack of gunpowder and the stack of dye:
Crafting a stack of firework stars.

Crafting a stack of firework stars.

  1. Use the crafting table again to make a stack of firework rockets from the firework stars, paper and the other stack of gunpowder:
Crafting a stack of firework rockets.

Crafting a stack of firework rockets.

  1. Right-click the dispenser and put the firework rockets in the dispenser.

All done! Now, when the shootFireworks() function runs, the five redstone pulses trigger the dispenser to shoot five fireworks into the sky.

Step 8: Play the game!

Now comes the fun bit! Right-click the computer again to access it, then run your game by typing:

numberGuess

then pressing Enter. If all goes well, you’ll see the game’s welcome message, and a prompt to make your first guess. Type your guess (from 1 to 100) and press Return. See if you can guess the number within 5 tries. If you guess correctly, quickly hit Esc and look up at the sky to see your reward!

The video below shows the game in action:

Getting the game into your computer quickly

If you don’t want to type all of the game’s code into your ComputerCraft computer, there’s a quick way to get the program installed. ComputerCraft supports a service called Pastebin that lets you copy and paste chunks of code between ComputerCraft computers, and computers in the real world.

I’ve uploaded the numberGuess program to Pastebin here. To install it in a ComputerCraft computer, just type this command at the computer’s terminal:

pastebin get CsVCwpJ6 numberGuess

and press Return.

To find out more about ComputerCraft’s Pastebin support, type:

help pastebin

and press Return.

Have fun writing your own programs!

I hope this tutorial has inspired you and your kid to learn coding in ComputerCraft, and build some amazing Minecraft creations using virtual computers! Take a look at the ComputerCraft Wiki for details on all the other functionality in ComputerCraft, including turtles, disk drives, colour computers, modems and more!

If your kid would like to learn Lua in more depth, the Lua website has a free online reference manual, and there are also several good Lua books available, including Programming in Lua, written by the language’s chief architect.

Thanks for reading, and if you have any questions or comments on this tutorial, please feel free to post them below!

Tagged with: , ,

Get Free Updates

Enjoyed this article? Get the latest news and great ideas on technology, kids, and learning sent straight to your inbox!

9 comments on “With ComputerCraft, Your Clever Minecrafter Can Learn to Code
  1. Laura Harmon says:

    Thanks for this post! Very helpful!

  2. Coolstar422 says:

    So, I created it, and I double checked everything, and I messed it up somehow, when I try to run it, this message pops up.
    bios:14: [string “.temp”]:49: ‘=’ expected

    so, trying to be smart I went to line 49, and I did not see what it was talking about, I had exactly how it was told.

    I’m just slightly confused…

  3. Thanks for the post, it’s very helpful. I do have an error message coming up 🙁 and I’ve tried the pastebin version and it returns the same error

    numberguess:31: attempt to call nil

    so what I understand, it fails to call the function???

  4. Alissa says:

    My kids have been on Minecraft for quite some time. I would love for them to try ComputerCraft, though. It looks like fun and I know they would like to make the turtles.

    Are Forge and ComputerCraft only for PC’s? I couldn’t figure out how to load it onto an iPAD.

    Thanks for your help!

    • Matt Doyle says:

      Hi Alissa, yes ComputerCraft and other mods are only for the PC/Mac version of Minecraft I’m afraid (although this may change in the future!).

  5. Alissa says:

    Thanks so much for the quick answer! I will stop trying to figure out how to do this on their iPADs! We will go for it on the PC.

    Thanks for your post… It is helpful to have a knowledgeable parent out there for those of us trying to learn. I don’t want to get into Minecraft to figure it out, but I do want to encourage my kids to take something they enjoy and go to the next level (and learn something useful in the process!!) ?

Leave a Reply

Your email address will not be published. Required fields are marked *

*