Chapter 2. Animating graphics

Topics:

movement, animation speed, keyboard control

Constructs:

assignment, variable, object, if-statement, while-loop

In this chapter, we will make our graphical character actually do something. It won’t be very much at first, but at least we want to make it move across the screen. We continue straight where we left off in Chapter 1.

If you have done the exercises in Chapter 1, and you compare the two lines we currently have in our program to create actors, we can see that they look different:

Strype code

The difference is not only the additional coordinates that we have specified with our second actor, but also the arrow symbol () and name (fish) that we have used in the first line. This is called an assignment, and we will investigate this next.

2.1. Assignment – a first look

The purpose of an assignment is to keep a reference to our actor object, so that we can continue to work with it afterwards. When we create an actor on a line on its own (as in our second line above), the actor object is created, it is automatically placed into the world, and that is all that happens. After this statement, we do not have access to the actor anymore, and we cannot directly work with it further.

This is why we often use an assignment to assign the actor to a variable, which allows us to continue working with this actor. Let us investigate what this means.

We can enter an assignment frame into our code by typing the = key. When we enter the frame, it looks like this:

Strype code

The effect of an assignment frame is that it creates a variable and stores a value into it. A variable is a small amount of storage that allows us to store some information, and to access and use it again later. Variables have names – this is how we refer to them – and store a value.

Terminology A variable is a small amount of storage space that allows us to store a value and retrieve and use it again later. Variables have names, which are used to refer to them.

We can see that the assignment frame has two slots which we must fill in. The slot on the left lets us provide a name for the variable. We can make up this name, and we usually choose a word that describes what we will store in this variable.

The right hand side of the assignment has a slot labelled "value". Here, we can specify what we want to store in the variable.

Some examples of assignments to variables are:

Strype code

We can see from these examples that we can use variables to store different kinds of thing. We can store numbers, or we can store text (words, or whole sentences), or we can store actor objects. We will see later that we can also store all sorts of other things – we will get to that in due course.

Concept An assignment stores a value into a variable.

We can then use the value stored in that variable just by using the variable’s name. For example

Strype code

will print out the contents of the 'age' variable (which will be 17 after the assignment which we made above). Compare that with the statement

Strype code

This statement would print out the word "age". Note the difference: the quotation marks around the word "age". If we print "age" with quotation marks, we are printing the word "age". If we print age (without quotation marks), we are referring to our variable named age, so we are printing out the value stored in this variable: 17.

Now that we have seen the first basics of variables, let us get back to our yellow-fish project.

2.2. Actor movement

We can now properly interpret the two lines of code we have seen before:

Strype code

The first line creates an actor with a fish image and assigns it to a variable named fish, while the second line creates an actor and does nothing further with it.

We want to do further actions with our actor, so we need to assign it to a variable. But we do not need two actors at the moment, so we can delete one of the actors again. For this book, we will continue to use the fish actor, but you are welcome to use your own actor for the remainder of this project while you read on.

Exercise 2.1   Change your code again so that only one actor is created and assigned to a variable. The actor should use your own selected image. Rename the variable so that it correctly describes the type of actor that you have chosen. (For example, if your image shows a beetle, you might like to name the variable beetle, if it is a car, name it car. Whenever we use our fish variable in the remainder of this chapter, you should then use your own variable.)

Now that we have our actor, and we have stored it in a variable, we can make it move:

Strype code

Try this out with the following exercises.

Exercise 2.2   Add the line of code which makes the actor move (shown above) to your own code, after the actor has been created. You can do this by adding a function call frame, typing fish.move as the function name, and adding the parameter. Run your program. What do you observe?

Exercise 2.3   Change the parameter from 8 to 300. Run your program again. What do you observe?

After the first exercise, you will probably notice that the fish does not appear to move. This is because the parameter is in pixels. Eight pixels is a very small distance on screen, so when you ran your program, the fish was shown and then – very quickly – moved eight pixels to the right. But this distance is so small, and the movement so quick, that it is hard to notice it at all.

In the second exercise, the distance we have used is larger, so we can see that the fish is now at a different place. But again, the movement is so quick that we do not really see the fish move. If we want to turn this project into a game, we need our fish to move more slowly.

Before we go on to do this, a little more terminology: A function that is called on an object, such as the move function above, is called a method. Objects have a fixed set of methods, and we shall see over time what kinds of methods our actors have, and what we can do with them.

Methods are called by specifying the object, a dot, and the method name and parameters.

Terminology A function that is called on an object is called a method. Methods are called by specifying the object we want to call, a dot, and the method name and parameters.

2.3. Controlled movement

We have seen in the previous exercises that calling the move method moves the actor very quickly. If we want to have slow, visible movement, we need to move the actor repeatedly, in small steps. We can do this by placing the move method call into a loop:

Strype code

Exercise 2.4   Add a while loop to your program to create the code shown above. Also add the call to the pace function as shown above. Run your program. What does it do now?

Terminology If you have a statement in your code, and you want to place it into a loop, you have two options: You can either insert the loop frame into your code and then drag your statement into the loop body with the mouse. Or you can select your initial statement (use shift-arrow-down) and then insert the while loop – this will surround the statement with the loop.

Let us look at this code a bit more closely. The while statement which we have just inserted is a loop statement: it repeats the statements inside it over and over again. Since the fish.move method call is inside the loop, it will be executed over and over, many times. Thus, we move the fish eight pixels to the right, and then move it eight pixels again, and so on.

If we did this without the pace function in our loop, this would still be so quick that we would not see the fish move slowly. (Computers are fast – try it out!) The pace function, however, has the effect of slowing down the loop. To be precise: the parameter of the pace function specifies how quickly the loop should run. A parameter of 30 means that the loop will run 30 times per second. This is a good speed to actually see the movement of the fish as a smooth movement across the screen.

Note that because we now have a program that runs forever, when we want to edit it again, we need to manually stop the execution. You will see that the Run button becomes a Stop button; click the button while it says Stop in order to stop the execution and return to editing the program.

Exercise 2.5   Experiment with different parameter values for the pace function. Also change the parameter to the move function to different values. You will see that you can use either one to change the speed of movement of the fish on screen. What is the difference between changing one or the other value?

The loop we have used here is called a while loop, because it starts with the keyword while. It has the ability to repeat a set of statements several times.

In the slot after the word while, we can specify how long we want to loop to run for. Using the word True here has the effect that the loop will run forever (or at least until we stop the program). We will see a bit later how we can use more sophisticated loop conditions to write loops that run a specified number of times.

Running our loop forever has the effect that the fish keeps moving until it hits the edge of the world. In Strype, actors cannot leave the world, so the fish gets stuck at the edge – every further attempt to move in that direction has no effect, but the program will keep running until we stop it.

Exercise 2.6   Actor objects also have a method called turn, which also takes one parameter. The parameter is a number, and specifies the angle to turn in degrees. Try out this method: replace the fish.move method call with a call to fish.turn, and run your program. What do you observe?

Exercise 2.7   Experiment with different parameter values for the turn method. What value gives you a nice, slow turning motion?

Exercise 2.8   Can you make the fish turn the other way?

Exercise 2.9   Try inserting the call to the move method back into the loop, so that you have a call to the move method and a call to the turn method, following each other. What does the fish do now? Try to predict this before trying it out.

Exercise 2.10   What would you have to change to make the fish swim in a larger circle? Try it.

The program that we have written so far is available in the book projects as yellow-fish-v2. If you have written your own program while reading this, keep using your own program. If you want to compare your program with ours, you can look at this version, or use this one as a starting point for the next exercises.

2.4. Keyboard control

The next obvious step towards our goal to turn this into a game is to give us control: We would like to control the fish with our keyboard, so that it can become our player character. That is what we will do next.

Our plan is to use the left and right arrow keys to control the fish: If the left arrow key is pressed, we want the fish to turn left, and if the right arrow key is pressed, it should turn right.

Luckily, Python has a statement to express exactly this: an if-statement.

Terminology An if-statement is an instruction that allows us to execute a set of statements only if a certain condition is true.

Strype-Tip You can enter an if-statement in two ways: You can press space and then i (the shortcut is shown top-right), as we have done before. Alternatively, you can type it: typing if followed by space at the blue frame cursor will create an if-frame. Either way works. This works for other frames as well.

Modify your program so that the loop looks like this:

Strype code

In this code, we have added an if-statement into the loop, and using this if-statement, we make the fish turn only if the left arrow key is pressed down.

When you insert a frame for an if-statement into your code, it looks like this:

Strype code

We can see that this frame has two slots: a text slot for the condition and a frame slot for the statements that should be executed if this condition is true. This frame slot is also called the body of the if-statement.

Concept An if-statement has two slots: the condition and the body.

In our loop, we use a function call as the condition: key_pressed. This function takes as its parameter the name of the key we want to check, and returns true if this key is currently pressed down. If it is true, then it executes its body to make the fish turn.

If the condition is false, then the body is not executed, and the fish does not turn.

Exercise 2.11   Insert this code in your own program. Test it. This should work – if you see any errors, fix them.

All keys on the keyboard have names that we can use with the key_pressed function. The name of the character keys is just their character (so the a-key is called "a", and so on) and other key names include "left", "right", "up" and "down" for the arrow keys, and "enter", "tab" and "backspace" for some of the others.

Using this, we can now add a second if-statement to make the fish turn right when the right arrow key is pressed.

Exercise 2.12   Add a second if-statement to your code, immediately following the first one. Use this statement to make the fish turn right when the right arrow key is being pressed. Test your program.

You can find this version of the program in the book projects as yellow-fish-v3.

2.5. Summary

We have now managed quite a big step forward in our goal to turn this project into a game: we can control a game character with our keyboard.

Along the way, we have seen quite a number of very useful and important Python programming constructs: function calls, parameters, variables, assignments, objects, methods, if-statements and a while loop.

That is a long list!

We have had a first contact with each of these constructs, and we can roughly understand what they do, but there is more to learn about each of them. So we will now – in the next chapter – take a step back and have a closer look at each of these constructs to deepen our understanding, before we get back to completing our yellow-fish game.

Concept summary

  • A variable is a small amount of storage space that allows us to store a value and retrieve and use it again later. Variables have names, which are used to refer to them.

  • An assignment stores a value into a variable.

  • A function that is called on an object is called a method. Methods are called by specifying the object we want to call, a dot, and the method name and parameters.

  • An if-statement is an instruction that allows us to execute a set of statements only if a certain condition is true.

  • An if-statement has two slots: the condition and the body.

Project Ideas

At the end of some chapters, we will suggest additional projects which you may like to try out at this stage. These projects will not be discussed in detail, and it is up to you to study them, decide what you would like to do with them, and take them forward. They are designed to give you some ideas what you can do with the constructs you know now. They can generally be approached with the knowledge you have at this stage in the book (and sometimes require looking something up on your own). You should take these projects as suggestions and ideas what you might do – in either a new project, or to add to an existing project of yours – not as rigid specifications.

Pong

Project Ideas Pong is a very old-school, classic arcade game. If you have not seen it before, you can find out about it by doing a web search for "pong game".

You can find a starter project in the book projects under the name pong-classic. This shows you how to do two-dimensional movement (up/down only), by directly setting the x/y-coordinates of an Actor, instead of using the move method. You can take it from here.