본문 바로가기
08.개발&프로그래밍/1.파이썬

2. Python Snake Game (뱀 게임)

by JWJ Family 2025. 7. 18.
728x90

아래 코드는 Pygame 라이브러리로 구현한 간단한 뱀 게임입니다. 먼저 pip install pygame로 Pygame을 설치한 뒤, 이 코드를 snake_game.py로 저장하고 python snake_game.py로 실행하세요.

# snake_game.py

import pygame
import sys
import random

# 게임 초기화
pygame.init()
WIDTH, HEIGHT = 600, 600
CELL_SIZE = 20
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 36)

# 색상 정의
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED   = (255, 0, 0)

def draw_rect(color, pos):
    r = pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE)
    pygame.draw.rect(screen, color, r)

def show_text(text, pos):
    img = font.render(text, True, WHITE)
    screen.blit(img, pos)

def game_loop():
    snake = [(100, 100), (80,100), (60,100)]
    direction = (CELL_SIZE, 0)
    food = (random.randrange(0, WIDTH, CELL_SIZE), random.randrange(0, HEIGHT, CELL_SIZE))
    score = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP    and direction != (0, CELL_SIZE):
                    direction = (0, -CELL_SIZE)
                elif event.key == pygame.K_DOWN and direction != (0, -CELL_SIZE):
                    direction = (0, CELL_SIZE)
                elif event.key == pygame.K_LEFT and direction != (CELL_SIZE, 0):
                    direction = (-CELL_SIZE, 0)
                elif event.key == pygame.K_RIGHT and direction != (-CELL_SIZE, 0):
                    direction = (CELL_SIZE, 0)

        # 뱀 이동
        head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
        snake.insert(0, head)

        # 음식 먹기
        if head == food:
            score += 1
            food = (random.randrange(0, WIDTH, CELL_SIZE), random.randrange(0, HEIGHT, CELL_SIZE))
        else:
            snake.pop()

        # 충돌 체크: 벽
        if not (0 <= head[0] < WIDTH and 0 <= head[1] < HEIGHT):
            break
        # 충돌 체크: 자기 자신
        if head in snake[1:]:
            break

        # 그리기
        screen.fill(BLACK)
        draw_rect(RED, food)
        for segment in snake:
            draw_rect(GREEN, segment)
        show_text(f"Score: {score}", (10, 10))

        pygame.display.flip()
        clock.tick(10)

    # 게임 오버 화면
    screen.fill(BLACK)
    show_text("Game Over!", (WIDTH//2 - 100, HEIGHT//2 - 20))
    show_text(f"Final Score: {score}", (WIDTH//2 - 120, HEIGHT//2 + 20))
    pygame.display.flip()
    pygame.time.delay(2000)
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    game_loop()
반응형