TeachCraft Lesson 5

Sword as a Magic Code-Wand

Now for a new construct, the while loop! The while True: loop below continuously runs the code indented underneath it.

Keep in mind, a computer is superfast! To not overload the server, we need to add a delay! Note that we added an import time to the script, and then at the end of the while loop we add a time.sleep(1) to wait 1 second before going through the loop again.

Try running the script on the right, and watch it make a trail of flowers continously spawn behind your character. Try other blocks (such as minecart tracks, or even flowing lava)!

Sample Code

import mcpi.minecraft as minecraft
import time

mc = minecraft.Minecraft.create(address="", name="steve")

while True:

    pos = mc.player.getPos()
    flower_block_id = 38
    mc.setBlock(pos.x, pos.y, pos.z, flower_block_id)


Now for a new part of the minecraft api - polling events! With this new feature, we can execute code whenever you perform a certain action.

This makes it so you don't have to swap between windows to execute code anymore, you can simply do an action in minecraft and have your code be triggered.

In this specific example, it's setup so when you right click a block while holding a sword, your code is executed.

You'll see the first change is adding
for blockhit in mc.player.pollBlockHits():
inside the while loop. For loops are a new type of loop. In this one, each time the loop runs, the blockhit variable contains information on the block you hit, and we can access its position via blockhit.pos

In the script on the right, everytime we right-click a block with a sword, the code executes that turns that block into gold. Try it!

Note! If you get an error here that says AttributeError: CmdPlayer instance has no attribute 'pollBlockHits', this means you are using the wrong version of the mcpi library! You need to use the teachcraft version - just copy the mcpi folder from this repository to be in the same folder as your code.
import time
from mcpi import minecraft
mc = minecraft.Minecraft.create(address="", name="steve")

while True:

    for blockhit in mc.player.pollBlockHits():
        pos = blockhit.pos
        gold_block_id = 41
        mc.setBlock(pos.x, pos.y, pos.z, gold_block_id)


Your Challenge: Turn your sword into a magic wand!

There's a lot of different actions you can trigger with your sword...

Your Challenge: Write a script that creates a 3x3 building of air on any block you click with a sword. In this way, you can use your sword as a magic wand that banishes materials in front of you!