This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

Before starting the character movement, optimize the background to avoid eye injury during debugging (· ∀ · (· ∀ · (· ∀ · *).

def update(self) :
    self.draw_background()

    self.screen.blit(self.player.image, self.player.rect)

    self.player.update()
    self.display.update()
Copy the code

Self.draw_background () : update (); self.draw_background() : update ();

def draw_background(self) :
    self.screen.fill(THECOLORS['white'])
    for i in range(6):
        self.screen.blit(self.tree, [150 * i, 0])
    for i in range(18):
        self.screen.blit(self.road, [50 * i, 300])
        self.screen.blit(self.dirt, [50 * i, 350])
Copy the code

In the background drawing function, we also take out all the resource loading statements (put them in __init__) as a property of the Game, so that we only need to read them once to get the resources directly from memory, instead of repeatedly reading the file, which causes the speed to slow down. (If the project is bigger, we should clean up unnecessary resources in time, in case of OOM)

This is the optimized background picture (the material is pulled from the project next door (~ ~ ▽ ~) ~).

One, listen to the button

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                print("I hit the a button.")
            elif event.key == pygame.K_d:
                print("I hit the D button.")
        elif event.type == pygame.KEYUP:
            print("Button release")
Copy the code

The key listener and the previous close listener are both part of the PyGame event listener, so just add the key listener to the previous while loop event listener.

With event.key, we can see the key code (integer type) being pressed, and by matching pyGame constants, using a bunch of if statements, we can listen for the key we want, and make different responses for different keys.

Second, the realization of character movement

In the previous article, we translated the characters by giving them a starting speed and using the update function to change the coordinates of the characters according to the speed when updating the game frame.

So whenever the move button is pressed, we will give the character a horizontal speed, the speed will be zero after the release of the button, can not achieve the character’s movement?

  • Print (” press a “) -> self.player.speed = -5
  • Print (” press d “) -> self.player.speed = 5
  • Print (” release “) -> self.player.speed = 0

Start the program by replacing the above code with the following:

Three, moving action

Just a simple pan, that is too monotonous, a series of actions to the characters can make the game lively.

First of all, load all the images first, and store them in an array, which is convenient for us to call in a loop later and import them in a more convenient way:

Then add the index field to the Player to record which image the person’s action is in.

def update(self) :
    if self.speed:
        self.rect.left += self.speed
        self.index = (self.index + 1) % len(self.walk_images)
    else:
        self.index = 0
    self.image = self.walk_images[self.index]
Copy the code

Modify the update function of Player to keep the code of character x-coordinate updating with speed unchanged, and conduct a loop for the character walking animation (add the array and take the remainder length to realize the loop, while keeping the array within bounds).

The image index is set to 0 when the speed is 0, which shows the character standing on the spot after releasing the move key.

The realization effect is as follows: