Technical summary

Posted by khefner on Wed, 08 May 2019 02:15:03 +0200

Install pygame module

Install modules for making games

Installation through pip command

pip install pygame

Game Initialization and Exit



Sign out


Rectangular area object

Four Elements of Rectangular Area

x coordinates, y coordinates, width, height


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


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


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

  1. 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()
  2. Draw the picture on the screen

    Game Window. BLIT
    for example

    Another way is blit.

    Game window. blit (picture, rectangular object)
    for example
  3. 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.

  1. Loading image data means reading pictures into memory to prepare them.

  2. 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)

  3. Display updates, rather turn a page, so that the pictures we just drew are displayed.

Rendering Heroes

Draw heroes according to the drawing trilogy.

  1. Load hero pictures
  2. Draw hero pictures in Windows
  3. update display

Game clock

Game Clock Class


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.


If the background map is not redrawn

The newly drawn pictures will appear in conjunction with the original ones.

event listeners

Event module


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'>


<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


Click on the event type number of the closed window

More event types are numbered in


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



Method of setting timer


Detailed parameters of the method

set_timer(eventid, milliseconds)

Evetid is commonly used
 To specify

 In milliseconds, 1000 is equivalent to one second.

A set of tricks for using timers

  • Define event number
  • set timer
  • Monitoring events




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


        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 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:

sprite groups

Wizard group class, inherited from AbstractGroup class


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):
                # See if sprite is an iterator, like a list or sprite
                # group.
            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):
                elif not self.has_internal(sprite):

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():

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):
       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


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
        for s in groupa:
            c = SC(s, groupb, dokillb, collided)
            if c:
                crashed[s] = c
    return crashed

Collision between Elves and Groups

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):
            spritecollide = sprite.rect.colliderect
            for s in group.sprites():
                if spritecollide(s.rect):

        return crashed

    elif collided:
        return [s for s in group if collided(sprite, s)]
        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



Screen, screen object

Clock, clock object

Elves or Elves Group



Initialization method


The Way to Create Elves

Private method


The method of starting the game includes the following contents:

  • __event_handler(self):


  • __check_collide(self):

    collision detection

  • __update_sprites(self):

    Update or draw Elf Group

  • __game_over():

    Game over

Topics: pip Windows Attribute