Step 7 - Add Coins And Sound#

../../_images/title_07.png

Next we will add some coins that the player can pickup. We’ll also add a sound to be played when they pick it up, as well as a sound for when they jump.

Adding Coins to the Scene#

First we need to add our coins to the scene. Let’s start by adding a constant at the top of our application for the coin sprite scaling, similar to our TILE_SCALING one.

Add Coins and Sound#

Next in our setup function we can create our coins using a for loop like we’ve done for the ground previously, and then add them to the scene.

Add Coins and Sound#
            )
            wall.position = coordinate
            self.scene.add_sprite("Walls", wall)

        # Use a loop to place some coins for our character to pick up
        for x in range(128, 1250, 256):

Loading Sounds#

Now we can load in our sounds for collecting the coin and jumping. Later we will use these variables to play the sounds when the specific events happen. Add the following to the __init__ function to load the sounds:

Add Coins and Sound#

        # A Camera that can be used for scrolling the screen
        self.camera = None

Then we can play our jump sound when the player jumps, by adding it to the on_key_press function:

Add Coins and Sound#

        # Draw our Scene
        self.scene.draw()

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

        if key == arcade.key.UP or key == arcade.key.W:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = PLAYER_JUMP_SPEED
                arcade.play_sound(self.jump_sound)

Collision Detection#

Lastly, we need to find out if the player hit a coin. We can do this in our on_update function by using the arcade.check_for_collision_with_list function. We can pass the player sprite, along with a SpriteList that holds the coins. The function will return a list of the coins that the player is currently colliding with. If there are no coins in contact, the list will be empty.

Then we can use the Sprite.remove_from_sprite_lists function which will remove a given sprite from any SpriteLists it belongs to, effectively deleting it from the game.

Note

Notice that any transparent “white-space” around the image counts as the hitbox. You can trim the space in a graphics editor, or later on, we’ll go over how to customize the hitbox of a Sprite.

Add the following to the on_update function to add collision detection and play a sound when the player picks up a coin.

Add Coins and Sound#

        # Move the player with the physics engine
        self.physics_engine.update()

        # See if we hit any coins
        coin_hit_list = arcade.check_for_collision_with_list(
            self.player_sprite, self.scene["Coins"]
        )

        # Loop through each coin we hit (if any) and remove it
        for coin in coin_hit_list:

Note

Spend time placing the coins where you would like them. If you have extra time, try adding more than just coins. Also add gems or keys from the graphics provided.

You could also subclass the coin sprite and add an attribute for a score value. Then you could have coins worth one point, and gems worth 5, 10, and 15 points.

Source Code#

Add Coins and Sound#
  1"""
  2Platformer Game
  3
  4python -m arcade.examples.platform_tutorial.07_coins_and_sound
  5"""
  6from __future__ import annotations
  7
  8import arcade
  9
 10# Constants
 11SCREEN_WIDTH = 1000
 12SCREEN_HEIGHT = 650
 13SCREEN_TITLE = "Platformer"
 14
 15# Constants used to scale our sprites from their original size
 16CHARACTER_SCALING = 1
 17TILE_SCALING = 0.5
 18COIN_SCALING = 0.5
 19
 20# Movement speed of player, in pixels per frame
 21PLAYER_MOVEMENT_SPEED = 5
 22GRAVITY = 1
 23PLAYER_JUMP_SPEED = 20
 24
 25
 26class MyGame(arcade.Window):
 27    """
 28    Main application class.
 29    """
 30
 31    def __init__(self):
 32
 33        # Call the parent class and set up the window
 34        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
 35
 36        # Our Scene Object
 37        self.scene = None
 38
 39        # Separate variable that holds the player sprite
 40        self.player_sprite = None
 41
 42        # Our physics engine
 43        self.physics_engine = None
 44
 45        # A Camera that can be used for scrolling the screen
 46        self.camera = None
 47
 48        # Load sounds
 49        self.collect_coin_sound = arcade.load_sound(":resources:sounds/coin1.wav")
 50        self.jump_sound = arcade.load_sound(":resources:sounds/jump1.wav")
 51
 52        self.background_color = arcade.csscolor.CORNFLOWER_BLUE
 53
 54    def setup(self):
 55        """Set up the game here. Call this function to restart the game."""
 56
 57        # Set up the Camera
 58        self.camera = arcade.SimpleCamera(viewport=(0, 0, self.width, self.height))
 59
 60        # Initialize Scene
 61        self.scene = arcade.Scene()
 62
 63        # Set up the player, specifically placing it at these coordinates.
 64        image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png"
 65        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
 66        self.player_sprite.center_x = 64
 67        self.player_sprite.center_y = 128
 68        self.scene.add_sprite("Player", self.player_sprite)
 69
 70        # Create the ground
 71        # This shows using a loop to place multiple sprites horizontally
 72        for x in range(0, 1250, 64):
 73            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
 74            wall.center_x = x
 75            wall.center_y = 32
 76            self.scene.add_sprite("Walls", wall)
 77
 78        # Put some crates on the ground
 79        # This shows using a coordinate list to place sprites
 80        coordinate_list = [[512, 96], [256, 96], [768, 96]]
 81
 82        for coordinate in coordinate_list:
 83            # Add a crate on the ground
 84            wall = arcade.Sprite(
 85                ":resources:images/tiles/boxCrate_double.png", TILE_SCALING
 86            )
 87            wall.position = coordinate
 88            self.scene.add_sprite("Walls", wall)
 89
 90        # Use a loop to place some coins for our character to pick up
 91        for x in range(128, 1250, 256):
 92            coin = arcade.Sprite(":resources:images/items/coinGold.png", COIN_SCALING)
 93            coin.center_x = x
 94            coin.center_y = 96
 95            self.scene.add_sprite("Coins", coin)
 96
 97        # Create the 'physics engine'
 98        self.physics_engine = arcade.PhysicsEnginePlatformer(
 99            self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Walls"]
100        )
101
102    def on_draw(self):
103        """Render the screen."""
104
105        # Clear the screen to the background color
106        self.clear()
107
108        # Activate our Camera
109        self.camera.use()
110
111        # Draw our Scene
112        self.scene.draw()
113
114    def on_key_press(self, key, modifiers):
115        """Called whenever a key is pressed."""
116
117        if key == arcade.key.UP or key == arcade.key.W:
118            if self.physics_engine.can_jump():
119                self.player_sprite.change_y = PLAYER_JUMP_SPEED
120                arcade.play_sound(self.jump_sound)
121        elif key == arcade.key.LEFT or key == arcade.key.A:
122            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
123        elif key == arcade.key.RIGHT or key == arcade.key.D:
124            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
125
126    def on_key_release(self, key, modifiers):
127        """Called when the user releases a key."""
128
129        if key == arcade.key.LEFT or key == arcade.key.A:
130            self.player_sprite.change_x = 0
131        elif key == arcade.key.RIGHT or key == arcade.key.D:
132            self.player_sprite.change_x = 0
133
134    def center_camera_to_player(self):
135        screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)
136        screen_center_y = self.player_sprite.center_y - (
137            self.camera.viewport_height / 2
138        )
139        if screen_center_x < 0:
140            screen_center_x = 0
141        if screen_center_y < 0:
142            screen_center_y = 0
143        player_centered = screen_center_x, screen_center_y
144
145        self.camera.move_to(player_centered)
146
147    def on_update(self, delta_time):
148        """Movement and game logic"""
149
150        # Move the player with the physics engine
151        self.physics_engine.update()
152
153        # See if we hit any coins
154        coin_hit_list = arcade.check_for_collision_with_list(
155            self.player_sprite, self.scene["Coins"]
156        )
157
158        # Loop through each coin we hit (if any) and remove it
159        for coin in coin_hit_list:
160            # Remove the coin
161            coin.remove_from_sprite_lists()
162            # Play a sound
163            arcade.play_sound(self.collect_coin_sound)
164
165        # Position the camera
166        self.center_camera_to_player()
167
168
169def main():
170    """Main function"""
171    window = MyGame()
172    window.setup()
173    arcade.run()
174
175
176if __name__ == "__main__":
177    main()