The modify version of the Pygame Missile Manager Class

Before we go ahead and create the Game Manager class we will need to take out all the code which are related to the missile manager in the main python file as shown in the previous article and put them all under a single missile manager class. Here is the modify version of the missile manager class as compared with the previous version.. This class will take in both the scene as well as the player object to start with.

from Missile import Missile
from GameSprite import GameSprite
from pygame.locals import *

class MissileManager(object):

    def __init__(self, scene, player):
        self.scene = scene
        self.player = player
        self.missile_count = 10
        self.missile_list = []
        self.image = 'Asset/missile.png'
        self.width = 20
        self.height = 20
        self.rect = Rect(0, 0, self.width, self.height)
        self.strike = False
        self.strike_again = 0
        # initialize game sprite object
        self.sprite = GameSprite(self.image, self.rect)

    def setStrike(self, strike):

        # set the missile strike flag
        self.strike = strike
        self.strike_again += 1

    def create_missile(self, x, y):
        if(self.missile_count >= 0):
            self.missile_surface = self.sprite.getImage()
            self.missile_list.append(Missile(self.missile_surface, x, y))
            self.missile_count -= 1

    def update(self):
        if (self.strike == True and self.strike_again > 1):
            self.strike_again = 0
            x, y = self.player.get()
            self.create_missile(x + 5, y - 8)  # create more missile

    def missile_update(self):

        for item in list(self.missile_list):
            if(item.on == False):
                self.missile_count += 1

    def check_boundary(self):
        for i in range(len(self.missile_list)):
            if (self.missile_list[i].y < 0):
                self.missile_list[i].on = False

    def draw(self):

        # blit the missile on  the scene
        for i in range(len(self.missile_list)):
            self.scene.blit(self.missile_list[i].missile_surface, self.missile_list[i].missile_pos)

As you can see we will use a single update method to control both the missile update and the check boundary method. We have also included a new draw method to draw the missiles on the game scene. The missile manager class does not need to return the missile list anymore to the main file so the previous method has been totally removed. Finally we have a set strike method to turn the strike flag on or off depends on whether the space key has been pressed or released.

That is it for this one, now lets us look at the Game Manager class in the next chapter.

Leave a Reply

Your email address will not be published. Required fields are marked *