如何使用Pyxel与Python实现场景切换时重置计时器
文本RPG场景切换计时器重置问题修复
问题根源
现有代码存在三个核心问题:
- 场景状态混淆:用
self.timer布尔值同时控制计时状态和场景切换,按下方向键后self.timer被设为False,导致escape()函数直接进入成功分支,跳过新场景显示 - 计时器未重置:场景切换时没有重新设置
self.start的时间戳,计时器会沿用初始时间,不会重新开始倒计时 - 绘制逻辑混乱:在
draw()里直接调用escape(),会重复执行清屏和绘制,逻辑嵌套导致场景切换判断失效
修复后的完整代码
import time import pyxel class App: def __init__(self): pyxel.init(250, 150, display_scale=3, title='Kingsforth') # 用场景名称跟踪当前位置,替代原来的timer布尔值 self.current_scene = 'guard_room' # 初始化计时器起始时间 self.start_timer() pyxel.run(self.update, self.draw) def start_timer(self): # 封装计时器重置逻辑,方便调用 self.start = time.time() self.time_left = 5 def update(self): # 实时计算剩余时间 self.time_left = 5 - int(time.time() - self.start) # 根据当前场景处理输入 if self.time_left >= 0: if (pyxel.btnp(pyxel.KEY_LEFT) or pyxel.btnp(pyxel.KEY_RIGHT) or pyxel.btnp(pyxel.KEY_UP)): # 切换场景并重置计时器 if self.current_scene == 'guard_room': self.current_scene = 'junk_yard' self.start_timer() elif self.current_scene == 'junk_yard': # 这里可以继续扩展下一个场景,或者设置为成功状态 self.current_scene = 'success' def draw(self): pyxel.cls(pyxel.COLOR_BLACK) # 守卫房间场景 if self.current_scene == 'guard_room': if self.time_left >= 0: pyxel.text(1, 1, 'You walk into an opening filled with guards! Where do you go?', pyxel.COLOR_WHITE) pyxel.text(1, 10, 'Options:', pyxel.COLOR_WHITE) pyxel.text(35, 10, 'Left, Right, Up', pyxel.COLOR_GREEN) pyxel.text(1, 20, 'Time left:', pyxel.COLOR_WHITE) pyxel.text(45, 20, str(self.time_left), pyxel.COLOR_RED) else: pyxel.text(1, 1, 'The guards catch you. They execute you on the spot.. You die.', pyxel.COLOR_WHITE) # 垃圾场场景 elif self.current_scene == 'junk_yard': if self.time_left >= 0: pyxel.text(1, 1, 'You run into junk yard filled with debris.. Where do you go?', pyxel.COLOR_WHITE) pyxel.text(1, 10, 'Options:', pyxel.COLOR_WHITE) pyxel.text(35, 10, 'Left, Right, Up', pyxel.COLOR_GREEN) pyxel.text(1, 20, 'Time left:', pyxel.COLOR_WHITE) pyxel.text(45, 20, str(self.time_left), pyxel.COLOR_RED) else: pyxel.text(1, 1, 'The guards catch you. They execute you on the spot.. You die.', pyxel.COLOR_WHITE) # 成功场景 elif self.current_scene == 'success': pyxel.text(1, 1, 'You did it!', pyxel.COLOR_WHITE) App()
核心修复点说明
- 场景状态管理:新增
current_scene变量,用字符串明确标识当前场景,避免和计时状态混淆 - 计时器重置封装:把重置计时器的逻辑封装成
start_timer()方法,每次切换场景时调用,确保倒计时重新开始 - 输入处理优化:用
pyxel.btnp()替代pyxel.btn(),避免按住按键时连续触发场景切换 - 绘制逻辑拆分:每个场景的绘制逻辑独立,避免嵌套调用导致的混乱
内容的提问来源于stack exchange,提问作者Viul
相关产品推荐
相关产品推荐

