프로그래밍

파이썬을 이용한 뱀 게임 만들기

코드금융 2025. 1. 5. 23:19
728x90
반응형

 

 

Python으로 뱀 게임 만들기

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

1. Pygame 설치

뱀 게임 개발을 위해 Pygame 라이브러리를 설치하세요:

pip install pygame
        

2. 기본 게임 창 설정

게임 화면을 생성하고 설정하는 코드를 작성합니다.

import pygame
import sys

# Pygame 초기화
pygame.init()

# 화면 설정
screen_width = 600
screen_height = 400
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. 뱀 생성

뱀의 몸체를 구성하는 코드입니다.

# 뱀 초기화
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
snake_direction = 'RIGHT'
change_to = snake_direction

# 뱀 그리기
for pos in snake_body:
    pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(pos[0], pos[1], 10, 10))
        

4. 먹이 생성

뱀이 먹을 수 있는 먹이를 화면에 추가합니다.

import random

# 먹이 초기화
food_pos = [random.randrange(1, screen_width//10) * 10, random.randrange(1, screen_height//10) * 10]
food_spawn = True

# 먹이 그리기
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(food_pos[0], food_pos[1], 10, 10))
        

5. 뱀의 움직임

뱀이 방향키로 움직일 수 있도록 설정합니다.

# 방향키 입력 처리
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP and not snake_direction == 'DOWN':
            snake_direction = 'UP'
        if event.key == pygame.K_DOWN and not snake_direction == 'UP':
            snake_direction = 'DOWN'
        if event.key == pygame.K_LEFT and not snake_direction == 'RIGHT':
            snake_direction = 'LEFT'
        if event.key == pygame.K_RIGHT and not snake_direction == 'LEFT':
            snake_direction = 'RIGHT'

# 뱀 이동
if snake_direction == 'UP':
    snake_pos[1] -= 10
if snake_direction == 'DOWN':
    snake_pos[1] += 10
if snake_direction == 'LEFT':
    snake_pos[0] -= 10
if snake_direction == 'RIGHT':
    snake_pos[0] += 10

# 새로운 위치 업데이트
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
    food_spawn = False
else:
    snake_body.pop()
        

6. 충돌 처리

뱀이 벽이나 자신의 몸에 부딪히면 게임이 종료되도록 설정합니다.

# 벽 충돌 처리
if snake_pos[0] < 0 or snake_pos[0] > screen_width-10:
    running = False
if snake_pos[1] < 0 or snake_pos[1] > screen_height-10:
    running = False

# 몸 충돌 처리
for block in snake_body[1:]:
    if snake_pos == block:
        running = False
        

7. 전체 코드 통합

위 코드를 통합하여 완성된 뱀 게임을 만들어보세요. 점수 시스템과 난이도 조정을 추가하면 더욱 재미있게 즐길 수 있습니다.

결론

Python과 Pygame을 활용해 간단한 뱀 게임을 만들어 보았습니다. 이 게임은 초보자도 쉽게 구현할 수 있으며, 다양한 기능을 추가하며 확장할 수 있습니다.

© 2025. All rights reserved. 코딩 전문 블로그

728x90
반응형