프로그래밍
파이썬을 이용한 슈팅게임 만들기
코드금융
2025. 1. 5. 23:10
728x90
반응형
Python으로 슈팅 게임 만들기
Pygame을 활용한 단계별 튜토리얼
1. Pygame 설치
Python으로 게임을 개발하기 위해 Pygame 라이브러리를 사용합니다. 먼저 터미널에서 아래 명령어를 실행하여 Pygame을 설치하세요:
pip install pygame
2. 기본 게임 창 만들기
게임의 기본 창을 설정하는 코드입니다. Pygame을 초기화하고 간단한 화면을 만듭니다.
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("슈팅 게임")
# 게임 루프
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0)) # 검은 배경
pygame.display.flip() # 화면 업데이트
pygame.quit()
sys.exit()
3. 플레이어 캐릭터 추가
플레이어의 우주선을 화면에 표시해 보겠습니다. 이미지 파일을 사용하거나 간단한 도형으로 그릴 수 있습니다.
# 플레이어 초기화
player_width = 50
player_height = 30
player_x = screen_width // 2 - player_width // 2
player_y = screen_height - player_height - 10
player_color = (0, 255, 0)
# 게임 루프 안에 추가
pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height))
4. 적 캐릭터와 이동
적 캐릭터를 화면 위에 생성하고, 아래로 움직이게 만들어 보겠습니다.
# 적 초기화
enemy_width = 50
enemy_height = 30
enemy_x = screen_width // 2 - enemy_width // 2
enemy_y = 0
enemy_color = (255, 0, 0)
enemy_speed = 5
# 적 이동
enemy_y += enemy_speed
pygame.draw.rect(screen, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
5. 총알 발사 구현
플레이어가 스페이스바를 누르면 총알이 발사되도록 구현합니다.
# 총알 초기화
bullets = []
# 총알 발사
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
bullets.append([player_x + player_width // 2, player_y])
# 총알 이동 및 그리기
for bullet in bullets:
bullet[1] -= 10 # 위로 이동
pygame.draw.rect(screen, (255, 255, 0), (bullet[0], bullet[1], 5, 10))
6. 충돌 감지
총알과 적이 충돌했을 때 적을 제거하는 코드를 추가합니다.
# 충돌 감지
for bullet in bullets:
if enemy_x < bullet[0] < enemy_x + enemy_width and enemy_y < bullet[1] < enemy_y + enemy_height:
bullets.remove(bullet)
enemy_y = 0 # 적을 초기화
enemy_x = random.randint(0, screen_width - enemy_width)
7. 전체 코드 통합
위의 코드를 통합하여 완성된 슈팅 게임 코드를 만들어보세요. 단계적으로 개선하면서 재미있는 게임을 만들어 보세요!
결론
Python과 Pygame으로 간단한 슈팅 게임을 만들어 보았습니다. 게임 개발의 기본 원리를 이해하고, 더 나아가 다양한 기능을 추가하며 나만의 게임을 완성해 보세요!
728x90
반응형