如何在 Pygame 中使 HP 成为实例变量
How to make HP an instance variable in Pygame
我遇到了 完全相同 的问题,就像这位先生:Health for each enemy,好像他找到了一个对他有用的答案。然而,这个答案是针对 java 代码的,而我正在使用 Pygame,所以我不明白如何将他们所做的应用到我的 Pygame 代码中。
有谁知道如何让游戏中的每个敌人不共享相同的生命值?他发现他需要将他的 class 变量设为瞬时变量,但我不知道该怎么做。
这是僵尸代码。请注意如何为整个 class:
设置 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
class没问题。由于您使用 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
我遇到了 完全相同 的问题,就像这位先生:Health for each enemy,好像他找到了一个对他有用的答案。然而,这个答案是针对 java 代码的,而我正在使用 Pygame,所以我不明白如何将他们所做的应用到我的 Pygame 代码中。
有谁知道如何让游戏中的每个敌人不共享相同的生命值?他发现他需要将他的 class 变量设为瞬时变量,但我不知道该怎么做。
这是僵尸代码。请注意如何为整个 class:
设置 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
class没问题。由于您使用 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