For loop
Now that you can build separate blocks by calling game.set_block()
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. Make sure to type in the colon, :
, at the end of the first line and indent 4 spaces at the beginning of the second line. Both of these tell the computer that the second statement is part of the for
loop.
for i in range(5):
print(i)
The first line tells Python to repeat 5 times. The second line represents the body of the for
loop, the part that is repeated 5 times. i
is a variable which receives a different value from 0 to 4 in each loop. The for loop body many contain one or more lines of code, all of which need to have the same number of spaces (at least 1) at the beginning. It's a convention to use 4 spaces.
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 i in range(5):
game.set_block(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.set_block(Position(i, 8, -20), 8)
The x-coordinate of the parameter Position(x, y, z)
is the variable i
instead of just one fixed number.
The variable i
holds one of the values in a number sequence generated by range(5)
: 0, 1, 2, 3, 4
. The loop runs through the sequence, starting with the first element 0
and ending at 4
, placing blocks at those x-coordinates but the same y- and z-coordinates. The 5 blocks form a lime green bar as shown in the picture: