Wall & Cube
With a for
loop, we were able to build an entire row of blocks with only two lines of code. What if we need to build a wall? We can certainly copy and paste that for
loop multiple times. But a better solution would be to use nested for
loop. How about a 3D cube? Just add another layer of loop!
To build a 2D wall, we need to loop through two directions: use i
to iterate through x locations and j
to iterate through y locations.
Brick wall:
# Build a 5 x 10 (width x height) wall
for i in range(5):
for j in range(1, 11):
game.set_block(Position(i, j, -15), 17)
Cube:
To build a 3D cube, we need to loop through three directions: i -> x, j -> y, k -> z
for i in range(5):
for j in range(1, 6):
for k in range(5):
game.set_block(Position(i, j, k - 20), 18)
Exercises:
Please try the follow two structures:
#line of yellow columns
for i in range(0, 30, 4):
for j in range(10):
game.set_block(Position(i, j, -10), 59)
# brick stairs
for i in range(10, 20):
for k in range(-10, -5):
game.set_block(Position(i, i-9, k), 17)
The picture of the wall, cube, yellow columns and the brick stairs:
Challenge
Here is a challenge project. Try to figure out how to build the structures in this picture:
Answer:
# black
for j in range(0,10,2):
for i in range (-j, j+1, 2):
game.set_block(Position(i, j+1, -20), 1)
# blue
for j in range(0,10,3):
for i in range (-j, j+1, 3):
for k in range(-j, j+1, 3):
game.set_block(Position(i, j+1, k), 45)