We can use the programming language Python to interact with the Minecraft world in a few short lines of code.
First, we have to do a bit of setting up. To keep our code separate to the original code in the MCPI folder, we will make a new directory to keep all of our code in. In LXTerminal, type mkdir python This will make a directory called python. To use the MCPI API we will have to copy that folder over to our new directory. Make sure that you are in your new directory (cd python) and then type the following command: cp -r ~mcpi/api/python/* . Include the full-stop one space after the *!
Finally, we are ready to start coding. By default, the API only uses Python 2. x but you can change this to allow Python3 use as well by following this link, however, I will not be going in to that today, for now, we will stick with Python 2. I will also be using the command line text editor nano but you can use other text editors if you wish.
Our first task is to make the file that we will run. Make sure that you are in your new directory, then type cd mcpi followed by sudo nano block_placer.py This should open up an empty file in nano. The first two lines of code are import minecraft and then import block underneath it. Next, we have to connect to our Minecraft world which we do by typing mc = minecraft.Minecraft.create() This first example will simply place a block at a set of co-ordinates, so first, we will define three variables, one under the other, called x, y and z. The code could look a bit like this:
x = 5
y = 0
z = 5
Now that we have our co-ordinates, we just need to place the block. Our last line of text will be mc.setBlock(x, y, z, block.STONE) Note, this is case sensitive so make sure that everything is capitalised correctly if you get an error message. The final file should look like this:
mc = minecraft.Minecraft.create()
x = 5
y = 0
z = 5
mc.setBlock(x, y, z, block.STONE)
Now we can just save the file (press ctrl x, then press y to save changes and then enter) and get Minecraft running. These programs will not work unless Minecraft is running and a world is loaded. Open up another LXTerminal window, type cd mcpi and then ./minecraft-pi to get Minecraft going and then load into a world. Now, press the tab key to release the mouse from Minecraft, go back to our other LXTerminal window and type python block_placer . This should run the file and at the co-ordinate 5, 0, 5 there should now be a block of stone.
That’s it for the basic python stuff. In the next tutorial, we will move on to some more complicated code and look at how to build structures and some of the other useful commands we can use.