Pygame combat alien invasion NO.5 - operating bullets

In the previous article, we can fire bullets, and we can clearly see that the bullet "disappears" on the upper part of the screen. In fact, this is an illusion. It just disappears from our field of vision, but it is still in memory, consuming precious resources. We're going to wipe it out completely...
In game_functions.py we add the new function update_bullets:
def update_bullets(bullets):
        bullets.update() # will call bullets.update() for each bullet in the group bullets
        #delete bullets that have disappeared
        for bullet in bullets.copy(): # Iterate over the marshalled copies so that the entries in the list are not deleted
            if bullet.rect.bottom<=0:
                bullets.remove(bullet)
        #print(len(bullets)) #Display how many bullets there are currently

In fact, this section is written in the main program. In order to simplify the main program, it is here for him to settle down. Pay attention to update the position of the bullet first and then judge whether it flew out of the screen. Obviously, the bottom attribute is used here, because the top of the screen is used. The y coordinate of the rect is 0, (the four attributes of rect are left, right, bottom, top, the first two look at the x coordinate, and the last two look at the y coordinate. I don’t know if I can understand it this way..) The bullet keeps going up, the y coordinate It gradually becomes smaller, and when it becomes 0, it reaches the top of the screen, and then it becomes a negative number~~
Pay attention to the last line of code, output the current number of bullets for testing, and then comment it out, otherwise it will consume a lot of memory:

By the way, don't forget to call this function in the main program:
gf.update_bullets(bullets)

This is placed in the main loop. .
Finally, we want to limit the number of bullets so that we can strike with purpose, rather than shooting indiscriminately:

Add a new property to the bullet in settings.py:
self.bullet_count=5

Then in game_functions.py check what happens when you press the space bar:
elif event.key==pygame.K_SPACE:
        if len(bullets)<ai_settings.bullet_count: #Limit the number of bullets that appear on the screen
          new_b=Bullet(ai_settings,screen,ship) #Create bullet
          bullets.add(new_b) #Add bullets to bullets

This fires up to five bullets at a time:
Ok, the next article is about to appear our protagonist - the alien...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205809&siteId=291194637