Loops are fundamental to any coding language. In this tutorial, we’ll look at how we use loops to run some simple tasks. This tutorial is also a great way to show pupils that – in code – there are often multiple ways to solve a problem.

Let’s load up puzzle 5 from the Minecraft Hour of Code. And, so things aren’t too easy for us, let’s click Start Over in the top right hand corner. This will clear our workspace.

startOver

In this puzzle, the idea is for our character to lay some planks of wood on the dirt.

We do this by dragging commands from the Blocks section onto the Workspace.

In this case, we could manually code up the instructions one by one. So let’s do that first.

We have four planks to lay so drag across a place birch planks block, followed by a move forward block. As you drag these commands over, they’ll glow indicating where to drop them so they connect.

mc2

Now, if you click Run, you’ll see Steve (or Alex) lay one plank and move forwards. Although we have grasped the idea, we’ve failed the challenge, so let’s click Try Again.

mc3

Now, let’s repeat our earlier steps, chaining together place birch planks blocks, followed by move forward blocks until we have four of each.

mc4

And now let us click Run again! This time you’ll see we have passed the test!

mc5

Great! But we’ve written eight lines of code.

What we can do is write this code in a far more efficient way.

Clear your screen (click Start Over) and, this time, drag up the pink Loop block.

mc6

Anything we “code” within this block will repeat the number of times we have set. So if we set this to repeat 4 times, and drag up one place birch planks block, followed by a move forward block, and nest these within the loop, you should have something that looks like this.

mc7

Click Run now and you’ll see exactly the same result as last time, only with far more efficient code!

Learning about loops is a great first step as nearly all games use loops in some way. Think of Tetris which makes shapes on a loop. Think of Minecraft where multiple blocks are generated. A more advanced time of loop would be to loop through something until something else happens. For example, make Sonic run until the time runs out, play Candy Crush until a certain score is met.

We’ll take a look at some more advanced loops soon!