Blocks into bombs using events

Here is a very cool script again by the amazing author Martin O’Hanlon, you can right click block and have it explode like TNT in Minecraft.

Here is the code:

#Raspberry Pi, Minecraft Bombs - Turn any block into a bomb!

#import the module from the minecraft directory
import minecraft.minecraft as minecraft
#import minecraft block module
import minecraft.block as block
#import time, so delays can be used
import time
#import threading, so threads can be used
import threading

class ExplodingBlock(threading.Thread):

def __init__(self, pos, fuseInSecs, blastRadius):
 #Setup object
 self.pos = pos
 self.fuseInSecs = fuseInSecs
 self.blastRadius = blastRadius

def run(self):
 #Open connect to minecraft
 mc = minecraft.Minecraft.create()

#Get values
 pos = self.pos
 blastRadius = self.blastRadius

#Explode the block!
 # get block type
 blockType = mc.getBlock(pos.x, pos.y, pos.z)
 # flash the block
 for fuse in range(0, self.fuseInSecs):
 mc.setBlock(pos.x, pos.y, pos.z, block.AIR)
 mc.setBlock(pos.x, pos.y, pos.z, blockType)
 # create sphere of air
 for x in range(blastRadius*-1,blastRadius):
 for y in range(blastRadius*-1, blastRadius):
 for z in range(blastRadius*-1,blastRadius):
 if x**2 + y**2 + z**2 < blastRadius**2:
 mc.setBlock(pos.x + x, pos.y + y, pos.z + z, block.AIR)

if __name__ == "__main__":

 #Connect to minecraft by creating the minecraft object
 # - minecraft needs to be running and in a game
 mc = minecraft.Minecraft.create()

#Post a message to the minecraft chat window
 mc.postToChat("Minecraft Bombs, Hit (Right Click) a Block,")

#loop until Ctrl C
 while True:
 #Get the block hit events
 blockHits =
 # if a block has been hit
 if blockHits:
 # for each block that has been hit
 for blockHit in blockHits:
 #Create and run the exploding block class in its own thread
 # pass the position of the block, fuse time in seconds and blast radius
 # threads are used so multiple exploding blocks can be created
 explodingBlock = ExplodingBlock(blockHit.pos, 3, 3)
 except KeyboardInterrupt:

It’s also on the github

Source: Here


Minecraft Cannon

Hey back, I would like to show you guys a new script i found out there it allows you to play the classic game Snake by Martin O’Hanlon.


Here is a video i found on the page


#Raspberry Pi, Minecraft Snake

#import the module from the minecraft directory
import minecraft.minecraft as minecraft
#import minecraft block module
import minecraft.block as block
#import time, so delays can be used
import time
#import random module to create random number
import random

#snake class which controls the whole game
class Snake:
 def __init__(self, mc, startVec3, playingBottomLeft, playingTopRight): = mc
 self.direction = "up"
 self.lenght = 5
 self.tail = []
 self.tail.insert(0, startVec3)
 self.playingBottomLeft = playingBottomLeft
 self.playingTopRight = playingTopRight
 self.score = 0

#draw's the whole snake
 def draw(self):
 for segment in self.tail:, segment.y, segment.z, block.DIAMOND_BLOCK)

#add's one segment to the snake
 def addSegment(self, segment):, segment.y, segment.z, block.DIAMOND_BLOCK)
 self.tail.insert(0, segment)
 #do I need to clear the last segment
 if (len(self.tail) > self.lenght):
 lastSegment = self.tail[len(self.tail)-1], lastSegment.y, lastSegment.z, block.AIR)
 #pop the last segment off the tail

#moves the snake, if it cant it returns false (i.e. game over)
 def move(self):
 newSegment = minecraft.Vec3(self.tail[0].x, self.tail[0].y, self.tail[0].z)
 if self.direction == "up":
 newSegment.y = newSegment.y + 1
 elif self.direction == "down":
 newSegment.y = newSegment.y - 1
 elif self.direction == "left":
 newSegment.x = newSegment.x - 1
 elif self.direction == "right":
 newSegment.x = newSegment.x + 1
 if (self.checkCollision(newSegment) == False):
 #have I eaten the apple?
 if (matchVec3(newSegment, == True):
 #increase my lenght
 self.lenght = self.lenght + 2
 #increase my score
 self.score = self.score + 10
 #create a new apple
 return True
 #game over
 #flash snake head
 mc.setBlock(self.tail[0].x, self.tail[0].y, self.tail[0].z, block.AIR)
 mc.setBlock(self.tail[0].x, self.tail[0].y, self.tail[0].z, block.DIAMOND_BLOCK)
 mc.setBlock(self.tail[0].x, self.tail[0].y, self.tail[0].z, block.AIR)
 mc.setBlock(self.tail[0].x, self.tail[0].y, self.tail[0].z, block.DIAMOND_BLOCK)
 #show score
 mc.postToChat("Game over - score = " + str(self.score))
 return False

#function to check if a new segment (or apple) can go there
 def checkCollision(self, newSegment):
 #am I going the boundary
 if ((newSegment.x == playingBottomLeft.x) or (newSegment.y == playingBottomLeft.y) or (newSegment.x == playingTopRight.x) or (newSegment.y == playingTopRight.y)):
 return True
 #or my own tail
 hitTail = False
 for segment in self.tail:
 if (matchVec3(segment, newSegment) == True):
 hitTail = True
 return hitTail

#function to change the snake's direction
 def changeDirection(self, newDirection):
 #code to make sure user doesnt try and make the snake move back on itself
 if (newDirection == "up"):
 if (self.direction != "down"): self.direction = newDirection
 elif (newDirection == "down"):
 if (self.direction != "up"): self.direction = newDirection
 elif (newDirection == "left"):
 if (self.direction != "right"): self.direction = newDirection
 elif (newDirection == "right"):
 if (self.direction != "left"): self.direction = newDirection

#create the apple at a random position on the board
 def createApple(self):
 badApple = True
 #loop until an apple is created which doesnt collide with the boundary or the snake
 while (badApple == True):
 x = random.randrange(playingBottomLeft.x, playingTopRight.x)
 y = random.randrange(playingBottomLeft.y, playingTopRight.y)
 z = playingBottomLeft.z
 newApple = minecraft.Vec3(x, y, z)
 badApple = self.checkCollision(newApple) = newApple,,, block.GLOWING_OBSIDIAN)

#Compares vec3 objects, if they are the same returns true
def matchVec3(vec1, vec2):
 if ((vec1.x == vec2.x) and (vec1.y == vec2.y) and (vec1.z == vec2.z)):
 return True
 return False

#draws a vertical outline
def drawVerticalOutline(mc, x0, y0, x1, y1, z, blockType, blockData=0):
 mc.setBlocks(x0, y0, z, x0, y1, z, blockType, blockData)
 mc.setBlocks(x0, y1, z, x1, y1, z, blockType, blockData)
 mc.setBlocks(x1, y1, z, x1, y0, z, blockType, blockData)
 mc.setBlocks(x1, y0, z, x0, y0, z, blockType, blockData)

#main program
if __name__ == "__main__":

 screenBottomLeft = minecraft.Vec3(-10,4,15)
 screenTopRight = minecraft.Vec3(10,24,15)
 playingBottomLeft = minecraft.Vec3(-10, 4, 14)
 playingTopRight = minecraft.Vec3(10, 24, 14)
 snakeStart = minecraft.Vec3(0, 5, 14)
 upControl = minecraft.Vec3(0, -1, 1)
 downControl = minecraft.Vec3(0, -1, -1)
 leftControl = minecraft.Vec3(-1, -1, 0)
 rightControl = minecraft.Vec3(1, -1, 0)
 middleControl = minecraft.Vec3(0, 0, 0)

 #Connect to minecraft by creating the minecraft object
 # - minecraft needs to be running and in a game
 mc = minecraft.Minecraft.create()

#Post a message to the minecraft chat window
 mc.postToChat("Hi, Minecraft Snake,")

 #Build game board
 # clear a suitably large area
 mc.setBlocks(-10, 0, -5, 10, 25, 16, block.AIR)
 # create playing board
 mc.setBlocks(screenBottomLeft.x, screenBottomLeft.y, screenBottomLeft.z, screenTopRight.x, screenTopRight.y, screenTopRight.z, block.STONE)
 drawVerticalOutline(mc, playingBottomLeft.x, playingBottomLeft.y, playingTopRight.x, playingTopRight.y, playingTopRight.z, block.OBSIDIAN)

 # create control buttons
 mc.setBlock(upControl.x, upControl.y, upControl.z, block.DIAMOND_BLOCK)
 mc.setBlock(downControl.x, downControl.y, downControl.z, block.DIAMOND_BLOCK)
 mc.setBlock(leftControl.x, leftControl.y, leftControl.z, block.DIAMOND_BLOCK)
 mc.setBlock(rightControl.x, rightControl.y, rightControl.z, block.DIAMOND_BLOCK)
 # blocks around control buttons, to stop player moving off buttons
 mc.setBlock(middleControl.x + 2,middleControl.y + 1,middleControl.z, block.GLASS)
 mc.setBlock(middleControl.x - 2,middleControl.y + 1,middleControl.z, block.GLASS)
 mc.setBlock(middleControl.x,middleControl.y + 1,middleControl.z + 2, block.GLASS)
 mc.setBlock(middleControl.x,middleControl.y + 1,middleControl.z - 2, block.GLASS)
 mc.setBlock(middleControl.x - 1,middleControl.y + 1,middleControl.z - 1, block.GLASS)
 mc.setBlock(middleControl.x - 1,middleControl.y + 1,middleControl.z + 1, block.GLASS)
 mc.setBlock(middleControl.x + 1,middleControl.y + 1,middleControl.z + 1, block.GLASS)
 mc.setBlock(middleControl.x + 1,middleControl.y + 1,middleControl.z - 1, block.GLASS)
 mc.setBlock(middleControl.x,middleControl.y - 1,middleControl.z, block.STONE)
 # put player in the middle of the control
 mc.player.setPos(middleControl.x + 0.5,middleControl.y,middleControl.z + 0,5)

#time for minecraft to catchup

mc.postToChat("Walk forward, backward, left, right to control the snake")

#create snake
 snake = Snake(mc, snakeStart, playingBottomLeft, playingTopRight)

playing = True

 #loop until game over
 while playing == True:
 #sleep otherwise the snake moves WAY too fast
 #get players position - are they on a control tile, if so change snake's direction
 playerTilePos = mc.player.getTilePos()
 playerTilePos.y = playerTilePos.y - 1
 if matchVec3(playerTilePos, upControl) == True: snake.changeDirection("up")
 elif matchVec3(playerTilePos, downControl) == True: snake.changeDirection("down")
 elif matchVec3(playerTilePos, leftControl) == True: snake.changeDirection("left")
 elif matchVec3(playerTilePos, rightControl) == True: snake.changeDirection("right")
 #move the snake
 playing = snake.move()
 except KeyboardInterrupt:
 print "stopped"

Note! I changed the glowing obsidian aka ‘The Snakes food’ to a gold blocks because i was testing it on raspberry juice

Here is a link to the original thread!

It’s also on the github @

Going to minecon?

Hi all, this is Brooks. Sorry we’ve been absent for a while, but I wanted to drop a note that Phillip and I will be at minecon this weekend.

If you are going and you’d like to meet up, please drop an email to mcpipy at!

Update: Sorry, our email is mcpipy at, I don’t think we have the gmail account 😦

jjinux’s Sierpinske Triangle Script

Hi it’s Phillip and I’m back updating the site – here is our first script to highlight!

Jjinux has submitted his script to our github code archive, thanks!

This script makes a Sierpinske Triangle in the sky made out of snow!!!

Here are some photos and a video to show you what it does:

jjinux's script pic jjinux's script pic

here’s a video of the script. Please Subscribe, Like, Comment or please do them all!! 🙂

Here’s the code:

#!/usr/bin/env python

# retrieved from URL below, written by jjinux

"""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.


# 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.


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(),

    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),
            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)

And the source is on our github as usual!! Source: Pull Request On Github

3 new scripts from goldfish – HelloWorld, clearZone and drawBuilding!

Ryan (goldfish) has submitted 3 new programs — and he has my many thanks for doing so by pushing his changed to the github repo and making them compatible with the other scripts!!

Here’s what he’s contributed:

This is a simple program that connects to the minecraft server and does a quick chat — this is a great template for starting new programs…

#! /usr/bin/python
import mcpi.minecraft as minecraft
import server

""" hello world test app

    @author: goldfish"""

mc = minecraft.Minecraft.create( server.address )
mc.postToChat("Hello, Minecraft!")

This one creates a 20×20 block and adds a stone floor.  Even better you can import it and call clearZone(x1,y1,x2,y2) to create a clear zone of the size you specify.

Screen Shot 2013-03-01 at 3.07.42 PM

#! /usr/bin/python
import mcpi.minecraft as minecraft
import mcpi.block as block
import server

""" clearZone clears an area and sets a stone floor
    takes two x,z pairs clears everything above 0y and then sets
    a stone floor at -1y
    @author: goldfish"""

def clearZone( alocx, alocz, blocx, blocz ):
    mc.setBlocks( alocx, 0, alocz, blocx, 64, blocz, block.AIR )
    mc.setBlocks( alocx, -1, alocz, blocx, -1, blocz, block.STONE )

if __name__ == "__main__":
    mc = minecraft.Minecraft.create( server.address )
    clearZone( -20, -20, 20, 20 )

This one creates a building with floors and windows in it — or you can call it again with your own parameters.  Call the following function..

drawBuilding( locx, locy, locz, floors, width, depth, floorheight, wallmaterial, floormaterial)

Screen Shot 2013-03-01 at 3.08.56 PM
Screen Shot 2013-03-01 at 3.09.20 PM
Screen Shot 2013-03-01 at 3.09.39 PM

#! /usr/bin/python
import mcpi.minecraft as minecraft
import mcpi.block as block
import server
import random

""" draw a building

    @author: goldfish"""

def drawBuilding( locx, locy, locz, floors, width, depth, floorheight, wallmaterial, floormaterial ):
    topx = locx+width
    topy = locy+((floorheight+1)*floors)
    topz = locz+depth
    #draw building shell
    mc.setBlocks( locx, locy, locz, topx, topy, topz, wallmaterial )
    mc.setBlocks( locx+1, locy+1, locz+1, topx-1, topy-1, topz-1, block.AIR )
    #draw floors
    if( floors > 1 ):
        for i in range( floors -1 ):
            floorYloc = locy+( (floorheight+1)*(i+1) )
            mc.setBlocks( locx+1, floorYloc, locz+1, topx-1, floorYloc, topz-1, floormaterial )
    #draw door
    doorloc = random.randint( 1, width-2 )
    mc.setBlock( locx, locy+1, locz+doorloc, block.AIR )
    mc.setBlock( locx, locy+2, locz+doorloc, block.AIR )
    #draw front windows
    if( floors > 1 ):
        for i in range( floors-1 ):
            windowYloc = locy+2+( (floorheight+1)*(i+1) )
            for j in range( floorheight-1 ):
                mc.setBlocks( locx, windowYloc+j , locz+1, locx, windowYloc+j, locz+(width-1), block.GLASS_PANE )
    #draw back windows
    if( floors > 1 ):
        for i in range( floors-1 ):
            windowYloc = locy+2+( (floorheight+1)*(i+1) )
            for j in range( floorheight-1 ):
                mc.setBlocks( locx+depth, windowYloc+j , locz+1, locx+depth, windowYloc+j, locz+(width-1), block.GLASS_PANE )
    #connect levels with ladder
    #mc.setBlocks( topx-1, locy+1, topz-1, topx-1, topy-1, topz-1, block.LADDER )

if __name__ == "__main__":
    mc = minecraft.Minecraft.create( server.address )
    drawBuilding( 0, 0, 0, 5, 5, 5, 3, block.STONE, block.WOOD_PLANKS )

RaspberryJuice v1.2 update available, thanks Zhuowei!

Zhuowei Zhang has updated RaspberryJuice to v1.2! v1.2 includes the following changes:

  1. added world.getBlockWithData to be compatible with Minecraft Pi 1.1.
  2. changed block hit events to listen for right-click with sword
  3. added ban-ip feature: if an IP is banned in the server, connections to the Pi API will be automatically kicked

I’m most excited about the addition of getBlockWithData. With this change, the program works just as well against the desktop as the raspberry pi.

Download the v1.2 change here.

Thanks Zhuowei for making this change!

If you’re not familiar with RaspberryJuice, check out my previous post on it here

Getting a Raspberry Pi to play Minecraft Pi…

If you already have a Raspberry Pi, feel free to skip to the next blog post.

Occasionally I have a discussion with someone about the Raspberry Pi and at some point I mention what a wonderful device this $35 computer is…  they typically get excited they can do so much for just $35.  And if I have the chance, I’ll try to adjust their expectations noting that it can cost “as little as $35” if you have all the “accessories” already.

So I wanted to try to lay out in this post just what it costs to get started – and hopefully this may be a useful list if you want to buy one yourself.

The Raspberry Pi is an amazing little computer and it only costs $35.  However if you want to play minecraft pi or access the web, you’ll need a few more things including:

  1. a TV or PC Monitor capable of receiving a signal via HDMI.  (For this post, I’ll assume only HDMI – although Raspberry PI includes analog/composite video and analog stereo support)
  2. A HDMI cable to connect from the Raspberry PI to the TV/Monitor.
  3. A cable to power the USB – e.g. a micro USB power cable with 1 amp of power.
  4. A 4GB+ SD card for local storage (including the operating system)
  5. A keyboard with USB connection
  6. A mouse with USB connection
  7. a USB Wifi 802.11b+ adapter so you can connect to Wifi.  (You can also connect via Ethernet, but I’ll assume Wifi is what most people want)
  8. A USB hub (because the Pi includes 2 USB ports, and I’ve specified 3 USB devices above – Wifi, keyboard and mouse)
  9. And of course… the Rasbperry Pi device — 256MB of RAM or 512MB of RAM

Now for me, I already had everything else when I got the Rapsberry Pi.  I had a micro USB device from my kindle ebook reader, with a USB charger.  I had a keyboard, mouse and USB hub from an old computer.  I did have to buy the USB Wifi adapter/chip, but my cost was closer to $35.  If you have nothing though (other than a HDMI Capable TV/monitor) you’ll need to spend more like $130 (including the $35 for the Raspberry Pi).

Here’s how I came up with the $130 price. (aka Element 14) is one of the manufacturers and retailers of the Raspberry PI – so via their web site I added the following to my cart:

Screen Shot 2013-02-26 at 4.35.26 PM

And the total for the above was:

Screen Shot 2013-02-26 at 4.35.35 PM

Add another approximately $8 for shipping and you get to $130…

So again — hopefully this will cost you less as you have some of the above things already not being used, but worst cast it’s like $130.

Is it worth it?

So if you’re asking whether it’s worth spending that much money for one of these devices?  I’d say:

  1. If you are considering buying a kid a Raspberry PI vs. a low cost desktop/laptop PC — I’d say go for the PC!  Yes you can access the web, etc with the Raspberry PI — but it’s slow and it’s more complex for a kid to start out.
  2. If you are considering buying this to experiment, play or other purposes — then absolutely go for it!

For me, as a father wanting to teach my kids more about computers — it was a great investment (and I just bought two more today).

Of course my bias is on software — and Rapsberry Pi is as much about connecting to to hardware of all types – and controlling it with software.  That’s something you can’t get to the same degree on a PC..

Beware the starter kits — know what it includes and whether it’s important to you…

Again if you are mostly looking for how to get it up and running so you can interact with the software — the list above is what you need.

There are lots of great web sites that sell starter kits that include what you need to connect raspberry pi to other hardware — but not the mouse, keyboard, power, SD card, hdmi cable, etc described above.  So look carefully at what’s included in these kits.

Are you looking at Raspberry Pi primarily as a way to play minecraft?

In that case, you should know that Minecraft Pi Edition is free — but it’s a subset of the full Minecraft experience on the PC.  Minecraft Pi is based on Minecraft Pocked Edition and both are missing some features that many kids enjoy like the ability to connect to multiplayer servers across the internet.

What did I miss?

Hopefully the above is helpful — and make no mistake, I’m very excited about Raspberry Pi and I recommend to most people to get one — as long as they understand what it is they are and are not getting…

Please add your comments though on your view.  If there are cheaper options to get a starter kit as described above – please add that in the comments as well!

Calling contributors for anything and everything!

Writing this blog has been a lot of fun — far more than I expected.  It was started as a way to collect the python programs Phillip and I found and to encourage ourselves and others to learn about Python by playing with Minecraft and Raspberry Pi.  It’s been great to see how many people are discovering Minecraft PI Edition (MCPI) themselves and writing python scripts… and I given this is just v0.1.1 and a few weeks old, I expect it it will continue to take off.

Which is leading me to the realization — there is more already than Phillip and I can handle ourselves and we need the help of others to continue this.  So I’m making a request for help!

If you are interested in helping, please drop us an email at and if you have ideas on how you can help – please include that.

There is lots that can be done, here are a few ideas on how I’d like to get help from others — but if there is something you can do not on this list, please let us know!

  1. One time or repeat contributors – Write one or more articles to appear on the blog.  It can be any topic related to Python (or Programming), Minecraft and Raspberry PI (or RaspberryJuice)
  2. Finding scripts – help us search the far corners of the the net for interesting creations we should highlight.
  3. Testing scripts – we have a number of scripts we haven’t had time to test out.  Test them, grab some photos or even make a youtube video!
  4. Github updates – besides checking in the last scripts, we can discuss ideas on how to improve this resource further…
  5. Promotion – help us get the word out on how to program Minecraft in python on raspberry pi — and find others that can learn from the blog, and contribute!

Finally if you aren’t able to help — then please leave a comment to encourage us and note what you’d like to see on future blog posts.  We have a wide range of interests among the readers and we’d like to get to know you better so we can prioritize creating the right content.

As always, thanks for reading and all the contributions to date!!

Programming Minecraft with languages other than Python…

So this blog has been focused on Python because well that’s what I know (and continue to learn) and I think Python is beautiful.  But of course there are still people using other languages out there <g> and I’m thrilled to see people are connecting these up to Minecraft Pi Edition.

I don’t expect to blog any further about the non-python bindings, but wanted to share what I’ve seen so far.  If I’ve missed any, please feel free to add them via the comments and I’ll update this posting periodically to catalog them.

Also please let me know as well if there are collections of programs written in other languages as well and I’m happy to link to them!