In part 4 of this series, learn how to code the control of a mobile game character.

In the first article in this series, I explained how to create a simple text-based dice game using Python. In Part 2, I showed you how to build a game from scratch, starting with the environment in which it was created. Then in the third part, we created a player goblin and made it spawn in your (not empty) game world. You may have noticed that if you can’t move your character, the game isn’t that much fun. In this article, we will use Pygame to add keyboard controls so that you can control the movement of your character.

There are many functions in Pygame that you can use to add controls (other than the keyboard), but if you’re typing Python code, you must have a keyboard, which will be the controls we’ll use next. Once you understand the keyboard controls, you can explore other options on your own.

In the second article of this series, you created a button for exiting the game, and the principles for moving your character are the same. However, getting your character to move is a little more complicated.

Let’s start with the easy part: setting up the controller buttons.

Set buttons for the goblins that control you

Open your Python game script in IDLE, Ninja-IDE, or a text editor.

Because the game needs to “listen” for keyboard events all the time, your code needs to run continuously. Do you know where to put code that needs to run continuously throughout the game cycle?

If you answered “in the main loop,” then you are correct! Remember that unless the code is in a loop, it will (most of the time) only run once. If it is written in a class or function that is never used, it may not run at all.

To make Python listen for incoming keys, add the following code to the main loop. The current code does not produce any effect, so use a print statement to signal success. This is a common debugging technique.

while main == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a') :print('left')
            if event.key == pygame.K_RIGHT or event.key == ord('d') :print('right')
            if event.key == pygame.K_UP or event.key == ord('w') :print('jump')

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a') :print('left stop')
            if event.key == pygame.K_RIGHT or event.key == ord('d') :print('right stop')
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False    
Copy the code

Some prefer using the keyboard letters W, A, S, and D to control the player character, while others prefer using the arrow keys. So make sure you include both options.

Note: It is important to consider all users at the same time when you are programming. If you write code just to run it yourself, chances are you’ll be the only user of the program you write. More importantly, if you want to get paid to write code, you should write code that everyone can run. Giving your users options, such as the option to use arrow keys or WASD, is a sign of a good programmer.

Start your game in Python and view the output of the console window when you press up, down, left or right or the A, D, and W keys.

$ python ./your-name_game.py
  left
  left stop
  right
  right stop
  jump
Copy the code

This verifies that Pygame can detect keys correctly. Now it’s time to complete the difficult task of making the goblin move.

Write the player movement function

To make your goblin move, you must create an attribute for your goblin that represents movement. This variable is set to 0 when your goblin is not moving.

If you are animating your goblin, or if you decide to animate it in the future, you will also have to track frames to keep the walking loop on track.

Create the following variables in the Player class. The first two lines serve as context control (you already have them in your code if you keep following along), so just add the last three lines:

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0 # moving in the X direction
        self.movey = 0 # in the Y direction
        self.frame = 0 Frame # count
Copy the code

With these variables set up, it’s time to code for goblin movement.

The player goblin does not need to respond to the controls at all times, and sometimes it is not moving. The code that controls goblins is just a small part of the list of things a player goblin can do. In Python, when you want to make an object do something independent of the rest of the code, you can put your new code into a function. Python functions begin with the keyword def, which stands for defining functions.

Create the following function in your Player class to add a few pixels to your goblin’s position on the screen. Don’t worry about adding a few pixels just yet, this will be determined later in the code.

    def control(self,x,y):
        ' ''Control player movement'' '
        self.movex += x
        self.movey += y
Copy the code

To move goblins in Pygame, you need to tell Python to redraw goblins in a new location, and where that new location is.

Because the Player goblin is not always on the move, updates need only be a function in the Player class. Add this function to the control function you created earlier.

To make it look like the goblin is walking (or flying, or whatever your goblin is supposed to do), you need to change its position on the screen when you press the appropriate key. To move it around the screen, you need to redefine its position (specified by the self.rect.x and self.rect.y attributes) to the current position plus any moveX or Movey that has been applied. (The number of pixels moved will be set later.)

    def update(self):
        ' ''Update goblin position'' '
        self.rect.x = self.rect.x + self.movex        
Copy the code

Do the same for the Y direction:

        self.rect.y = self.rect.y + self.movey
Copy the code

For animation, advance the animation frame when the goblin moves and use the corresponding animation frame as the player’s image:

        # Move left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[self.frame//ani]

        # Move right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[(self.frame//ani)+4]
Copy the code

Set a variable that tells the code how many pixels to add to your goblin position, and then use this variable when triggering your player goblin function.

First, create this variable in your Settings section. In the following code, the first two lines are context references, so just add a third line to your script:

player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10  # How many pixels to move
Copy the code

Now that you have the appropriate functions and variables, use your buttons to trigger the function and pass the variables to your goblin.

To do this, replace the print statement in the main loop with the name of the player goblin (Player), the function (.control), and the number of steps you want the player goblin to take along the X and Y axes in each loop.

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(steps,0)
            if event.key == pygame.K_UP or event.key == ord('w') :print('jump')

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(-steps,0)
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False
Copy the code

Remember, the Steps variable represents how many pixels your goblin moves when a button is pressed. If your goblin’s position is increased by 10 pixels when you press D or the right arrow key. So when you stop pressing this key, you must subtract 10 (-steps) to get your goblin’s momentum back to 0.

Try your game now. Note: It will not work as you expect.

Why can’t your goblins move? The update function has not been called for the main loop.

Add the following code to your main loop to tell Python to update your player’s goblin location. Add the commented line:

    player.update()  # Update player position
    player_list.draw(world)
    pygame.display.flip()
    clock.tick(fps)
Copy the code

Restart your game again to witness your player goblins move back and forth across the screen at your command. There’s no vertical movement yet, because this part of the function is controlled by gravity, but that’s a lesson for another article.

In the meantime, if you have a joystick, try reading the documentation for the Joystick module in Pygame and see if you can make your goblins move this way. Or, see if you can interact with your goblin via a mouse.

Most of all, have fun!

All of the code used in this tutorial

For ease of reference, here is all the code used so far in this series.

#! /usr/bin/env python3
# Draw the world
# Add player and player control
# Add player movement controls

# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.

import pygame
import sys
import os

' ''
Objects
'' '

class Player(pygame.sprite.Sprite):
    ' ''Spawn player'' '
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0
        self.movey = 0
        self.frame = 0
        self.images = []
        for i inRange (1, 5) : img = pygame. Image. The load (OS) path) join ('images'.'hero' + str(i) + '.png')).convert() img.convert_alpha() img.set_colorkey(ALPHA) self.images.append(img) self.image = self.images[0] self.rect =  self.image.get_rect() def control(self,x,y):' ''Control player movement'' '
        self.movex += x
        self.movey += y

    def update(self):
        ' ''Update goblin position'' '

        self.rect.x = self.rect.x + self.movex
        self.rect.y = self.rect.y + self.movey

        # Move left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[self.frame//ani]

        # Move right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[(self.frame//ani)+4]


' ''set'' '
worldx = 960
worldy = 720

fps = 40        Frame refresh rate
ani = 4        # animation loopClock = pygame.time.clock () pygame.init() main = True BLUE = (25,25,200) BLACK = (23,23,23) WHITE = (254,254,254) ALPHA = (0,255,0) world = pygame.display.set_mode([worldx,worldy]) backdrop = pygame.image.load(os.path.join('images'.'stage.png')).convert()
backdropbox = world.get_rect()
player = Player()   # Generate players
player.rect.x = 0
player.rect.y = 0
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10      # Movement speed

' ''Main loop'' '
while main == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(steps,0)
            if event.key == pygame.K_UP or event.key == ord('w') :print('jump')

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(-steps,0)
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False

# world.fill(BLACK)
    world.blit(backdrop, backdropbox)
    player.update()
    player_list.draw(world) # Update player position
    pygame.display.flip()
    clock.tick(fps)
Copy the code

You’ve learned a lot, but there’s still a lot you can do. In the next few articles, you will implement adding enemy goblins, simulating gravity, and more. In the meantime, practice Python!


Via: opensource.com/article/17/…

By Seth Kenlon (lujun9972

This article is originally compiled by LCTT and released in Linux China