For Loops
Now that you can build separate blocks by calling game.setBlock()
function, let's think about how we can build a fence containing 100 blocks. Wouldn't it be boring to call the same function 100 times? Instead, what if we could just tell the computer once to build 100 blocks at a time? This can be done using a loop. With a loop, we can ask the computer to repeat a task as many times as we wish.
Here is an example of a for
loop. Try it out in the code editor.
for (let i = 0; i < 5; i++) {
console.log(i);
}
A for
loop starts with for
keyword, then three statements in parenthesis:
for (let i = 0; i < 5; i++)
Initialization, let i = 0
, declares a loop variable i
and sets a value to start with;
The limiting step, i < 5
, specifies the condition for the loop to go on, so it's clear when to stop looping;
The increment step, i++
(add 1
to i
), specifies how to increase the loop counter.
A curly bracket follows at the end of the header line to indicate the start of loop body. Every thing inside curly brackets {...} are the loop body. Code in loop body are indented for easy reading.
Click run and check results in the console:
0
1
2
3
4
Build structures with for
loop
We can use for
loop in CodeCraft to build patterned structures.
Type in the following code and run it:
for (let i = 0; i < 5; i++) {
game.setBlock(new Position(i, 8, -20), 8);
}
In this program, we have only one line in the for loop body, calling a function to build a block:
game.setBlock(new Position(i, 8, -20), 8);
The x-coordinate of the parameter new Position(x, y, z)
is the variable i
instead of just one fixed number, therefore each block is placed at a different position.