Build a horizontal row

Here is a copy of the code that should appear in CodeCraft:

# CodeCraft Setup
from codecraft import Game, Position
game = Game()
materials = game.materials

game.clear_console()
print('Hello, CodeCraft!')
print(materials)

# A black block
game.set_block(Position(0, 1, -20), 1)

You already know how to build separate blocks by calling game.set_block() function.

Old way to build 5 connecting lime green blocks:

game.set_block(Position(0, 5, -20), 8)
game.set_block(Position(1, 5, -20), 8)
game.set_block(Position(2, 5, -20), 8)
game.set_block(Position(3, 5, -20), 8)
game.set_block(Position(4, 5, -20), 8)

Use for loop to build a row of blocks

We can use the for loop in CodeCraft to build patterned structures.

At the end of the existing file, start a new line and type in the following code:

for i in range(5):
    game.set_block(Position(i, 8, -20), 7)

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), 7)

The x-coordinate of the parameter Position(x, y, z) is represented by the variable i, instead of just one fixed number.

The 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 light blue row as shown in the picture:

results matching ""

    No results matching ""