arghbox

Tactical Computer Action (for beginners and their support team)

Minecraft Pi Recipe Cards

These Raspberry Pi recipe cards include a selection of basic Python programs that work with Minecraft: Pi Edition. They are designed to be used in workshops or classrooms and cover some fundamentals of programming in Python. You can also use them by yourself as a quick introduction to Python programming with Minecraft Pi.

Each of the six recipe card has three parts. The front page gives an overview of what you’ll be doing:
Picture 4

The inside pages contain Python code that will create the program alongside an explanation:
Picture 6

The last page covers the concepts that were used in the program:
Picture 5

The first recipe card includes steps on how to allow Python to interact with a Minecraft Pi game. You’ll need to have Minecraft Pi installed, instructions to do this can be found here.

There are two sets available, one which is designed to be read on the computer and the other which is designed to be easily printed.

Recipe Cards Formatted for Computer

1. Teleport
2. Flower Path
3. Warehouse
4. Chat
5. Freeze
6. Block Fighter

Recipe Cards Formatted for Printing

1. Intro (Printer Friendly)
2. Flower Path (Printer Friendly)
3. Warehouse (Printer Friendly)
4. Chat (Printer Friendly)
5. Freeze (Printer Friendly)
6. Block Fighter (Printer Friendly)

There is also a free draft book on Python Programming with Minecraft Pi that goes into more depth, which can be found on here.

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

2013-08-18 12.13.30
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

2013-08-11 17.43.50

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
  6. A breadboard
  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:

potatoTouch_bb

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: Controls Cheat Sheet

Minecraft Pi Controls

I’ve made a cheat sheet for the game controls in Minecraft Pi Edition. It provides a quick and easy way for beginners to familiarise themselves with the game controls. Check it out in the link below:

Minecraft Pi Controls

Minecraft Pi API: Setting Blocks

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:

3D

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.

cuboid2

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.

Creating a Desktop Shortcut for Minecraft Pi

2013-06-16-153057_1366x768_scrot

So you’re using Minecraft Pi on your Raspberry Pi. You enjoy the game, but starting it from the terminal just isn’t your thing. You wish there was an easier way to run it. You’re in luck. In this tutorial I’ll show you how to create a desktop short-cut for Minecraft on your Raspberry Pi.

Note: for all these instructions I assume your main mcpi directory is in the pi directory. If it isn’t you will need to change these instructions to match your setup.

1. Make Minecraft Pi Executable

In your main mcpi directory you need to make the Minecraft file executable. To do this open a terminal, navigate to the main mcpi directory and make Minecraft executable the following commands:

cd ~/mcpi
chmod +x minecraft-pi

2. Find an Icon

Next thing we need is an icon for our desktop shortcut. You can make your own or search for one online. Personally, I just use the logo for Minecraft Pocket edition, which can be found here.

Save the file into the main mcpi directory and call it logo.png (or whatever other extension you’re using e.g. logo.jpg).

3. Create a File on the Desktop

Navigate to the Desktop directory within the pi directory using the terminal and create a new file called “minecraft.desktop” with the nano text editor:

cd ~/Desktop
nano minecraft.desktop

Now right click and paste the following code into the file:

[Desktop Entry]
Name=Minecraft Pi
Comment=Creative Block Game
Exec=/home/pi/mcpi/minecraft-pi
Icon=/home/pi/mcpi/logo.png
Terminal=false
Type=Application
Categories=Games;Education;
StartupNotify=true

Save and exit the file. You should now have a Minecraft Pi shortcut on your desktop. When you double click it the game should launch. If the icon doesn’t show up immediately try restarting the desktop or rebooting the Pi.

Have fun with Minecraft Pi. If you want to learn more about Minecraft Pi, check out my API tutorials. I have also written a free book for learning Python programming with the Minecraft Pi API that is available here.

Minecraft Pi API: Setting Up

mcpiSettingUp

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.

Python Programming with Minecraft Pi: Early Draft

minecraft

When I first heard that Minecraft would be released for the Raspberry Pi I punched the air. The nice people at Mojang had just given me the perfect platform to teach students programming: a creative platform. One where students are encouraged to explore ideas in a familiar environment, while seeing the tangible results of their efforts.

Minecraft Pi uses an application programmer interface (API for short) that allows programmers to interact with a Minecraft game world. Students can combine the API into their own Python programs to do things like place blocks, teleport the player or access hidden features like chat. For example they can create a castle with code in a few seconds, instead of building it by hand (which takes ages). Using Minecraft Pi to help students learn programming has the potential to be very engaging and effective.

That is why I have developed a book of resources to teach Python programming with Minecraft Pi.

The Book

The book consists of a series of exercises and documentation developed to test a student’s understanding of Python and also develop their problem solving skills. Each chapter uses differentiation, challenging students with more complex exercises as they progress and offers a number of extension tasks for every exercise. The content was developed to be used alongside Codecademy’s Python track and has documentation for each concept introduced.

Codecademy is my favorite resource for learning to program. Instead of rewriting the wheel, I decided that students should complete a Codecademy lesson and then attempt the corresponding exercises in the book. The exercises draw from the same Python concepts introduced at Codecademy, yet require the students to develop stronger problem solving skills.

The book is free to use and is open source. This means you can share it with whoever you want without giving me any money. The source of the book will be available in the near future if you want to modify it. A teacher’s answer book and an API reference sheet are also included.

Right now the book is incomplete, especially in the later chapters. The vast majority of content is there, some bits are missing, and a lot of it needs polishing. I am just about to start teacher training and won’t be able to dedicate any time to the book for the next few months. After previewing the book to a number of people at the York Raspberry Jam, the demand was so great that I decided to release it as soon as possible so that people had access to these resources. I do plan to finish the book, I’m just not sure when I will have the time. If you are interested in helping to further develop these resources please get in touch.

Any constructive feedback is very appreciated. Please let me know if you decide to use the resources in the classroom or in a club as I would love to hear about it. Feel free to adapt the resources to your own needs and please share them with others.

Download

The files are really small despite the number of pages. Small enough to fit on a floppy disc. I’d recommend copying the main book onto each student’s Raspberry Pi, keep the teacher notes to yourself (which contain all the answers) and print a copy of the cheat sheet for each student.

Student Exercise and Reference Book
Teacher Notes

API cheat sheet

Other Minecraft Pi Resources

Martin O’Hanlon’s Minecraft Pi Programs

David Whale’s Minecraft Pi Flashcards

MCPIPY – Python Programs

Just to note, I am not affiliated with the Raspberry Pi foundation, Mojang/Minecraft or Codecademy. They probably don’t endorse these resources.

The Value of Raspberry Jam

“Wow, that makes learning to program really accessible. I’ll finally have my household of robotic servants in a few years thanks to this device and the army of young techno-geniuses it creates” is the usual response when I tell someone about the Raspberry Pi. Since discovering the Raspberry Pi I have been a strong believer in the foundation’s mission to inspire a new generation of makers and computer programmers. The hardware cuts the cost barrier for children who want their own computer, around the price of a Christmas present from Grandma. The default operating system and software also remove the ridiculously steep learning curve of installing a powerful Linux operating system and using it to learn to program. In other words, they’ve got the hardware and software sorted.

The major challenge that faces the Raspberry is the access and visibility of teaching and learning resources. Without access to resources many people will have no guidance or starting point for learning to program. Guidance and support is essential when starting on the road of programming. Starting is the biggest and hardest step in the journey and without a helping prod in the right direction, the sad fact is many beginners will give up and let their Raspberry Pi gather dust. Saying that, luckily there are some amazing resources out there, the only problem is finding them and knowing where to start. That’s where Raspberry Jams come in.

Due to the magical powers of their founder, Alan O’Donohue, Raspberry Jams have been around longer than time itself. In essence Raspberry Jams are gatherings of Raspberry Pi enthusiasts and beginners from all walks of life. They’re held worldwide and during the Jam a series of presentations, workshops and informal chats give attendants the opportunity to share their ideas, resources and enthusiasm.

Raspberry Jams are therefore an amazing place for beginners to start their journey with the Raspberry Pi. By the end of any workshop, participants, young and old, are guaranteed to learn new skills. Through networking (in the business buzz-word sense, not in the wires, internet and magic sense) like-minded people meet and share ideas. Some walk away with solutions to their problems, many are inspired to try something new and others join forces to collaborate and develop resources that others can use.

At Raspberry Jams, amazing people come together and do amazing things. The community that surrounds the Raspberry Pi is just as essential as the device itself. What often evades our gaze is that, as with any technology, the Raspberry Pi is not about circuits and bits, it’s about people. They are the people on the ground sharing their knowledge, skills, and enthusiasm so that the Raspberry Pi can achieve its mission. They provide the spark that ignites the imagination of young ladies and men, who in a matter of years will achieve things that far surpass our dreams of robotic servants.

Of course Raspberry Jams are just one piece of the puzzle. Over the life of this blog I will focus on making learning to program accessible. Look out for my upcoming blogs on  free resources for learning to program on the Raspberry Pi. I’ll also recount my experience at my first Raspberry Jam in another post where I’ll give you concrete examples of the value of Raspberry Jams.

Follow

Get every new post delivered to your Inbox.

Join 52 other followers