Home » Worksheets » Minecraft with Python.
  • Minecraft with Python.

    Controlling Minecraft with Python programming language.

    This is one of the fun sessions we have. You don’t need to wire anything up or download any modules, you don’t even need to be connected to the internet as Minecraft is intalled on the Raspberry Pi operating system. Check out the instructions below.


    Here is your first go at coding in Minecraft!

    Minecraft Command KeysPlug in the white power lead to the Raspberry Pi & give it some life!. Open Minecraft from the Start Menu – Games – MinecraftPi. Click Start Game, Create New. You are now in Minecraft! Have a move around & hack at blocks with the left mouse key & drop items (E) with the right mouse key. Use the mouse to look around in your new virtual world. Move to a fairly large open, flat space before you start this worksheet.

    Hit tab & come out of Minecraft. Open the programming tool with Start – Programming – Python2 (not 3). Move Minecraft out of the way a little to give you some space to type.

    Enter the following code in the Python2 window >>> – Do this carefully without mistakes & commas in-between where needed. You don’t need to add the line starting with the # unless you want to as these are handy comments & good practice, but don’t do anything.


    from mcpi.minecraft import Minecraft
    mc = Minecraft.create()

    mc.postToChat (“Hacked”)

    x, y, z = mc.player.getPos()

    # Place a Gold block in the ground
    mc.setBlock(x+1, y-1, z, 14)


    Run the code with F5 & save it as mine.py. You must have .py at the end of the file name. Now go over to Minecraft – Look around and you will see a gold block in the ground – YOU DID THAT! Any mistakes are reported and you need to find the line with the fault and re-type it exactly how it is above.

    Change the value in the mc.setBlock line from number 14 to something else & see what appears. Use 0 (zero) to delete blocks. There is a table of numbers on the next page for you to try out!

    Now remove the mc.setBlock line & replace with the following line. (note the set Block now has the letter ‘s’ on the end)


    # Make a Stone Patio on the surface
    mc.setBlocks(x, y, z, x+10, y-0, z+10, 4)


    Can you make a 100 block long bridge, 3 blocks wide from stone? Then at the end of the bridge make a left or right turn & another bridge 50 blocks long.

    • Now for that explosion you have been promised!

    Replace the mc.setBlocks line with the following line – remember to change the # line so you know what you have done. The 46 is for TNT & the number one at the end makes it live and primed!!!


    mc.setBlocks(x, y, z, x+5, y-0, z+5, 46, 1)


    Try hitting the dynamite with your sword & then run away & turn back to watch it explode. Can you make it bigger than 5×5? Don’t worry about closing Minecraft & starting again if you need a new start, as your code is safe in the Python2 window.



    Tags: ,