Python文本类RPG游戏inspectable_objects列表重置Bug求助
解决Python文本RPG中inspectable_objects列表被意外重置的问题
问题根源
你遇到的核心问题是变量作用域混淆:在inspect_object函数中直接给inspectable_objects赋值时,Python会默认将其视为函数内部的局部变量,而非你在全局作用域定义的那个列表。函数内修改的只是局部版本,全局的inspectable_objects完全没被改动,因此下一次进入play函数时,依旧会使用之前未更新的全局值。
解决方案
在inspect_object函数开头添加global inspectable_objects声明,明确告诉Python你要操作的是全局变量,而非创建新的局部变量。
修改后的inspect_object函数代码:
def inspect_object(subject): global inspectable_objects # 添加全局变量声明 if active_map == 1: if subject == 'beach': print('the beach is made of soft, white, glistening sand') elif subject == 'grassland': print('the grassland is made of lucious, green grass, still wet from the morning dew') elif subject == 'ocean': print("the ocean glistens in the sun, and is slightly warm on top, but cool by the sea bed") elif subject == 'forest': print("the forest is birch, with dappled sunlight projected on the dirt floor, You can see berry bushes dotted on it") inspectable_objects = ['berry bushes','trees'] # 后续所有分支代码保持不变...
补充说明
你在play函数中已经正确声明了global inspectable_objects,所以play里对该列表的修改是生效的;但inspect_object函数缺少这个声明,导致内部的赋值操作创建了局部变量——你调试时打印的inspectable_objects其实是局部变量的值,全局变量根本没被更新。
修改完成后,执行inspect forest操作后,全局的inspectable_objects会被正确设置为['berry bushes', 'trees'],下一次进入inspect命令时就能看到预期的列表内容了。
内容的提问来源于stack exchange,提问作者Crazyscientist09
相关产品推荐
相关产品推荐

