Pygame Snake,第4部分

发布: (2026年5月3日 GMT+8 14:43)
3 分钟阅读
原文: Dev.to

Source: Dev.to

介绍

在第 1、2、3 部分中,我们已经组装好了一切,除了实际的游戏逻辑。现在我们来添加贪吃蛇的机制。

用蛇列表替换单个点

将原来的定义:

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

改为:

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

添加增长计数器

while 循环上方加入:

grow = 3

这会让蛇的初始长度为 4。

更新游戏循环

计算新的头部位置

dot += vel 替换为:

new_head = snake[-1] + vel

检测自碰撞

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

追加新的头部

snake.append(new_head)

处理增长与普通移动

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

绘制整条蛇

找到之前绘制单个点的两行代码:

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)

此时的完整代码

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()

后续步骤

继续阅读教程的下一部分:Part 5

0 浏览
Back to Blog

相关文章

阅读更多 »

Python 入门指南

今天我开始学习 Python,并且探索了一些基本概念,这些概念帮助我了解 Python 在幕后是如何实际工作的。Python 是什么?...

Claude 运行快速。Codex 发布。

摘要:我给 Claude 和 Codex 两个大型编码任务。- Claude 大约在一小时内完成。- Codex 大约用了八小时。乍一看,这看起来像是……