파이썬 게임 개발 강좌 5강에 오신 것을 환영합니다!
이제 우리는 캐릭터를 만들고, 이동시키고, 장애물과의 충돌까지 처리하는 기능을 익혔습니다. 이번 강의에서는 게임에 **제한 시간**을 설정하고, 시간이 끝났을 때 **게임 종료 메시지를 출력하는 방법**을 배워봅니다.
이 기능은 게임에 긴장감과 목적을 부여할 수 있어 꼭 필요한 요소입니다.
이번 강의 목표
- 게임 시간 제한 설정
- 남은 시간 표시
- 시간 종료 시 ‘Game Over’ 메시지 출력
1. Pygame 시간 관련 함수
Pygame에서는 시간을 제어하기 위해 pygame.time.get_ticks()
함수를 사용합니다. 이 함수는 게임이 시작된 이후의 시간을 밀리초 단위로 반환합니다.
예:
start_ticks = pygame.time.get_ticks()
이후 게임 루프 안에서 남은 시간을 계산하여 제한 시간을 구현할 수 있습니다.
2. 전체 코드 예제
아래는 10초 동안 캐릭터가 움직이다가 시간이 끝나면 ‘Game Over’ 메시지를 출력하는 예시입니다.
import pygame
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("게임 시간 제한")
# 배경, 캐릭터
background = pygame.image.load("background.png")
character = pygame.image.load("character.png")
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width - character_width) / 2
character_y_pos = screen_height - character_height
# 이동 속도
to_x = 0
to_y = 0
speed = 0.6
# 폰트
game_font = pygame.font.Font(None, 40)
# 시작 시간
start_ticks = pygame.time.get_ticks()
# 제한 시간 (초)
total_time = 10
clock = pygame.time.Clock()
running = True
while running:
dt = clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
to_x -= speed
elif event.key == pygame.K_RIGHT:
to_x += speed
elif event.key == pygame.K_UP:
to_y -= speed
elif event.key == pygame.K_DOWN:
to_y += speed
if event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
to_x = 0
if event.key in [pygame.K_UP, pygame.K_DOWN]:
to_y = 0
character_x_pos += to_x * dt
character_y_pos += to_y * dt
# 경계값 설정
if character_x_pos < 0:
character_x_pos = 0
elif character_x_pos > screen_width - character_width:
character_x_pos = screen_width - character_width
if character_y_pos < 0:
character_y_pos = 0
elif character_y_pos > screen_height - character_height:
character_y_pos = screen_height - character_height
# 타이머 계산
elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000
timer = game_font.render(f"Time: {int(total_time - elapsed_time)}", True, (255, 255, 255))
screen.blit(background, (0, 0))
screen.blit(character, (character_x_pos, character_y_pos))
screen.blit(timer, (10, 10))
pygame.display.update()
if total_time - elapsed_time <= 0:
running = False
# 게임 종료 메시지 출력
msg_font = pygame.font.Font(None, 70)
msg = msg_font.render("Game Over", True, (255, 0, 0))
msg_rect = msg.get_rect(center=(screen_width / 2, screen_height / 2))
screen.blit(msg, msg_rect)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
3. 코드 설명
- pygame.font.Font() : 텍스트 출력용 폰트 설정
- render() : 문자열을 화면에 출력 가능한 Surface로 변환
- get_ticks() : 게임 시작 후 경과 시간 측정
- delay() : 메시지 보여주는 시간 조정
4. 응용 아이디어
- 미션 완료 시 시간 멈추고 성공 메시지 출력
- 남은 시간에 따라 캐릭터 속도나 난이도 조절
- 남은 시간을 화면 가운데 크고 빨간 글씨로 강조
5. 다음 강의 예고
6강: 점수판 만들기 – 점수 계산 및 출력 기능 추가하기
다음 시간에는 게임 진행 중 특정 조건에 따라 점수를 획득하고, 화면 상단에 점수를 실시간으로 출력하는 기능을 만들어볼게요. 드디어 ‘게임스러운’ 요소들이 하나씩 완성됩니다!
---
이 강의는 파이썬 Pygame을 통해 기초부터 직접 게임을 만드는 실전 입문 과정입니다.