Trigger code in Python from Minecraft

To find out what is happening in the Minecraft world, Python can ask via the API. The pollBlockHits() method will return data about each block hit with a sword since the last time it was called. Note: You must use a sword, and you must Right-Click. This is the only action detected by this function.

Like in other exercises, we need to bring in some libraries of code that enable Python to speak to Minecraft.


In [ ]:
import mcpi.minecraft as minecraft
import mcpi.block as block
import time

Connect to the Minecraft server, store the connection in a variable named world:


In [ ]:
world  =  minecraft.Minecraft.create()

This script works best with blocks that change appearance when their block data changes. One good example is wool, so let's create a small field of wool for you to hit with the sword:


In [ ]:
[x,y,z] =  world.player.getPos()
world.setBlocks(x,y-1,z,x+10,y-1,z+10, block.WOOL)

Start looping forever. This is an example of a game loop, because it keeps on processsing until it is interrupted. If you want to stop the loop, press the "stop" button, or use the Kernel -> Interrupt option in the notebook menubar.


In [ ]:
while True:
    hits = world.events.pollBlockHits()
    for hit in hits:
        print "Have hit {h.x},{h.y},{h.z}".format(h=hit.pos)
        block = world.getBlockWithData(hit.pos.x, hit.pos.y, hit.pos.z)
        block.data = (block.data + 1) & 0xf ## The & 0xf keeps the block data value below 16 (0xf in hexadecimal)
        world.setBlock(hit.pos.x, hit.pos.y, hit.pos.z, block.id, block.data)
        world.postToChat("Block data is now " + str(block.data))
    time.sleep(1)

The block of code above is more interesting with blocks that change based on their data value, such as wool, flowers, and wood. Wool changes color with the different data values.

Advanced Exercises and Questions

  1. What other block types change their appearance when you hit them with a sword while this script is running?
  2. Can you draw a creeper with just this code and a sword?