如何在太空入侵者游戏python中添加五行入侵者

时间:2015-12-18 09:13:39

标签: python-3.x pygame

我目前在我的太空入侵者游戏中有一排11个入侵者,并且希望再添加5行,我需要在下面的代码中添加哪些代码?

导入系统 导入pygame 导入入侵者 进口导弹 来自pygame.locals import *

类SpaceInvaders:

# Constructor of the basic game class.
# This constructor calls initialize and main_loop method.
def __init__(self):
    self.initialize()
    self.main_loop()

# Initialization method. Allows the game to initialize different
# parameters and load assets before the game runs
def initialize(self):
    pygame.init()
    pygame.key.set_repeat(1, 1)

    self.width = 1024
    self.height = 768
    self.screen = pygame.display.set_mode((self.width, self.height))

    self.caption = "Space Invader!!"
    pygame.display.set_caption(self.caption)

    self.framerate = 30

    self.clock = pygame.time.Clock()
    self.missileXPos = -1
    self.missileYPos = -1

    self.missileFired = False

    self.gameState = 1
    self.font = pygame.font.Font(None, 40)
    self.explosionSound = pygame.mixer.Sound("explosion.wav")
    self.initializeGameVariables()

def initializeGameVariables(self):
    self.starfieldImg = pygame.image.load('Starfield1024x768.png')
    self.invaderImg = pygame.image.load('inv1.png')
    self.altInvaderImg = pygame.image.load('inv12.png')
    self.rocketLauncherImg = pygame.image.load('LaserBase.png')        
    self.missileImg = pygame.image.load('bullet.png')

    self.rocketXPos = 512

    self.alienDirection = -1            
    self.alienSpeed = 20

    self.ticks = 0

    self.invaders = []
    xPos = 512



    for i in range(11):
       invader = Invader.Invader()
       invader.setPosX(xPos)
       invader.setPosY(100)
       self.invaders.append(invader)            
       xPos += 32


    self.missileFired = None
    self.playerScore = 0


# main loop method keeps the game running. This method continuously
# calls the update and draw methods to keep the game alive.
def main_loop(self):
    self.clock = pygame.time.Clock()
    while True:
        gametime = self.clock.get_time()
        self.update(gametime)
        self.draw(gametime)
        self.clock.tick(self.framerate)


def updateStarted(self, gametime):        
    '''add action statements for start screen'''
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                self.gameState = 2
                break


def updatePlaying(self, gametime):
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                self.rocketXPos = self.rocketXPos + 4
            elif event.key == pygame.K_LEFT:
                self.rocketXPos = self.rocketXPos - 4
            elif event.key == pygame.K_SPACE:
                self.missileFired = Missile.Missile(self.rocketXPos, 650)

    isInvaderRemaining = False
    for i in range(11):
        if self.invaders[i] != None:
            isInvaderRemaining = True
            break
    if isInvaderRemaining == False:
        self.gameState = 3
        return

    if self.missileFired != None:
        self.missileFired.move()

    if self.rocketXPos < 100:
        self.rocketXPos = 100

    if self.rocketXPos > 924:
        self.rocketXPos = 924

    self.ticks = self.ticks + gametime

    if self.ticks > 500:
        for i in range(11):
            if self.invaders[i] != None:
                self.invaders[i].moveHorizontal(self.alienSpeed * self.alienDirection)

        leftMostInvader = None
        rightMostInvader = None

        for i in range(11):
            if self.invaders[i] != None:
                leftMostInvader = self.invaders[i]
                break

        for i in range(10, -1, -1):
            if self.invaders[i] != None:
                rightMostInvader = self.invaders[i]
                break

        if leftMostInvader.getPosX() < 96:
            self.alienDirection = +1

            xPos = 96
            for i in range(11):
                if self.invaders[i] != None:
                    self.invaders[i].moveVertical(4)
                    self.invaders[i].setPosX(xPos)
                xPos = xPos + self.invaderImg.get_width()

        if rightMostInvader.getPosX() > 924 :
            self.alienDirection = -1

            xPos = 924 - self.invaderImg.get_width() * 10 
            for i in range(11):
                if self.invaders[i] != None:
                    self.invaders[i].moveVertical(4)
                    self.invaders[i].setPosX(xPos)
                xPos = xPos + self.invaderImg.get_width()

        self.ticks = 0

    if self.missileFired != None:
        rectMissile = pygame.Rect(self.missileFired.getPosX(), self.missileFired.getPosY(), self.missileImg.get_width(), self.missileImg.get_height())
        for i in range(11):
            if self.invaders[i] != None:
                rectInvader = pygame.Rect(self.invaders[i].getPosX(), self.invaders[i].getPosY(), self.invaderImg.get_width(), self.invaderImg.get_height())
                if rectMissile.colliderect(rectInvader):
                    self.missileFired = None
                    self.invaders[i] = None

                    self.playerScore = self.playerScore + 100
                    self.explosionSound.play()
                    break

def updateEnded(self, gametime):
    '''add action statements for end screen'''
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                pygame.quit()
                sys.exit()
            elif event.key == pygame.K_r:
                self.initializeGameVariables()
                self.gameState = 1



# Update method contains game update logic, such as updating the game
# variables, checking for collisions, gathering input, and
# playing audio.
def update(self, gametime):        
    if self.gameState == 1:
        self.updateStarted(gametime)
    elif self.gameState == 2:
        self.updatePlaying(gametime)
    elif self.gameState == 3:
        self.updateEnded(gametime)


def drawStarted(self, gametime):
    '''add drawing statements for start screen'''
    self.screen.blit(self.starfieldImg, (0,0))

    width, height = self.font.size("S P A C E  I N V A D E R S!")
    text = self.font.render("S P A C E  I N V A D E R S!", True, (255, 0, 0))
    xPos = (1024 - width)/2
    self.screen.blit(text, (xPos, 200))

    width, height = self.font.size("P R E S S 'S' T O   S T A R T")
    text = self.font.render("P R E S S  'S' T O  S T A R T", True, (255, 0, 0))
    xPos = (1024 - width)/2
    self.screen.blit(text, (xPos, 400))
    pygame.display.flip()

def drawPlaying(self, gametime):
    self.screen.blit(self.starfieldImg, (0,0))

    score_text = self.font.render("Score : %d" %self.playerScore, True, (255, 0, 0))
    self.screen.blit(score_text, (10, 10))
    self.screen.blit(self.rocketLauncherImg, (self.rocketXPos, 650))
    if self.missileFired != None:
        self.screen.blit(self.missileImg, (self.missileFired.getPosX(), self.missileFired.getPosY() - self.missileImg.get_height()))
    for i in range(11):
        if self.invaders[i] != None:
            self.screen.blit(self.invaderImg, self.invaders[i].getPosition())
    pygame.display.flip()    


# Draw method, draws the current state of the game on the screen                        
def draw(self, gametime):              
    if self.gameState == 1:
        self.drawStarted(gametime)
    elif self.gameState == 2:
        self.drawPlaying(gametime)
    elif self.gameState == 3:
        self.drawEnded(gametime)        

def drawEnded(self, gametime):
    '''add drawing statements for end screen'''
    self.screen.blit(self.starfieldImg, (0,0))

    width, height = self.font.size("P R E S S  'R' T O  R E S T A R T  G A M E")
    text = self.font.render("P R E S S 'R'  T O  R E S T A R T  G A M E", True, (255, 0, 0))
    xPos = (1024 - width)/2
    self.screen.blit(text, (xPos, 200))

    width, height = self.font.size("P R E S S   'X'  T O   E X I T   G A M E")
    text= self.font.render("P R E S S   'X' T O  E X I T  G A M E", True, (255, 0, 0))
    xPos = (1024 - width)/2
    self.screen.blit(text, (xPos, 300))

    pygame.display.flip()

如果名称 ==&#34; 主要&#34;:     game = SpaceInvaders()

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是创建一个专门处理外星人的新类。您可以使用position属性创建该类。这样你就可以根据需要创建尽可能多的东西,并将它们放在你想要的任何地方。 这些方面的东西:

class Invaders(position, screen): # where position is the tuple of the position
    def __init__(self):
        self.screen = screen
        self.x = position[0] # assign the initial x and y
        self.y = position[1]
        self.image = # load the image
        # other code, i.e. load the image of the invaders and other proprierties

    def update(self): # use this method to update the position of the alien and blit the new image
        self.x = self.x + #add here a method or function that compute the new relative position
        self.x = self.x + #add here a method or function that compute the new relative position
        self.screen.blit(self.image, (self.x, self.y))