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

时间:2015-12-17 17:06:17

标签: python pygame

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

import sys
import pygame
import Invader
import Missile
from pygame.locals import *

class 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()


if __name__ == "__main__":
    game = SpaceInvaders()

类入侵者:     def init (个体经营):         self .__ alienPosX = 0         self .__ alienPosY = 0

def setPosX(self, x):
    self.__alienPosX = x

def setPosY(self, y):
    self.__alienPosY = y

def getPosX(self):
    return self.__alienPosX

def getPosY(self):
    return self.__alienPosY

def getPosition(self):
    return (self.__alienPosX, self.__alienPosY)

def moveHorizontal(self, amount):
    self.__alienPosX = self.__alienPosX + amount

def moveVertical(self, amount):
    self.__alienPosY = self.__alienPosY + amount    

1 个答案:

答案 0 :(得分:0)

从看起来,你只需要做一个嵌套循环

for b in range(5):
   XPos = #insert original starting value
   for i in range(11):
       invader = Invader.Invader()
       invader.setPosX(xPos)
       invader.setPosY(20 * b) #adjust y values to your preference
       self.invaders.append(invader)            
       xPos += 32

这将创建五行11.请确保将值更改为您的首选项,并设置我评论的起始位置。