IT/Python

[Python] Pygame으로 간단한 2D 게임 만들기

멋진 선배 2025. 1. 19. 06:35
반응형

Pygame을 이용해 간단한 2D 게임을 만드는 방법에 대해서 알아보겠습니다. Pygame은 Python을 사용하여 게임을 쉽게 만들 수 있게 해주는 강력한 라이브러리 입니다. 초보자도 쉽게 접근할 수 있어 게임 개발 입문에 아주 좋습니다.

실행된 게임 화면

Pygame 설치하기

먼저 Pygame을 설치해야 합니다. 터이널이나 명령 프롬프트를 이용하여 다음 명령어를 입력하세요.

pip install pygame

게임 기본 구조 만들기

 Pygame 게임의 기본 구조는 다음과 같습니다.

  •  Pygame 초기화
  • 게임 창 설정
  • 게임 루프(이벤트 처리, 게임 로직 업데이트,  화면 그리기)
  • 게임 종료

아래는 기본 구조의 코드 입니다.

import pygame
import sys

# Pygame 초기화
pygame.init()

# 화면 설정
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My First Pygame Game")

# 색상 정의
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# 게임 루프
clock = pygame.time.Clock()
while True:
    # 이벤트 처리
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # 화면 그리기
    screen.fill(WHITE)
    
    # 화면 업데이트
    pygame.display.flip()
    clock.tick(60)

이 코드를 실행하면 흰색 창이 나타납니다. 이제 이 기본 구조에 게임 요소들을 추가해 볼까요?

캐릭터 추가하기

간단한 사각형 캐릭터를 추가해 보겠습니다.

# 캐릭터 설정
player_size = 50
player_x = WIDTH // 2 - player_size // 2
player_y = HEIGHT - player_size - 10
player_speed = 5

# 게임 루프 내부에 추가
pygame.draw.rect(screen, BLACK, (player_x, player_y, player_size, player_size))

캐릭터 움직이기

키보드 입력으로 캐릭터를 움직여 봅시다.

# 게임 루프 내부에 추가
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
    player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size:
    player_x += player_speed

적 추가하기

이제 위에서 떨어지는 적을 추가해 봅시다.

import random

# 적 설정
enemy_size = 50
enemy_x = random.randint(0, WIDTH - enemy_size)
enemy_y = 0
enemy_speed = 3

# 게임 루프 내부에 추가
pygame.draw.rect(screen, (255, 0, 0), (enemy_x, enemy_y, enemy_size, enemy_size))
enemy_y += enemy_speed

if enemy_y > HEIGHT:
    enemy_y = 0
    enemy_x = random.randint(0, WIDTH - enemy_size)

충돌 감지 추가하기

캐릭터와 적의 충돌을 감지해 봅시다.

# 게임 루프 내부에 추가
if (player_x < enemy_x + enemy_size and
    player_x + player_size > enemy_x and
    player_y < enemy_y + enemy_size and
    player_y + player_size > enemy_y):
    print("Game Over!")
    pygame.quit()
    sys.exit()

점수 시스템 추가하기

마지막으로 간단한 점수 시스템을 추가해 봅시다.

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

# 게임 루프 내부에 추가
if enemy_y > HEIGHT:
    score += 1

score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))

완성된 게임 코드

이제 모든 요소를 합쳐 완성된 게임 코드를 만들어 보겠습니다.

import pygame
import sys
import random

# Pygame 초기화
pygame.init()

# 화면 설정
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My First Pygame Game")

# 색상 정의
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# 캐릭터 설정
player_size = 50
player_x = WIDTH // 2 - player_size // 2
player_y = HEIGHT - player_size - 10
player_speed = 5

# 적 설정
enemy_size = 50
enemy_x = random.randint(0, WIDTH - enemy_size)
enemy_y = 0
enemy_speed = 3

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

# 게임 루프
clock = pygame.time.Clock()
while True:
    # 이벤트 처리
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # 캐릭터 움직이기
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size:
        player_x += player_speed
    
    # 적 움직이기
    enemy_y += enemy_speed
    if enemy_y > HEIGHT:
        enemy_y = 0
        enemy_x = random.randint(0, WIDTH - enemy_size)
        score += 1
    
    # 충돌 감지
    if (player_x < enemy_x + enemy_size and
        player_x + player_size > enemy_x and
        player_y < enemy_y + enemy_size and
        player_y + player_size > enemy_y):
        print("Game Over!")
        pygame.quit()
        sys.exit()
    
    # 화면 그리기
    screen.fill(WHITE)
    pygame.draw.rect(screen, BLACK, (player_x, player_y, player_size, player_size))
    pygame.draw.rect(screen, RED, (enemy_x, enemy_y, enemy_size, enemy_size))
    
    # 점수 표시
    score_text = font.render(f"Score: {score}", True, BLACK)
    screen.blit(score_text, (10, 10))
    
    # 화면 업데이트
    pygame.display.flip()
    clock.tick(60)

이렇게 해서 간단한 2D 게임이 완성되었습니다. 이 게임에서는 플레이어가 떠어지는 적을 피하면서 점수를 얻는 구조 입니다.

마치며

Pygame을 사용하면 이렇게 간단한 게임도 쉽게 만들 수 있습니다. 이 기본 구조를 바탕으로 더 복잡한 게임 로직, 그래픽, 사운드 등을 추가하여 자신만의 게임을 만들어 보세요. 게임 개발은 프로그래밍 실력 향상에 큰 도움이 됩니다.

 

다음 단계로는 이미지를 사용하여 캐릭터와 적을 표현하거나, 배경 음악을 추가하거나, 레벨 시스템을 구현해 볼 수 있습니다. Pygame의 공식 문서를 참고하면 더 많은 기능을 활용할 수 있을거에요.

 

 Pygame으로 게임을 만들면서 프로그래밍의 즐거움을 느껴보세요.

반응형