Get started with the Minecraft API.

Welcome to the eighth blog of Christmas! Unfortunately, as I’m going to be very busy over the coming weeks this will be the last blog of Christmas. Here’s our final song:

On the eighth day of Christmas my true love sent to me
eight blocks inserted
seven quizzing questions
blog five improved
five objects tested
four lines of code
three LEDs in cardboard
two functions in a module
and a micro:bit in a Christmas tree

Firstly boot up your Pi and start the Operating System by typing startx into the command line. Then open Minecraft Pi from Menu > Games. Click on start game and create a new world. After it has finished loading, press tab to free the mouse and minimize the window. Now open Python 3 from  Menu > Programming and then go to file > New File. A new blank window should appear. Copy in this code:

from mcpi.minecraft import Minecraft
mc = Minecraft.create()
air = 0
stone = 1

First we import the Minecraft module and configure it. In this module every different type of block has its own number. For example, wood is 5. In the code we create variables called ‘stone’ and ‘air’ so that we don’t have to remember their numbers – we can just type in ‘stone’ or ‘air’.

while True:
    x,y,z = mc.player.getPos()
    mc.setBlocks (x+2, y+1, z+2, x-2,y,z-2, air)
    mc.setBlock (x, y-1, z, stone)

Next we create a forever loop to constantly execute a piece of code. Then we set the variables x, y and z to the player’s coordinates (position) in the world. After that we replace the blocks around the player with air (nothing) using mc.setBlocks(). Then we place a block of stone underneath the player so that he/she can baisically walk in the air. This all happens constantly again and again and again. Here’s the code all together:

from mcpi.minecraft import Minecraft
mc = Minecraft.create()
air = 0
stone = 1

while True:
    x,y,z = mc.player.getPos()
    mc.setBlocks (x+2, y+1, z+2, x-2,y,z-2, air)
    mc.setBlock (x, y-1, z, stone)

Save your code and click on Run then Run Module. Then open your  Minecraft window. You should see that wherever you walk all the blocks around you disappear, and you make a tunnel through anything – whether it’s a mountain or a tree!  You should also see that wherever you walk a stone block appears underneath your feet. Try jumping up – now you’r walking in the sky!

Thanks for reading this tutorial! If you want to do some more Minecraft coding or want to find out more check out this tutorial from http://www.raspberrypi.org: getting started with minecraft pi.

Advertisements