Arcade Library를 이용한 2D 게임 시작하기 (파트 9): 점수 표시

발행: (2025년 12월 24일 오후 09:05 GMT+9)
5 min read
원문: Dev.to

Source: Dev.to

Source:

점수 표시

이 문서에서는 화면에 수집한 동전 개수를 점수로 표시하는 방법을 다룹니다.

1. 텍스트 객체 만들기

main.pyGameView 클래스 생성자에서 숫자 점수 변수를 준비하고 arcade.Text() 로 텍스트 객체를 생성합니다.

다음 정보를 인수로 지정합니다:

  • 표시할 텍스트
  • X / Y 좌표
  • 텍스트 색상
  • 폰트 크기
  • X 기준점 (텍스트의 가로 중심 사용)
  • Y 기준점 (텍스트의 위쪽 사용)
# 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"
)

2. 점수를 증가시키고 텍스트 업데이트하기

main.pyGameView 클래스 on_update() 메서드에서 이미 충돌 검사를 수행하고 있습니다.
이 시점에 점수를 증가시키고 텍스트를 업데이트합니다. 플레이어가 동시에 여러 동전을 터치하면 그만큼 점수가 증가합니다.

# 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)

3. 텍스트 그리기

마지막으로 main.pyGameView 클래스 on_draw() 메서드에서 텍스트 객체를 그립니다.
(이 단계는 놀라울 정도로 잊기 쉬워요 😅)

# 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

전체 코드

아래는 지금까지 구현한 모든 기능을 포함한 전체 코드입니다.
그대로 복사해서 실행할 수 있습니다.

sprite.py (전체 코드)

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(ar```

#### `main.py` (전체 코드)

```python
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,
                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_show(self):
        arcade.set_background_color(self.background_color)

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

    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)

    def on_key_press(self, key, modifiers):
        # Example movement controls (optional)
        if key == arcade.key.LEFT:
            self.player.move(200, 180)
        elif key == arcade.key.RIGHT:
            self.player.move(200, 0)
        elif key == arcade.key.UP:
            self.player.move(200, 90)
        elif key == arcade.key.DOWN:
            self.player.move(200, 270)

    def on_key_release(self, key, modifiers):
        if key in (arcade.key.LEFT, arcade.key.RIGHT,
                   arcade.key.UP, arcade.key.DOWN):
            self.player.stop()

def main():
    window = arcade.Window(800, 600, "Coin Collector")
    game_view = GameView(window)
    window.show_view(game_view)
    arcade.run()

if __name__ == "__main__":
    main()

Kajiru

전체 화면 제어

  • 전체 화면 모드 진입
  • 전체 화면 모드 종료

결과 미리보기

결과 GIF

다음에…

읽어 주셔서 감사합니다!

다음 제목은 “Playing Sound Effects” 입니다.

계속 기대해 주세요 👍

Back to Blog

관련 글

더 보기 »