Have you always wanted to learn how to code but didn’t know where to start? Learn how to control Minecraft on Raspberry Pi using Python and simple electronics. Here is the end result:

You’ll need a Pi 2 or newer for this project, and while most of these tasks you could do through the command line via Secure Shell (SSH), this tutorial will focus on coding directly on the Pi.

New in Minecraft? Don’t worry — here’s our Minecraft Beginner’s Guide Beginner’s Guide

Introduction to Minecraft Pi

minecraft-pi-menu

Minecraft for Raspberry Pi was designed for learning and mastering (and it’s free). It comes with an Application Programming Interface (API) that makes it easy to communicate with Minecraft. It’s great for learning to code in Python, as well as getting started with electronics.

What is Python?

Python is a programming language. it interpreted which means that when you run a Python file or program, the computer must first do a little work on the file. The downside is that it can be considered slow compared to compiled languages.

The advantages of interpreted languages ​​are the speed of coding and their convenience. You don’t need to tell the computer what kind the data you want to save, you just want to save something, and the computer will figure out what to do. Of course, there are exceptions, and this is a bit of a simplification, but programming should be fun! If you start digging into the complex technical details, it can get a little time consuming.

Python is case sensitive. This is important to know since Python will not recognize objects even if they are spelled correctly, if things go wrong. «Dosomething()» won’t work if the method is actually called «DoSomething()». Python also uses indentation . Other programming languages ​​may not care how much indentation your code has, while Python does. Indentation is used to tell Python where the code is. Other languages ​​may use «curly braces» ({}) to group code — Python does not use them. Python uses a hash (#) for comments, and comments are used to tell other developers or people looking at the code what a particular part does or why it is needed. Python ignores anything after a hash.

Finally, there are two major versions of Python — Python 2.7.x and Python 3.x. There are some differences between the two (what are the differences?). This tutorial will use Python 3.

Initial setup

If your Pi is already set up and running Raspbian there is no need for initial setup.

Open Terminal ( Menu > Accessories > Terminal ) and run this command. It is always recommended to update the repositories list regularly, this will download the latest list of programs (it will not download the programs themselves, this will help the Pi know what programs are called and where to find them).

sudo apt-get update 

Now update the Pi (this may take a while):

 sudo apt-get upgrade 

Python and Minecraft Pi are already installed, however, if Minecraft Pi is not installed for any reason, just install :

 sudo apt-get install minecraft-pi 

Go to Documents and create a new folder called «Minecraft»:

 cd Documents/ mkdir Minecraft 

You can view the contents of this new folder:

 ls 

Here’s a hint — if you start typing and press the TAB key, the command prompt will try to auto-complete the statement for you.

You can check the current directory path using pwd which stands for Print Working Directory:

 pwd 

Launch Minecraft by going to Menu > Games > Minecraft Pi . You will need this run, but you will come back to it later.

Open Python 3 from Menu > Programming > Python 3 (IDLE) . This program allows you to run Python commands and write programs.

Now you can type Python commands here, but it’s not very convenient. Select » File» > «New File» then » File» > «Save» and save it in the folder you created earlier. ( Documents> Minecraft ). Let’s call it » hello_world.py «. You don’t need to use the .py extension, it will be added automatically, but it’s good practice.

If you return to the terminal and navigate to the Minecraft folder, you will see the file you just created:

 cd Minecraft/ ls 

You can run this file like this:

 python hello_world 

Note that «python» is all lowercase. This must come before the file name, as it tells the Pi that the next file is Python, so it must be executed as such.

Return to the Python editor and type:

 print "Hello, World!" 

Save this file and run it again — you should now see «Hello, World!» On the command line, be careful! The print command simply tells Python to print the following text in double quotes. It’s good but not very useful for Minecraft, let’s link it:

 from mcpi.minecraft import Minecraft mc = Minecraft.create() mc.postToChat("Hello, World!") 

Now if you save and run this file, you should see «Hello, World!» In the Minecraft game. Let’s break down the code:

 from mcpi.minecraft import Minecraft 

This line tells Python that you want to use code from another file. This mcpi.minecraft file has been designed to easily control Minecraft.

 mc = Minecraft.create() 

This line creates an object called «mc» (Minecraft). You must create this to enable communication in a Minecraft game — it’s not enough to just include the file.

 mc.postToChat("Hello, World!") 

Finally, this line tells Minecraft to write text to the chat. Try changing «Hello, World!» To something else and see what happens, but don’t forget to include both double quotes. If you are having software issues, these are some common Python and Minecraft Pi errors:

  • AttributeError is a typo, like pint or prnt instead of print
  • NameError: The name ‘Minecraft’ is not defined — don’t forget to import the modules you need
  • NameError: name ‘true’ is not defined — Python is case sensitive, change to ‘True’
  • socket.error: [Errno 111] Connection refused — make sure Minecraft is running

projects

Now that you’re familiar with the basics of Python and Minecraft, let’s make some cool projects. All code can be downloaded from Github.

Automated bridge builder

minecraft-pi-bridge-builder

This program will effectively build a bridge across the water. When the player approaches a body of water, the program will convert several blocks into stone. Because Minecraft uses a coordinate system, it’s very easy to determine the player’s location as well as the type of blocks around the player. The Minecraft Pi is a bit limited, so it’s not possible to upgrade multiple different blocks in bulk. However, you can easily code this behavior yourself.

Create a new file (» File» > «New File» ) and save it as » bridge_builder.py «.

 from mcpi.minecraft import Minecraft mc = Minecraft.create() # create Minecraft Object while True: x, y, z = mc.player.getPos() # store player position # store the surrounding blocks a = mc.getBlock(x, y - 1, z + 1) b = mc.getBlock(x, y - 1, z - 1) c = mc.getBlock(x - 1, y - 1, z) d = mc.getBlock(x + 1, y - 1, z) if a == 8 or a == 9 or b == 8 or b == 9 or c == 8 or c == 9 or d == 8 or d == 9: # 8 or 9 is water. Set surrounding blocks on floor to a solid (stone) if water is found mc.setBlocks(x, y - 1, z, x + 1, y - 1, z + 1, 1) mc.setBlocks(x, y - 1, z, x - 1, y - 1, z - 1, 1) mc.setBlocks(x, y - 1, z, x - 1, y - 1, z + 1, 1) mc.setBlocks(x, y - 1, z, x + 1, y - 1, z - 1, 1) 

Notice how the y value actually looks at y — 1. This is the floor level. If you use a y value, the script will look for blocks at about knee level — it won’t work very well! Mc.getBlock() returns the block ID for the given coordinates. Since x, y and z are player coordinates, you can add or subtract them to get positions around the player. You don’t need to use x, y and z values, you can use any number, however you may not know how this particular block is related to the player — it’s better to use values ​​relative to the player. Run this file from the command line and see what happens.

You should see a small piece of land turn to stone when the player reaches the body of water. It’s not great — you can go fast enough to cause problems. You can solve this problem by turning more water into land. The last part of the mc.setBlocks() method is the block ID. One of them is the block ID for the stone. You can change this to tree, grass, or whatever. If you wanted to, you could turn this into an intricate design quite easily — maybe a suspension bridge!

Super Mountain Button

minecraft-pi-super-mine

This example will do a short mining job. It consists of a physical button that, when pressed, will mine 10 blocks in a cube. Let’s start with the button. Similar to the buttons on the Arduino, you will need a small amount of electronics, which are all found in a basic starter kit. :

  • 1 x breadboard
  • 1 x momentary switch
  • 1 x 220 ohm resistor
  • Female > male cable
  • Male > Male cable

Here is the diagram:

Pi-Button connection

This resistor is called a «step-down» resistor. This helps ensure that what the Pi thinks is a button press, i.e. a button press. You do not need to use this, however it is recommended as you may find a lot of noise and false readings without it.

The button is connected to pin 14 of the general purpose input (GPIO). You can use any GPIO pin, however look at the pinout first, as they are not all controllable with the Pi and vary slightly between models.

Now that the button is connected, it’s time to test it. Create a new file and save it as » button_test.py «. Add this code, save it and run it in a terminal.

 import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # tell the Pi what headers to use GPIO.setup(14, GPIO.IN) # tell the Pi this pin is an input while True: if GPIO.input(14) == True: # look for button press print "BUTTON WORKS!" # log result time.sleep(0.5) # wait 0.5 seconds 

Click Control+C to stop the script. If everything works correctly, you should see «BUTTON WORKS!» In the Terminal. Note that, like the Minecraft module, this test uses RPi.GPIO and temporary modules. They allow the Pi to access hardware pins and provide useful timing features.

Now let’s finish the rest of the code. Create a new file named » super_mine.py «. Here is the code:

 import RPi.GPIO as GPIO import time from mcpi.minecraft import Minecraft mc = Minecraft.create() # create Minecraft Object GPIO.setmode(GPIO.BCM) # tell the Pi what headers to use GPIO.setup(14, GPIO.IN) # tell the Pi this pin is an input while True: if GPIO.input(14) == True: # look for button press x, y, z = mc.player.getPos() # read the player position mc.setBlocks(x, y, z, x + 10, y + 10, z + 10, 0) # mine 10 blocks mc.setBlocks(x, y, z, x - 10, y + 10, z - 10, 0) # mine 10 blocks time.sleep(0.5) # wait 0.5 seconds 

mc.player.getPos() returns the current coordinates of the players, which are then stored in x, y and z. Method setBlocks() tells Minecraft to fill all the blocks between the start and end of the next block. Zero is the block ID for air. You can change this to a different block ID to completely fill the area. You can also change the coordinates to +100 or even +1000 blocks, however Pi can start to struggle if you get too pissed off. Note that +10 is the same for both strings. You can change this to y — 10 if you want to remove blocks underground.

teleportation

minecraft-pi-teleportation

Another simple use of this button is to «teleport». The Minecraft Pi Api provides a way to set the player’s position. The following code «teleports» the player to a given location:

 mc.player.setPos(0, 0, 0) 

Note that its method takes three parameters; x, y and z — so you can set them to anything to instantly teleport the player to that location.

Make a copy of super_mine(» File» > «Save Copy As» ) and change it by replacing the if with the following:

 if GPIO.input(14) == True: # look for button press mc.player.setPos(0, 0, 0) # teleport player time.sleep(0.5) # wait 0.5 seconds 

This file should now look like this:

 import RPi.GPIO as GPIO from mcpi.minecraft import Minecraft import time mc = Minecraft.create() # create Minecraft Object GPIO.setmode(GPIO.BCM) # tell the Pi what headers to use GPIO.setup(14, GPIO.IN) # tell the Pi this pin is an input while True: if GPIO.input(14) == True: # look for button press mc.player.setPos(0, 0, 0) # teleport player time.sleep(0.5) # wait 0.5 seconds 

Save it as » teleport.py ‘ and run.

When used, you may find that the player is stuck inside some blocks, in which case you will need to adjust the coordinates to a known open space (your current location is displayed in the upper left corner of the screen).

Build a house

Minecraft-Pi-House

The last task for this button is to build a house. Like the fast mining example, it will simply replace the blocks surrounding the player to build a house. Different block IDs will be used for different materials (windows, walls, etc.). To make coding easier, a solid block will be created and then the inside removed (set the block to air), this will create a hollow shell. You can add extras like a bed or a door, however the Minecraft Pi project is a bit incomplete and while these objects work when placed by the player, they are not brilliant when using Python.

 from mcpi.minecraft import Minecraft import RPi.GPIO as GPIO import time mc = Minecraft.create() # create Minecraft Object GPIO.setmode(GPIO.BCM) # tell the Pi what headers to use GPIO.setup(14, GPIO.IN) # tell the Pi this pin is an input while True: if GPIO.input(14) == True: x, y, z = mc.player.getPos() mc.setBlocks(x + 2, y - 1, z + 2, x + 7, y + 3, z + 8, 5) # make shell mc.setBlocks(x + 3, y, z + 3, x + 6, y + 2, z + 7, 0) # remove inside mc.setBlocks(x + 2, y, z + 5, x + 2, y + 1, z + 5, 0) # make doorway mc.setBlocks(x + 4, y + 1, z + 8, x + 5, y + 1, z + 8, 102) # make window 1 mc.setBlocks(x + 4, y + 1, z + 2, x + 5, y + 1, z + 2, 102) # make window 2 mc.setBlocks(x + 7, y + 1, z + 4, x + 7, y + 1, z + 6, 102) # make window 3 

Save it as » house.py ‘ and run. All is well, you should see a small house (you may have to turn around to find it). It’s very simple, opening and a few windows. Theoretically, there is no limit to how big or complex a building you can build.

Make a mini game

Minecraft-Pi-Lava-Game

Next, let’s make a mini-game! It will be quite easy when the player steps on a piece of sand, after a while it will turn into lava. This is a good game that you can create as you can create your own levels or modify them to make it harder. You won’t need a button for this example.

Create a new file and save it as » mini_game.py «. Here is the code:

 from mcpi.minecraft import Minecraft import random import time mc = Minecraft.create() # create Minecraft Object while True: x, y, z = mc.player.getPos() block_under_player = mc.getBlock(x, y - 1, z) if block_under_player == 12: # player standing on sand, start the timer random_time = random.uniform(0.1, 2.5) # generate random number time.sleep(random_time); # wait mc.setBlock(x, y - 1, z, 11) # turn it into lava 

This code is a good start of a function random() : random.uniform(0.1, 2.5) will generate a random number in range 0.1 (1/10th second) to 2.5 (2 1/2 second). Increasing these numbers will make the game easier.

Try it! Step on a piece of sand and it will soon turn into lava. This can form the basis of a more complex game.

Make another mini game

Minecraft-Pi-Mini-Game

The essence of this game is simple — do not stand on the wooden floor when the time is up. The player is teleported to the «arena». They are forced to stand still before the start of the game. Once launched, the floor will turn into water when the timer runs out. The player must stand in a safe zone (diamond blocks) in order to survive. Each level reduces the timer by one second. After each successful level, the safe zone increases. Check out the code below:

 import time import random from mcpi.minecraft import Minecraft mc = Minecraft.create() # create Minecraft Object # clear area mc.setBlocks(-10, 1, -10, 25, 5, 25, 0) # create arena shell mc.setBlocks(0, 0, 0, 25, 10, 25, 17) # hollow out arena mc.setBlocks(1, 1, 1, 24, 10, 24, 0) # move player to arena mc.player.setPos(14, 25, 20) # teleport player # make them stay put # teleport player to start position every 1/10th second. # do this for 5 seconds then start the game time.sleep(2) total_wait = 0 mc.postToChat("Waiting to Start") while total_wait < 5: mc.player.setPos(14, 1, 20) # teleport player time.sleep(0.1) total_wait += 0.1 mc.postToChat("BEGIN!") # 10 levels for level in range(10): x, y, z = mc.player.getPos() level_time = 10 - level # reduce time by 1 second for each level mc.postToChat("Level - " + str(level + 1) + " start") # build floor mc.setBlocks(0, 0, 0, 25, 0, 25, 17) # make safe area safe_area_start = random.uniform(0, 22) safe_area_end = random.uniform(0, 22) mc.setBlocks(safe_area_start, 0, safe_area_end, safe_area_start + level, 0, safe_area_end + level, 57) elapsed_time = 0 while elapsed_time < 10: x, y, z = mc.player.getPos() time.sleep(0.25) elapsed_time += 0.25 # check player is still on floor if y < 0.75: mc.postToChat("Game Over") break; else: # remove floor mc.setBlocks(-10, 0, -10, 25, 0, 25, 8) # put safe area back mc.setBlocks(safe_area_start, 0, safe_area_end, safe_area_start + level, 0, safe_area_end + level, 57) time.sleep(2.5) continue break 

Save it as " mini_game_2.py ' and run.

The Pi 2 has some performance issues while running Minecraft. Graph of central processing unit (CPU) usage ( upper right corner ) never shows any kind of heavy load, so this must be due to poor design and optimization by the developers. These problems are not related to running the code (because they continue when Python is not running), however they are exacerbated by this mini-game. If your pi is really struggling you can reduce the size of the arena or overclock your pi .

Diamond detector

minecraft-pi-diamonds

Let's make another diagram. This will use an LED to light up when there are diamonds underneath (within 15 blocks). Here's what you need:

Here is the diagram:

Pi-LED connection

Connect the anode (long leg) to pin 14 of the GPIO. This pin works as +5V. Connect the cathode (short leg) to ground.

I used a cheap ore toy and modified it by removing the back cover and electronics and then placing an LED under it. You can easily make this permanent with hot glue or something similar.

minecraft-ore-toy

Save this code as " diamonds.py ":

 import RPi.GPIO as GPIO import time from mcpi.minecraft import Minecraft mc = Minecraft.create() # create Minecraft Object led_pin = 14 # store the GPIO pin number GPIO.setmode(GPIO.BCM) # tell the Pi what headers to use GPIO.setup(14, GPIO.OUT) # tell the Pi this pin is an output while True: # repeat indefinitely x, y, z = mc.player.getPos() for i in range(15): # look at every block until block 15 if mc.getBlock(x, y - i, z) == 56: GPIO.output(led_pin, True) # turn LED on time.sleep(0.25) # wait GPIO.output(led_pin, False) # turn LED off time.sleep(0.25) # wait 

When a block of diamond ore is under the player (within 15 blocks), the indicator will blink.

Have you done anything cool with Minecraft Pi? Let me know in the comments what you've done or how far you've made it in games.

Похожие записи