[python] Pygame에서 인벤토리 시스템 구현하기

인벤토리 시스템은 게임 개발에서 중요한 요소 중 하나입니다. 이번 포스트에서는 Python의 Pygame 라이브러리를 사용하여 간단한 인벤토리 시스템을 구현하는 방법에 대해 알아보겠습니다.

Pygame 설치하기

먼저 Pygame을 설치해야 합니다. 아래 명령을 사용하여 Pygame을 설치할 수 있습니다.

pip install pygame

인벤토리 UI 만들기

인벤토리 시스템을 구현하려면 먼저 UI 요소를 만들어야 합니다. Pygame의 기능을 사용하여 간단한 인벤토리 UI를 만들 수 있습니다. 예를 들어, 아이템 슬롯을 표시하는 격자 모양의 UI를 생성해 보겠습니다.

import pygame

# Pygame 초기화
pygame.init()

# 화면 크기 설정
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("인벤토리")

# 셀 크기와 셀 개수 설정
cell_size = 50
cell_count = 10

def draw_inventory_ui():
    for row in range(cell_count):
        for col in range(cell_count):
            cell_x = col * cell_size
            cell_y = row * cell_size
            pygame.draw.rect(screen, (255, 255, 255), (cell_x, cell_y, cell_size, cell_size), 1)

# 메인 루프
running = True
while running:
    # 이벤트 처리
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 배경 색상 설정
    screen.fill((0, 0, 0))
    
    # 인벤토리 UI 그리기
    draw_inventory_ui()

    # 화면 업데이트
    pygame.display.flip()

# Pygame 종료
pygame.quit()

위 코드를 실행하면 10x10 크기의 셀로 이루어진 인벤토리 UI가 생성됩니다.

아이템 추가 및 제거 기능 구현하기

이제 인벤토리에 아이템을 추가하고 제거하는 기능을 구현해 보겠습니다. 아이템은 간단히 아이템 번호로 구분하고, 인벤토리는 2차원 배열로 표현할 수 있습니다.

# 인벤토리 데이터 초기화
inventory_data = [[0 for _ in range(cell_count)] for _ in range(cell_count)]

def add_item(item_id, row, col):
    if inventory_data[row][col] == 0:
        inventory_data[row][col] = item_id

def remove_item(row, col):
    if inventory_data[row][col] != 0:
        inventory_data[row][col] = 0

위 코드에서는 add_item 함수를 사용하여 아이템을 인벤토리에 추가하고, remove_item 함수를 사용하여 아이템을 인벤토리에서 제거합니다.

아이템 아이콘 표시하기

인벤토리에 추가된 아이템을 아이콘으로 표시해 보겠습니다. 각 아이템은 이미지 파일로 표현될 수 있습니다.

item_icons = {
    1: pygame.image.load("item_icon_1.png"),
    2: pygame.image.load("item_icon_2.png"),
    # ...
}

def draw_item_icons():
    for row in range(cell_count):
        for col in range(cell_count):
            item_id = inventory_data[row][col]
            if item_id != 0:
                item_icon = item_icons[item_id]
                cell_x = col * cell_size
                cell_y = row * cell_size
                screen.blit(item_icon, (cell_x, cell_y))

# 메인 루프
running = True
while running:
    # ...

    # 아이템 아이콘 그리기
    draw_item_icons()
  
    # ...

위의 코드에서는 item_icons 변수에 각 아이템의 아이콘 이미지를 할당하고, draw_item_icons 함수를 사용하여 아이템 아이콘을 그립니다. screen.blit 함수를 사용하여 아이템 아이콘을 화면에 그립니다.

결론

이번 포스트에서는 Pygame을 사용하여 간단한 인벤토리 시스템을 구현하는 방법에 대해 알아보았습니다. Pygame의 기능을 활용하여 UI를 생성하고, 아이템을 추가하고 제거하는 기능을 구현할 수 있습니다. 인벤토리 시스템은 게임에서 필수적인 기능이므로 유용하게 활용할 수 있을 것입니다.