Pygame Study Notes (5)-genie

Source: Internet
Author: User

reprint Please note: @ Small Five Yi http://www.cnblogs.com/xiaowuyi

it is said that in the Nintendo FC era, the genie played a huge role. However, at that time, I only knew how to play Super Mario and Soldado, but I did not know about the genie. Pygame. sprite. sprite is a class used in pygame to implement the Genie. It does not need to be instantiated during use. It only needs to inherit from it and then write its own class as needed. Therefore, it is very simple and practical.
1. What is genie
A genie can be considered as a small image, a graphical object that can be moved on the screen and can interact with other graphic objects. The sprite image can be an image drawn using the pygame function, or an original image file.
2. The main and common variables in Sprite are as follows: For more details, see what is displayed in http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite
self. image. Such as self. image = pygame. surface ([x, y]) indicates that the Sprite is an X, Y-sized gap, self. image = pygame. image. load (filename) indicates that the sprite calls to display the filename image file.
self. image. fill ([color]), responsible for self. image coloring, such as self. image = pygame. surface ([x, y])
self. image. fill ([, 0])
Fill in red with the X and Y shapes.
where is self. rect responsible for display. Generally, use self. rect = self. image. get_rect () obtains the image size and then returns it to self. rect is used to set the display position. rect. topleft (topright, bottomleft, and bottomright) to set the display position of a certain angle. In addition, self. rect. Top, self. rect. Bottom, self. rect. Right, and self. rect. Left indicate the upper, lower, and lower sides respectively.
self. Update takes effect for the genie action.
Add Sprite. Add to group.
Sprite. Remove Delete from group
Sprite. Kill Delete All genie from groups
Sprite. Alive determine whether the genie belongs to groups

3. Create a simple genie
All genie are inherited from pygame. Sprite. Sprite at the time of creation.
(1) Create an Genie and draw a distance of 30 in width and 30 in height.CodeAs follows:

 
ClassTemp (pygame. Sprite. sprite ):Def _ Init __(Self, color, initial_position): pygame. Sprite. Sprite._ Init __(Self) self. Image= Pygame. Surface ([30, 30]) Self. image. Fill (color) self. rect=Self. image. get_rect () self. rect. topleft= Initial_position

Here we will analyze it one by one. pygame. Sprite. Sprite. _ init _ (Self) completes initialization. Self. Image = pygame. Surface ([30, 30]) defines a surface with a distance of 30*30. Self. image. Fill (color) uses color to fill the color. Self. rect = self. image. get_rect () to get the size of self. image. Self. rect. topleft = initial_position: determines the position displayed in the upper left corner. Of course, you can also use topright, bottomrigh, and bottomleft to determine the positions of other corners. The Wizard shows that a 30*30-size red margin is drawn at the position of a 640*480-size White Form [50,100]. The complete code is as follows:

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi  Import  Pygame, syspygame. INIT ()  Class  Temp (pygame. Sprite. sprite ):  Def   _ Init __  (Self, color, initial_position): pygame. Sprite. Sprite. _ Init __  (Self) self. Image = Pygame. Surface ([30, 30 ]) Self. image. Fill (color) self. rect = Self. image. get_rect () self. rect. topleft = Initial_positionscreen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) B = Temp ([255, 0], [50,100 ]) Screen. Bits (B. Image, B. rect) pygame. display. Update ()  While  True:  For EventIn  Pygame. event. Get ():  If Event. type = Pygame. Quit: SYS. Exit () 

(2) Make an Genie and show the content as an image. The previous car image is used as an example. The Code is as follows:

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi  Import  Pygame, syspygame. INIT ()  Class  Car (pygame. Sprite. sprite ):  Def   _ Init __  (Self, filename, initial_position): pygame. Sprite. Sprite. _ Init __  (Self) self. Image = Pygame. image. Load (filename) self. rect = Self. image. get_rect ()  #  Self. rect. topleft = initial_position Self. rect. bottomright = Initial_position  Print  Self. rect. Right Screen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) Fi = ' Ok1.jpg  '  B = Car (FI, [150,100 ]) Screen. Bits (B. Image, B. rect) pygame. display. Update ()  While  True:  For Event In  Pygame. event. Get ():  If Event. type = Pygame. Quit: SYS. Exit () 

The inventory file, and defines the display position of the right corner of the car is [150,100].

3. Learning genie Group
(1) using the genie to put multiple images on the screen, this method does not use the concept of the genie group, but uses the list to generate each genie. Cargroup is used to store cars in different locations. Screen. Bits (Carlist. Image, Carlist. rect) show each genie one by one. For details, see the code:

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi  Import  Pygame, syspygame. INIT ()  Class  Car (pygame. Sprite. sprite ):  Def   _ Init __  (Self, filename, initial_position): pygame. Sprite. Sprite.  _ Init __  (Self) self. Image =Pygame. image. Load (filename) self. rect = Self. image. get_rect () self. rect. bottomright = Initial_position Screen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) Fi = '  Ok1.jpg  '  Locationgroup = ([150,200], [350,360], [250,280] ]) Cargroup = []  For LoIn  Locationgroup: cargroup. append (CAR (FI, LO ))  For Carlist In  Cargroup: screen. Bits (Carlist. Image, Carlist. rect) pygame. display. Update ()  While  True:  For Event In  Pygame. event. Get ():  If Event. type = Pygame. Quit: SYS. Exit () 

The specific effect is shown in the following figure:

(2) Use a Sprite group to implement multiple images. The above genie is in a list, which is very convenient, and is a little inefficient. In addition to the genie, pygame also provides the genie group, which is suitable for handling the genie list, adding, removing, plotting, updating, and other methods. Specific as follows: http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite
Group. sprites genie Group
Group. Copy copy
Add group. Add
Group. Remove remove
Group. Has judge members of the genie Group
Group. Update
Group. Draw bit block display
Group. Clear-draw background
Group. Empty clear
In the same example above, the sprite group is used here.

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi  Import  Pygame, syspygame. INIT ()  Class  Car (pygame. Sprite. sprite ):  Def   _ Init __ (Self, filename, initial_position): pygame. Sprite. Sprite.  _ Init __  (Self) self. Image = Pygame. image. Load (filename) self. rect = Self. image. get_rect () self. rect. bottomright = Initial_positionscreen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) Fi = '  Ok1.jpg  '  Locationgroup = ([150,200], [350,360], [250,280] ]) Cargroup = Pygame. Sprite. Group ()  For Lo In  Locationgroup: cargroup. Add (CAR (FI, LO ))  For Carlist In  Cargroup. Sprites (): screen. Bits (Carlist. Image, Carlist. rect) pygame. display. Update ()  While  True:  For Event In Pygame. event. Get ():  If Event. type = Pygame. Quit: SYS. Exit () 

In both examples, three cars are displayed in [150,200], [350,360], [250,280]. The first is list, and the second is Sprite. The difference lies in a few words. First, cargroup = pygame. sprite. group () defines cargroup as the genie group, and the second is cargroup. add (CAR (FI, LO) replaces append with ADD. The third is for Carlist in cargroup. sprites () shows the genie one by one. I tried it here. It is also possible to directly use for Carlist in cargroup. The code of the sprite group is highly optimized and is often faster than the list. Insert and delete operations are common, and the code can avoid repeated consumption in the loop.
4. Animation
It is convenient to use the sprite group for animation. Here we first let the three cars above move.
(1) three cars move forward at different speeds and use random. choice randomly generates a value between [-10,-1] As the speed to move the car from bottom to top, and then appears from the bottom when it reaches the top. The Code is as follows:

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi  Import  Pygame, sys From Random Import * Pygame. INIT ()  Class  Car (pygame. Sprite. sprite ):  Def   _ Init __  (Self, filename, initial_position, speed): pygame. Sprite. Sprite.  _ Init __  (Self) self. Image = Pygame. image. Load (filename) self. rect = Self. image. get_rect () self. rect. topleft =Initial_position self. Speed = Speed  Def  Move (Self): Self. rect = Self. rect. Move (self. Speed)  If Self. rect. Bottom <0: #  When the bottom of the Car reaches the top of the window, let the car out from below Self. rect. Top = 480 Screen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) Fi = ' Ok1.jpg  '  Locationgroup = ([150,200], [350,300], [250,200] ]) Cargroup = Pygame. Sprite. Group ()  For Lo In  Locationgroup: Speed = [0, choice ([-10,-1 ])] Cargroup. Add (CAR (FI, lo, speed ))  While  True:  For Event In Pygame. event. Get ():  If Event. type = Pygame. Quit: SYS. Exit () pygame. Time. Delay ( 20 ) Screen. Fill ([ 255,255,255 ])  For Carlist In  Cargroup. Sprites (): Carlist. Move () screen. Bits (Carlist. Image, Carlist. rect) pygame. display. Update () 

(2) You can use the left and right keys to control the left and right movements of the three cars, and press the left button to move to the left. When it reaches the left, it is no longer moved. Right-click and move to the right, when it reaches the rightmost, it does not move any more. The Code is as follows:

 #  Xiaowuyi http://www.cnblogs.com/xiaowuyi Import  Pygame, sys  From Random Import * Pygame. INIT ()  Class  Car (pygame. Sprite. sprite ):  Def   _ Init __  (Self, filename, initial_position, speed): pygame. Sprite. Sprite.  _ Init __  (Self) self. Image = Pygame. image. Load (filename) self. rect =Self. image. get_rect () self. rect. topleft = Initial_position self. Speed = Speed  Def  Move (Self): Self. rect = Self. rect. Move (self. Speed)  If Self. rect. Bottom < 0: Self. rect. Top = 480 Def  Moveleft (Self): Self. rect. Left = Self. rect. Left-10 If Self. rect. Left <0: Self. rect. Left = 0  Def  Moveright (Self): Self. rect. Right = Self. rect. Right + 10 If Self. rect. Right> 640 : Self. rect. Right = 640 Screen = Pygame. display. set_mode ([640,480 ]) Screen. Fill ([ 255,255,255 ]) Fi = '  Ok1.jpg  ' Locationgroup = ([150,200], [350,300], [250,200] ]) Cargroup = Pygame. Sprite. Group ()  For Lo In  Locationgroup: Speed = [0, choice ([-10,-1 ])] Cargroup. Add (CAR (FI, lo, speed ))  While  True:  For Event In  Pygame. event. Get ():  If Event. type =Pygame. Quit: SYS. Exit ()  Elif Event. type = Pygame. keydown:  If Event. Key = Pygame. k_left:  For Carlist In  Cargroup. Sprites (): Carlist. moveleft () screen. Bits (Carlist. Image, Carlist. rect)  If Event. Key = Pygame. k_right:  For CarlistIn  Cargroup. Sprites (): Carlist. moveright () screen. Bits (Carlist. Image, Carlist. rect) pygame. Time. Delay ( 20 ) Screen. Fill ([ 255,255,255 ])  For Carlist In  Cargroup. Sprites (): Carlist. Move () screen. Bits (Carlist. Image, Carlist. rect) pygame. display. Update () 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.