[파이썬] pygame 성과 및 리더보드 시스템

pygame logo

소개

Pygame은 파이썬으로 게임을 개발하기 위한 라이브러리이다. 사용하기 쉽고 강력한 기능을 제공하여 게임 제작자들에게 널리 사용되고 있다. 이 글에서는 pygame을 사용하여 게임 성과와 리더보드 시스템을 구현하는 방법에 대해 알아볼 것이다.

게임 성과 시스템

게임 성과 시스템은 플레이어가 게임 내에서 이룬 성과를 기록하고 표시하는 기능이다. 보통 게임 성과는 점수, 레벨 혹은 특정 도전 과제의 완료 여부 등으로 표현된다. pygame을 사용하면 쉽게 게임 성과 시스템을 구현할 수 있다.

import pygame

def display_score(score):
    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(score), True, (255, 255, 255))
    screen.blit(text, (10, 10))

def game():
    score = 0
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 게임 로직
        score += 10

        screen.fill((0, 0, 0))
        display_score(score)
        pygame.display.flip()

    pygame.quit()

game()

위 예제 코드는 간단한 게임 성과 시스템을 구현한 것이다. 게임을 플레이하면서 획득한 점수가 실시간으로 화면에 표시된다.

리더보드 시스템

리더보드 시스템은 플레이어들의 점수를 기록하고 순위를 확인할 수 있는 기능이다. pygame을 사용하여 리더보드 시스템을 구현하려면 점수를 파일에 저장하고 읽어오는 방법을 이용하면 된다.

import pygame
import json

def display_leaderboard(leaderboard):
    font = pygame.font.Font(None, 24)
    y = 50

    for i, entry in enumerate(leaderboard, start=1):
        text = font.render(f"{i}. {entry['name']}: {entry['score']}", True, (255, 255, 255))
        screen.blit(text, (10, y))
        y += 30

def save_score(name, score):
    with open('leaderboard.json', 'r') as file:
        leaderboard = json.load(file)

    leaderboard.append({
        'name': name,
        'score': score
    })

    leaderboard = sorted(leaderboard, key=lambda x: x['score'], reverse=True)

    with open('leaderboard.json', 'w') as file:
        json.dump(leaderboard, file)

def game():
    name = input("Enter your name: ")
    score = 0
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 게임 로직
        score += 10

        screen.fill((0, 0, 0))
        display_leaderboard(leaderboard)
        pygame.display.flip()

    save_score(name, score)
    pygame.quit()

game()

위 예제 코드는 간단한 리더보드 시스템을 구현한 것이다. 게임 종료 후 플레이어의 이름과 점수를 입력받아 리더보드에 저장한다.

마치며

이렇게 pygame을 사용하여 게임 성과와 리더보드 시스템을 구현할 수 있다. pygame의 강력한 기능을 활용하여 더욱 다양하고 창의적인 시스템을 만들어보는 것을 추천한다. Happy coding!