Pygame Snake,第2部分
发布: (2026年4月22日 GMT+8 06:23)
3 分钟阅读
原文: Dev.to
Source: Dev.to
介绍
在第 1 部分中,我们设置了一个基本的 pygame 窗口,画布大小为 1000 × 1000 像素,并有一个 50 × 50 像素的方块持续移动。对于贪吃蛇游戏,我们需要一个固定的网格,所以我们会把瓦片和画布都缩小。
更新瓦片大小和网格
我们将使用 30 × 30 的网格,每个瓦片为 20 像素正方形(30 瓦片 × 20 像素 = 600 像素)。定义三个常量,并用它们来替换所有硬编码的数字:
W = 30 # 网格宽度(瓦片数)
H = 30 # 网格高度(瓦片数)
S = 20 # 瓦片大小(像素)
使用这些值创建屏幕:
screen = pygame.display.set_mode((W * S, H * S))
将蛇的头部(或“点”)大致放在网格中心:
dot = pygame.Vector2(W / 2, H / 2)
绘制方块时,通过将网格坐标乘以 S 将其缩放到像素坐标:
square = pygame.Rect(dot * S, (S, S))
在创建方块之前,为水平轴添加一次环绕检查:
if dot.x > W:
dot.x = 0
此时的完整代码
import pygame
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
dot = pygame.Vector2(W / 2, H / 2)
while running:
# poll for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# fill buffer with white
screen.fill("white")
# move the dot to the right
dot.x += 1
if dot.x > W:
dot.x = 0
# draw the square (scaled to pixel size)
square = pygame.Rect(dot * S, (S, S))
screen.fill("black", square)
# copy buffer to screen
pygame.display.flip()
# limit FPS
clock.tick(20)
pygame.quit()
缩放原理
棋盘现在是一个逻辑上的 30 × 30 网格,网格单元大小为 1 × 1。绘制时,我们把这些网格坐标缩放到实际的像素位置。
dot保存的是网格坐标,例如(15, 15)。- 将其乘以
S(dot * S)会转换为像素空间:(15 * 20, 15 * 20) = (300, 300)。
因此,方块会在正确的像素位置绘制,而我们仍然可以以网格瓦片的方式思考。