Python – Project – Game 3 – Sprite? Smurf?


Wait a minute. We just made a moving picture

Project source code

I don’t know if you have found that we just drew a moving picture, just a picture!!! That’s all. If there are 100, 10000 + pieces? So we’re so tall?

Don’t worry, pyGame provides us with a solution – sprites and sprites

spirit? Elves? Smurf? Pikachu?


In the game development, the object to display the image is the spirit

  1. Don’t worry. Let’s take a look first. It is indeed a class. Here is its class diagram

  1. effect:
    • pygame.sprite.Sprite——StorageImage dataandPosition rectThe * * object of
    • pygame.sprite.Group , to store the pygame.sprite.Sprite Created objects, unified in the main window program for drawing
  2. Analyze the composition of this class
    • spiritThere needs to beTwo important attributes
    • imageThe image to display,rectThe location of the image to be displayed on the screen
    • defaultupdate()Method does nothing. Subclasses can override this method to update the wizard location every time the screen is refreshed
  3. Be careful of the pit!
    • pygame.sprite.SpriteThey didn’t provide itimageandrectTwo properties
    • It requires programmers topygame.sprite.SpriteDerived subclass
    • And in theSubclassOfInitialization methodSettingimageandrectattribute

Spirit group

  1. OneSpirit groupCan contain multiplespiritobject
  2. callSpirit groupObject’supdate()method
    • sureautomaticcallEvery elf in the groupOfupdate()method
  3. callSpirit groupObject’sDraw (screen object)method
    • You canEvery elf in the groupOfimageDraw inrectposition
  4. Generally speaking, it is unified command and action, but each item has its own independent movement method and attribute
Group(*sprites) -> Group

Example code:

#1. New ` plane_ `Documents
#2. The definition 'gamesprite' is inherited from` pygame.sprite.Sprite `
import pygame

#3. Written in brackets means inheriting the parent class
class GameSprite(pygame.sprite.Sprite):
    "Game spirit in the aircraft war, write code according to the designed UML"
#Note that the init method is to be rewritten here. We pass parameters in the init initialization method (line function)
    def __init__(self, image_name, speed=1):

        #Call the initialization method of the parent class. When our parent class is not the object base class, we must call the super () object to call the initialization init method of the parent class

        #Define the properties of the object, which record the image position, speed and movement mode of the sprite
        #Load image
        self.image = pygame.image.load(image_name)
        #Set size
        self.rect = self.image.get_rect()
        #Record the speed
        self.speed = speed

    def update(self):

        #Move in the vertical direction of the screen
        self.rect.y += self.speed

How to use them in our previous main program?

what? You don’t know what our main program is? Well, I forgot to tell you that our main program is the program we wrote to draw windows,

In fact, this is also very simple, you only need to import the package in the main program of the game
How to complete the “enemy” wizard, and let it move, and then put them into the game cycle on the line

  1. be careful:
Let's first clarify the division of labor between the elves and the elves
1. Spirit
    *Encapsulate * * image * *, * * position rect * * and * * speed**
    *Provide the 'update()' method, and * * update the location rect according to the game requirements**
2. Spirit group
    *Contains * * multiple * * sprite objects**
    *The 'Update' method allows all sprites in the wizard group to call the 'Update' method to update the location
    *The 'draw (screen)' method is used to draw all the sprites in the sprite group on the 'screen'
  1. Complete code example
import pygame
#You need to import form and import. When using inprom, you need to use the tools provided by the module directly when using form.
#They all implement the function of import module
from plane_sprites import *

#Game initialization

#Create game window 480 * 700
screen = pygame.display.set_mode((480, 700))

#Draw background image
bg = pygame.image.load("./images/background.png")
screen.blit(bg, (0, 0))
# pygame.display.update()

#Drawing a hero's plane
hero = pygame.image.load("./images/me1.png")
screen.blit(hero, (150, 300))

#The update method can be called uniformly after all drawing work is completed

#Create clock object
clock = pygame.time.Clock()

#1. Define rect to record the initial position of the aircraft
hero_rect = pygame.Rect(150, 300, 102, 126)

#Start our business logic
#The spirit of creating enemy aircraft
#Enemy fighter target
enemy = GameSprite("./images/enemy1.png")
enemy1 = GameSprite("./images/enemy1.png", 2)
#The spirit of creating enemy aircraft组,我们可以使用多值的方式传递精灵组合,有了这个精灵组,我们就可以直接使用精灵的方法了,一次性的绘制所有的图像
enemy_group = pygame.sprite.Group(enemy, enemy1)

    #Let the wizard group call two methods
    #Update - let all sprites in the group update the location. This is the update location
    # enemy_group.update()

    #Draw - draw all the sprites on screen. This is drawing
    # enemy_group.draw(screen)
    #We just call it once, and now we throw it into our game loop

#Game cycle > means the official start of the game!
while True:

    #You can specify how often code is executed inside the body of the loop

    #Monitoring events
    for event in pygame.event.get():

        #Determine whether the event type is an exit event
        if event.type == pygame.QUIT:
            Print ("game exit...")

            #Unload all modules of quit

            #Exit() directly terminates the currently executing program

    #2. Modify the position of the aircraft
    hero_rect.y -= 1

    #Determine the position of the aircraft
    if hero_rect.y <= 0:
        hero_rect.y = 700

    #3. Call BLIT method to draw image
    screen.blit(bg, (0, 0))
    screen.blit(hero, hero_rect)

    #Let the sprite group call two methods
    #Update - let all the sprites in the group update the location. This is the update location

    #Draw - draws all the sprites on screen. This is drawing

    #4. Call the update method to update the display


Recommended Today

Understand mybatis step by step through the project

Reprint please be sure to indicate the source, original is not easy! Related articles:Understand mybatis < 1 > step by step through the project All code address of the project:Github-Mybatis Mybatis solves the problem of JDBC programming 1. The frequent creation and release of database links results in the waste of system resources, which affects […]