我有完全相同的问题:每个敌人的生命值,似乎他找到了一个适合他的答案。然而,这个答案是针对java代码的,我使用Pygame,所以我不明白如何将他们所做的应用到我的Pygame代码。
有谁知道如何让游戏中的每个敌人的生命值不相同吗?他发现他需要使他的类变量为瞬时的,但我不知道如何做到这一点。
这是僵尸代码。注意如何为整个类设置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
您的Enemy
类很好。由于您使用的是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