Attempting to make a space invaders style game, and I want to affect all enemies using a for loop - but with the code shown I get a logical error where only the 1st enemy is affected, and only the first enemy can access/use the enemy.moveLR() method within the enemy class. The method of the class is not highlighted as yellow, nor does VS Code's intellisense pick it up.
Code concerning the enemy:
class Enemy(pygame.sprite.Sprite):
def __init__(self,path):
super().__init__()
self.image = pygame.image.load(path)
self.rect = self.image.get_rect()
self.xChange = 0
self.hp = 0
def moveLR(self):
if self.rect.x >= 750 and self.xChange > 0:
self.xChange = -5
self.rect.y = self.rect.y +30
if self.rect.x <= 0 and self.xChange < 0:
self.xChange = 5
self.rect.y = self.rect.y +30
And my main loop, including the code that isn't working: (The final for loop)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
bullet = Bullet('bullet.png')
allActiveSpritesList.add(bullet)
bulletList.add(bullet)
bullet.rect.x = player.rect.x + 45
bullet.rect.y = player.rect.y
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player.goLeft()
if event.key == pygame.K_d:
player.goRight()
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or pygame.K_d:
player.stop()
player.rect.x += player.changeX
player.rect.y += player.changeY
enemy.rect.x += enemy.xChange
timer = timer + 1
for enemy in enemyList:
enemy.moveLR()
Thanks to anyone that can help.