Pygame Snake, 파트 4

발행: (2026년 5월 3일 PM 03:43 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

Introduction

1 ~ 3부에서는 실제 게임 로직을 제외한 모든 것을 조립했습니다. 이제 뱀의 동작을 추가합니다.

Replace the single dot with a snake list

원래 정의를 다음과 같이 바꾸세요:

dot = pygame.Vector2(W / 2, H / 2)

snake = [pygame.Vector2(W / 2, H / 2)]

Add a growth counter

while 루프 바로 위에 다음을 추가합니다:

grow = 3

이렇게 하면 뱀의 초기 길이가 4가 됩니다.

Update the game loop

Compute the new head position

dot += vel 를 다음으로 교체합니다:

new_head = snake[-1] + vel

Detect self‑collision

if new_head in snake:
    print("hit self")
    break

Append the new head

snake.append(new_head)

Handle growth vs. normal movement

if grow > 0:
    grow -= 1
else:
    snake.pop(0)

Draw the whole snake

이전에 단일 점을 그리던 두 줄을 찾으세요:

square = pygame.Rect(dot * S, (S, S))
screen.fill("black", square)

이를 모든 세그먼트를 그리는 루프로 교체합니다:

for dot in snake:
    square = pygame.Rect(dot * S, (S, S))
    screen.fill("black", square)

Full code at this point

import pygame
import random

W = 30
H = 30
S = 20

# pygame setup
pygame.init()
screen = pygame.display.set_mode((W * S, H * S))
clock = pygame.time.Clock()
running = True

# game setup
snake = [pygame.Vector2(W / 2, H / 2)]
vel = pygame.Vector2(1, 0)

key_vel = {
    pygame.K_RIGHT: pygame.Vector2(1, 0),
    pygame.K_DOWN: pygame.Vector2(0, 1),
    pygame.K_LEFT: pygame.Vector2(-1, 0),
    pygame.K_UP: pygame.Vector2(0, -1)
}

grow = 3

def place_food():
    global food_pos
    food_pos = pygame.Vector2(
        random.randrange(W),
        random.randrange(H)
    )
    while food_pos in snake:
        food_pos = pygame.Vector2(
            random.randrange(W),
            random.randrange(H)
        )

place_food()

while running:
    # poll for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key in key_vel:
            vel = key_vel[event.key]

    # clear screen
    screen.fill("white")

    new_head = snake[-1] + vel

    if new_head in snake:
        print("hit self")
        break

    if new_head == food_pos:
        grow += 1
        place_food()

    snake.append(new_head)

    if grow > 0:
        grow -= 1
    else:
        snake.pop(0)

    for dot in snake:
        square = pygame.Rect(dot * S, (S, S))
        screen.fill("black", square)

    square = pygame.Rect(food_pos * S, (S, S))
    screen.fill("green", square)

    # update display
    pygame.display.flip()

    # limit FPS
    clock.tick(20)

pygame.quit()

Next steps

다음 튜토리얼 파트인 Part 5 를 계속 진행하세요.

0 조회
Back to Blog

관련 글

더 보기 »

Python 시작하기

오늘 나는 파이썬을 배우기 시작했고, 파이썬이 실제로 어떻게 작동하는지 이해하는 데 도움이 되는 몇 가지 기본 개념을 탐구했습니다. 파이썬이란 무엇인가요?

개발자로서 당신의 Fear Score는?

두려움은 우리에게 모든 것을 앗아갑니다. 나는 한 번 “You miss 100% of the shots you don’t take”라는 말을 들었고, 그것이 내 경력 전반에 울려 퍼졌습니다. 돌아보면, 나는 man…

TanStack Start와 Bun을 Railway에 배포

문제 Railway의 Nixpacks 자동 빌드가 Bun 프로젝트를 감지하지만, 이 사이트가 필요로 하는 순서를 처리할 수 없습니다: - 빌드 시 prisma generate - Vite + TanStack ...