Python塔防游戏报UnboundLocalError:Enemys引用前未赋值求解
塔防游戏Enemys类实例化UnboundLocalError修复
问题表现
运行塔防游戏代码时无法正常创建敌人实体,抛出局部变量引用错误。
报错信息
line 98, in <module> loop() File "/home/trystanwipf/tower defencec game/the main game.py", line 92, in loop wt.append(Enemys('n',1,'white')) UnboundLocalError: local variable 'Enemys' referenced before assignment
相关源码
#enemys class Enemys(turtle.Turtle): def __init__(self,ability,healthp,color): turtle.Turtle.__init__(self) self.penup() self.speed(0) self.color(color) self.hp=healthp self.power=ability self.goto(-370,250) self.setheading(0) def run_path(self,sp): global player_lives self.forward(sp) if self.xcor()==-170: self.setheading(-90) if self.ycor()==-110: self.setheading(0) if self.xcor()==220: self.setheading(90) if self.xcor()==220 and self.ycor()==250: self.setheading(0) if self.xcor()==370: self.setheading(0) self.hideturtle() self.goto(-370,250) player_lives-=1 self.showturtle() def lives(): pen.clear() pen.goto(250,270) pen.write('lives:{}'.format(player_lives),font=('times new roman',14,'normal')) wt=[] def loop(): w.tracer(0) global run run=True while run==True: w.update() #if len(wt)<=7: #wt.append(Enemys('n',1,'white')) for Enemys in wt: Enemys.run_path(10) lives() if player_lives<=0: run=False loop()
根因分析
loop函数内的for循环使用Enemys作为遍历wt列表的迭代变量名,和全局作用域定义的Enemys类重名,触发Python局部作用域规则:Python会在函数编译阶段将所有出现赋值行为的变量名统一判定为局部变量,因此执行实例化Enemys的逻辑时,解释器不会向外查找全局定义的Enemys类,而是尝试访问还未被for循环赋值的同名局部变量,最终抛出引用前未赋值的UnboundLocalError。
修复方案
将for循环的迭代变量修改为不与类名冲突的名称,遍历逻辑修改为:
for enemy in wt: enemy.run_path(10)
修改后Enemys名称不会在loop函数内被作为局部变量赋值,解释器可以正常找到全局定义的Enemys类,放开注释的敌人生成代码wt.append(Enemys('n',1,'white'))后即可正常创建敌人实体。
内容的提问来源于stack exchange,提问作者Trystan
相关产品推荐
相关产品推荐

