Step 2 - Add Sprites

Our next step is to add some sprites, which are graphics we can see and interact with on the screen.

../../_images/listing_02.png

Setup vs. Init

In the next code example, 02_draw_sprites, we’ll have both an __init__ method and a setup.

The __init__ creates the variables. The variables are set to values such as 0 or None. The setup actually creates the object instances, such as graphical sprites.

I often get the very reasonable question, “Why have two methods? Why not just put everything into __init__? Seems like we are doing twice the work.” Here’s why. With a setup method split out, later on we can easily add “restart/play again” functionality to the game. A simple call to setup will reset everything. Later, we can expand our game with different levels, and have functions such as setup_level_1 and setup_level_2.

Sprite Lists

Sprites are managed in lists. The SpriteList class optimizes drawing, movement, and collision detection.

We are using three logical groups in our game. A player_list for the player. A wall_list for walls we can’t move through. And finally a coin_list for coins we can pick up.

self.player_list = arcade.SpriteList()
self.wall_list = arcade.SpriteList(use_spatial_hash=True)
self.coin_list = arcade.SpriteList(use_spatial_hash=True)

Sprite lists have an option to use something called “spatial hashing.” Spatial hashing speeds the time it takes to find collisions, but increases the time it takes to move a sprite. Since I don’t expect most of my walls or coins to move, I’ll turn on spatial hashing for these lists. My player moves around a lot, so I’ll leave it off for her.

Add Sprites to the Game

To create sprites we’ll use the arcade.Sprite class. We can create an instance of the sprite class with code like this:

self.player_sprite = arcade.Sprite("images/player_1/player_stand.png", CHARACTER_SCALING)

The first parameter is a string or path to the image you want it to load. An optional second parameter will scale the sprite up or down. If the second parameter (in this case a constant CHARACTER_SCALING) is set to 0.5, and the the sprite is 128x128, then both width and height will be scaled down 50% for a 64x64 sprite.

Next, we need to tell where the sprite goes. You can use the attributes center_x and center_y to position the sprite. You can also use top, bottom, left, and right to get or set the sprites location by an edge instead of the center. You can also use position attribute to set both the x and y at the same time.

self.player_sprite.center_x = 64
self.player_sprite.center_y = 120

Finally, all instances of the Sprite class need to go in a SpriteList class.

self.player_list.append(self.player_sprite)

We manage groups of sprites by the list that they are in. In the example below there’s a wall_list that will hold everything that the player character can’t walk through, and a coin_list for sprites we can pick up to get points. There’s also a player_list which holds only the player.

Notice that the code creates Sprites three ways:

  • Creating a Sprite class, positioning it, adding it to the list

  • Create a series of sprites in a loop

  • Create a series of sprites using coordinates

02_draw_sprites - Draw and Position Sprites
 1"""
 2Platformer Game
 3"""
 4import arcade
 5
 6# Constants
 7SCREEN_WIDTH = 1000
 8SCREEN_HEIGHT = 650
 9SCREEN_TITLE = "Platformer"
10
11# Constants used to scale our sprites from their original size
12CHARACTER_SCALING = 1
13TILE_SCALING = 0.5
14COIN_SCALING = 0.5
15
16
17class MyGame(arcade.Window):
18    """
19    Main application class.
20    """
21
22    def __init__(self):
23
24        # Call the parent class and set up the window
25        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
26
27        # These are 'lists' that keep track of our sprites. Each sprite should
28        # go into a list.
29        self.coin_list = None
30        self.wall_list = None
31        self.player_list = None
32
33        # Separate variable that holds the player sprite
34        self.player_sprite = None
35
36        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)
37
38    def setup(self):
39        """ Set up the game here. Call this function to restart the game. """
40        # Create the Sprite lists
41        self.player_list = arcade.SpriteList()
42        self.wall_list = arcade.SpriteList(use_spatial_hash=True)
43        self.coin_list = arcade.SpriteList(use_spatial_hash=True)
44
45        # Set up the player, specifically placing it at these coordinates.
46        image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png"
47        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
48        self.player_sprite.center_x = 64
49        self.player_sprite.center_y = 128
50        self.player_list.append(self.player_sprite)
51
52        # Create the ground
53        # This shows using a loop to place multiple sprites horizontally
54        for x in range(0, 1250, 64):
55            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
56            wall.center_x = x
57            wall.center_y = 32
58            self.wall_list.append(wall)
59
60        # Put some crates on the ground
61        # This shows using a coordinate list to place sprites
62        coordinate_list = [[512, 96],
63                           [256, 96],
64                           [768, 96]]
65
66        for coordinate in coordinate_list:
67            # Add a crate on the ground
68            wall = arcade.Sprite(":resources:images/tiles/boxCrate_double.png", TILE_SCALING)
69            wall.position = coordinate
70            self.wall_list.append(wall)
71
72    def on_draw(self):
73        """ Render the screen. """
74
75        # Clear the screen to the background color
76        arcade.start_render()
77
78        # Draw our sprites
79        self.wall_list.draw()
80        self.coin_list.draw()
81        self.player_list.draw()
82
83
84def main():
85    """ Main method """
86    window = MyGame()
87    window.setup()
88    arcade.run()
89
90
91if __name__ == "__main__":
92    main()

Note

Once the code example is up and working:

  • Adjust the code and try putting sprites in new positions.

  • Use different images for sprites (see the images folder).

  • Practice placing individually, via a loop, and by coordinates in a list.