DEV Community

Kajiru
Kajiru

Posted on

Getting Started with 2D Games Using Arcade Library (Part 9): Displaying the Score

Displaying the Score

In this article, we will display the number of collected coins as a score on the screen.

1. Create a Text Object

In the constructor of the GameView class in main.py, prepare a numeric score variable and a text object using arcade.Text().

Specify the following information as arguments:

  • The text to display
  • X / Y coordinates
  • Text color
  • Font size
  • X anchor point (use the horizontal center of the text)
  • Y anchor point (use the top of the text)
# main.py (excerpt)

# Score
self.score = 0
# Text object
self.score_text = arcade.Text(
    "SCORE: {}".format(self.score),
    self.w / 2, self.h - 20,
    arcade.color.BLACK,
    16, anchor_x="center", anchor_y="top"
)
Enter fullscreen mode Exit fullscreen mode

2. Increase the Score and Update the Text

In the on_update() method of the GameView class in main.py, we already perform collision detection.
At this timing, we also increase the score and update the text.

If the player touches multiple coins at the same time, the score will be increased by that amount.

# main.py (excerpt)

def on_update(self, delta_time):
    self.players.update(delta_time)
    self.coins.update(delta_time)

    # Player x coin list
    hit_coins = arcade.check_for_collision_with_list(
        self.player,
        self.coins
    )
    for coin in hit_coins:
        coin.remove_from_sprite_lists()
        # Add to score
        self.score += 1
        # Update the text of the text object
        self.score_text.text = "SCORE: {}".format(self.score)
Enter fullscreen mode Exit fullscreen mode

3. Draw the Text

Finally, draw the text object in the on_draw() method of the GameView class in main.py.
(This step is surprisingly easy to forget 😅)

# main.py (excerpt)

def on_draw(self):
    self.clear()  # Clear
    self.backgrounds.draw()
    self.players.draw()
    self.coins.draw()
    self.score_text.draw()  # Draw the text object
Enter fullscreen mode Exit fullscreen mode

Complete Code

Below is the complete code with all the features implemented so far.
You can copy and run it as-is.

# sprite.py (complete code)

import arcade
import math

class BaseSprite(arcade.Sprite):

    def __init__(self, filename, x, y):
        super().__init__(filename)
        # Position
        self.center_x = x
        self.center_y = y
        # Velocity
        self.vx = 0
        self.vy = 0
        # Animation
        self.anim_counter = 0
        self.anim_interval = 4
        self.anim_index = 0
        self.anim = []

    def update(self, delta_time):
        """ Update """
        self.center_x += self.vx * delta_time
        self.center_y += self.vy * delta_time
        # Animation
        self.update_animation()

    def move(self, spd, deg):
        """ Move Sprite """
        rad = deg * math.pi / 180
        self.vx = spd * math.cos(rad)
        self.vy = spd * math.sin(rad)

    def stop(self):
        """ Stop Sprite """
        self.vx = 0
        self.vy = 0

    def update_animation(self):
        """ Animation """
        if not self.anim:
            return
        self.anim_counter += 1
        if self.anim_counter < self.anim_interval:
            return
        self.anim_counter = 0
        self.anim_index += 1
        if len(self.anim) <= self.anim_index:
            self.anim_index = 0
        self.texture = self.anim[self.anim_index]


class Player(BaseSprite):

    def __init__(self, filename, x, y):
        super().__init__(filename, x, y)

        self.anim.append(arcade.load_texture("images/ninja/front_01.png"))
        self.anim.append(arcade.load_texture("images/ninja/front_02.png"))
        self.anim.append(arcade.load_texture("images/ninja/front_03.png"))
        self.anim.append(arcade.load_texture("images/ninja/front_04.png"))
        self.anim.append(arcade.load_texture("images/ninja/front_05.png"))


class Coin(BaseSprite):

    def __init__(self, filename, x, y):
        super().__init__(filename, x, y)

        self.anim.append(arcade.load_texture("images/coin/coin_01.png"))
        self.anim.append(arcade.load_texture("images/coin/coin_02.png"))
        self.anim.append(arcade.load_texture("images/coin/coin_03.png"))
        self.anim.append(arcade.load_texture("images/coin/coin_04.png"))
        self.anim.append(arcade.load_texture("images/coin/coin_05.png"))
Enter fullscreen mode Exit fullscreen mode
# main.py (complete code)

import arcade
import sprite
import random

class GameView(arcade.View):

    def __init__(self, window):
        super().__init__()
        self.window = window
        self.w = self.window.width
        self.h = self.window.height

        # Background color
        self.background_color = arcade.color.PAYNE_GREY

        # Background sprites
        self.backgrounds = arcade.SpriteList()
        bkg = arcade.Sprite("images/bg_temple.png")
        bkg.center_x = self.w / 2
        bkg.center_y = self.h / 2
        self.backgrounds.append(bkg)

        # Player sprite
        self.players = arcade.SpriteList()
        self.player = sprite.Player(
            "images/ninja/front_01.png",
            x=self.w / 2, y=self.h / 2
        )
        self.players.append(self.player)

        # Coin sprites
        self.coins = arcade.SpriteList()
        for i in range(10):
            x = random.random() * self.w
            y = random.random() * self.h
            coin = sprite.Coin(
                "images/coin/coin_01.png",
                x=x, y=y
            )
            self.coins.append(coin)

        # Score
        self.score = 0
        # Text object
        self.score_text = arcade.Text(
            "SCORE: {}".format(self.score),
            self.w / 2, self.h - 20,
            arcade.color.BLACK,
            16, anchor_x="center", anchor_y="top"
        )

    def on_key_press(self, key, key_modifiers):
        # Move (WASD)
        if key == arcade.key.W:
            self.player.move(90, 90)
        if key == arcade.key.A:
            self.player.move(90, 180)
        if key == arcade.key.S:
            self.player.move(90, 270)
        if key == arcade.key.D:
            self.player.move(90, 0)

    def on_key_release(self, key, key_modifiers):
        self.player.stop()

    def on_update(self, delta_time):
        self.players.update(delta_time)
        self.coins.update(delta_time)

        # Player x coin list
        hit_coins = arcade.check_for_collision_with_list(
            self.player,
            self.coins
        )
        for coin in hit_coins:
            coin.remove_from_sprite_lists()
            # Score
            self.score += 1
            # Update the text of the text object
            self.score_text.text = "SCORE: {}".format(self.score)

    def on_draw(self):
        self.clear()  # Clear
        self.backgrounds.draw()
        self.players.draw()
        self.coins.draw()
        self.score_text.draw()


def main():
    """ Main process """
    window = arcade.Window(480, 320, "Hello, Arcade!!")
    game = GameView(window)
    window.show_view(game)
    arcade.run()


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The result will look like this:

Next Time...

Thank you for reading!
The next title will be "Playing Sound Effects".

Stay tuned 👍

Top comments (0)