Pygame, self 未定义 [英] Pygame, self is not defined
本文介绍了Pygame, self 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在编译时遇到这个错误,我不明白,因为我有 2 个相同的类,一个工作正常,另一个抛出这个错误.
So I'm getting this error when I compile, I don't understand though because I've got 2 identical classes, one works fine the other throws out this error.
如果 self.currentState2==1:NameError: 名称self"未定义
class EnemyShip(pygame.sprite.Sprite):
def __init__(self, (x, y), playerShip):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("enemy.png")
self.image = self.image.convert()
tranColor = self.image.get_at((1, 1))
self.image.set_colorkey(tranColor)
self.rect = self.image.get_rect()
self.enemyX = float(x)
self.enemyY = float(y)
self.ship = playerShip
self.count = 0
self.currentState2 = 0
def update(self):
self.count += 1
x_component = self.ship.rect.centerx-self.enemyX
y_component = self.ship.rect.centery-self.enemyY
distance = math.hypot(x_component, y_component)
if distance < 100:
self.currentState2 = 1
print distance
elif distance > 100:
self.currentState2 = 0
print "test2"
if self.count < 600:
self.caculateNextPosition()
self.rect.center = (self.enemyX, self.enemyY)
elif self.count < 600:
self.caculateNextPositionEvade()
self.rect.center = (self.enemyX, self.enemyY)
else:
self.count = 0
def caculateNextPosition(self):
shipX = self.ship.rect.centerx
shipY = self.ship.rect.centery
if self.currentState2==1:
if self.enemyY < shipY:
self.enemyY += 4
elif self.enemyY > shipY:
self.enemyY -= 4
if self.enemyX < shipX:
self.enemyX += 4
elif self.enemyX > shipX:
self.enemyX -= 4
elif self.currentState2==0:
if self.enemyY < shipY:
self.enemyY += 0
elif self.enemyY > shipY:
self.enemyY -= 0
if self.enemyX < shipX:
self.enemyX += 0
elif self.enemyX > shipX:
self.enemyX -= 0
推荐答案
这些行需要缩进:
if self.currentState2==1:
elif self.currentState2==0:
它们不被视为函数 def 的一部分,因为它们与函数名称具有相同的缩进.
They are not considered part of the function def since they have the same indentation as the function name.
这篇关于Pygame, self 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文