본문 바로가기

[Pygame] ✈️ 전투기 슈팅 게임 만들기 8강 | 점수 UI 표시하기

@도마22026. 1. 18. 19:00
728x90


1. 이번 강의 목표

이번 강의에서는 점수 시스템을 추가합니다.

구현할 내용은 다음과 같습니다.

  • 적을 처치하면 점수 증가
  • 점수 변수 관리
  • pygame.font를 이용한 텍스트 출력
  • 화면 상단에 점수 UI 고정 표시

이번 강의부터 게임에 목표와 성취감이 생깁니다.


2. 점수 변수 만들기

먼저 점수를 저장할 변수를 하나 추가합니다.

score = 0

이 변수는 게임이 시작될 때 0으로 초기화됩니다.


3. 적 처치 시 점수 증가

이전 강의에서 구현한
총알 ↔ 적 충돌 처리 부분에서 점수를 증가시킵니다.

if b.colliderect(e):
    bullets.remove(b)
    enemies.remove(e)
    score += 10
    break

 

  • 적 1기 처치 시 점수 10점
  • 점수 단위는 이후 자유롭게 조절 가능합니다.

4. 폰트(Font) 준비하기

Pygame에서 텍스트를 출력하려면 폰트 객체가 필요합니다.

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

 

 

  • None : 기본 시스템 폰트 사용
  • 36 : 글자 크기

5. 점수 텍스트 생성

점수는 매 프레임마다 갱신되므로
문자열을 렌더링해서 Surface로 만들어야 합니다.

score_text = font.render(f"Score : {score}", True, (255, 255, 255))

 

 

  • 두 번째 인자 True : 안티앨리어싱
  • 색상은 흰색으로 설정

6. 점수 UI 화면에 출력하기

렌더링된 텍스트를 화면에 출력합니다.

screen.blit(score_text, (10, 10))

 

 

  • 화면 왼쪽 상단에 고정 표시
  • 게임 진행 중 항상 보이도록 설정

7. 실행 결과

이제 게임을 실행하면 다음과 같은 변화가 있습니다.

  • 적을 처치할 때마다 점수가 올라갑니다.
  • 화면 상단에 현재 점수가 표시됩니다.
  • 게임의 진행 상황이 한눈에 보입니다.


8. 마무리

이번 강의에서는 다음 내용을 구현했습니다.

  • 점수 변수 관리
  • 적 처치 시 점수 증가
  • pygame.font를 이용한 점수 UI 출력

이제 게임에는 명확한 목표(점수) 가 생겼습니다.


전체 코드

더보기
import pygame
import sys
import random

pygame.init()

# 화면 설정
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 640
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Shooting Game")

# FPS 설정
clock = pygame.time.Clock()
FPS = 60

# ===== 스프라이트 로드 =====
player_img = pygame.image.load("images/player.png").convert_alpha()
enemy_img = pygame.image.load("images/enemy.png").convert_alpha()
bullet_img = pygame.image.load("images/bullet.png").convert_alpha()

# ===== 스프라이트 크기 조정 =====
PLAYER_SIZE = (40, 40)
ENEMY_SIZE = (40, 40)
BULLET_SIZE = (6, 16)

player_img = pygame.transform.scale(player_img, PLAYER_SIZE)
enemy_img = pygame.transform.scale(enemy_img, ENEMY_SIZE)
bullet_img = pygame.transform.scale(bullet_img, BULLET_SIZE)

# 플레이어 설정
player_speed = 5
player_rect = player_img.get_rect()
player_rect.centerx = SCREEN_WIDTH // 2
player_rect.bottom = SCREEN_HEIGHT - 20

# 총알 설정
bullet_speed = 8
bullets = []

# 연사 제한
fire_delay = 150
last_fire_time = 0

# 적 설정
enemy_speed = 3
enemies = []
enemy_spawn_delay = 60
enemy_timer = 0

# ===== 점수 설정 =====
score = 0
font = pygame.font.SysFont(None, 36)

# 게임 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()

    # 플레이어 이동
    if keys[pygame.K_w]:
        player_rect.y -= player_speed
    if keys[pygame.K_s]:
        player_rect.y += player_speed
    if keys[pygame.K_a]:
        player_rect.x -= player_speed
    if keys[pygame.K_d]:
        player_rect.x += player_speed

    # 화면 밖 제한
    if player_rect.left < 0:
        player_rect.left = 0
    if player_rect.right > SCREEN_WIDTH:
        player_rect.right = SCREEN_WIDTH
    if player_rect.top < 0:
        player_rect.top = 0
    if player_rect.bottom > SCREEN_HEIGHT:
        player_rect.bottom = SCREEN_HEIGHT

    # 총알 발사 (연사 제한)
    now = pygame.time.get_ticks()
    if keys[pygame.K_SPACE]:
        if now - last_fire_time >= fire_delay:
            last_fire_time = now
            bullet_rect = bullet_img.get_rect()
            bullet_rect.centerx = player_rect.centerx
            bullet_rect.bottom = player_rect.top
            bullets.append(bullet_rect)

    # 총알 이동
    for b in bullets:
        b.y -= bullet_speed

    # 총알 제거
    for b in bullets[:]:
        if b.bottom < 0:
            bullets.remove(b)

    # 적 생성
    enemy_timer += 1
    if enemy_timer >= enemy_spawn_delay:
        enemy_timer = 0
        enemy_rect = enemy_img.get_rect()
        enemy_rect.x = random.randint(0, SCREEN_WIDTH - enemy_rect.width)
        enemy_rect.y = -enemy_rect.height
        enemies.append(enemy_rect)

    # 적 이동
    for e in enemies:
        e.y += enemy_speed

    # 적 제거
    for e in enemies[:]:
        if e.top > SCREEN_HEIGHT:
            enemies.remove(e)

    # 충돌 처리 (총알 vs 적)
    for b in bullets[:]:
        for e in enemies[:]:
            if b.colliderect(e):
                bullets.remove(b)
                enemies.remove(e)
                score += 10
                break

    # ===== 화면 그리기 =====
    screen.fill((0, 0, 0))

    # 플레이어
    screen.blit(player_img, player_rect)

    # 총알
    for b in bullets:
        screen.blit(bullet_img, b)

    # 적
    for e in enemies:
        screen.blit(enemy_img, e)

    # 점수 UI
    score_text = font.render(f"Score : {score}", True, (255, 255, 255))
    screen.blit(score_text, (10, 10))

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

pygame.quit()
sys.exit()

 


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

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

목차