Tkinter를 사용한 2D 게임 시작하기 (파트 9): 카운터 표시

발행: (2025년 12월 24일 오후 02:58 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

카운터 표시

이 문서에서는 화면에 남아 있는 악마 수를 보여주는 카운터를 추가합니다.

먼저, 남아 있는 악마 수를 추적하기 위해 counter라는 변수를 만듭니다.

# Demon counter
counter = TOTAL_DEMONS

악마가 잡힐 때마다 on_mouse_clicked() 함수 안에서 카운터를 감소시킵니다.
counter는 전역 변수이므로 global 키워드로 선언합니다.

def on_mouse_clicked(e):
    global counter

    # Demon group
    for demon in demons:
        if demon.is_inside(e.x, e.y):
            if demon.is_dead():
                continue
            demon.die(cvs)
            counter = counter - 1  # Decrease demon counter
            break

update() 함수 안에서 counter 변수를 이용해 화면에 카운터를 그립니다.

def update():
    """Update function"""

    cvs.delete("hud")

    # Draw mouse coordinates
    msg = "x:{}, y:{}".format(mx, my)
    cvs.create_text(
        mx, my,
        text=msg,
        fill="white",
        font=FONT,
        tag="hud"
    )

    # Draw demon counter
    msg = "Remaining Demons: {}".format(counter)
    cvs.create_text(
        20, 20,
        text=msg,
        fill="white",
        font=FONT,
        tag="hud",
        anchor="nw"
    )

    # Demon group
    for demon in demons:
        overlap_area(demon)  # Screen wrap check
        demon.update(cvs)

    root.after(F_INTERVAL, update)

이를 구현하면 남아 있는 악마 수가 화면에 표시됩니다.

전체 코드

sprite.py

import math
import random
import tkinter

class DemonSprite:

    def __init__(self, cvs, x, y, r):
        self.x = x
        self.y = y
        self.r = r
        self.vx = 0
        self.vy = 0
        self.dead = False

        # Circle for collision detection
        self.oval = cvs.create_oval(
            x - r, y - r, x + r, y + r,
            fill="white", width=0
        )

        # Random demon type: r, g, b
        self.type = random.choice(("r", "g", "b"))

        file_alive = f"images/dmn_alive_{self.type}.png"
        self.photo_alive = tkinter.PhotoImage(file=file_alive)

        file_dead = f"images/dmn_dead_{self.type}.png"
        self.photo_dead = tkinter.PhotoImage(file=file_dead)

        self.image = cvs.create_image(x, y, image=self.photo_alive)

    def update(self, cvs):
        self.x += self.vx
        self.y += self.vy

        # Update circle position
        cvs.coords(
            self.oval,
            self.x - self.r, self.y - self.r,
            self.x + self.r, self.y + self.r
        )

        # Update image position
        cvs.coords(self.image, self.x, self.y)

    def set_x(self, x):
        self.x = x

    def set_y(self, y):
        self.y = y

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

    def stop(self):
        self.move(0, 0)

    def die(self, cvs):
        self.dead = True
        self.stop()
        cvs.itemconfig(self.oval, fill="red")
        cvs.itemconfig(self.image, image=self.photo_dead)

    def is_dead(self):
        return self.dead

    def is_inside(self, x, y):
        dx = (self.x - x) ** 2
        dy = (self.y - y) ** 2
        dist = (dx + dy) ** 0.5
        return dist  W: obj.set_x(0)
    if obj.y  H: obj.set_y(0)

메인 스크립트

def on_mouse_clicked(e):
    global counter

    for demon in demons:
        if demon.is_inside(e.x, e.y):
            if demon.is_dead():
                continue
            demon.die(cvs)
            counter -= 1
            break

def on_mouse_moved(e):
    global mx, my
    mx, my = e.x, e.y

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)
root.bind("", on_mouse_clicked)
root.bind("", on_mouse_moved)

cvs = tkinter.Canvas(width=W, height=H, bg="black")
cvs.pack()

init()
update()
root.mainloop()

계속 지켜봐 주세요!

Back to Blog

관련 글

더 보기 »