To get images moving, we'll need to draw them many times, very fast, each time in a slightly different position. This way, we create an illusion of an object moving. We can use a loop to get this effect.
In Python, the word while
is used to create a loop. Start a new program from scratch. Type it as follows:
count = 0
while count < 10:
print(count)
count = count + 1
We had to stop for a moment to learn loops because we need them to create animations. Now let's go back to the program we were writing with Pygame. It's time to use this knowledge.
Here's a list of steps. Each one explains a line of the program we are going to write. Translate each step into a line of code (revisit the previous lessons to remember how to do all this):
When you are done with it, it's time to make the image move. To this program we just wrote, we are going to add code to do the following:
This is not going to be only one line of code, but several. You will have to combine the following:
Go on, give it a whirl.
If you did everything correctly, you should have an image moving across the screen, but leaving a "wake" behind it. How can we avoid this?
The problem here is that we are drawing on top of the previous screen. Instead, we need to make sure that the screen is deleted before we start painting a new frame. You can use the following piece of code, which paints the whole screen black:
screen.fill([0, 0, 0])
Where do you think that line should go?