Python 如何使HP成为Pygame中的实例变量

Python 如何使HP成为Pygame中的实例变量,python,class,pygame,instance-variables,Python,Class,Pygame,Instance Variables,我和这位先生有着完全相同的问题:,似乎他找到了一个对他有用的答案。然而,这个答案是针对java代码的,我正在使用Pygame,所以我不知道如何将他们所做的应用到我的Pygame代码中 有人知道如何使我的游戏中的每个敌人不共享相同的hp值吗?他发现他需要使他的类变量成为瞬时变量,但我不知道如何做到这一点 这是僵尸代码。请注意如何为整个类设置hp值: class Enemy(pygame.sprite.Sprite): def __init__(self, color): s

我和这位先生有着完全相同的问题:,似乎他找到了一个对他有用的答案。然而,这个答案是针对java代码的,我正在使用Pygame,所以我不知道如何将他们所做的应用到我的Pygame代码中

有人知道如何使我的游戏中的每个敌人不共享相同的hp值吗?他发现他需要使他的类变量成为瞬时变量,但我不知道如何做到这一点

这是僵尸代码。请注意如何为整个类设置hp值:

class Enemy(pygame.sprite.Sprite):
    def __init__(self, color):
        super().__init__()
        self.image = pygame.Surface([20, 20])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.pos_x = self.rect.x = random.randrange(35, screen_width - 35)
        self.pos_y = self.rect.y = random.randrange(35, screen_height - 135)

        self.hp = 3
以下是子弹击中僵尸的碰撞代码:

for bullet in bullet_list:
            block_hit_list = pygame.sprite.spritecollide(bullet, zombie_list, False)
            for i in block_hit_list:
                zombie.hp -= 1
                bullet.kill()
                if self.hp <= 0:
                    pygame.sprite.spritecollide(bullet, zombie_list, True)
                    bullet.kill()
                    score += 100
对于项目符号列表中的项目符号:
block\u hit\u list=pygame.sprite.spritecollide(子弹,僵尸列表,False)
对于block_hit_列表中的i:
zombie.hp-=1
子弹

如果self.hp你的
敌人
类没问题。由于您使用的是
self.hp=3
hp
已经是您想要的实例属性

但是您的冲突代码似乎是错误的。我想应该是这样的

for bullet in bullet_list:
    # get a list of zombies that are hit
    zombies = pygame.sprite.spritecollide(bullet, zombie_list, False)

    # for each of those zombies
    for z in zombies:
        z.hp -= 1         # reduce the health of that very zombie
        bullet.kill()
        if z.hp <= 0:     # and if the health is <= 0
            z.kill()      # remove it 
            score += 100  # and get some points
对于项目符号列表中的项目符号:
#获取被击中的僵尸列表
僵尸=pygame.sprite.spritecollide(子弹,僵尸列表,False)
#每一个僵尸
对于僵尸中的z:
z、 hp-=1#降低僵尸的生命值
子弹

如果您提供的代码中有z.hp,
hp
是实例属性。那你的问题是什么?!懒惰吧,伙计,你又干了。谢谢你,伙计!我现在意识到,当我在zombies:zombie.hp-=1中为z添加
时,我正在更改整个zombie类hp,但当我添加
z.hp-=1
时,它会更改zombie列表中的特定对象。非常感谢你!我觉得自己很傻,这是一种明显的哈哈,我的坏!