Python文本冒险游戏go方向移动函数报NameError未定义如何解决?
错误原因
- 函数作用域错误:
go_north/go_south等方法嵌套定义在go()函数内部,仅能在go()函数内部被访问,全局作用域下无法调用这些嵌套函数。 - 面向对象语法错误:从代码中的
self关键字判断,这些移动方法属于Player类的成员方法,你既没有声明Player类,也没有实例化玩家对象,全局作用域下不存在self变量,也不能直接调用类方法。 - 分支逻辑错误:现有代码的
else分支仅和最后一个if x == "go west"判断绑定,就算输入go north等合法命令,也会触发else逻辑输出无效命令的提示。
修复方案
先调整类定义,把所有移动方法调整到和go()方法同级的类成员位置,实例化玩家对象之后,通过实例调用对应方法,同时修正分支判断逻辑。
修正后的参考代码
# 定义Player类 class Player: def __init__(self, location_x=0, location_y=0): self.location_x = location_x self.location_y = location_y def go(self, dx, dy): self.location_x += dx self.location_y += dy # 请提前实例化你自己的world对象,否则该行会报错 print(world.tile_exists(self.location_x, self.location_y).intro_text()) def go_north(self): self.go(dx=0, dy=-1) def go_south(self): self.go(dx=0, dy=1) def go_east(self): self.go(dx=1, dy=0) def go_west(self): self.go(dx=-1, dy=0) # 实例化玩家对象 player = Player() # 在这里补充你自己的world对象实例化代码 # world = 你的World类实例化逻辑 game = "play" while game == "play": x = input() if x == "go north": player.go_north() elif x == "go south": player.go_south() elif x == "go east": player.go_east() elif x == "go west": player.go_west() else: print(f"{x} is not a valid command")
内容的提问来源于stack exchange,提问作者AmberD
相关产品推荐
相关产品推荐

