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 를 계속 진행하세요.