[python] 파이썬으로 슈팅 게임 만들기

이번 프로젝트에서는 파이썬과 pygame 라이브러리를 사용하여 간단한 슈팅 게임을 만들어 보겠습니다. 이 게임은 우주선이 적들을 피해가며 발사체를 발사하여 적을 제거하는 형식의 게임입니다.

게임 화면 설정

먼저, pygame 라이브러리를 설치하고 기본적인 게임 화면을 설정합니다. 다음은 간단한 게임 창을 생성하는 코드입니다.

import pygame
pygame.init()

# 화면 크기 설정
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 게임 타이틀 설정
pygame.display.set_caption("Simple Shooting Game")

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

pygame.quit()

우주선 만들기

이제 우주선을 만들어 게임 화면에 표시해 보겠습니다. 다음은 간단한 우주선 이미지를 로드하여 화면에 표시하는 코드입니다.

# 우주선 이미지 로드
spaceship_img = pygame.image.load('spaceship.png')
spaceship_x = 370
spaceship_y = 480

# 우주선 그리기
def draw_spaceship(x, y):
    screen.blit(spaceship_img, (x, y))

# 게임 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    screen.fill((255, 255, 255))  # 화면을 흰색으로 지움
    draw_spaceship(spaceship_x, spaceship_y)  # 우주선을 화면에 그림
    pygame.display.update()  # 화면을 업데이트

pygame.quit()

총알 발사하기

이제 우주선이 총알을 발사할 수 있도록 만들어 보겠습니다.

# 총알 이미지 로드
bullet_img = pygame.image.load('bullet.png')
bullet_x = 0
bullet_y = 480
bullet_y_change = 1
bullet_state = "ready"  # ready: 발사 대기 상태, fire: 발사된 상태

# 총알 그리기
def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bullet_img, (x + 16, y + 10))

# 게임 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bullet_x = spaceship_x
                    fire_bullet(bullet_x, bullet_y)

    if bullet_state == "fire":
        fire_bullet(bullet_x, bullet_y)
        bullet_y -= bullet_y_change

    pygame.display.update()

pygame.quit()

결론

이제 여러분은 간단한 슈팅 게임을 파이썬과 pygame을 활용하여 만들 수 있습니다. 게임에는 적을 추가하고 충돌을 처리하는 등 여러 기능들을 추가할 수 있습니다. 이를 통해 게임 프로그래밍에 대한 기본적인 이해를 높일 수 있을 것입니다.

참고 자료: