Python Arcade Read Keyboard and Postgres

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Welcome to part 3 of a multi-part set of articles on building a 1980’s style top-down view video game. In this part we learn to use Python Arcade to read the keyboard and Postgres for saving and retrieving screens and Sprite location data.

In this lesson we learn how to get input from the keyboard. We’ll back track over some of parts 1 and 2 of this series and add some more.

Prerequisites

  • IMPORTANT: All source code, image files, and sound files are available here for download. For each lesson we are copying only parts of that full source code into the current lesson and analyzing it, explaining how that portion works.

  • Be sure to read part 1 and part 2 of this series where we get some of the basics out of the way.

  • Use PIP to install the arcade, datetime, flask, math, os, psycopg2, pyautogui, and random frameworks. As we progress through each part (lesson), we’ll use more functions that require these libraries (frameworks).

  • Arcade framework documentation. The Python library we will use for much of the purely game-related functionality of this game is Arcade.

  • Attain a basic understanding of Python Arcade resources.

Before we dive in to reading the keyboard, let’s do a brief recap by creating a screen and placing a player on that screen.

Create a screen with Arcade

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# install the arcade framework.
import arcade

# Initialize variables for screen width, screen height, and screen title.
screen_width = 1200
screen_height = 900
screen_title = "Pyngo Skater"

# Open a window for game play.
arcade.open_window(screen_width, screen_height, screen_title)

# Set screen color for the background.
arcade.set_background_color(arcade.color.WHITE)

# Initialize and set an image for a Sprite.
spritePlayer = arcade.Sprite("sprites/penguin.png")

# Set up variables for player coordinates.
#   Divide screen width by two to get the horizontal center of the screen
x = int(screen_width / 2)
#   Divide screen height by two to get the vertical center of the screen
y = int(screen_height / 2)

# Set Player Sprite position.
spritePlayer.set_position(x, y)

# Draw the Player Sprite.
spritePlayer.draw()

# Keep the screen open until the player closes it.
arcade.run()

Analysis of the above code:

  • import arcade: The library called “arcade” affords us with many functions useful in making a video game.

  • screen_width = 1200: Initializing a variable to store the screen width. We are using a width of 1200 pixels.

  • screen_height = 900: Initializing a variable to store the screen height. We are using a height of 900 pixels.

  • screen_title = “Pyngo Skater”: Initializing a variable for the caption that will go in the screen’s title bar.

  • arcade.open_window: The open_window function uses 3 parameters; width, height, and caption/title. Width and height must be integer. Caption/title must be a text string encapsulated in quotes or semi-quotes.

  • arcade.set_background_color: The set_background_color function needs one parameter, which is color. The color can be set using arcade constants as you see above or as an RGBA value.

  • arcade.Sprite: This line of code creates a Sprite, names it “spritePlayer”, and gives it an image.

  • x = int(screen_width / 2): Initialize a variable to handle the distance from the left side of the screen.

  • y = int(screen_height / 2): Initialize a variable to store the distance from the bottom of the screen. So zero would be the very bottom and 900 would be the very top. I want to emphasize that this is “from the bottom” because some other game screen systems start from the top.

  • spritePlayer.set_position: Sets the Player Sprite’s coordinate position to be at the x and y coordinates we had set to be in the center of the screen.

  • spritePlayer.draw: Makes the Player’s Sprite visible on the game window.

  • arcade.run: Runs the current code.

Now that we have recapped how to set up a game environment and added a bit more flavor, we will look at how to read the keyboard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# When any key is pressed, this event fires:
def on_key_press(self, symbol, modifiers):
    # "symbol" is the key being pressed by the user.
    # If the player hit the space bar and is NOT respawning, throw a snow ball.
    if symbol == arcade.key.SPACE and not self.player_sprite.respawning:
        snowball_sprite = SnowballSprite("./resources/images/snowball.png", SCALE)
        # Name this object.
        snowball_sprite.guid = "Snowball"
        # Assign the snowball a velocity using speed and angle.
        snowball_speed = 12
        snowball_sprite.change_y = \
            math.cos(math.radians(self.player_sprite.angle)) * snowball_speed
        snowball_sprite.change_x = \
            -math.sin(math.radians(self.player_sprite.angle)) \
            * snowball_speed
        # Set/change the snowball's position on the screen
        snowball_sprite.center_x = self.player_sprite.center_x
        snowball_sprite.center_y = self.player_sprite.center_y
        # Update the snowball's position. Required.
        snowball_sprite.update()
        # Add the new snowball to our list of all game Sprites.
        self.list_all_sprites.append(snowball_sprite)
        # Add the new snowball to our list of snowball Sprites
        #   because we can have more than one on the screen at a time.
        self.list_snowballs.append(snowball_sprite)
        # Later we will explore how sounds work and set them up.
        arcade.play_sound(self.sound_snowball_throw)

    # PLAYER ANGLE CHANGE
    # If the user pressed the left cursor control key or the "A" key,
    # change player angle by 3 degrees (counter clockwise)
    if symbol == arcade.key.LEFT or symbol == arcade.key.A:
        self.player_sprite.change_angle = 2
    # Same as above but clockwise
    elif symbol == arcade.key.RIGHT or symbol == arcade.key.D:
        self.player_sprite.change_angle = -2
    # If they pressed the up cursor or the "W" key,
    # increase thrust.
    elif symbol == arcade.key.UP or symbol == arcade.key.W:
        self.player_sprite.thrust = 0.15
    # If they pressed the down cursor or the "S" key,
    # decrease thrust toward opposite direction.
    elif symbol == arcade.key.DOWN or symbol == arcade.key.S:
        self.player_sprite.thrust = -.2
    # Increase game difficulty.
    #   We chose "equals" key instead of "plus" key here
    #   so Player does not have to use the SHIFT key.
    elif symbol == arcade.key.EQUAL:
        self.player_sprite.difficulty += 1
        if self.player_sprite.difficulty > 15:
            self.player_sprite.difficulty = 15
    # Decrease game difficulty.
    elif symbol == arcade.key.MINUS:
        self.player_sprite.difficulty -= 1
        if self.player_sprite.difficulty < 1:
            self.player_sprite.difficulty = 1

# When any movement key is released.
def on_key_release(self, symbol, modifiers):
    # If LEFT cursor or "A" UNpressed: Set change angle to zero
    if symbol == arcade.key.LEFT or symbol == arcade.key.A:
        self.player_sprite.change_angle = 0
    # If RIGHT cursor or "D" UNpressed: Set change angle to zero
    elif symbol == arcade.key.RIGHT or symbol == arcade.key.D:
        self.player_sprite.change_angle = 0
    # If UP cursor or "W" UNpressed: Set thrust to zero
    elif symbol == arcade.key.UP or symbol == arcade.key.W:
        self.player_sprite.thrust = 0
    # If DOWN cursor or "S" UNpressed: Set thrust to zero
    elif symbol == arcade.key.DOWN or symbol == arcade.key.S:
        self.player_sprite.thrust = 0

CONCLUSION

In this part 3 of our multi-part set of tutorials for building a top-down view video game, we learned to use the Python Arcade framework to get input from the keyboard and process that input into changes in the angle and position of the player’s Sprite.

In the next part 4, we will learn take this further with more code to process the player Sprite’s movement around the screen. After that, we’ll work on enemy movement, bullet firing, detecting collisions, adding sound effects, keeping score, and allowing the player to change game difficulty and game speed.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.