TeachCraft Lesson 2

If statements, while loops, and "beam me up Scotty!"

To start with, we need to gather the coordinates for two different spots.

First, find a spot close by that gives you a good view (like the top of a hill, or an open meadow). Once you get to that spot, run the script on the right to print out your coordinates. Write these down somewhere, you'll need them later.

Second, find a spot close by that you'd like to make a secret teleportation pad. Again using the script on the right, retrieve your x/y/z coordinates and write them down.

Sample Code


from mcpi import minecraft
mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve")

pos = mc.player.getTilePos()
print("x", pos.x)
print("y", pos.y)
print("z", pos.z)

Output will be something like:

x -3
y 0
z -3

In lesson 1, we discussed how to teleport a user to a location relative to their current position (e.g. 100 units higher).

You can actually also teleport directly to a specific location. Tweak the script on the right, replacing the x/y/z variables with your own coordinates for your secret teleportation pad and your "good view" locations.

Sample Code


from mcpi import minecraft
mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve")

x = 3
y = 100
z = 3
mc.player.setPos(x, y, z)


Let's use an if statement to detect if we are standing on the teleportation pad. If we are on the x/y/z coordinates of the teleportation pad, the if statement executes the code within it, causing "Beam me up, Scotty" to be posted into chat!

Try running the code on the right. Do you notice any problems? We aren't checking the "y" coordinate! This means that the teleportation will activate regardless of height (so even if you are several blocks under your teleportation pad.)

Try editing the code to fix this, by checking the "y" value in the if statement.

Sample Code


from mcpi import minecraft
mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve")

# Teleportation pad coordinates
x = 3
y = 100
z = 3

pos = mc.player.getTilePos()

# If player position is same as teleportation pad...
if pos.x == x and pos.z == z:

    # We are on the teleportation pad!
    mc.postToChat("Beam me up, Scotty!")



Your Challenge: Create a working teleportation pad!

Your Challenge: Combine the concepts in the previous two scripts to make a new script.

This new script should compare the user's current coordinates to the coordinates of the teleportation pad. If they are the same, then inside the if statement you should add the code that teleports your user to the "good view" location, and posts the message "Beam me up, Scotty!" into Minecraft's chat.