Pygame Snake, 파트 1

발행: (2026년 4월 22일 AM 05:50 GMT+9)
4 분 소요
원문: Dev.to

Source: Dev.to

Introduction

Pygame은 Python으로 2D 게임을 만들 수 있게 해 주는 모듈입니다. 프로그래밍 개념을 배우기에 좋은 방법이며, 고전 게임 Snake은 초보자에게 훌륭한 프로젝트가 됩니다.

Pygame을 사용할 때, 각 프레임은 화면 밖 버퍼(메모리상의 보이지 않는 캔버스)에 그려집니다. 씬이 완성되면 버퍼가 화면 캔버스로 복사됩니다. Pygame은 또한 이벤트 루프를 관리해 주어 목표 프레임‑퍼‑초(FPS)를 지정하고 키 입력(KEYDOWN)이나 창 닫힘(QUIT) 같은 이벤트를 처리합니다.

Minimal Pygame Setup

아래는 최소한의 Pygame 프로그램(공식 문서에서 가져옴)입니다. 1000 × 1000 창을 만들고, 매 프레임 화면을 지우며, 루프를 20 FPS로 제한합니다.

import pygame

# initialize pygame
pygame.init()

# create 1000x1000 pixel pygame window
screen = pygame.display.set_mode((1000, 1000))

# clock used to set FPS
clock = pygame.time.Clock()

# game runs as long as this is True
running = True

while running:
    # poll for events
    for event in pygame.event.get():
        # pygame.QUIT = user closed window
        if event.type == pygame.QUIT:
            running = False

    # fill buffer with white
    screen.fill("white")

    # copy buffer to screen
    pygame.display.flip()

    # limits FPS
    clock.tick(20)

pygame.quit()

Note: running 플래그는 QUIT 이벤트가 발생했을 때 루프를 깔끔하게 종료하기 위해 사용됩니다. Python은 중첩 루프를 직접 빠져나올 수 없으므로, 이 패턴이 Pygame 프로그램에서 흔히 쓰입니다.

Adding a Moving Square

사각형을 애니메이션하려면 위치를 추적하는 변수가 필요합니다. Pygame은 2‑D 좌표를 위한 편리한 Vector2 클래스를 제공합니다.

  1. 메인 루프 바로 앞에 위치 벡터를 생성합니다:

    dot = pygame.Vector2(500, 500)
  2. 루프 안에서 화면을 지운 뒤 위치를 업데이트하고 사각형을 그립니다:

    # fill buffer with white
    screen.fill("white")
    
    # move the square
    dot.x += 10
    square = pygame.Rect(dot, (50, 50))
    screen.fill("black", square)

screen.fill("white") 호출은 이전 프레임을 지우고, 새로 추가된 세 줄은 업데이트된 좌표에 50 × 50 검은색 사각형을 그립니다.

Full Code with Moving Square

import pygame

# pygame setup
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
clock = pygame.time.Clock()
running = True

# initial position of the square
dot = pygame.Vector2(500, 500)

while running:
    # poll for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # clear the screen
    screen.fill("white")

    # update position and draw the square
    dot.x += 10
    square = pygame.Rect(dot, (50, 50))
    screen.fill("black", square)

    # present the frame
    pygame.display.flip()

    # limit FPS
    clock.tick(20)

pygame.quit()

Challenge

Python에 익숙하다면 프로그램을 확장해 보세요:

  • dot.x가 창 너비(1000)를 초과하는지 확인하는 코드를 추가합니다.
  • 초과한다면 dot.x0으로 재설정해 사각형이 오른쪽 끝을 넘어가면 왼쪽에서 다시 나타나게 합니다.
dot.x += 10
if dot.x > 1000:
    dot.x = 0
0 조회
Back to Blog

관련 글

더 보기 »

Pygame Snake, 파트 2

소개 파트 1에서는 1000 × 1000 픽셀 캔버스와 지속적으로 움직이는 50 × 50 픽셀 정사각형을 가진 기본 pygame 창을 설정했습니다. 뱀 게임을 위해 w...

Pygame Snake, 파트 3

키보드 입력으로 정사각형 제어 파트 2에서 우리는 격자 위를 움직이는 정사각형을 보았습니다. 이제 KEYDOWN 이벤트에 반응하도록 만들어 플레이어가 제어할 수 있게 합니다.