我认为之前已经提出过这个问题,但我找不到适合我的问题的答案。我基本上有一个不同字符的类,每个字符都有成本。在创建角色时,我希望从玩家得分中节省成本。
以下是一个类的示例:
class Assassin(pygame.sprite.Sprite):
def __init__(self, x, y, row, column):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assassin.png")
self.x = x
self.type = "assassin"
self.y = y
self.rect = self.image.get_rect(center=(self.x, self.y))
self.damage = 60
self.health = 40
self.speed = 2
self.move = False
self.cost = 4
self.row = row
self.column = column
以下是我想要使用变量的代码:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column ==1:
team1.add(Assassin(block.team1[0], block.team1[1], block.row, block.column))
block.team1Taken = True
score -= Assassin.__init__.cost #Example of what I think you would do
break
我希望我已经很好地解释了这一点,以便了解我想要的东西。
答案 0 :(得分:2)
您需要保留对您创建的Assassin
实例的引用,然后访问其cost
属性:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column == 1:
new_assassin = Assassin(block.team1[0], block.team1[1],
block.row, block.column)
team1.add(new_assassin)
block.team1Taken = True
score -= new_assassin.cost
break
答案 1 :(得分:2)
您无法在python中调用score -= Assassin.__init__.cost
。
init 方法是Class的构造函数,应该用它来实现。
您想要的值在您创建的对象内,因此您可以直接调用assassin.cost
,假设刺客是对象。
所以,你只需要改为:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column ==1:
current_assassin = Assassin(block.team1[0], block.team1[1], block.row, block.column)
team1.add(current_assassin)
block.team1Taken = True
score -= current_assassin.cost
break