Use Python PyGame to Design a Game – Part 2

In my previous post, I introduced how to use PyGame to design a simple game and use project Catch Butterfly as an example. However, how to design a game with many butterflies at the same time? Based on the previous Catch Butterfly project, we might need to create several lists to store each butterfly’s position, image, speed, etc. That would make the whole projecct cumbersome.

This post will focus on how to restructre the previous code to make it scale up concisely. It will define classes to solve this problem. The final effect is shown in the following video clip.

Now let’s jump into the code.

For the beginning of the program from line 5 to line 8, there is nothing changed. The program defines the window size, font size and some constant color code. From line 10 to line 31, the program defines a class called “Bty_net”. This class represents the butterfly net you see in the game demo video. Usually, when we define a sprite class in PyGame, we need to define some typical attributes, such as its image and rect. The self.image is typically assigned an pygame.surface object, representing an image. self.rect represents the rectangle area of the image. Through specifying the rect’s attributes (such as left, top, centerx, centery, etc.), we could put the sprite image into proper positions of the game window.

For this class Bty_net, we have two special attributes: self.nc_x and self.nc_y. They are representing the center point of the net part. Since the net image contains handle, the image center and net center does not match. We use these two variables to represent the real center of the net part.

At line 25, the program defines a method called “center”. It is used to return a pygame.math.Vector2() object. This object is like a point object, containing x and y value of a 2-dimentional coordinate. At line 30, the program defines a method called “update”. It is responsible for bliting the sprite image onto the display surface.

From line 34 to line 92, the program defines Butterfly class. In “__init__” method, it defines some typical attributes, such as self.image_list, self.image and self.rect.

You might wonder why this class requires an input parameter of “img_list”. Each butterfly object contains several different costumes, so all the images are passed into the initializer as an image list. Meanwhile, the program adds two attributes self.dir and self.speed. In this way, butterfly object would have their own flying direction and speed.

At line 45, the method “fly” changes the position of the butterfly object. Depending on the value of self.speed, the horizontal movement amount of “dis” will be different, which decides how fast the butterfly could move. From line 54 to line 65, depending on the value of self.dir, the butterfly object would move either to the right, or to the left.

Through creating class, we successfully shift responsibility from functions onto the objects, making it possible to write more versatile methods, and making it easier to maintain and reuse code.

At line 74, the program defines a method called “next_costume”. This method changes butterfly image to the next one in butterfly_image list. The attribute self.frame is used as a counter. Through using “self.frame % image_len”, self.image will iterate the item in self.image_list repeatedly, making butterfly object change images periodically.

The method “center” will return a pygame.math.Vector2 object, which represents the center point of the butterfly image.

At line 85, the program defines a method called “collide_net”. This method is used to check if a butterfly object collides with net object. When we say a butterfly is caught by a net, it is not that the butterfly object just touches the net. Instead, the butterfly object should be within the net part. use pygame.math.Vector().distance_to method, we could get the distance between two Vector2 objects. When the distance is small enough (<=60 in this case), we say that the net catches the butterfly.

From line 94, the program defines the main() method. Line 97 to line 126 are the same as the previous version. The code just loads all the images and assigns them to different variables.

From line 129 to line 134, the program loads background music and plays it. It also loads another sound and assigns it to variable “sound_catch”, but does not play it yet. Please note that when playing background music, the code could use “pygame.mixer.music.load”, and then “pygame.mixer.music.play()” to play it. However, when you would like to load some short sounds to enhance gaming effects, use “pygame.mixer.sound”.

From line 136 to line 139, the program creates five Butterfly objects. Please note that using random.choice, each butterfly object’s flying speed and flying direction could be different.

At line 142, the program creates a Bty_net object. Its initial position is 0, 0, representing the top-left corner of the window.

From line 145, the program enters the main loop. It first checks the events to see if any keyboard and mouse events happens. This part is the same as the previous version. When event type is MOUSEMOTION, it represents the mouse movement event. The program will record mouse position to mouse_x and mouse_y. When the event type is MOUSEBUTTONUP, it represents the mouse button release. The program will set variable mouseClicked to True.

If mouseClicked is True, it indicates that the user clicks the mouse in the game window. The progam will iterate the butterfly_list and check if any Butterfly object collides with the net object. If the result is True, it means this Butterfly object is caught by the net. The program increases score by 1, plays the catching sound and removes this object from butterfly_list. The removed Butterfly object will not get blitted to the display surface, so the effect is that the Butterfly object disappears.

From line 179 to line 184, the program checks if all the Butterfly objects get caught. If that is the case, the program blits the win banner image to display_surface, and then exits the program.

That is all the code for the updated Catch Butterfly game. Hope you are clearer about how to design sprite class in PyGame and use it to make code structure tidy and scalable. Enjoy the coding and see you then.

Note: All the analysis articles are copyright products of http://www.thecodingfun.com. Anyone re-posting them should credit author and original source. Anyone using them for commercial purposes or translating them into other languages should notify TheCodingFun and get confirmation first. All Rights Reserved.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.