[python] Pygame을 활용한 실시간 전략 게임 만들기

pygame-logo

본 포스트에서는 Python의 게임 개발 라이브러리인 Pygame을 활용하여 실시간 전략 게임을 만들어보는 방법에 대해 알아보겠습니다.

목차

  1. Pygame 소개
  2. 전략 게임 개발 준비
  3. 게임 화면 구성
  4. 유닛 생성
  5. 유닛 이동
  6. 전투 시스템 구현
  7. 게임 로직 추가
  8. 결론

Pygame 소개

Pygame은 Python에서 2D 게임을 개발하기 위한 라이브러리로, 간단하고 효과적인 게임 개발을 위한 다양한 기능을 제공합니다. 게임 개발에 필요한 그래픽, 사운드, 이벤트 처리 등을 쉽게 구현할 수 있어 많은 개발자들에게 인기가 있습니다.

Pygame을 사용하기 위해서는 먼저 Python이 설치되어 있어야 합니다. Python을 설치한 후에는 다음 명령어를 사용하여 Pygame을 설치할 수 있습니다:

pip install pygame

전략 게임 개발 준비

전략 게임을 만들기 위해 필요한 요소들을 준비해야 합니다. 게임 맵, 유닛 종류, 리소스 등을 미리 설계하고 구현해야 합니다. 이 예제에서는 간단한 전략 게임을 만들기 위해 2D 맵과 기본적인 유닛 종류를 활용합니다.

게임 화면 구성

게임 화면을 구성하기 위해 Pygame의 기본적인 기능들을 사용합니다. pygame.init() 함수를 호출하여 Pygame을 초기화한 후, pygame.display.set_mode() 함수로 게임 창의 크기를 설정합니다. 게임 창 크기와 타이틀은 필요에 따라 변경할 수 있습니다.

import pygame

# 화면 초기화
pygame.init()

# 게임 창 설정
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("전략 게임")

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

    pygame.display.flip()

# 게임 종료
pygame.quit()

유닛 생성

유닛을 생성하기 위해 pygame.sprite.Sprite 클래스를 상속받는 Unit 클래스를 정의합니다. Unit 클래스는 유닛의 속성과 동작을 나타내는 멤버 변수와 메서드를 포함하게 됩니다.

import pygame

class Unit(pygame.sprite.Sprite):
    def __init__(self, x, y, image):
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5

    def update(self):
        pass

# 유닛 생성
unit = Unit(100, 100, "unit.png")

유닛 이동

유닛을 이동시키기 위해 update() 메서드를 수정합니다. 유닛의 x, y 좌표를 이동시키고, 그림을 업데이트합니다. 화면을 그리는 곳에서는 pygame.display.flip() 대신 pygame.display.update()를 호출하여 화면을 업데이트합니다.

import pygame

class Unit(pygame.sprite.Sprite):
    def __init__(self, x, y, image):
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed

# 유닛 생성
unit = Unit(100, 100, "unit.png")

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

    # 배경 그리기
    screen.fill((0, 0, 0))
    
    # 유닛 업데이트
    unit.update()
    screen.blit(unit.image, unit.rect)

    pygame.display.update()

# 게임 종료
pygame.quit()

전투 시스템 구현

전투 시스템을 구현하기 위해 각 유닛마다 공격력과 체력을 가지도록 수정합니다. 마우스 클릭 이벤트를 처리하여 유닛을 선택하고 공격할 수 있도록 합니다.

import pygame

class Unit(pygame.sprite.Sprite):
    def __init__(self, x, y, image, attack, hp):
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5
        self.attack = attack
        self.hp = hp

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed

    def attack_unit(self, target_unit):
        target_unit.hp -= self.attack

# 유닛 생성
unit1 = Unit(100, 100, "unit1.png", 10, 100)
unit2 = Unit(200, 200, "unit2.png", 20, 150)

# 게임 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                pos = pygame.mouse.get_pos()
                if unit1.rect.collidepoint(pos):
                    unit1.attack_unit(unit2)

    # 배경 그리기
    screen.fill((0, 0, 0))
    
    # 유닛 업데이트
    unit1.update()
    unit2.update()
    screen.blit(unit1.image, unit1.rect)
    screen.blit(unit2.image, unit2.rect)

    pygame.display.update()

# 게임 종료
pygame.quit()

게임 로직 추가

게임에 추가적인 로직을 구현하여 게임의 진행을 제어할 수 있습니다. 예를 들어, 게임 종료 조건을 설정하거나 게임 결과를 표시하는 기능을 추가할 수 있습니다.

import pygame

class Unit(pygame.sprite.Sprite):
    def __init__(self, x, y, image, attack, hp):
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5
        self.attack = attack
        self.hp = hp

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed

    def attack_unit(self, target_unit):
        target_unit.hp -= self.attack

# 유닛 생성
unit1 = Unit(100, 100, "unit1.png", 10, 100)
unit2 = Unit(200, 200, "unit2.png", 20, 150)

# 게임 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                pos = pygame.mouse.get_pos()
                if unit1.rect.collidepoint(pos):
                    unit1.attack_unit(unit2)

    # 배경 그리기
    screen.fill((0, 0, 0))
    
    # 유닛 업데이트
    unit1.update()
    unit2.update()
    screen.blit(unit1.image, unit1.rect)
    screen.blit(unit2.image, unit2.rect)

    # 게임 종료 조건 체크
    if unit1.hp <= 0 or unit2.hp <= 0:
        running = False

    pygame.display.update()

# 게임 종료
pygame.quit()

결론

이제 Pygame을 활용하여 실시간 전략 게임을 만들어보았습니다. Pygame의 강력한 기능을 활용하면 다양한 게임을 개발할 수 있습니다. 창의적인 아이디어와 노력을 통해 멋진 게임을 만들어보세요!

참고 자료