Menu
CoddyTech

먹이

Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 31개 중 6번째.

먹이는 뱀 위가 아닌 무작위 칸에 나타납니다. 무작위 칸을 선택하고 뱀의 몸 위에 놓이면 다시 시도합니다.

def new_food(body):
    while True:
        cell = (random.randrange(COLS), random.randrange(ROWS))
        if cell not in body:
            return cell

random.randrange(COLS)는 0부터 COLS - 1까지의 정수입니다. 즉, 모든 열이 포함되지만 가장자리에서 한 칸 더 나아가지는 않습니다. 빈 칸이 나오면 return이 함수를 끝내고, 그와 함께 반복문도 끝냅니다.

cell not in body는 전체 목록을 한 번에 확인합니다.

challenge icon

챌린지

쉬움
  1. 맨 위에 import random을 추가하세요.
  2. draw_cell 아래에 위와 같이 new_food(body)를 작성하세요.
  3. direction 다음에 food = new_food(body)를 설정하세요.
  4. 화면을 채운 다음 빨간색 (235, 80, 80)으로 먹이를 그리세요.

직접 해보기

import pygame

CELL = 20
COLS, ROWS = 24, 18
TURNS = {
    pygame.K_LEFT: (-1, 0),
    pygame.K_RIGHT: (1, 0),
    pygame.K_UP: (0, -1),
    pygame.K_DOWN: (0, 1),
}

pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()


def draw_cell(cell, color):
    col, row = cell
    pygame.draw.rect(screen, color, (col * CELL + 1, row * CELL + 1, CELL - 2, CELL - 2))


body = [(5, 9), (4, 9), (3, 9)]
direction = (1, 0)

running = True
while running:
    moving = direction
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key in TURNS:
            turn = TURNS[event.key]
            if turn != (-moving[0], -moving[1]):
                direction = turn

    x = body[0][0] + direction[0]
    y = body[0][1] + direction[1]
    body.insert(0, (x, y))
    body.pop()

    screen.fill((30, 30, 46))
    for cell in body[1:]:
        draw_cell(cell, (120, 220, 120))
    draw_cell(body[0], (180, 255, 160))
    pygame.display.flip()
    clock.tick(10)

pygame.quit()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

프로젝트의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드