我是Python新手,最近开始使用PyGame。我在线阅读了一个教程,为2D游戏提供了逐步的代码。我接受了该代码并对其进行了修改以添加新内容。我为敌人添加了一个健康栏以使游戏更具挑战性,但是当屏幕上有多个敌人时,当我只射击一个敌人时,所有敌人的生命值都会降低,然后一旦敌人从屏幕上移除就会重置。我知道我可能需要创建一个Class,但我想知道我是否可以将敌人添加到列表中然后逐个减少每个敌人的健康状况?
编辑: 澄清困惑: 如果我向敌人开枪,只有那个敌人的健康价值才会下降而不是所有的敌人。目前正在发生的健康价值。我想为屏幕上的每个敌人提供一个单独的健康值,一旦该特定敌人的健康状况降至零或以下,就应该将其删除。
6.3.2 - Check for collisions
index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
weapon_damage = random.randint(8,20)
enemy.play()
acc[0]+=1
for badguy in badguys:
badguy_health -= weapon_damage
if badguy_health <= 0:
for shot in badguys:
arrow1 = pygame.transform.rotate(badguydead, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
for badguy in badguys:
if badguy_health < 65 and badguy_health > 0:
pass
else:
badguy_health = 65
badguys.pop(index)
rand_enemy= random.choice(enemyArray)
else:
screen.blit(explosion, (projectile[1], projectile[2]))
arrows.pop(index1)
index1+=1
# 6.3.3 - Next bad guy
index+=1
for badguy in badguys:
screen.blit(enemy_healthbar, (badguy[0], badguy[1]))
for health2 in range(badguy_health):
screen.blit(enemy_health_block, (badguy[0]+health2,badguy[1]))
screen.blit(rand_enemy, badguy)
if badtimer==0:
random_Y_position = random.randint(50,430)
badguys.append([800, random_Y_position])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
playerpos=[100,100]
enemyArray = [pygame.image.load("resources/images/badguy.png"), pygame.image.load("resources/images/badguy2.png"), pygame.image.load("resources/images/badguy3.png"),pygame.image.load("resources/images/badguy4.png")]
rand_enemy = random.choice(enemyArray)
bulletspeed = 180
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[800,100]]
healthy=[[800,100]]
healthvalue=150
答案 0 :(得分:1)
你应该对每一个坏人保持健康
badguys = [
[800,100,150],
[800,200,150],
[800,300,150],
]
或更复杂的
badguys = [
[ [800,100], 150],
[ [800,200], 150],
[ [800,300], 150],
]
或作为字典
badguys = [
{"pos": [800,100], "health": 150},
{"pos": [800,200], "health": 150},
{"pos": [800,300], "health": 150},
]
这样你几乎可以使用class:)
class BadGuy()
def __init__(self, x, y, health):
self.rect = pygame.Rect(x, y, 100, 100)
self.health = health
self.image = rand_enemy = random.choice(enemyArray)
#...
def draw(self)
self.screen.blit(self.image, self.rect)
# ---
badguys = [
BadGuy(800, 100, 150),
BadGuy(800, 200, 150),
BadGuy(800, 300, 150),
]