Menu
CoddyTech

关卡

本课属于 Coddy Pygame 学习旅程的“项目”单元。第 10 课,共 33 课。

每吃到 5 个食物,蛇就会升到新等级,移动速度也会加快。等级由分数决定:整除运算 score // 5 在分数为 0 到 4 时结果为 0,为 5 到 9 时结果为 1,以此类推。

level = score // 5 + 1
clock.tick(8 + 2 * level)

蛇每帧移动一个格子,所以每秒帧数越多,蛇的速度就越快:等级 1 时每秒移动 10 步,等级 2 时每秒移动 12 步,等级 3 时每秒移动 14 步。

吃到 15 个食物即可获胜。当 alive and score < 15 为假时,游戏停止,并显示 You win!。

challenge icon

挑战

困难

让蛇随着身体变长而加速,直到获胜。

  1. 每一帧,将 level = score // 5 + 1 设为变量,并在 (370, 6) 显示 f"Level: {level}"。
  2. 将每秒帧数设为 8 + 2 * level。
  3. 仅在 alive and score < 15 时移动,并在分数为 15 时,将 You win! 显示在中心位置 (240, 180)。

按“开始”:顶部会显示 Level: 1。然后按“检查”。

亲手试试

import random
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()
font = pygame.font.Font(None, 32)


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


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


body = [(5, 9), (4, 9), (3, 9)]
direction = (1, 0)
food = new_food(body)
score = 0
alive = True

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

    if alive:
        x = body[0][0] + direction[0]
        y = body[0][1] + direction[1]
        if x < 0 or x >= COLS or y < 0 or y >= ROWS or (x, y) in body[:-1]:
            alive = False
        else:
            body.insert(0, (x, y))
            if (x, y) == food:
                score += 1
                food = new_food(body)
            else:
                body.pop()

    screen.fill((30, 30, 46))
    draw_cell(food, (235, 80, 80))
    for cell in body[1:]:
        draw_cell(cell, (120, 220, 120))
    draw_cell(body[0], (180, 255, 160))
    score_text = font.render(f"Score: {score}", True, (240, 240, 240))
    screen.blit(score_text, (8, 6))
    if not alive:
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 180)))
    pygame.display.flip()
    clock.tick(10)

pygame.quit()

项目中的所有课

自己练习: Pygame 在线编辑器