본문 바로가기

[Pygame] 🏰 2D 타워 디펜스 게임 만들기 6강 | 적 HP & 골드 시스템 추가

@도마22026. 2. 6. 19:00
728x90


이번 6강에서는 다음 요소를 추가합니다.

  • 적에게 HP(체력) 부여
  • 적이 죽으면 골드 획득
  • 현재 골드를 UI로 표시

이제부터 게임에 목표와 보상 구조가 생깁니다.


1. 골드(Gold) 변수 만들기

게임 시작 시 기본 골드를 하나 정합니다.

gold = 100

이 골드는 이후 타워 설치와 업그레이드에 사용됩니다.


2. Enemy에 HP와 보상 추가

적은 이제 단순히 “도착하는 객체”가 아니라
체력을 가지고, 죽을 수 있는 객체가 됩니다.

Enemy 클래스에 아래 요소를 추가합니다.

  • hp : 현재 체력
  • max_hp : 최대 체력
  • reward : 처치 시 획득 골드
  • is_dead : 사망 여부

3. 적에게 임시 데미지 주기

아직 타워와 공격이 없기 때문에,
이번 강의에서는 시간이 지나면 자동으로 체력이 감소하도록 합니다.

self.hp -= 0.05

4. 적 사망 처리 & 골드 지급

적의 HP가 0 이하가 되면

  • 적은 삭제 대상이 되고
  • 골드를 획득합니다.
dead = [e for e in enemies if e.is_dead]
gold += sum(e.reward for e in dead)

5. 골드 UI 표시

HP 옆에 골드를 함께 표시합니다.

gold_text = font.render(f"Gold: {gold}", True, (255, 255, 0))
screen.blit(gold_text, (10, 40))

6. 실행 결과


전체 코드

더보기
import pygame
import sys

pygame.init()

# -----------------------------
# 화면 설정
# -----------------------------
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Tower Defense")

clock = pygame.time.Clock()
FPS = 60

# -----------------------------
# 경로 좌표
# -----------------------------
path_points = [
    (0, 300),
    (100, 300),
    (100, 100),
    (300, 100),
    (300, 500),
    (650, 500),
    (650, 300),
    (450, 300),
    (450, 100),
    (700, 100),
    (700, 200),
    (800, 200)
]

# -----------------------------
# Enemy 클래스
# -----------------------------
class Enemy:
    def __init__(self, path_points, speed=2):
        self.path_points = path_points
        self.speed = speed

        # 위치 및 경로 정보
        self.x, self.y = path_points[0]
        self.target_index = 1

        # 전투 관련
        self.max_hp = 50
        self.hp = self.max_hp
        self.reward = 10

        # 상태 플래그
        self.reached_end = False
        self.is_dead = False

        self.radius = 12

    def update(self):
        # 이미 죽었거나 도착한 적은 처리하지 않음
        if self.reached_end or self.is_dead:
            return

        # 임시 데미지 (추후 타워 공격으로 대체)
        self.hp -= 0.05
        if self.hp <= 0:
            self.is_dead = True
            return

        # 경로 끝 도달 처리
        if self.target_index >= len(self.path_points):
            self.reached_end = True
            return

        # 현재 목표 좌표
        tx, ty = self.path_points[self.target_index]
        dx = tx - self.x
        dy = ty - self.y

        dist = (dx * dx + dy * dy) ** 0.5
        if dist == 0:
            self.target_index += 1
            return

        # 목표 방향으로 이동
        self.x += (dx / dist) * self.speed
        self.y += (dy / dist) * self.speed

        # 웨이포인트 도착 처리
        if dist <= self.speed:
            self.x, self.y = tx, ty
            self.target_index += 1
            if self.target_index >= len(self.path_points):
                self.reached_end = True

    def draw(self, screen):
        # 적 본체
        pygame.draw.circle(
            screen, (220, 80, 80),
            (int(self.x), int(self.y)), self.radius
        )

        # HP 바 배경
        bar_width = 24
        bar_height = 4
        hp_ratio = self.hp / self.max_hp

        pygame.draw.rect(
            screen, (60, 60, 60),
            (self.x - 12, self.y - 20, bar_width, bar_height)
        )

        # HP 바
        pygame.draw.rect(
            screen, (80, 220, 80),
            (self.x - 12, self.y - 20, bar_width * hp_ratio, bar_height)
        )

# -----------------------------
# 게임 변수
# -----------------------------
enemies = []

spawn_interval = 1000
last_spawn_time = 0

base_hp = 20
gold = 100

font = pygame.font.SysFont(None, 32)

# -----------------------------
# 메인 루프
# -----------------------------
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    game_over = base_hp <= 0

    if not game_over:
        # 적 스폰
        now = pygame.time.get_ticks()
        if now - last_spawn_time >= spawn_interval:
            enemies.append(Enemy(path_points))
            last_spawn_time = now

        # 적 업데이트
        for enemy in enemies:
            enemy.update()

        # 도착한 적 처리 (베이스 HP 감소)
        arrived = [e for e in enemies if e.reached_end]
        base_hp -= len(arrived)

        # 죽은 적 처리 (골드 획득)
        dead = [e for e in enemies if e.is_dead]
        gold += sum(e.reward for e in dead)

        # 적 정리
        enemies = [e for e in enemies if not e.reached_end and not e.is_dead]

    # -----------------------------
    # 화면 그리기
    # -----------------------------
    screen.fill((30, 30, 30))
    pygame.draw.lines(screen, (200, 180, 100), False, path_points, 40)

    for enemy in enemies:
        enemy.draw(screen)

    # UI
    screen.blit(font.render(f"HP: {base_hp}", True, (255, 255, 255)), (10, 10))
    screen.blit(font.render(f"Gold: {gold}", True, (255, 255, 0)), (10, 40))

    if game_over:
        over_text = font.render("GAME OVER", True, (255, 255, 255))
        screen.blit(
            over_text,
            (SCREEN_WIDTH // 2 - over_text.get_width() // 2,
             SCREEN_HEIGHT // 2)
        )

    pygame.display.update()
    clock.tick(FPS)

728x90
도마2
@도마2 :: 도마의 코드노트

초보자를 위한 코딩 강의를 정리합니다. 파이썬부터 C#, Unity 게임 제작까지 차근차근 기록합니다. — 도마

목차