My First Raspberry Pi Game – Part 05 – Say something

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 some writing on that blank screen we made last time.

But first, a couple of tricks (we are doing magic after all). We’re going to make our program know it is a Python program, without needing to be told. To do this we need to do 2 things.

First, open up LeadPad as normal and add this line at the very (very) top of the file. Make sure there are no empty lines above it:

#!/usr/bin/env python

That’s a “hash” (or, for Americans, “pound”) symbol, followed by an exclamation mark. Note that all the slashes are forward slashes, not backward.

This tells our Raspberry Pi that this is a Python program. Now we need to tell our Pi that this program is allowed to run by itself, instead of its name being passed to the python program like we have been doing before.

To do this, open up LXTerminal as before, and type exactly this (and press Return):

chmod +x redgreen.py

If all of this worked correctly, you should be able to run our program in a new way. Instead of typing python redgreen.py like we were before, we can type this in to LXTerminal:

./redgreen.py

That’s a dot, followed by a forward slash, followed by the name of our program.

This means run the program in this directory (that is the “./” part) called “redgreen.py”. Your Pi will look at redgreen.py and find the line we added that starts with “#!” and know to use Python to run it.

Now let’s get on with writing something on the screen. Go back to LeafPad and change the line starting with screen_size = to be these 3 lines:

screen_width = 640
screen_height = 480
screen_size = screen_width, screen_height

This creates 3 variables – screen_width, screen_height and the one we had before screen_size, which is now made by putting the first 2 together. We’re going to use screen_height later.

Just below those 3 lines, type this:

screen = None
ready_text = None

This gets 2 variables ready for us, and makes them empty. We’re going to fill them in inside start.

Change the start function to look exactly like this:

def start():
    global screen, ready_text
    pygame.init()
    screen = pygame.display.set_mode( screen_size )
    font = pygame.font.Font( None, screen_height / 5 )
    ready_text = font.render( "Ready?", 1, pygame.Color( "white" ) )

The green lines above are the bits we’ve added. The line beginning global tells Python we want to work with those variables we got ready earlier inside this function, even though we created them outside it. (Without saying they were “global” we would be in danger of working with versions of them that only existed while we were inside the function, and disappeared as soon as we left.)

The font line makes a new font (a font is a typeface, or way of writing text). The first argument we passed was None because we don’t care at the moment which font we use (e.g. “Arial” or “Times New Roman”) – we are happy with the default. The second argument is for the size of the font we want, and we passed in screen_height / 5, which means the value of the screen_height variable we created near the top, divided by 5. The “/” character is how we write division in Python – it is supposed to look a bit like a fraction.

Finally, on the last line we create another variable called ready_text, which contains the “rendered” version of the word “Ready?”, using the font we created, in white. “Render” means we create a picture showing the writing we wanted. We’ll draw this picture onto the screen in a second.

Now that all our preparation is over, we can finally write a fuller version of the ready_screen function. Change it to look like this:

def ready_screen():
    textpos = ready_text.get_rect(
        centerx = screen.get_width() / 2,
        centery = screen.get_height() / 2
    )

    screen.blit( ready_text, textpos )
    pygame.display.flip()

The first 4 lines (textpos up to the closing bracket all on its own) are really all one “line of code” – they are like one sentence of our program, that happens to span multiple lines. In Python if we want to continue a sentence (we call it a “statement”) we just leave a bracket unclosed. Python knows we have finished when we have closed all the brackets.

This “line” from textpost = up to ) creates a variable called textpos, which contains the place on the screen where we want to put our writing. We look inside ready_text (which is our rendered writing that we created above) for a function called get_rect that calculates a rectangle for us that is the right place on the screen to put the writing. The arguments we pass to get_rect are screen.get_width() / 2 and screen.get_height() / 2, which are telling it that it should calculate the rectangle by putting its centre in the middle of the screen. The middle of the screen is half-way across its width, and half-way down its height, which is why we are dividing the width and the height of the screen by 2.

Something worth noticing here is that the arguments to get_rect have names – we wrote centerx = and centery =. In Python we are allowed to give the names of arguments, or sometimes we can miss them out if we are happy just to put them in the right order. The get_rect function can actually take lots of different arguments, so it needs to know which ones you mean, which is why we named them.

Finally the last 2 lines do the real work. The screen.blit line tells PyGame to write the ready_text picture (the rendered writing) onto the screen at the position stored inside textpos. pygame.display.flip() is what we do to tell PyGame we’ve finished messing about with the screen, and we’re ready for it to display what we’ve done.

[The word “blit” is an oddity from the olden days which I’m afraid you’ll just have to memorise, and “flip” comes from the fact that behind the scenes there are really two screens – the one we are displaying, and the one we are working on. flip() switches them over, displaying the one we were working on, and making the other one ready to be worked on.]

If you’ve got this far, well done! With any luck, we’re going to see the word “Ready?” on the screen in big letters.

Switch to LXTerminal again and type our new spell:

./redgreen.py

Don’t move the mouse or press anything: a window should appear, with the word “Ready?” written in big white letters. When you press a key or move the mouse over it, it should disappear.

If something goes wrong, check back over the instructions carefully, and compare your file with this one: redgreen.py.

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!