-1

I am making space invaders in pygame, I am relatively new to python and this is my first project in pygame. I am trying to make my aliens move down when reaching the edge of the screen on either side. However, it is not quite working as expected. I am adding a link to a GitHub page so that anyone willing to help can view my code.

Basically what's happening is I have set the aliens to move down 1 pixel when touching the sides because when there are a lot of aliens, this moves them down quite a bit. Obviously, as the aliens start getting killed off, they move down less. However, that is not the strange part. The strange part is the fact that sometimes they will move down 1 px on the one side, but many on the other side. I'm not quite sure what I am doing wrong.

https://github.com/Kris-Stoltz/space_invaders

3
  • 1
    You need to add the code to the question. A link to an off-site resource is not sufficient. Links to external resources tend to break and the resource may no longer be available in the future. Please read How to create a Minimal, Reproducible Example and How do I ask a good question?.
    – Rabbid76
    Sep 25, 2021 at 16:41
  • I do have a code for that but my code is differ from your.
    – AbduRahman
    Sep 25, 2021 at 16:53
  • Just put a break after your two aliens.update() call so you only run the update on the first alien that hits the wall, not for each alien that hits the wall, otherwise you'll do it multiple times. If it's an even number of aliens, you end up going the same direction and hitting the wall again.
    – RufusVS
    Sep 25, 2021 at 17:18

2 Answers 2

1

Add break statements so you don't call update multiple times (if an even number of aliens hit the wall, you end up traveling the same direction!) You have to increase the y advance in update too:

for alien in aliens:
    if alien.rect.right >= WIDTH:
        aliens.update()
        break
    elif alien.rect.left <= 0:
        aliens.update()
        break

and:

def update(self):
    self.direction *= -1
    self.rect.y += 10

The code looks pretty cool though!

0

I changed that code to

    for alien in aliens:
        if alien.rect.right >= WIDTH-1:
            aliens.update()
        elif alien.rect.left <= 1:
            aliens.update()

But I see if enemies too less they don't move down

def update(self):
    print("x",self.rect.y)
    self.rect.y += 1
    print("y",self.rect.y)
    self.direction *= -1
That peace of code looks like incorrect
2
  • How many answers do you give? You can edit an answer. Give only 1 answer, unless you have completely different answers with different solutions to the same problem. I recommend deleting one of your answers. See How do I write a good answer?
    – Rabbid76
    Sep 25, 2021 at 17:15
  • Thanks! I'm new in this field and don't know how to use it properly Sep 25, 2021 at 17:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.