Meeting 2020-02-25

Looping in Python Part 2

Last week we learned how to loop over blocks of code in Python using the for keyword and the range() function. This is really important and useful stuff, so I'd like to get some more practice with a new project - building an instant house.

Project: Build an Instant House

This week we will use for loops and the mc.setBlock() function to build an instant house around where the player is standing in the Minecraft world. To make it a little easier, I will give you a Python file that gives you step-by-step instructions for building as comments, and you just have to figure out the Python code to make the steps happen. Feel free to review the information from last week on for loops and the range()function if you need a reminder.

from mcpi.minecraft import Minecraft

mc = Minecraft.create()

### Program constants - names in UPPERCASE

WALLBLOCK = 3 # DIRT

ROOFBLOCK = 3 # also DIRT but you can change it

DOORBLOCK = 0 # AIR

HOUSEHEIGHT = 3 # height of house walls

HOUSERADIUS = 3 # half of house length and width

### Get the player's current location

# save location as playerX, playerY, playerZ for convenience

### Build the house around the player

# for loop in Y from playerY to playerY+HOUSEHEIGHT levels to build the walls

# for loop in X from (playerX - HOUSERADIUS) to (playerX + HOUSERADIUS)

# place a wall block at (X,Y,(playerZ-HOUSERADIUS))

# place a wall block at (X,Y,(playerZ+HOUSERADIUS))

# for loop in Z from (playerZ - HOUSERADIUS) to (playerZ + HOUSERADIUS)

# place a wall block at (playerX-HOUSERADIUS,Y,Z)

# place a wall block at (playerX+HOUSERADIUS,Y,Z)

### nested loop over X and Z to build the roof at Y=playerY+HOUSEHEIGHT

# for loop in X from playerX-HOUSERADIUS to playerX+HOUSERADIUS

# for loop in Z from playerZ-HOUSERADIUS to playerZ+HOUSERADIUS

# place a roof block at (X,playerY+HOUSEHEIGHT,Z)

### Make a doorway by placing air blocks

# place a DOORBLOCK at (playerX, playerY, playerZ-HOUSERADIUS)

# place a DOORBLOCK at (playerX, playerY+1, playerZ-HOUSERADIUS)

Once you have added all the lines of code, save you program in the %appdata%\roaming\.minecraft\mcpipy folder and try running it!

You may find that your house is missing some corners and edges - Python coordinate ranges strike again! In a range(start,end) function, the for loop doesn't actually get to the end value. You will need to add one to many of the ending coordinates to build a perfectly square house.

Project: Add Multiple Stories

If you have finished the instant house program and want another challenge, add another level of for loops outside the house building routine to make a multi-story house. You will need to add an offset to all the y-coordinates that depends on the floor of the house you are building.