Pygame开发贪吃蛇时简单2D移动严重卡顿,是什么原因?
问题修复方案
你的代码存在4个核心错误,修复后即可实现蛇的平稳移动:
错误点列表
- 1、
move方法中向下移动的逻辑写错:self.y = self.x + 1会把x坐标值赋值给y,直接导致坐标混乱,应该改为self.y = self.y + 1 - 2、移动逻辑
snak.move()被错误放在事件遍历循环for event in pygame.event.get()内部,导致每触发一次事件就执行一次移动,帧内移动次数完全不稳定,出现时快时慢/跳步的情况 - 3、帧率控制代码
CLOCK.tick(10)被注释,没有帧率限制下主循环运行速度完全由硬件性能决定,无法保证恒定移动速度 - 4、
pygame.key.get_pressed()全局按键检测放在事件循环内部逻辑错误,应该放到事件循环外
修复后可运行代码
import pygame import random DIM = (800, 800) WIN = pygame.display.set_mode(DIM) CLOCK = pygame.time.Clock() SIZE = 20 GRID = [DIM[0] / SIZE, DIM[1] / SIZE] class snake: def __init__(self): self.color = (0, 255, 0) self.x = 1 self.y = 1 self.direct = 0 def draw(self, win=WIN): pygame.draw.rect(win, self.color, (self.x * SIZE, self.y * SIZE, SIZE, SIZE)) def move(self, direct): self.direct = direct if self.direct == 1: self.x = self.x - 1 if self.direct == 2: self.x = self.x + 1 if self.direct == 3: self.y = self.y - 1 if self.direct == 4: self.y = self.y + 1 # 修复坐标赋值错误 def main(win=WIN): direction = 0 running = True snak = snake() while running: win.fill((120, 120, 120)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 按键检测和移动逻辑移到事件循环外部 keys = pygame.key.get_pressed() if keys[pygame.K_a]: direction = 1 elif keys[pygame.K_d]: direction = 2 elif keys[pygame.K_w]: direction = 3 elif keys[pygame.K_s]: direction = 4 snak.move(direction) snak.draw() CLOCK.tick(10) # 开启帧率控制保证恒定速度 pygame.display.flip() main()
补充优化建议
如果需要避免蛇反向移动(比如正在向右走的时候按向左直接掉头),可以在修改direction前判断当前方向和要修改的方向是否为相反方向,不符合条件就不修改direction值即可。
内容的提问来源于stack exchange,提问作者hilton hotels
相关产品推荐
相关产品推荐

