Pygame Snake, 파트 1
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 클래스를 제공합니다.
-
메인 루프 바로 앞에 위치 벡터를 생성합니다:
dot = pygame.Vector2(500, 500) -
루프 안에서 화면을 지운 뒤 위치를 업데이트하고 사각형을 그립니다:
# 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.x를0으로 재설정해 사각형이 오른쪽 끝을 넘어가면 왼쪽에서 다시 나타나게 합니다.
dot.x += 10
if dot.x > 1000:
dot.x = 0