Moving images are the essence of most games, and most forms of entertainment for that matter. With sprites, going from stationary to moving is easy. Sprite objects have additional attributes and methods that allow them to move around a graphics screen.
According to the latest research, pizza doesn't float, it falls. So I wrote the Falling Pizza program. This new program is a modification of the Pizza Sprite program. In this program, the pizza falls down the screen. All I need to do is change a few lines of code to get the pizza to move. That's the power of sprites. Figure 11.11 illustrates the program.
Figure 11.11: The pizza falls down the screen in the direction of the arrow.
First, I modify the Pizza class from the Pizza Sprite program:
class Pizza(games.Sprite): """ A falling pizza. """ def __init__(self, screen, x, y, image, dx, dy): """ Initialize pizza object. """ self.init_sprite(screen = screen, x = x, y = y, image = image, dx = dx, dy = dy)
The class doesn't look all that different. When I invoke the init_sprite() method for a newly created Pizza object, I pass optional values to the parameters dx and dy. Every object based on Games_Object has dx and dy attributes that represent the object's velocity along the x and y axes respectively. ("d," by the way, stands for "delta," which means a change.) So, dx is the change in the object's x attribute and dy is the change in the object's y value each time the Screen object is updated by mainloop(). A positive value for dx moves the object to the right, while a negative value moves it to the left. A positive value for dy moves the object down, while a negative value moves it up.
Back in the Pizza Sprite program, I didn't pass any values to the init_sprite() method for the dx or dy. Although the sprite in that program did have these dx and dy attributes, they were both assigned their default value of 0 by the init_sprite() method.
Next, I modify the code that creates a new Pizza object in the main part of the program by providing additional values for dx and dy to the constructor method:
Pizza(screen = my_screen, x = SCREEN_WIDTH/2, y = SCREEN_HEIGHT/2, image = pizza_image, dx = 0, dy =1)
I want the pizza to fall down the screen so I pass 1 to dy. Since I don't want any vertical movement, I pass 0 to dx. As a result, every time the graphics window is updated by mainloop(), the Pizza object's y value is increased by 1, moving it down the screen. It's falling!