Install pygame module
Install modules for making games
Installation through pip command
pip install pygame
Game Initialization and Exit
Initialization
pygame.init()
Sign out
pygame.quit()
Rectangular area object
Four Elements of Rectangular Area
x coordinates, y coordinates, width, height
x,y,width,heigh
Description Classes of Rectangular Areas
Rectangular areas have four elements
- x
- y
- width
- height
There are three ways to create rectangular objects
Rectangular area object = pygame.Rect(x,y,width,height) Rectangular area object = pygame.Rect((x,y),(width,height)) Rectangular area object = pygame.Rect(object)
Comments in source code
Rect(left, top, width, height) -> Rect Rect((left, top), (width, height)) -> Rect Rect(object) -> Rect pygame object for storing rectangular coordinates
Additional explanation
Rect objects do not depend on the initialization of pygame.init().
This means that you can create objects using the pygame.Rect class even if you don't initialize pyGame
Game Main Window
First create the window, then go to the window and draw the picture.
Create modules to manage game windows
pygame.display Major use of two functions set_mode(), which is used to initialize the window of the game display update(), which refreshes the screen display
Initialize Game Display Window
function
Pygame. display. set_mode (wide and high tuples) Returns a window object for example screen = pygame.display.set_mode((480,700))
Parameters of functions
set_mode(resolution=(0,0), flags=0, depth=0) resolution,Width and height of screen flag,Whether full screen, etc., generally do not change the default value depth,Color location, default is automatic matching
Game cycle
To keep the window from disappearing immediately, you need to set up Game cycle
Drawing Trilogy
Drawing steps
-
Load image data
Picture object = pygame. image. load (picture path)
Printing results of image objects and their types
<Surface(480x700x24 SW)> <class 'pygame.Surface'>
A method of generating rectangular objects with a picture object
Picture Rectangular Object = Picture Object. get_rect()
-
Draw the picture on the screen
Game Window. BLIT for example screen.blit(bg,(0,0))
Another way is blit.
Game window. blit (picture, rectangular object) for example screen.blit(hero,hero_rect)
-
Display update
pygame.display.update()
Analogical understanding
First of all, we need to clarify the principle of animation.
Understanding that animation is actually a visual effect of fast switching from frame to frame
Then you can follow the following train of thought to understand.
-
Loading image data means reading pictures into memory to prepare them.
-
Drawing on the screen is equivalent to drawing pictures into the display area (a frame of the screen).
Note that we are drawing the next page (next frame)
-
Display updates, rather turn a page, so that the pictures we just drew are displayed.
Rendering Heroes
Draw heroes according to the drawing trilogy.
- Load hero pictures
- Draw hero pictures in Windows
- update display
Game clock
Game Clock Class
pygame.time.Clock
Create a clock object
clock = pygame.time.Clock()
Frame Rate Control
Inside the game loop, use the tick() method of the clock object
Clock. tick (frame rate)
About frame rate
The bigger the value, the smoother the animation will be.
Drawing attention
Drawing is done on the basis of the previous picture.
therefore
If the background map is not redrawn
The newly drawn pictures will appear in conjunction with the original ones.
event listeners
Event module
pygame.event
Get a list of events for the user's current action
event_list = pygame.event.get()
Event object... type
Fork out window
<Event(12-Quit {})> .. <class 'Event'>
mousedown
<Event(5-MouseButtonDown {'pos': (359, 264), 'button': 1})> .. <class 'Event'>
Press keyboard
To be added
Event type
Event object.type This is an integer.
Exit Game Event Type
pygame.QUIT Click on the event type number of the closed window
More event types are numbered in
pygame/constants.py
Press keyboard
There are two situations.
-
Press and hold to trigger only once
event.type vs. pygame.KEYDOWN event.key and pygame.K_RIGHT, for comparison
-
Hold on to the incessant trigger
Key tuple = pygame.key.get_pressed() According to the number corresponding to the pressed key, event.key, the subscript can look up the data in the tuple. If the value is not zero, it means that it is held down.
Exit the game trick
pygame.quit() exit()
timer
Method of setting timer
pygame.time.set_timer()
Detailed parameters of the method
set_timer(eventid, milliseconds) Evetid is commonly used pygame.USEREVENT To specify milliseconds In milliseconds, 1000 is equivalent to one second.
A set of tricks for using timers
- Define event number
- set timer
- Monitoring events
Spirit
ccsprite
pygame.sprite.Sprite
The update Method of Elves
An update method is defined in the wizard class
It's a placeholder method. Code uses pass placeholder.
We can rewrite this method.
def update(self, *args): """method to control sprite behavior Sprite.update(*args): The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update() with whatever arguments you give it. There is no need to use this method if not using the convenience method by the same name in the Group class. """ pass
pass Method in Elves
This method can make the generated wizard object disappear and be deleted from memory.
kill method
Remove it from all Elf Groups
def kill(self): """remove the Sprite from all Groups Sprite.kill(): return None The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups. """ for c in self.__g: c.remove_internal(self) self.__g.clear()
sprite groups
Wizard group class, inherited from AbstractGroup class
pygame.sprite.Group
add method
Adding wizards to groups
def add(self, *sprites): """add sprite(s) to group Group.add(sprite, list, group, ...): return None Adds a sprite or sequence of sprites to a group. """ for sprite in sprites: # It's possible that some sprite is also an iterator. # If this is the case, we should add the sprite itself, # and not the iterator object. if isinstance(sprite, Sprite): if not self.has_internal(sprite): self.add_internal(sprite) sprite.add_internal(self) else: try: # See if sprite is an iterator, like a list or sprite # group. self.add(*sprite) except (TypeError, AttributeError): # Not iterable. This is probably a sprite that is not an # instance of the Sprite class or is not an instance of a # subclass of the Sprite class. Alternately, it could be an # old-style sprite group. if hasattr(sprite, '_spritegroup'): for spr in sprite.sprites(): if not self.has_internal(spr): self.add_internal(spr) spr.add_internal(self) elif not self.has_internal(sprite): self.add_internal(sprite) sprite.add_internal(self)
sprites method
Returns a list of all the wizards, that is, all the members of the wizard group
def sprites(self): """get a list of sprites in the group Group.sprite(): return list Returns an object that can be looped over with a 'for' loop. (For now, it is always a list, but this could change in a future version of pygame.) Alternatively, you can get the same information by iterating directly over the sprite group, e.g. 'for sprite in group'. """ return list(self.spritedict)
update method
Let all the Wizards in the wizard group call their own update methods
def update(self, *args): """call the update method of every member sprite Group.update(*args): return None Calls the update method of every member sprite. All arguments that were passed to this method are passed to the Sprite update function. """ for s in self.sprites(): s.update(*args)
draw method
Draw Elves on the Screen
def draw(self, surface): spritedict = self.spritedict surface_blit = surface.blit dirty = self.lostsprites self.lostsprites = [] dirty_append = dirty.append for s in self.sprites(): r = spritedict[s] newrect = surface_blit(s.image, s.rect) if r: if newrect.colliderect(r): dirty_append(newrect.union(r)) else: dirty_append(newrect) dirty_append(r) else: dirty_append(newrect) spritedict[s] = newrect return dirty
The Elf of Demand
Function overview
- image, data for recording images
- rect, record image position
- Speed, moving speed and direction
- Update method, update the location of the wizard
- kill method, deleted from all wizard groups
Elf Group of Requirements
Function overview
- Initialization method
- Add method to add wizards to groups
- Sprites method, returning all sprites list
- The update method, which lets all the Wizards in the group call their own update methods
- draw method, which draws all the image images of the Wizards in the group to the corresponding positions of the screen objects
collision detection
Group and Group Collision
pygame.sprite.groupcollide()
Source code
def groupcollide(groupa, groupb, dokilla, dokillb, collided=None): """detect collision between a group and another group pygame.sprite.groupcollide(groupa, groupb, dokilla, dokillb): return dict Given two groups, this will find the intersections between all sprites in each group. It returns a dictionary of all sprites in the first group that collide. The value for each item in the dictionary is a list of the sprites in the second group it collides with. The two dokill arguments control if the sprites from either group will be automatically removed from all groups. Collided is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area that will be used to calculate the collision. """ crashed = {} SC = spritecollide if dokilla: for s in groupa.sprites(): c = SC(s, groupb, dokillb, collided) if c: crashed[s] = c s.kill() else: for s in groupa: c = SC(s, groupb, dokillb, collided) if c: crashed[s] = c return crashed
Collision between Elves and Groups
pygame.sprite.spritecollide() The return value is a list, a list of members of the Elf Group that have been hit.
Source code
def spritecollide(sprite, group, dokill, collided=None): """find Sprites in a Group that intersect another Sprite pygame.sprite.spritecollide(sprite, group, dokill, collided=None): return Sprite_list Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite. The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group. The collided argument is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision. """ if dokill: crashed = [] append = crashed.append if collided: for s in group.sprites(): if collided(sprite, s): s.kill() append(s) else: spritecollide = sprite.rect.colliderect for s in group.sprites(): if spritecollide(s.rect): s.kill() append(s) return crashed elif collided: return [s for s in group if collided(sprite, s)] else: spritecollide = sprite.rect.colliderect return [s for s in group if spritecollide(s.rect)]
- Begin to formalize ___________
analytical framework
Main Composition of Games
- Game Initialization
- Game cycle
Aircraft games
PlaneGame
attribute
Screen, screen object
Clock, clock object
Elves or Elves Group
Method
__init__(self):
Initialization method
__create_sprites(self):
The Way to Create Elves
Private method
start_game(self):
The method of starting the game includes the following contents:
-
__event_handler(self):
onclick
-
__check_collide(self):
collision detection
-
__update_sprites(self):
Update or draw Elf Group
-
__game_over():
Game over