13   Sprites and Walls

(Note: Show how to place individual blocks. Blocks in a row, in a column. Use a list.)

13.1   The Simple Physics Engine

Many games with sprites often have “walls” that the character can’t move through. There are rather straight-forward to create.

To begin with, let’s get a couple images. Our character, and a box that will act as a blocking wall. Both images are from kenney.nl.

../../_images/character1.png

images/character.png

../../_images/boxCrate_double.png

images/boxCrate_double.png

In our setup method, we can create a row of box sprites using a for loop. In the code below, our y value is always 200, and we change the x value from 173 to 650. We put a box every 64 pixels because each box happens to be 64 pixels wide.

for x in range(173, 650, 64):
    wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING)
    wall.center_x = x
    wall.center_y = 200
    self.all_sprites_list.append(wall)
    self.wall_list.append(wall)

The Arcade Library has a built in “physics engine.” A physics engine handles the interactions between the virtual physical objects in the game. For example, a physics engine might be several balls running into each other, a character sliding down a hill, or a car making a turn on the road.

Physics engines have made impressive gains on what they can simulate. For our game, we’ll just keep things simple and make sure our character can’t walk through walls.

We can create the physics engine in our setup method with the following code:

self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)

This identifies the player character (player_sprite), and a list of sprites (wall_list) that the player character isn’t allowed to pass through.

self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)

Before, we updated all the sprites with a self.all_sprites_list.update() command. With the physics engine, we will instead update the sprites by using the physics engine’s update:

self.physics_engine.update()

The simple physics engine follows the following algorithm:

  • Move the player in the x direction according to the player’s change_x value.

  • Check the player against the wall list and see if there are any collisions.

  • If the player is colliding:

    • If the player is moving right, set the player’s right edge to the wall’s left edge.
    • If the player is moving left, set the player’s left edge to the wall’s right edge.
    • If the player isn’t moving left or right, print out a message that we are confused how we hit something when we aren’t moving.
  • Then we just do the same thing, except with the y coordinates.

You can see the physics engine source code on GitHub.

Here’s the full example:

sprite_move_walls.py
  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""
Sprite Move With Walls

Simple program to show basic sprite usage.

Artwork from http://kenney.nl
"""
import arcade

SPRITE_SCALING = 0.5

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

MOVEMENT_SPEED = 5


class MyApplication(arcade.Window):
    """ Main application class. """

    def __init__(self, width, height):
        """
        Initializer
        """
        super().__init__(width, height)
        # Sprite lists
        self.all_sprites_list = None
        self.coin_list = None

        # Set up the player
        self.score = 0
        self.player_sprite = None
        self.wall_list = None

        # This variable holds our simple "physics engine"
        self.physics_engine = None

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists
        self.all_sprites_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()

        # Set up the player
        self.score = 0
        self.player_sprite = arcade.Sprite("images/character.png",
                                           SPRITE_SCALING)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 64
        self.all_sprites_list.append(self.player_sprite)

        # -- Set up the walls
        # Create a row of boxes
        for x in range(173, 650, 64):
            wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING)
            wall.center_x = x
            wall.center_y = 200
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)

        # Create a column of boxes
        for y in range(273, 500, 64):
            wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING)
            wall.center_x = 465
            wall.center_y = y
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)

        # Create the physics engine. Give it a reference to the player, and
        # the walls we can't run into.
        self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite,
                                                         self.wall_list)

        # Set the background color
        arcade.set_background_color(arcade.color.AMAZON)

    def on_draw(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        arcade.start_render()

        # Draw all the sprites.
        self.all_sprites_list.draw()

    def on_key_press(self, key, modifiers):
        """Called whenever a key is pressed. """

        if key == arcade.key.UP:
            self.player_sprite.change_y = MOVEMENT_SPEED
        elif key == arcade.key.DOWN:
            self.player_sprite.change_y = -MOVEMENT_SPEED
        elif key == arcade.key.LEFT:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif key == arcade.key.RIGHT:
            self.player_sprite.change_x = MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key. """

        if key == arcade.key.UP or key == arcade.key.DOWN:
            self.player_sprite.change_y = 0
        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player_sprite.change_x = 0

    def animate(self, delta_time):
        """ Movement and game logic """

        # Call update on the player, using the physics engine.
        self.physics_engine.update()


window = MyApplication(SCREEN_WIDTH, SCREEN_HEIGHT)
window.setup()

arcade.run()

13.2   Using a View Port for Scrolling

What if one screen isn’t enough to hold your maze of walls? We can have a world that is larger than just our window. We do this by adjusting the view port. Normally coordinate (0, 0) is the lower left corner of our screen. We can change that! We could have an entire world stretch from (0, 0) to (3000, 3000), and have a smaller view port that was 800x640 that scrolled around that.

The command for using the view port is set_viewport. This command takes four arguments. The first two are the left and bottom boundaries of the window. By default these are zero. That is why (0, 0) is in the lower left of the screen. The next two commands are the top and right coordinates of the screen. By default these are the screen width and height, minus one. So an 800 pixel-wide window would have x-coordinates from 0 - 799.

A command like this would shift the whole “view” of the window 200 pixels to the right:

arcade.set_viewport(200, 0, 200 + SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1)

So with a 800 wide pixel window, we would show x-coordinates 200 - 999 instead of 0 - 799.

Instead of hard-coding the shift at 200 pixels, we need to use a variable and have rules around when to shift the view. In our next example, we will create two new instance variables in our application class that hold the left and bottom coordinates for our view port. We’ll default to zero.

self.view_left = 0
self.view_bottom = 0

We are also going to create two new constants. We don’t want the player to reach the edge of the screen before we start scrolling. Because then the player would have no idea where she is going. In our example we will set a “margin” of 40 pixels. When the player is 40 pixels from the edge of the screen, we’ll move the view port so she can see at least 40 pixels around her.

VIEWPORT_MARGIN = 40

Next, in our update method, we need to see if the user has moved too close to the edge of the screen and we need to update the boundaries.

# Keep track of if we changed the boundary. We don't want to call the
# set_viewport command if we didn't change the view port.
changed = False

# Scroll left
left_bndry = self.view_left + VIEWPORT_MARGIN
if self.player_sprite.left < left_bndry:
    self.view_left -= left_bndry - self.player_sprite.left
    changed = True

# Scroll right
right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_MARGIN
if self.player_sprite.right > right_bndry:
    self.view_left += self.player_sprite.right - right_bndry
    changed = True

# Scroll up
top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN
if self.player_sprite.top > top_bndry:
    self.view_bottom += self.player_sprite.top - top_bndry
    changed = True

# Scroll down
bottom_bndry = self.view_bottom + VIEWPORT_MARGIN
if self.player_sprite.bottom < bottom_bndry:
    self.view_bottom -= bottom_bndry - self.player_sprite.bottom
    changed = True

# Make sure our boundaries are integer values. While the view port does
# support floating point numbers, for this application we want every pixel
# in the view port to map directly onto a pixel on the screen. We don't want
# any rounding errors.
self.view_left = int(self.view_left)
self.view_bottom = int(self.view_bottom)

# If we changed the boundary values, update the view port to match
if changed:
    arcade.set_viewport(self.view_left,
                        SCREEN_WIDTH + self.view_left - 1,
                        self.view_bottom,
                        SCREEN_HEIGHT + self.view_bottom - 1)

The full example is below:

sprite_move_scrolling.py
  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""
Use sprites to scroll around a large screen.

Simple program to show basic sprite usage.

Artwork from http://kenney.nl
"""
import random
import arcade

SPRITE_SCALING = 0.5

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# How many pixels to keep as a minimum margin between the character
# and the edge of the screen.
VIEWPORT_MARGIN = 40

MOVEMENT_SPEED = 5


class MyApplication(arcade.Window):
    """ Main application class. """

    def __init__(self, width, height):
        """
        Initializer
        """
        super().__init__(width, height)
        # Sprite lists
        self.all_sprites_list = None
        self.coin_list = None

        # Set up the player
        self.score = 0
        self.player_sprite = None
        self.wall_list = None
        self.physics_engine = None
        self.view_bottom = 0
        self.view_left = 0

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists
        self.all_sprites_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()

        # Set up the player
        self.score = 0
        self.player_sprite = arcade.Sprite("images/character.png",
                                           0.4)
        self.player_sprite.center_x = 64
        self.player_sprite.center_y = 270
        self.all_sprites_list.append(self.player_sprite)

        # -- Set up several columns of walls
        for x in range(200, 1650, 210):
            for y in range(0, 1000, 64):
                # Randomly skip a box so the player can find a way through
                if random.randrange(5) > 0:
                    wall = arcade.Sprite("images/boxCrate_double.png",
                                         SPRITE_SCALING)
                    wall.center_x = x
                    wall.center_y = y
                    self.all_sprites_list.append(wall)
                    self.wall_list.append(wall)

        self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite,
                                                         self.wall_list)

        # Set the background color
        arcade.set_background_color(arcade.color.AMAZON)

        # Set the view port boundaries
        # These numbers set where we have 'scrolled' to.
        self.view_left = 0
        self.view_bottom = 0

    def on_draw(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        arcade.start_render()

        # Draw all the sprites.
        self.all_sprites_list.draw()

        margin_bottom = 10
        margin_left = 20
        text = f"Bottom left corner: ({self.view_left}, {self.view_bottom})"
        arcade.draw_text(text,
                         margin_left + self.view_left,
                         margin_bottom + self.view_bottom,
                         arcade.color.WHITE)

    def on_key_press(self, key, modifiers):
        """Called whenever a key is pressed. """

        if key == arcade.key.UP:
            self.player_sprite.change_y = MOVEMENT_SPEED
        elif key == arcade.key.DOWN:
            self.player_sprite.change_y = -MOVEMENT_SPEED
        elif key == arcade.key.LEFT:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif key == arcade.key.RIGHT:
            self.player_sprite.change_x = MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key. """

        if key == arcade.key.UP or key == arcade.key.DOWN:
            self.player_sprite.change_y = 0
        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player_sprite.change_x = 0

    def animate(self, delta_time):
        """ Movement and game logic """

        # Call update on all sprites (The sprites don't do much in this
        # example though.)
        self.physics_engine.update()

        # --- Manage Scrolling ---

        # Track if we need to change the viewport

        changed = False

        # Scroll left
        left_bndry = self.view_left + VIEWPORT_MARGIN
        if self.player_sprite.left < left_bndry:
            self.view_left -= left_bndry - self.player_sprite.left
            changed = True

        # Scroll right
        right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_MARGIN
        if self.player_sprite.right > right_bndry:
            self.view_left += self.player_sprite.right - right_bndry
            changed = True

        # Scroll up
        top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN
        if self.player_sprite.top > top_bndry:
            self.view_bottom += self.player_sprite.top - top_bndry
            changed = True

        # Scroll down
        bottom_bndry = self.view_bottom + VIEWPORT_MARGIN
        if self.player_sprite.bottom < bottom_bndry:
            self.view_bottom -= bottom_bndry - self.player_sprite.bottom
            changed = True

        self.view_left = int(self.view_left)
        self.view_bottom = int(self.view_bottom)

        if changed:
            arcade.set_viewport(self.view_left,
                                SCREEN_WIDTH + self.view_left - 1,
                                self.view_bottom,
                                SCREEN_HEIGHT + self.view_bottom - 1)


window = MyApplication(SCREEN_WIDTH, SCREEN_HEIGHT)
window.setup()

arcade.run()