Exercise 2: Make the little guy walk

Download the following files:

Goal

"Animate" the image of the little boxy guy by continuously swapping out the picture.

Idea: Create a list of pictures. Start by showing the first picture in the list. Every nth iteration through the game loop, go to the next picture in the list. When you reach the end of the list, start at the beginning.

Step 1: Create a list of pictures and display the first

The code I gave you just loads and displays one single image.

Change the code where the picture is loaded, so a variable that refers to the list of all images is created. (Note: you need to convert each picture.)

Suggested strategy: Make a list of all filenames. Go through the list and load each picture creating a new list of loaded picture objects. Go through this new list and convert each picture creating a thirs list containing all the converted pictures.

Now that we have a list of pictures instead of just a single picture, we need a variable to keep track of which picture we want to show. We can do that by having this variable hold the index of the picture in the list that is currently on the screen.

Create a variable called cur_idx and set it to 0. Then change the command that actually draws the picture, such that it draws the picture from the list that we currently want to show (as indicated by the cur_idx variable.

Try it out. You should see the same thing as before. Just one still picture of the character. (But it is working with the list now, instead of just one single picture.)

Step 2: Cycle through the images

Now we need to increase cur_idx by 1 every so often and reset it to 0 every time we reach the end of the list.

At first, increase cur_idx by 1 in every frame (i.e., every pass through the game loop). And get the code right for resetting it to 0 when reaching the end of the list.

Try it. The timing will not be very good, but you should see the feet moving.

Step 3: Slow it down

Idea: The guy is walking really fast because we are switching to a new image in every run through the game loop. To slow it down, we should only switch every n runs through the loop, where n is 10, 50, 100, .... The higher the number the slower the guy will move.

Add a counter variable, that counts ever run through the game loop.

If the counter reaches a threshold, change the value of cur_idx and reset the counter variable to 0.