My First Raspberry Pi Game – Part 04 – A small black screen

Parts: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Writing your first ever computer program on the Raspberry Pi.

Today we will get an actual window to appear, with nothing on it!

Last time we wrote a magic spell describing the bare outline of what how our game will work. It’s going to pause, show a shape, and then the player must either press a key (if it’s green) or not press a key (if it’s red).

The program we’ve written calls several mini-programs called functions, but they don’t exist yet, and if we run it, it fails with an error. The names of the functions we have imagined are start, ready_screen, wait, shape and end.

The first thing we need to do is write those functions, so that the program runs correctly, even though it does nothing.

Open up LeafPad again and open redgreen.py from inside the pi folder. At the top, above the code we’ve already written (which uses the functions) type exactly this:

def start():
    pass

def ready_screen():
    pass

def wait():
    pass

def shape():
    pass

def end():
    pass

Notice that the word pass is “indented” by 4 spaces. This is how Python knows which lines of code are part of your function, and which are another part of the program. It’s very important that all lines are indented by the same amount, and that you never mix “tab” characters with spaces. To make life simple, I suggest always using 4 spaces.

What we’ve done is define 5 functions (the ones we call further down). def just means define a function, and we’ve followed that by the name of the function, then (). So far, each of our functions is empty: they are all just one line, which says pass, which means “do nothing”.

If we’ve typed this correctly, our program should now run correctly, and do nothing. Let’s try it. Open LXTerminal and type:

python redgreen.py

If it’s working, the computer should say absolutely nothing to you, and give you another prompt, ending with $.

If you get an error message, read it (especially the last line) and try to work out what you typed wrong.

Now we’re going to write some actual useful code, and make a black screen appear.

At the very top, above everything else we’ve done today, add this line:

import pygame

This tells Python we want to use the PyGame library, which is some code written by someone else, designed to help us write games in Python. The Raspberry Pi comes with PyGame already installed, so to use it all we need to do is add this line.

Just below that line, type this:

screen_size = 640, 480

This is how we define a “variable”. A variable is a thing with a name and a value that we can refer back to later. The variable’s name is screen_size and its value is “640, 480”. We’re going to use this variable to remember how big we want our window to be.

Now we need to modify our start function to bring up a black screen. Replace both lines of the start function with this:

def start():
    pygame.init()
    screen = pygame.display.set_mode( screen_size )

The first line, starting with def is the same as before – it means we are defining a function called “start”.

Where we used to have just pass, we now have 2 lines (both indented by 4 spaces as before). The pygame.init() line just tells PyGame to get ready to start. We need something like this in our program whenever we use PyGame. The second line creates a window of the size we want. It calls a function inside pygame. The dots mean we should “look inside” the thing on the left, so pygame.display.set_mode means something like “look inside pygame for something called display, then look inside display for something called set_mode”. set_mode is a function, which we are calling (that is what the brackets mean).

Unlike other functions we have called, which just use “()”, set_mode takes an “argument” which means we are passing information to it. The information we are passing is the size of the screen, which we have already stored in the variable screen_size. So the value “640, 480” gets passed in to set_mode, telling it how big to make the window.

We’ve made a window, but if we leave things as they are now, we will open it, then immediately finish, so it will go away again. We need to wait a while.

Edit the end function to look like this:

def end():
    pygame.event.clear()
    pygame.event.wait()

This code means “wait until something happens”.

The first line (clear) tells PyGame we’re not interested in anything that happened before – clear the list of events that has built up – and the second line (wait) means wait until something happens. In this case we are waiting until the person using the program presses a key, closes the window, or even moves the mouse in front of the window.

Let’s try it out. Open up LXTerminal as before, and type the same thing we’ve typed before:

python redgreen.py

Make sure you don’t move the mouse or press any keys after you’ve pressed Return. If all has gone well, a small, black, empty window will appear. Then if you press a key or move the mouse in front of it, it should disappear.

If this isn’t what happens, check back and make sure you typed everything exactly as above. Your complete file should look like this: redgreen.py.

Well done! You made a window appear. Next time, if we’re lucky, we’ll put something in it…

Length of Open Source licenses

I have been choosing a license for my ficticious programming language, Pepper. One consideration is the complexity of the (combination of) license(s) used. Complexity may be related to length, so for your enjoyment, here are the lengths of some popular licenses:

Length of Open Source Licenses

Is it a coincidence I’ve decided to use the MIT License?

Here’s how I made it (on my Ubuntu Linux 12.04 system):

#!/bin/bash

declare -A LICENSES

LICENSES[Apache]=file:///usr/share/common-licenses/Apache-2.0
LICENSES[GPL2]=file:///usr/share/common-licenses/GPL-2
LICENSES[GPL3]=file:///usr/share/common-licenses/GPL-3
LICENSES[BSD]=file:///usr/share/common-licenses/BSD
LICENSES[Artistic]=file:///usr/share/common-licenses/Artistic

LICENSES[MIT]=http://www.jclark.com/xml/copying.txt
LICENSES[Mozilla]=http://www.mozilla.org/MPL/2.0/index.txt
LICENSES[Python]=http://hg.python.org/cpython/raw-file/tip/LICENSE
LICENSES[Eclipse]=http://www.eclipse.org/legal/epl-v10.html

function wordcounts()
{
	for K in "${!LICENSES[@]}"; do
	{
		echo `lynx -dump ${LICENSES[$K]} | wc -w` $K
	}; done
}

wordcounts | sort -n | awk '{print $2 " " $1}' > data.txt

gnuplot <<END
set terminal png large enhanced font "Helvetica,11"
set output 'license-length.png'
unset key
set style fill solid
set title "Number of words in common Free and Open Source licenses"
plot 'data.txt' using (column(0)):2:(0.5):(\$0):xtic(1) with boxes lc variable;
END

rm data.txt

My First Raspberry Pi Game – Part 03 – It’s like a magic spell

Parts: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Writing your first ever computer program on the Raspberry Pi.

Today we will write the very basic outline of our game. When we’ve finished it won’t actually do anything. In fact, it won’t even run.

Writing a computer program is a lot like doing magic. To write programs well it is really helpful to treat it like magic, and not think about how it works (until you have to…). We’re going to do that – write down in very simple terms what our program will do, but not yet think about how it will do it.

The program we are going to write is a very simple test of your reactions. It will show you either a green circle or a red square. If you see a green circle, you have to press a key as quickly as you can. If you see a red square, you must not press anything.

That’s the whole of the game (for now).

To make this game, we need to start up, then show a ready screen, then wait for a while showing the ready screen, then show a shape and wait for a key press, then finish.

So, let’s write our magic spell. Start up LeafPad just like we did in part 2. Click File, then Open, click on “pi” on the left, then double-click redgreen.py to load up our Hello, world program. Delete everything that’s there, and type exactly this instead:

start()

ready_screen()

wait()

shape()

end()

The brackets after each word mean “do it” – what they really mean is find a “function” with this name, and run it. A function is like a mini-program.

So, now our program is finished, right?

Let’s run it. Go to the File menu in LeafPad and click Save, then open LXTerminal just like in part 2 and run the program by typing “python redgreen.py” as before. Here’s what happens:

$ python redgreen.py 
Traceback (most recent call last):
  File "redgreen.py", line 3, in 
    start()
NameError: name 'start' is not defined

We told python to run a function called “start”, but we haven’t written any functions yet, so it couldn’t find it.

Our spell is cast, but we next time we need to start on the ingredients it uses. See you then.

My First Raspberry Pi Game – Part 02 – Saying hello

Parts: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Writing your first ever computer program on the Raspberry Pi. See Part 1 for how to get and set up the Pi.

Today we will find out how to write a computer program, and how to run it.

We’re going to write one of the simplest programs you can write – we’re going to get the computer to say hello to us.

First, we need a text editor to write down our program. Click the weird aeroplane-y thing in the bottom left – that brings up the menu (like the Start button on Windows), then choose Accessories, then Leafpad. Leafpad is the text editor we will be using.

Leafpad will start, and show you an empty page. This is where we will write our program.

Type in exactly this:

print "Hello, world!"

and then click the File menu at the top of the Leafpad window and choose Save As. Click the word “pi” on the left and then click in the empty box next to the word Name, and type the name of our program, which is:

redgreen.py

“redgreen” is the name and the “.py” means this is a program written in the language Python. We’ll be finding out more about Python as we go on.

Click the Save button.

Our program is finished! Now we need to run it.

Click the aeroplane-y thing again, then Accessories, then LXTerminal. A terminal is a program you use to run other programs.

When LXTerminal has started, your cursor will appear next to a $ sign. This means it is ready for you to tell it what to do.

Type exactly this:

python redgreen.py

What this means is run the program called “python”, and pass the name of our program (redgreen.py) to it. This is how you run Python programs.

Now press the RETURN key.

If all goes well, our program will talk back to us, and say what we told it to say:

Hello, world!

Let’s look again at our program.

It’s just one “statement”, a print statement. A statement is something to do.

We pass one “argument” to print, “Hello, world!”. An argument is some information you give to a statement.

“print” doesn’t mean print to the printer, but write to the screen. So our program did exactly what we told it to do – it wrote our message to the screen.

Next time, we’ll map out the whole of our real program – a simple game.

Update: congratulations to sparkboy123 on getting this working!

My First Raspberry Pi Game – Part 01 – Before we start

Parts: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

In this series I intend to guide you through writing your first ever computer program.

We will write our own game on the Raspberry Pi, which is a cheap-as-chips computer designed for learning about computers.

Get a Raspberry Pi

To follow along, here’s what you will need:

  • A Raspberry Pi (about £25) – I got it from RS
  • An SD card (about £10) – be careful – not all of them work. I use: Kingston Technology 16GB
  • If your TV supports it, an HDMI cable (about £1) – I got: HDMI to HDMI Connector. If your TV doesn’t support HDMI, get a composite cable, but it won’t look as good or work as well.
  • A power supply (about £4) e.g. a smartphone charger (micro USB, at least 5V, 1A) – I got Micro USB Mains Charger but my existing HTC Wildfire S charger worked too.
  • USB keyboard and mouse (about £7) – I had them lying around, but a quick search suggests this one might be ok: CiT USB Keyboard and Mouse.

(Total cost, very approximately: £47)

Install “Raspian”

To use the Pi you will need to install some software onto your SD card.

To do this you will need a PC or laptop. If you don’t have one, or you’d prefer not to download and install software to an SD card, check out The Pi Hut. They sell SD cards that already have Raspian installed on them.

Raspian is the name of the software we will use to start up and run our Raspberry Pi. You need to download it and install it onto your SD card before you can put the SD card into the Pi and turn it on. To do this, you’ll need a way of writing to the SD card. Lots of laptops (and some desktops) have built-in SD card readers, or you can get a USB reader (I got this one: SD Card Reader USB 2.0).

To install Raspian “wheezy” (wheezy is the name of the latest version) go to the Raspberry Pi download page at www.raspberrypi.org/downloads and click the link in the Raspian “wheezy” section next to the words “Direct download”. Follow the instructions on how to install Raspian to your SD card here: elinux.org/RPi_Easy_SD_Card_Setup.

(There are also some helpful instructions here: reviews.cnet.co.uk/desktops/how-to-get-started-with-the-raspberry-pi-50009845/.)

Start the Pi

Once you’ve got an SD card with Raspian on it, insert it into your Pi (the SD card slot is underneath, which surprised me a bit). Plug the Pi into your TV by connecting the HDMI cable to it and plugging the other end into the TV’s HDMI port. Plug your keyboard and mouse into the 2 USB slots.

Take a deep breath, and plug the power supply into the micro-USB port.

If all goes well, some lights will appear on the Pi, you will be able to switch your TV to HDMI mode and your screen will show some writing and possibly pictures of raspberries. Wait for it all to settle down, and (hopefully) eventually you’ll see the setup screen.

First time setup

The first time your Pi boots it will ask you to do some setup. Read the raspi-config menu items and see whether there’s anything you want to change. You might want to change your keyboard and language settings, but I didn’t need to change anything at all. I just pressed TAB and then right-arrow to move onto the word Finish, then pressed RETURN.

There’s more information about how to set everything up at elinux.org/RPi_raspi-config, and there’s a nice detailed video here: First boot and Raspi-config.

Wait a bit more, and eventually you should see a huge raspberry, with a mouse cursor and desktop. If so, you’re ready for the next part!

Update: a real person really following this series!: