Python文本RPG游戏出现UnboundLocalError及流程异常求助
解决你的文本RPG游戏中的两个问题
嘿,我来帮你搞定这两个问题,咱们一个一个来拆解:
问题1:UnboundLocalError: local variable 'print' referenced before assignment
这个错误的根源是你在option_statue函数里写了一行语法错误的代码:
print:("""The statue appears before you...""")
你把print调用的括号写成了冒号!Python会把这个错误写法理解为你想要给**本地变量print**赋值(哪怕这个赋值本身是无效的),根据Python的作用域规则,只要函数里出现对变量的赋值操作(哪怕是错误的),Python就会把这个变量标记为本地变量。所以当你后面正常调用print("You now have" ,hp, "health points")时,Python会认为你在引用一个还没被赋值的本地print变量,于是抛出了UnboundLocalError。
修复方法:把冒号改成括号,让这行变成正常的print调用:
print("""The statue appears before you, a grand monument to its era, now faded into obscurity, it appeared to have been a humanoid of some sort, yet the eons of weather have worn the features to a near unrecognizable state""")
问题2:option_statue内的print未执行就回到游戏开头
这个问题其实是第一个错误引发的连锁反应——那行错误的print语句直接触发了异常,函数还没来得及执行后面的print就报错中断了。当你修复第一个问题后,那些print语句就会正常执行了。
不过还有个小细节需要调整:你在option_statue函数最后调用了intro(),这会导致玩家刚看完雕像的描述,就直接跳回游戏最开头。如果你想让游戏流程更合理,可以把这里改成回到树林的选择界面,比如调用option_lookaround(),或者添加新的探索选项。
比如修改后的option_statue函数:
def option_statue(): global hp print("""The statue appears before you, a grand monument to its era, now faded into obscurity, it appeared to have been a humanoid of some sort, yet the eons of weather have worn the features to a near unrecognizable state""") hp -= goblin_damage # 简化减法写法 print(f"You now have {hp} health points") # 用f-string让输出更整洁 time.sleep(1) print("\nYou step back from the statue, scanning the grove again for your next move.") time.sleep(1) option_lookaround() # 回到树林的选择界面,而非直接跳回游戏开头
这样修复后,两个问题就都解决啦,祝你游戏开发顺利!
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

