PGZero游戏实现苍蝇平滑移动至随机坐标的问题求助
PGZero 苍蝇平滑移动优化方案
核心问题排查
- 禁止在
update()函数中使用time.sleep():PGZero的游戏循环是固定帧率运行的,sleep操作会阻塞整个游戏的渲染、事件响应流程,是游戏卡顿的核心原因 - 直接为Actor的x/y属性赋值属于坐标瞬移,自然没有平滑移动的过渡效果
- 原有代码中
on_mouse_down函数修改muchaLife全局变量时未加global声明,变量修改不会全局生效,属于隐藏逻辑bug
实现思路
使用PGZero内置的animate方法实现平滑补间动画,每次动画播放完成后自动触发下一次随机位置的移动,全程无阻塞,自动完成缓动效果。
完整修改后代码
import pgzrun from pgzero.builtins import Actor, animate, keys from random import randint import os WIDTH = 800 HEIGHT = 600 TITLE = 'Zabij Muchę' ICON = 'data/mucha.png' tlo = Actor('background') mucha = Actor('fly') x = randint(150, 650) y = randint(100, 500) mucha.x = x mucha.y = y muchaSpeed = 2 muchaLife = True zabitych = 0 pudlo = 0 def move_mucha(): """苍蝇移动逻辑:生成随机坐标后播放平滑移动动画,动画结束自动触发下一次移动""" if not muchaLife: return x_los = randint(150, 650) y_los = randint(100, 500) # duration为动画时长,单位秒;tween为缓动效果,可选linear/accel_decel等 animate(mucha, duration=0.8, tween='accel_decel', x=x_los, y=y_los, on_finished=move_mucha) def killed_fly(): screen.draw.text('Mucha zabita!', (280, 350), color=(255,0 ,0), fontsize=60, alpha=0.8) def draw_score(): screen.draw.text('Trafione:', (5,10), color=(0, 128, 128)) screen.draw.text(str(zabitych), (100,10), color=(0, 128, 0)) screen.draw.text('Pudło:', (5,30), color=(0, 128, 128)) screen.draw.text(str(pudlo), (100,30), color=(0, 128, 0)) def on_mouse_down(pos): global zabitych, pudlo, muchaLife if mucha.collidepoint(pos): zabitych += 1 mucha.image = 'fly-swatter' muchaLife = False # 停止当前正在播放的苍蝇移动动画 animate.stop(mucha) # 延迟2秒后重置苍蝇状态 clock.schedule_unique(reset_mucha, 2) else: pudlo += 1 def reset_mucha(): """击中后重置苍蝇状态,继续游戏""" global muchaLife muchaLife = True mucha.image = 'fly' # 重置到随机位置 mucha.x = randint(150, 650) mucha.y = randint(100, 500) # 重新启动移动动画 move_mucha() def draw(): tlo.draw() mucha.draw() draw_score() if not muchaLife: killed_fly() # 游戏启动时触发第一次苍蝇移动 move_mucha() pgzrun.go()
关键修改说明
- 新增
move_mucha函数封装苍蝇的随机移动+动画播放逻辑,通过on_finished参数实现动画的循环触发 - 移除了
update函数中的阻塞逻辑和瞬移赋值代码,update函数无需额外编写移动逻辑 - 击中苍蝇后使用PGZero内置的
clock.schedule_unique实现延迟重置,替代原有的time.sleep,不会阻塞游戏运行 - 修复了全局变量
muchaLife的声明问题,新增了击中后停止当前动画、重置苍蝇状态的逻辑,游戏流程更完整 - 可以通过调整
animate的duration参数控制移动速度,调整tween参数修改运动曲线,比如设置为linear就是匀速移动
内容的提问来源于stack exchange,提问作者Slavo Heys
相关产品推荐
相关产品推荐

