Skip to main content

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python. Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening.

The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for Bukkit servers. Next, I found this handy guide to the Minecraft Pi Protocol. Finally, I found a Python library called mcpipy that implements the Minecraft Pi Protocol in Python.

Between looking at the Minecraft Pi Protocol documentation and peeking at the mcpipy source code, it's pretty easy to figure out how to control Minecraft from Python. My next step was to figure out how to draw something cool. Naturally, the first thing to come to mind was fractals, but it's not so easy to draw most fractals with fixed sized blocks. However, Sierpinski's triangle is not so hard to draw using blocks, so that's what I did.

Here's the psuedocode for drawing Sierpinski's triangle:

draw_the_three_vertices()
current_point =
    random_point_in_triangle()
while True:
    vertex = random_vertex()
    current_point = midpoint_between(
        current_point,
        vertex)
    draw(current_point)

Here's the actual source code:
#!/usr/bine/env python

"""Draw Sierpinski's triangle in Minecraft."""

import random

import mcpi.minecraft
import mcpi.block as block
import server

# It goes from -MAX_XZ to MAX_XZ.
MAX_XZ = 128
MAX_Y = 64

# These are the vertices of the triangle. It's a list of points. Each point
# is an (X, Y, X) tuple.
TRIANGLE_HEIGHT = MAX_Y - 1
TOP = (-MAX_XZ, TRIANGLE_HEIGHT, 0)
BOTTOM_LEFT = (MAX_XZ, TRIANGLE_HEIGHT, MAX_XZ)
BOTTOM_RIGHT = (MAX_XZ, TRIANGLE_HEIGHT, -MAX_XZ)
TRIANGLE_VERTICES = [TOP, BOTTOM_LEFT, BOTTOM_RIGHT]

BASE_BLOCK_ID = block.SANDSTONE.id
TRIANGLE_BLOCK_ID = block.SNOW.id

# This is the maximum number of iterations to let the algorithm run. The
# algorithm relies on randomness, so I'm just picking a sensible value.
MAX_ITERATIONS = MAX_XZ ** 2

PRINT_FREQ = 1000


def clear_board(minecraft):
    minecraft.setBlocks(-MAX_XZ, 0, -MAX_XZ, MAX_XZ, MAX_Y, MAX_XZ, 0)
    minecraft.setBlocks(-MAX_XZ, 0, -MAX_XZ, MAX_XZ, -MAX_Y, MAX_XZ, BASE_BLOCK_ID)


def draw_sierpinski_triangle(minecraft):

    def random_in_range():
        return random.randint(-MAX_XZ, MAX_XZ)

    def int_average(a, b):
        return int(round((a + b) / 2.0))

    # Draw the triangle vertices.

    for (x, y, z) in TRIANGLE_VERTICES:
        minecraft.setBlock(x, y, z, TRIANGLE_BLOCK_ID)

    # Pick a random point to start at.

    current = (random_in_range(),
               TRIANGLE_HEIGHT,
               random_in_range())

    for i in xrange(MAX_ITERATIONS):

        if i % PRINT_FREQ == 0:
            print("Drew %s blocks" % i)

        # Pick a random vertex to "walk" toward.

        destination = random.choice(TRIANGLE_VERTICES)

        # Draw a block in the middle of the current location and the
        # destination.

        (c_x, c_y, c_z) = current
        (d_x, d_y, d_z) = destination
        current = (
            int_average(c_x, d_x),
            TRIANGLE_HEIGHT,
            int_average(c_z, d_z)
        )
        (x, y, z) = current
        minecraft.setBlock(x, y, z, TRIANGLE_BLOCK_ID)


if __name__ == "__main__":
    minecraft = mcpi.minecraft.Minecraft.create(server.address)

    # Uncomment this if you need it.
    # clear_board(minecraft)
    
    draw_sierpinski_triangle(minecraft)
The Gory Details
If you're interested, here are all the gory details.

I got all of this running on OS X 10.7.

First, you'll need Java to run Bukkit. I installed Java SE Development Kit 7u21.

Next, you need to install Bukkit. Note, you must use a version of Bukkit that is compatible with your version of the Minecraft client. For me, that meant installing the latest, development version of Bukkit. See here for more information:
mkdir -p ~/Local/bukkit_server
cd ~/Local/bukkit_server
curl -L http://dl.bukkit.org/downloads/craftbukkit/get/02122_1.5.2-R0.2/craftbukkit-dev.jar -o craftbukkit.jar
echo "cd ~/Local/bukkit_server/" > start.command
echo "java -Xms1024M -Xmx1024M -jar craftbukkit.jar -o true" >> start.command
chmod +x start.command
To start the server, execute the start.command file. To stop the server, type "stop" into the console.

Next, I installed RasberryJuice. Download the jar file and move it to ~/Local/bukkit_server/plugins. Then type "reload" in the console where Bukkit is running.

Next, you'll need to install Minecraft itself. That costs roughly $30. I put it in ~/Local. When I first ran it, it insisted on installing "Java 6". To connect to your local server, choose Multiplayer, then Direct Connect, and then enter "localhost".

To install mcpipy, you can either use Git (if you have it installed), or you can download and uncompress the zip file. I put it in ~/Local/mcpipy. To test that it's working, try:
cd ~/Local/mcpipy
python zhuowei_rainbow.py
This will draw a rainbow in your running copy of Minecraft. After running the command, assuming there were no errors, it takes a little while for the rainbow to show up.

To try out my code, create a file called ~/Local/mcpipy/jjinux_sierpinski_triangle.py with the code from above. Then run:
cd ~/Local/mcpipy
python jjinux_sierpinski_triangle.py
It'll print out messages as it draws all the blocks. This will draw Sierpinski's triangle in the sky. It takes a minute or two to show up. You can tweak the script to draw the triangle using more blocks or with a different type of block. However, I've found that making certain changes causes Bukkit to crash, so keep an eye on the console where you started Bukkit to make sure nothing bad happened. If anything bad does happen, you might want to use control-c to stop the server. Then you can delete the world, world_nether, and world_the_end directories in ~/Local/bukkit_server and restart the server.

Comments

jjinux said…
I think I finally figured out why it would disconnect me when running my script. I saw a message that said:

23:17:49 [WARNING] myaccountname was kicked for floating too long!

When I clear the landscape, I delete stuff from under my avatar's feet. This leads to my avatar floating. That's what causes it to crash.
Unknown said…
Hi Shannon,

I enjoyed you post and followed the instructions.

I am running minecraft on a Mac and cannot find a way to cmd-tab out of the game to run the python files from a terminal window.

Can you share how to do that?

aye,

zak
jjinux said…
Hey, Zak, thanks for your comment. I actually can't remember. Does hitting escape work? You might want to Google for instructions on how to get out of full screen mode.
Unknown said…
you can just use T-key which is meant for chat but it actually cmd-tab out of the window

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from