Create classes directory to store classes.

Two, will write yesterday’s code for a simple encapsulation

I’m going to post the code, write a Game class, and add the background creation that I did yesterday

import pygame
from pygame.color import THECOLORS

class Game:
    def __init__(self, width=800, height=600) :
        self.display = pygame.display
        self.screen = pygame.display.set_mode((width, height))

    def update(self) :
        self.screen.fill(THECOLORS['white'])
        filename = './resourse/background/tree.png'
        picture = pygame.image.load(filename)
        for i in range(6):
            self.screen.blit(picture, [150 * i, 0])
        self.display.update()

    def run(self) :
        self.update()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    Exit the program after receiving the exit time
                    exit()
Copy the code
  • Start with the __init__ function, which is a python class’s own magic, right? ! Functions. Python can instantiate the designed class into an object by means of functions, and can pass parameters like functions to facilitate different requirements.
  • Note that in Python, the first field of an embedded function represents the object itself by default and is often represented by self (which most compilers fill out automatically).
  • After self, we can add the parameters we want. In this case, I left the window width width and height and set the default values (default values can only be set after the parameters without default values).

Here is the use of the __init__ function:

  • Empty the original main.py as our program entry and use import to import the Game class you just created into main.py.

  • This is instantiated using Game() and stored using the variable Game. Since we set the initial value, it’s ok to write Game().

  • Then there’s update(), which currently only populates the background when run() starts executing;

  • Next, the screen will be refreshed through this function, the detailed operation will be introduced in the following sections.

  • Finally, use run() as the program’s start function and implement persistence within that function.

The window is exactly the same as before:

# main.py
from classes.game import Game

if __name__ == '__main__':
    game = Game(800.600)
    game.run()
Copy the code

3. Create a role

class Player(pygame.sprite.Sprite) :
    def __init__(self) :
        self.image = pygame.image.load("./resourse/player/walk/1.png")
        self.rect = self.image.get_rect()
        self.speed = 5

    def update(self) :
        self.rect.left += self.speed
Copy the code
  • Create a new Player class under Classes that inherits from PyGame’s Sprite class (there are some easy interfaces to use).
  • Using self.image.get_rect(), we can get the width and length and coordinates of the image, which will be used in subsequent collision detection.
  • Here we implement the minimal translation of the character, using update() to update the coordinates, collision detection and key control to continue drawing the pie (The fog).

Before you import the character into the window, you need to add a new function to the Game class (some of the code has been omitted) :

class Game:
    def __init__(self, width, height) :. self.clock = pygame.time.Clock() self.player = Player()def run(self) :
        while True:... self.update() self.clock.tick(30)
Copy the code
  • Add pygame.time.clock () to __init__ and add self.clock.tick(30) to the loop.
  • Represents a maximum frame rate of 30 frames per second, and the program will delay for 1 30s after one cycle, during which we can complete the generation of the next frame.
  • (By the way, instantiate the Player and throw it into the Game).
def update(self) :
    self.screen.fill(THECOLORS['white'])
    filename = './resourse/background/tree.png'
    picture = pygame.image.load(filename)
    for i in range(6):
        self.screen.blit(picture, [150 * i, 0])
        
    self.screen.blit(self.player.image, self.player.rect)
    self.player.update()
    
    self.display.update()
Copy the code
  • Add two lines of code to update()self.screen.blit(self.player.image, self.player.rect)andself.player.update(), which are used to make the object appear on the screen and refresh the state of the object respectively.

Update the state of the object in a loop and display it on the screen:

Run the program and you can see the movement of the character.