본문 바로가기
프로그래밍

파이썬을 이용한 공 튀기기 게임 만들기

by 코드금융 2025. 1. 6.
728x90
반응형

 

 

Python으로 공 튕기기 게임 만들기

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

1. Pygame 설치

먼저 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("공 튕기기 게임")

# 색상
background_color = (0, 0, 0)

# 게임 루프
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. 공 생성

화면에 공을 생성하고 표시합니다.

# 공 초기화
ball_color = (255, 255, 0)
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_dx = 4  # x축 이동 속도
ball_dy = 4  # y축 이동 속도

# 공 그리기
pygame.draw.circle(screen, ball_color, (ball_x, ball_y), ball_radius)
        

4. 공 움직임 구현

공이 화면에서 튕기며 움직이도록 만듭니다.

# 공 이동
ball_x += ball_dx
ball_y += ball_dy

# 화면 경계에서 튕기기
if ball_x - ball_radius <= 0 or ball_x + ball_radius >= screen_width:
    ball_dx *= -1  # x축 방향 반전
if ball_y - ball_radius <= 0 or ball_y + ball_radius >= screen_height:
    ball_dy *= -1  # y축 방향 반전

# 공 다시 그리기
pygame.draw.circle(screen, ball_color, (ball_x, ball_y), ball_radius)
        

5. 배경 음악 추가

게임에 배경 음악을 추가하여 몰입감을 높입니다.

# 배경 음악 초기화
pygame.mixer.init()
pygame.mixer.music.load("background_music.mp3")  # 사용하려는 MP3 파일 경로
pygame.mixer.music.play(-1)  # 반복 재생
        

6. 전체 코드 통합

위 코드를 통합하여 완성된 공 튕기기 게임을 만들어보세요. 더 흥미로운 기능(점수 시스템, 난이도 설정 등)을 추가하며 확장할 수 있습니다.

결론

Python과 Pygame을 활용해 간단한 공 튕기기 게임을 만들어 보았습니다. 이 게임은 초보자에게 적합하며, 이를 기반으로 다양한 확장 기능을 추가하여 더욱 재미있는 게임을 완성할 수 있습니다.

728x90
반응형