Pygame 贪吃蛇,第1部分

发布: (2026年4月22日 GMT+8 04:50)
4 分钟阅读
原文: Dev.to

Source: Dev.to

介绍

Pygame 是一个让我们可以使用 Python 创建 2D 游戏的模块。它是学习编程概念的好方式,而经典游戏 Snake 则是初学者的优秀项目。

使用 Pygame 时,每一帧都会先绘制到离屏缓冲区(内存中的不可见画布)。场景组装完毕后,缓冲区会被复制到屏幕画布上。Pygame 还负责管理事件循环,允许我们指定目标帧率(FPS),并处理诸如键盘按下 (KEYDOWN) 和窗口关闭 (QUIT) 等事件。

最小化 Pygame 设置

下面是一个最小的 Pygame 程序(改编自官方文档)。它创建一个 1000 × 1000 的窗口,每帧清空屏幕,并将循环限制在 20 FPS。

import pygame

# initialize pygame
pygame.init()

# create 1000x1000 pixel pygame window
screen = pygame.display.set_mode((1000, 1000))

# clock used to set FPS
clock = pygame.time.Clock()

# game runs as long as this is True
running = True

while running:
    # poll for events
    for event in pygame.event.get():
        # pygame.QUIT = user closed window
        if event.type == pygame.QUIT:
            running = False

    # fill buffer with white
    screen.fill("white")

    # copy buffer to screen
    pygame.display.flip()

    # limits FPS
    clock.tick(20)

pygame.quit()

注意: running 标志用于在收到 QUIT 事件时干净地退出循环。Python 不能直接跳出嵌套循环,所以这种模式在 Pygame 程序中很常见。

添加移动方块

要让方块动起来,需要一个变量来跟踪它的位置。Pygame 提供了便利的 Vector2 类用于二维坐标。

  1. 在主循环之前创建位置向量:

    dot = pygame.Vector2(500, 500)
  2. 在循环内部、清空屏幕之后更新位置并绘制方块:

    # fill buffer with white
    screen.fill("white")
    
    # move the square
    dot.x += 10
    square = pygame.Rect(dot, (50, 50))
    screen.fill("black", square)

screen.fill("white") 调用会清除上一帧,而新增的三行代码会在更新后的坐标处绘制一个 50 × 50 的黑色方块。

完整代码(含移动方块)

import pygame

# pygame setup
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
clock = pygame.time.Clock()
running = True

# initial position of the square
dot = pygame.Vector2(500, 500)

while running:
    # poll for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # clear the screen
    screen.fill("white")

    # update position and draw the square
    dot.x += 10
    square = pygame.Rect(dot, (50, 50))
    screen.fill("black", square)

    # present the frame
    pygame.display.flip()

    # limit FPS
    clock.tick(20)

pygame.quit()

挑战

如果你已经对 Python 感到熟悉,尝试对程序进行扩展:

  • 添加检查,判断 dot.x 是否超过窗口宽度(1000)。
  • 若超过,则将 dot.x 重置为 0,使方块在右边缘消失后从左侧重新出现。
dot.x += 10
if dot.x > 1000:
    dot.x = 0
0 浏览
Back to Blog

相关文章

阅读更多 »

Pygame Snake,第2部分

介绍 在第一部分,我们建立了一个基本的 pygame 窗口,拥有 1000 × 1000 像素的画布和一个 50 × 50 像素的方块,该方块持续移动。对于贪吃蛇游戏 w...

Pygame Snake,第3部分

使用键盘输入控制方块 在第2部分中,我们有一个在网格上移动的方块。现在我们将让它响应 KEYDOWN 事件,以便玩家可以控制它……