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 (let i = 0; i < 5; i++) {
for (let j = 1; j < 11; j++) {
game.setBlock(new 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 (let i = 0; i < 5; i++) {
for (let j = 1; j < 6; j++) {
for (let k = 0; k < 5; k++) {
game.setBlock(new Position(i, j, k - 20), 18);
}
}
}
Exercises:
Please try the follow two structures:
// line of yellow columns
for (let i = 0; i < 30; i += 4) {
for (let j = 1; j < 10; j++) {
game.setBlock(new Position(i, j, -10), 59);
}
}
// brick stairs
for (let i = 10; i < 20; i++) {
for (let k = -10; k < -5; k++) {
game.setBlock(new 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 example:
// black sheet
for (let j = 0; j < 10; j += 2) {
for (let i = -j; i < j+1; i += 2) {
game.setBlock(new Position(i, j+1, -20), 1);
// blue array
for (let j = 0; j < 10; j += 3) {
for (let i = -j; i < j+1; i += 3) {
for (let k = -j; k < j+1; k += 3) {
game.setBlock(new Position(i, j+1, k), 45);
}
}
}