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#
CHARACTER_SCALING = 1

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#
            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):
            coin = arcade.Sprite(":resources:images/items/coinGold.png", COIN_SCALING)
            coin.center_x = x

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#
        self.camera = None

        # Load sounds

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

Add Coins and Sound#
        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)
        elif key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED

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#
        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:
            # Remove the coin
            coin.remove_from_sprite_lists()

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