In previous Minecraft projects, we remapped the control functions that are typically handled by keyboard presses and implemented them in a custom controller that we built. In this project, we're going to start actually manipulating blocks in the Minecraft world.

In this specific project, we will learn how to monitor when Minecraft blocks have been "hit" and then gather and use that information in our code.

For this project, we need just a single button mapped to GPIO24. You are welcome to keep the full hardware setup from a previous project that has a button attached to GPIO24, or you can simplify your hardware to the following:

Here is the code that will allow us to get information about blocks that were hit and then print out information about those blocks.

You should recognize most of the code below, but we've highlighted the important code with red arrows:

Here's how the code works:

mc.event.pollBlockHits()

In our code above, we used the function mc.event.pollBlockHits() to gather information about all the "events" that have taken place with all of the Minecraft blocks. The Minecraft API only supports one "event" type, which is a block being hit, so this function will simply return a list of all blocks that have been hit since the last time this function was called.

We can store that list of blocks that were hit in an object/variable (we use hits in our code above), and can then use that variable to gather information about those blocks or to act on them. The most common piece of information we will want to know about a block that was hit is the block's position, in X, Y and Z coordinates. This can be gathered using the .pos property of the object, as we saw in this line of code above:

print("The X, Y, Z coordinates of the block you hit is:", hit.pos)

Specific coordinate positions can be determined as well. For example, we could replace the previous line of code with:

print("The X coordinate of the block you hit is:", hit.pos.x)
print("The Y coordinate of the block you hit is:", hit.pos.y)
print("The Z coordinate of the block you hit is:", hit.pos.z)

(although the above code will print 3 lines instead of 1).

  1. Assuming you still have your controller wired up, add this shovel code to the Minecraft controller code ( project) to add shovel functionality to one of your controller buttons.

  2. The pollBlockHits function returns a list of new hits, and there can be more than one item in that list. However, our game loop runs pretty fast, so you'll probably never see more than one hit in the list. Instead of printing the coordinates, just print out how many hits occurred if there was more than one.

  3. If you completed the previous challenge, then try slowing the game loop down to see if you can create more than one new hit at a time.