Menu
CoddyTech

关卡

Coddy 用 Pygame 制作游戏 课程的第 28 课,共 41 课。

每吃到 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 时,在 (240, 180) 居中显示 You win!。

按下“开始”:顶部会显示 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 制作游戏中的所有课

自己练习: Pygame 在线编辑器