I am hacking the space invaders game from Python Crash Course. I'm using Python 3.5 and Pygame 1.9.2a0, groupcollide()
In the original, when bullets collide with spaceship both sprites are removed from screen.
In my version, I want the removal to me more random so that not all hits are successful.I have done this using the random module and making collisions successful if the random number is below a certain threshold (n). I have used the function in the code below, but it doesn't work as I want.
Using print(num) I have found that that random numbers are generated until the num <=n is reached. I just want one number generated per collision.
I think this is happening because multiple collisions are detected as the bullet moves through the ships sprite rect. Testing this theory, if I remove bullet at collision then only 1 number is generated.
Q1. How can I keep bullet but only generate one number per sprite collision?
Q2. Do you have a better suggestion than using random numbers?
Any direction much appreciated, thanks
def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
"""Respond to bullet-alien collisions."""
#I swapped True, True to False, False below
collisions = pygame.sprite.groupcollide(bullets, aliens, False, False)
#I added this if statement
if collissions:
num = randrange(100)
print (num) # lots of numbers generated just want 1
if num <= 30:
collissions = pygame.sprite.groupcollide(bullets, ships, True, True)
#below in original code
if len(aliens) == 0:
# Destroy existing bullets, and create new fleet.
bullets.empty()
create_fleet(ai_settings, screen, ship, aliens)
create_fleet(mi_settings, screen, decayingNucleus, ships)
Aucun commentaire:
Enregistrer un commentaire