Python 3.2错误“UnboundLocalError: 在赋值前引用了局部变量”
我现在正在制作一个2D游戏,玩家可以使用不同的枪,每把枪的射击速度都不一样。当我尝试为每把枪设置不同的射击速度时,出现了一个错误:
if currentTime - bulletGap >= 2 and bulletType == "pistol": # 2 seconds between bullets
UnboundLocalError: local variable 'bulletGap' referenced before assignment
我在使用这些变量的函数之前定义了“bulletGap = 0”和“gunFire = [True, True, True]”,但是我还是遇到了错误。下面是其余的(不工作的)代码。
def __init__(self, x, y, velx, vely, direction, bulletType):
currentTime = pygame.time.Clock()
if currentTime - bulletGap >= 2 and bulletType == "pistol": # 2 seconds between bullets
bulletGap = pygame.time.Clock()
gunFire[1] = True
return
elif currentTime - bulletGap >= 4 and bulletType == "shotgun": # 4 seconds between bullets
bulletGap = pygame.time.Clock()
gunFire[2] = True
return
elif currentTime - bulletGap >= 0.5 and bulletType == "automatic": # 0.5 seconds between bullets
bulletGap = pygame.time.Clock()
gunFire[3] = True
return
self.type = bulletType
self.direction = direction
self.velx, self.vely = velx, vely
for n in range(gunFire):
if gunFire[n] == True:
if direction == "north":
south = pygame.transform.rotate(Bullet.bulletImage[bulletType], 90)
self.image = pygame.transform.flip(south, False, True)
elif direction == "east":
self.image = pygame.transform.flip(Bullet.bulletImage[bulletType], True, False)
elif direction == "south":
self.image = pygame.transform.rotate(Bullet.bulletImage[bulletType], 90)
elif direction == "west":
self.image = Bullet.bulletImage[bulletType]
pygame.Rect.__init__(self, x, y, Bullet.width, Bullet.height)
Bullet.bulletList.append(self)
break
另外(顺便问一下),在if语句后面我还需要“return”吗?这些是我之前写的代码留下的,我试着把它们去掉,但还是出现了同样的错误。
1 个回答
0
假设你的代码大概是这样的:
class C:
bulletGap=0
def method(self):
print(bulletGap) # or any sort of reference
bulletGap = 1 # or any sort of assignment
c=C()
c.method()
那么你需要使用 self.
来正确地引用 bulletGap
:
class C:
bulletGap=0
def method(self):
print(self.bulletGap)
self.bulletGap = 1 # If bulletGap is instance-specific
C.builletGap = 1 # If bulletGap is class-specific
c=C()
c.method()