프로그래밍

파이썬을 이용한 2D 플랫폼 게임 만들기

코드금융 2025. 1. 6. 06:50
728x90
반응형

 

 

Python으로 2D 플랫폼 게임 만들기

Pygame을 활용한 단계별 코딩 튜토리얼

1. Pygame 설치

2D 플랫폼 게임을 개발하기 위해 Pygame 라이브러리를 설치하세요:

pip install pygame
        

2. 기본 게임 창 설정

게임 화면을 생성하고 설정합니다.

import pygame
import sys

# Pygame 초기화
pygame.init()

# 화면 설정
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("2D 플랫폼 게임")

# 색상 설정
background_color = (135, 206, 250)  # 하늘색

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

    screen.fill(background_color)
    pygame.display.flip()

pygame.quit()
sys.exit()
        

3. 플레이어 캐릭터 추가

플레이어 캐릭터를 화면에 추가합니다.

# 플레이어 초기화
player_color = (255, 0, 0)  # 빨간색
player_width = 50
player_height = 50
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 50
player_speed = 5

# 게임 루프 안에 추가
pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height))
        

4. 플랫폼 추가

플레이어가 점프하고 서 있을 수 있는 플랫폼을 추가합니다.

# 플랫폼 초기화
platform_color = (0, 255, 0)  # 초록색
platform_width = 200
platform_height = 20
platform_x = 300
platform_y = 400

# 플랫폼 그리기
pygame.draw.rect(screen, platform_color, (platform_x, platform_y, platform_width, platform_height))
        

5. 플레이어 이동 구현

키보드 입력을 통해 플레이어를 움직이도록 설정합니다.

# 키보드 입력 처리
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 < screen_width - player_width:
    player_x += player_speed

# 플레이어 다시 그리기
pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height))
        

6. 점프 기능 추가

플레이어가 점프할 수 있도록 기능을 구현합니다.

# 점프 초기화
is_jumping = False
jump_height = 10
gravity = 1
velocity = jump_height

# 점프 구현
if keys[pygame.K_SPACE] and not is_jumping:
    is_jumping = True
    velocity = -jump_height

if is_jumping:
    player_y += velocity
    velocity += gravity
    if player_y >= screen_height - player_height - 50:  # 바닥 도달 시
        player_y = screen_height - player_height - 50
        is_jumping = False
        

7. 전체 코드 통합

위의 코드를 통합하여 완성된 2D 플랫폼 게임을 만듭니다. 추가적으로 점수 시스템, 적 캐릭터 등을 추가해 게임을 확장할 수 있습니다.

결론

Python과 Pygame으로 간단한 2D 플랫폼 게임을 만들어 보았습니다. 기본적인 기능을 구현한 후, 게임의 재미를 더하기 위해 다양한 요소를 추가해 보세요!

728x90
반응형