Tactical Computer Action (for beginners and their support team)

## Tag: Programming

### Minecraft Pi API: Moving the Player

Using the Minecraft Pi Python API it is possible to change the position of the player in the game world. Effectively you can tell the game to teleport the player to a set of co-ordinates. There are many things you can do with this, from teleporting to your own castle, putting the player on top of a boat or trapping a friend in an unbreakable box.

There are two methods used for changing the position of the player: setPos() and setTilePos(). Both of them use x, y and z co-ordinates as arguments.

# setTilePos()

Using the setTilePos() method you can change the position of the player in the game. The setTilePos() takes the co-ordinates x, y and z as arguments. These co-ordinates must be integers (in other words whole numbers). The setTilePos() method is part of the player class. This means you need to call it using dot notation like this player.setTilePos().

```player.setTilePos()
```

The following example teleports the player to the co-ordinates (16, 1, -5):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 16
y = 1
z = -5
mc.player.setTilePos(x, y, z)
```

# setPos()

The setPos() method is similar to the setTilePos() method in that it changes the position of the player. It also takes co-ordinates as arguments. There is a major difference as these arguments can be floats (or in other words they can have decimal places). This allows the player to be placed precisely in the game. The setPos() method is part of the player class. This means you need to call it using dot notation like this player.setPos().

```player.setPos(x, y, z)
```

The following code will teleport the player to the co-ordinates (16.2, 1.6, -5.1):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 16.2
y = 1.6
z = -5.1
mc.player.setPos(x, y, z)
```

### Minecraft Pi API: Getting Blocks Finding the type of block at a specific location is very useful. With this information you can do a variety of things such as checking to see if the player is flying, finding out whether a door is open or seeing if the player has placed a melon on an alter as an offering to the melon god.

Like the methods that set blocks, the methods that find out what type a block is use co-ordinates to determine which block you are interested in. Each method returns a value or an object for that block. There are three methods that we will look at: getBlock(), getBlockWithData() and getBlocks().

# getBlock()

When you want to find the type of any block in the game, the getBlock() method is the one you need to use. It is pretty simple, you provide co-ordinates as arguments and it returns the block type as an integer value.

```getBlock(x, y, z)
```

The following example gets the block type at co-ordinates (12, 0, 16):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 12
y = 0
z = 16
blockType = getBlock(x, y, z)
```

# getBlockWithData()

Each block in the game has a number of different states, 16 in total. This allows a single block ID to have a number of different variations. For example the wool block has 16 different states, each one representing a different colour. The TNT block can be smashed like a regular block in state 0 and is explosive in state 1. To see how to set the states check out the section on optional arguments for setBlock() and setBlocks().

Finding out the state of a block with the getBlockWithData() method is relatively simple, yet a tiny bit more complex than the getBlock() method. The getBlockWithData() method takes co-ordinates as arguments in order to determine which block you are interested in. The method returns an object, which contains two attributes, id and data. The id and data attributes store the block type and its state respectively.

```getBlockWithData(x, y, z)
```

The following example finds out the block type and state of the block at co-ordinates (12, 0 ,16):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 12
y = 0
z = 16
block = getBlockWithData(x, y, z)

blockType = block.id
blockState = block.data
```

# getBlocks()

The getBlocks() method is supposed to return the values of all the blocks within a cuboid that is defined between two co-ordinates. At the moment the getBlocks() method does not work. I have written a function that achieves the same thing, however it is quite slow and may not be interchangeable with the getBlocks() method if it is ever corrected.

Below is my alternative function. It takes two sets of co-ordinates and returns a 3-dimensional list where x is the first list, y the first nested list and z the second nested list:

```def getBlocks(x1, y1, z1, x2, y2, z2):
xhigh = max(x1, x2)
xlow = min(x1, x2)
yhigh = max(y1, y2)
ylow = min(y1, y2)
zhigh = max(z1, z2)
zlow = min(z1, z2)

blocks = []
for x in range(xhigh - xlow + 1):
blocks.append([])
for y in range(yhigh - ylow + 1):
blocks[x].append([])
for z in range(zhigh - zlow + 1):
blocks[x][y].append([])
block = mc.getBlock(xlow + x, ylow + y, zlow + z)
blocks[x][y][z] = block
return blocks
```

### Capacitive Touch Potatoes on the Raspberry Pi With a capacitive touch sensor you can use everyday objects as switch inputs with the Raspberry Pi. You can use a variety of things as inputs including potatoes, pencil drawings, toys and anything else you can think of. In this post I’ll show you how to connect your Raspberry Pi to an Adafruit capacitive touch sensor to use potatoes as inputs for your Python programs.

You will need:

1. A Raspberry Pi (Model A or Model B)
2. A GPIO breakout with a ribbon cable (or jumper wires), like the Adafruit Pi Cobbler
3. An Adafruit 5-point capacitive touch sensor
4. 5 x 10k resistors
5. A selection of breadboard jumper wires
7. Something fun to use as input (I’m using potatoes)

# Step 1: Wiring

The first thing you need to connect the components on the breadboard. Use the following diagram: Note: the capacitive touch sensor is slightly wider in real life so there will be fewer breadboard rows to work with. Other than that this will not affect the layout.

# Step 2: Code

Before you start you need to have the GPIO Python module installed. To install it connect to the internet and run the following in a terminal:

```\$sudo apt-get update
\$sudo apt-get install python-dev
\$sudo apt-get install python-rpi.gpio
```

Now that you have the Python GPIO module installed you can run a Python program. Copy the following code into a Python file and save it as touchPotato.py:

```import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

# Set the GPIO pins
input1 = 4
input2 = 17
input3 = 18
input4 = 22
input5 = 23
GPIO.setup(input1, GPIO.IN)
GPIO.setup(input2, GPIO.IN)
GPIO.setup(input3, GPIO.IN)
GPIO.setup(input4, GPIO.IN)
GPIO.setup(input5, GPIO.IN)

# Used to make the switch only repeat once
prevInput1 = True
prevInput2 = True
prevInput3 = True
prevInput4 = True
prevInput5 = True

#repeats infinitely to check the GPIO input
while True:
# Get the state of the inputs.
# True = not pressed
# False = pressed
buttonInput1 = GPIO.input(input1)
buttonInput2 = GPIO.input(input2)
buttonInput3 = GPIO.input(input3)
buttonInput4 = GPIO.input(input4)
buttonInput5 = GPIO.input(input5)

# If input 1 has been pressed then print "Yellow"
if not buttonInput1 and prevInput1:
print "Yellow"
prevInput1 = buttonInput1

# If input 2 has been pressed then print "Green"
if not buttonInput2 and prevInput2:
print "Green"
prevInput2 = buttonInput2

# If input 3 has been pressed then print "White"
if not buttonInput3 and prevInput3:
print "White"
prevInput3 = buttonInput3

# If input 4 has been pressed then print "Orange"
if not buttonInput4 and prevInput4:
print "Orange"
prevInput4 = buttonInput4

# If input 5 has been pressed then print "Purple"
if not buttonInput5 and prevInput5:
print "Purple"
prevInput5 = buttonInput5

time.sleep(0.05)
```

# Step 3: Run it

Make sure everything is wired correctly and that the Raspberry Pi is connected to the breadboard with a ribbon cable. To run the code open the terminal and navigate to the directory that you saved touchPotato.py. Run the code with sudo:

```sudo python touchPotato.py
```

Press a potato your program should print a colour to the terminal.

# How it Works

When you press the potato connected to the the capacitive touch sensor the capacitance of the potato changes. Capacitance is the electronic charge stored by an object. The touch sensor detects this change and connects the corresponding input to ground changing the signal that goes to the inputs on the GPIO. Normally the GPIO receives 3.3v, but when the sensor connects it to ground the signal changes to 0v.

Our Python program checks the input from GPIO pins. Normally the GPIO receives 3.3v when the potato is not pressed. The Python program stores this state in the buttonInput variables as True. When the potato is pressed the input changes to 0v and the Python program stores this state as False in the buttonInput variables. When the buttonInput variable is False, code is run to print a colour string to the terminal. There are five buttonInput variables, one for each of the touch inputs.

### Minecraft Pi API: Setting Blocks Controlling blocks is one of the most powerful things you can do with the Minecraft Pi API. You can access blocks that are not usually available to the player or build complex structures with a few lines of code instead of placing each block by hand. In this post we will cover the API methods that allow you to place blocks using you Python programs. If you need to set up Minecraft Pi check out my post here.

All block methods in Minecraft Pi use co-ordinates to determine the location of blocks. In the top left of the game window you can see the current co-ordinates of the player. Three variables represent the coordinates x, y and z; x and z represent the horizontal plane and y represents vertical height. This is shown in the following diagram: All block methods use block IDs that identify the type of block you want to place at a location or already exists at a location. The block ID is an integer value and represents the blocks like soil, air, melon, lava and so on. You can find the IDs of the blocks on this cheat sheet, however not every block exists in Minecraft Pi Edition and most don’t function (for example you can’t use the chest to store things).

# setBlock()

When building anything in Minecraft the setBlock() is the most method you’ll be using. It takes four arguments – x, y and z co-ordinates and a block ID – and places a block at that location. The basic syntax for this method is:

```setBlock(x, y, z, blockID)
```

The following example creates a melon block (block ID 103) at coordinates (10, 11, 12):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 10
y = 11
z = 12
blockID = 103
mc.setBlock(x, y, z, blockID)
```

# setBlocks()

Placing blocks with setBlock() is powerful, yet can be inefficient when you want to cover large areas. When we want to place blocks across a large area we use the setBlocks() method (yes, that is a different method to setBlock(), it has an “s” at the end). The setBlocks() method places a single block type in a cuboid shape between two sets of co-ordinates. The setBlocks() method takes seven arguments: two sets of co-ordinates and a block ID. The basic syntax of setBlocks() is:

```
setBlocks(x1, y1, z1, x2, y2, z2, blockID)

```

For example the following code will place a cuboid of melon blocks (block ID 103) between coordinates (6, 5, 18) and (12, 10, 32):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x1 = 6
y1 = 5
z1 = 18
x2 = 12
y2 = 10
z2 = 32
blockID = 103
mc.setBlocks(x1, y1, z1, x2, y2, z2, blockID)
```

# Optional Arguments for setBlock() and setBlocks()

Both the setBlock() and setBlocks() methods can take an optional extra argument. This argument can be described as the block state. For example the wool block (block id 35) has 16 different states for 16 different colours. The red wool block for example has a state of 14. The TNT block is explosive in state 1. To use this  we just place the extra argument at the end of the arguments in both setBlock() and setBlocks():

```mc.setBlock(x, y, z, blockID, blockState)
mc.setBlocks(x1, y1, z1, x2, y2, z2, blockID, blockState)
```

The following code uses the optional argument to create an explosive TNT block (block ID 46 and state 1):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x = 10
y = 11
z = 12
blockID = 46
blockState = 1
mc.setBlock(x, y, z, blockID, blockState)
```

The next example uses the optional argument with setBlocks() to create a cuboid of red wool (block ID 35 state 14):

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

x1 = 6
y1 = 5
z1 = 18
x2 = 12
y2 = 10
z2 = 32
blockID = 35
blockState = 14
mc.setBlocks(x1, y1, z1, x2, y2, z2, blockID, blockState)
```

Have fun using these methods, they will save you loads of time when you’re building in Minecraft Pi. If you want to practice these methods while creating some useful programs check out my free book.

### Minecraft Pi API: Setting Up Minecraft Pi Edition can be a very fun and engaging way to learn programming.

For beginners getting started can be the biggest hurdle. There are a number of brilliant sources that demonstrate some really cool examples of what can be achieved – check out Martin O’Hanlon’s Stuff About Code. However, it can be a bit overwhelming for most beginners to break apart the code to find out how it works and use the Minecraft Pi API for their own ideas.

In this series of posts I’ll cover the basics of using the Minecraft Pi API. This post will concentrate on setting up the API for use with Python and creating a basic program to teleport the player. Following posts will explain different components with simple examples.

First things first. We will be using the Python programming language. No idea what that is or where to learn about it? Programs are a way of giving a computer instructions. Python is one programming language that we can use to write these instructions. You will be able to follow the explanations in this series without knowledge of Python, however I’d recommend you check out Codecademy.com for excellent (and free) Python tutorials.

# Setting Up

First off we need to install Minecraft Pi Edition on our Raspberry Pi. Follow the instructions on http://pi.minecraft.net/

Alert: the last instruction for installation is slightly wrong. You need to run this code instead to open the game:

```./minecraft-pi
```

After you’ve installed Minecraft and have familiarised yourself with the game, we can start start writing programs to interact with it.

Create a new directory to store your programs. Copy the mcpi directory located inside Python API directory into the directory you’ve just created. To achieve this in a terminal type in the following command after navigating to the directory you’ve just created:

```cp -r ~/mcpi/api/python/* .
```

Alternatively to do this with a file browser, navigate to the above directory, copy the mcpi folder and paste it into the folder you just created. We are now ready to start programming.

# Teleporting the Player

Open IDLE on your Raspberry Pi, create a new file and save it as teleport.py in the folder the folder you just created. We will write your first program in this file.

Every program that interacts with the Minecraft Pi API has the same two lines at the start. These lines connect our program to the game. Copy these two lines into your program:

```import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
```

In the same file we’re going to write some code to teleport the player to a new location. Copy this code into your program after the first two lines:

```x = 1
y = 24
z = 1
mc.player.setTilePos(x,y,z)
```

In IDLE click on the Run menu, then Run Module. Your character should now teleport to the coordinates (1, 24, 1). If this doesn’t work make sure you are in a Minecraft Pi game world. If you get a black screen, you’ve just teleported inside of a block – change the numbers next to x, y and z and rerun your program to fix this.

How this works: In our program we have created 3 variables x, y and z. A variable stores a piece of data, in this case a number. We then give these numbers to the setTilePos() function, which connects to your Minecraft game and tells it to move your player to the coordinates you have set as numbers in x, y and z.

Try playing around with different number values of x, y and z. Use negative numbers. See what happens if you teleport off the map (hint: you’ll either die or your game will crash). If you’ve built several amazing things in Minecraft and want a quick way to travel to them copy the code into a different a file for each and change the coordinates to match the building.

Have fun and check back in the future for more Minecraft Pi API tutorials.

If you are interested in learning more about Python programming with Minecraft Pi or using it in a classroom/club, check out my free book that is available here.