알았어! 파이썬으로 만들 수 있는 가장 간단하면서도 재밌는 공놀이 게임 중 하나는 '퐁(Pong)' 게임이야. 플레이어가 패들을 움직여 공을 튕겨내고, 컴퓨터(AI)와 대결하는 방식이지.
pygame 라이브러리를 사용할 거야. 설치되어 있지 않다면, 터미널에서 다음 명령어를 실행해 줘:
pip install pygame
아래 코드를 pong_game.py 같은 이름으로 저장하고 실행하면 돼.
import pygame
import sys
import random
# 1. 게임 초기화
pygame.init()
# 2. 화면 설정
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("신나는 파이썬 퐁 게임!")
# 3. 색상 정의
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0) # AI 패들 색상
# 4. 게임 오브젝트 속성 정의
# 볼
ball_radius = 15
ball_x = SCREEN_WIDTH // 2
ball_y = SCREEN_HEIGHT // 2
ball_speed_x = 7 * random.choice((1, -1)) # 처음 시작 방향 랜덤
ball_speed_y = 7 * random.choice((1, -1))
ball_speed_increase_factor = 0.1 # 공 속도 증가량
# 패들
paddle_width = 20
paddle_height = 100
player_paddle_x = 50
player_paddle_y = SCREEN_HEIGHT // 2 - paddle_height // 2
ai_paddle_x = SCREEN_WIDTH - 50 - paddle_width
ai_paddle_y = SCREEN_HEIGHT // 2 - paddle_height // 2
paddle_speed = 10 # 플레이어 패들 속도
ai_paddle_speed = 7 # AI 패들 속도
# 점수
player_score = 0
ai_score = 0
winning_score = 5 # 승리 조건 점수
# 폰트
font = pygame.font.Font(None, 74) # 점수 표시용
small_font = pygame.font.Font(None, 48) # 게임 오버 메시지용
# 게임 상태
game_state = "playing" # "playing", "game_over"
# 5. 게임 기능 함수
def reset_ball():
global ball_x, ball_y, ball_speed_x, ball_speed_y
ball_x = SCREEN_WIDTH // 2
ball_y = SCREEN_HEIGHT // 2
ball_speed_x = 7 * random.choice((1, -1)) # 새로운 방향으로 재설정
ball_speed_y = 7 * random.choice((1, -1))
def draw_objects():
screen.fill(BLACK) # 화면을 검은색으로 채움
# 중앙선 그리기
pygame.draw.aaline(screen, WHITE, (SCREEN_WIDTH // 2, 0), (SCREEN_WIDTH // 2, SCREEN_HEIGHT))
# 볼 그리기
pygame.draw.circle(screen, WHITE, (int(ball_x), int(ball_y)), ball_radius)
# 플레이어 패들 그리기 (빨간색)
pygame.draw.rect(screen, RED, (player_paddle_x, player_paddle_y, paddle_width, paddle_height))
# AI 패들 그리기 (초록색)
pygame.draw.rect(screen, GREEN, (ai_paddle_x, ai_paddle_y, paddle_width, paddle_height))
# 점수 표시
player_text = font.render(str(player_score), True, WHITE)
screen.blit(player_text, (SCREEN_WIDTH // 4, 20))
ai_text = font.render(str(ai_score), True, WHITE)
screen.blit(ai_text, (SCREEN_WIDTH * 3 // 4 - ai_text.get_width(), 20))
def display_game_over():
screen.fill(BLACK)
if player_score >= winning_score:
message = "당신 승리! 다시 하려면 'R' 키"
color = RED
else:
message = "AI 승리! 다시 하려면 'R' 키"
color = GREEN
game_over_text = font.render("게임 종료!", True, WHITE)
message_text = small_font.render(message, True, color)
game_over_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 50))
message_rect = message_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 20))
screen.blit(game_over_text, game_over_rect)
screen.blit(message_text, message_rect)
pygame.display.flip()
# 6. 게임 루프
clock = pygame.time.Clock()
running = True
player_paddle_dy = 0 # 플레이어 패들 이동 방향 (0:정지, -1:위, 1:아래)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if game_state == "playing":
# 키 입력 처리 (플레이어 패들)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_paddle_dy = -1
elif event.key == pygame.K_DOWN:
player_paddle_dy = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_paddle_dy = 0
elif game_state == "game_over":
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r: # 'R' 키를 누르면 게임 재시작
player_score = 0
ai_score = 0
reset_ball()
game_state = "playing"
if game_state == "playing":
# 플레이어 패들 이동
player_paddle_y += player_paddle_dy * paddle_speed
# 패들이 화면을 벗어나지 않도록 제한
if player_paddle_y < 0:
player_paddle_y = 0
if player_paddle_y > SCREEN_HEIGHT - paddle_height:
player_paddle_y = SCREEN_HEIGHT - paddle_height
# AI 패들 이동 (간단한 AI: 볼을 따라감)
if ai_paddle_y + paddle_height // 2 < ball_y:
ai_paddle_y += ai_paddle_speed
elif ai_paddle_y + paddle_height // 2 > ball_y:
ai_paddle_y -= ai_paddle_speed
# AI 패들도 화면을 벗어나지 않도록 제한
if ai_paddle_y < 0:
ai_paddle_y = 0
if ai_paddle_y > SCREEN_HEIGHT - paddle_height:
ai_paddle_y = SCREEN_HEIGHT - paddle_height
# 볼 이동
ball_x += ball_speed_x
ball_y += ball_speed_y
# 볼 벽 충돌 처리 (상하)
if ball_y - ball_radius < 0 or ball_y + ball_radius > SCREEN_HEIGHT:
ball_speed_y *= -1
# 볼 점수 처리 (좌우)
if ball_x - ball_radius < 0: # AI 득점
ai_score += 1
reset_ball()
if ball_x + ball_radius > SCREEN_WIDTH: # 플레이어 득점
player_score += 1
reset_ball()
# 볼과 패들 충돌 처리
# 플레이어 패들
player_paddle_rect = pygame.Rect(player_paddle_x, player_paddle_y, paddle_width, paddle_height)
# AI 패들
ai_paddle_rect = pygame.Rect(ai_paddle_x, ai_paddle_y, paddle_width, paddle_height)
# 볼
ball_rect = pygame.Rect(ball_x - ball_radius, ball_y - ball_radius, ball_radius * 2, ball_radius * 2)
if ball_rect.colliderect(player_paddle_rect):
if ball_speed_x < 0: # 공이 왼쪽으로 가고 있을 때만 충돌 처리 (중복 충돌 방지)
ball_speed_x *= -1.1 # 속도를 조금 더 빠르게
ball_speed_x *= (1 + ball_speed_increase_factor) # 속도 증가
ball_speed_y *= (1 + ball_speed_increase_factor) # 속도 증가
# 패들 어디에 맞았는지에 따라 Y축 속도 조절 (더 재밌게)
relative_impact_y = (ball_y - player_paddle_y) - paddle_height / 2
ball_speed_y = relative_impact_y * 0.3 # 튕기는 각도 변화
if ball_rect.colliderect(ai_paddle_rect):
if ball_speed_x > 0: # 공이 오른쪽으로 가고 있을 때만 충돌 처리
ball_speed_x *= -1.1 # 속도를 조금 더 빠르게
ball_speed_x *= (1 + ball_speed_increase_factor) # 속도 증가
ball_speed_y *= (1 + ball_speed_increase_factor) # 속도 증가
# 패들 어디에 맞았는지에 따라 Y축 속도 조절
relative_impact_y = (ball_y - ai_paddle_y) - paddle_height / 2
ball_speed_y = relative_impact_y * 0.3 # 튕기는 각도 변화
# 승리 조건 확인
if player_score >= winning_score or ai_score >= winning_score:
game_state = "game_over"
# 모든 오브젝트 그리기
draw_objects()
else: # game_state == "game_over"
display_game_over()
# 화면 업데이트
pygame.display.flip()
# 초당 프레임 설정
clock.tick(60)
# 7. 게임 종료
pygame.quit()
sys.exit()
게임 설명 및 플레이 방법
- 실행: 코드를
.py 파일로 저장한 후, 터미널에서 python your_file_name.py 명령으로 실행합니다.
- 목표: 공을 상대방(AI) 패들 뒤로 보내 점수를 얻는 것입니다. 먼저
5점을 얻는 플레이어가 승리합니다.
- 조작:
- ↑ (위쪽 화살표) 키: 내 패들(왼쪽 빨간색)을 위로 움직입니다.
- ↓ (아래쪽 화살표) 키: 내 패들(왼쪽 빨간색)을 아래로 움직입니다.
- 재미 요소:
- 속도 증가: 공이 패들에 부딪힐 때마다 점점 빨라져 게임이 점점 더 스릴 있어집니다.
- 튕기는 각도 변화: 공이 패들의 어느 부분에 맞느냐에 따라 튕겨 나가는 각도가 달라져서 좀 더 전략적인 플레이가 가능합니다. (패들 중앙에 맞으면 직선으로, 가장자리에 맞으면 더 큰 각도로 튕겨 나갑니다.)
- 간단한 AI: 컴퓨터(오른쪽 초록색 패들)는 공의 위치를 추적하여 움직이지만, 완벽하지 않아서 충분히 이길 수 있습니다!
- 게임 종료 및 재시작: 누가 이겼는지 보여주고,
R 키를 눌러 게임을 쉽게 재시작할 수 있습니다.
재밌게 즐겨보세요! 궁금한 점이 있으면 언제든지 다시 물어봐.