def spawnAliens(self): if random.randint(0, 90) == 1: alien = Alien() alien.pos = self.generateAlienPosition() alien.rect.x = alien.pos[0] alien.rect.y = alien.pos[1] self.aliens.append(alien)
def run_game(): pygame.init() ai_settings=Settings() screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") play_button=Button(ai_settings,screen,"Play") ship=Ship(ai_settings,screen) bullets=Group() aliens=Group() gf.create_fleet(ai_settings,screen,ship,aliens) stats=GameStats(ai_settings) sb=Scoreboard(ai_settings,screen,stats) bg_fill=(230,230,230) Gameexit=True alient=Alien(ai_settings,screen) while Gameexit: gf.check_events(ai_settings,screen,ship,bullets,stats,play_button,aliens,sb) if stats.game_active: ship.update() gf.update_bullets(ai_settings,screen,ship,bullets,aliens,sb,stats) gf.update_aliens(ai_settings,stats,screen,aliens,ship,bullets,sb) gf.update_screen(ai_settings,screen,ship,aliens,bullets,play_button,stats,sb)
def lose(aliens, bullets, ship, stats, settings, screen, play_button): '''当达成失败条件时应执行的指令''' time.sleep(0.5) if stats.ships_left - 1: aliens.empty() bullets.empty() ship.rect.bottom = ship.screen_rect.bottom ship.rect.centerx = ship.screen_rect.centerx Alien.creat_aliens(settings, screen, aliens, ship) stats.ships_left -= 1 time.sleep(0.5) else: play_button.button_active = True return False return True
def create_alien(ai_settings, screen, aliens, alien_number, row_number): """Create an alien and place it in the row""" alien = Alien.Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number aliens.add(alien)
def create_fleet(ai_settings, screen, ship, aliens): """Create full fleet of aliens""" alien = Alien.Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) # Create the fleet of aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): create_alien(ai_settings, screen, aliens, alien_number, row_number)
def fillWave(self): directory = "images\enemys\enemy1" for x in range(self.num_cols()): for y in range(self.num_rows()): if y == 0: directory = "images\enemys\enemy1" directory2 = "images\explosionpurple.png" elif y == 1 or y == 2: directory = "images\enemys\enemy2" directory2 = "images\explosionblue.png" elif y == 3 or y == 4: directory = "images\enemys\enemy3" directory2 = "images\explosiongreen.png" self.set((x,y),Alien(directory,directory2))
def reset(): global score global spaceship global bullets global aliens global GameOver global leftKeyPressed global rightKeyPressed global bulletKey GameOver = False leftKeyPressed = False rightKeyPressed = False bulletKey = False if score: score = 0 bullets = [] aliens = [] for n in xrange(10): aliens.append(Alien())
def create_fleet(settings, screen, aliens, reverse=False): """创建外星飞船队伍""" alien = Alien(screen=screen, settings=settings, image=settings.alien_image_4) alien_width = alien.rect.width space_x = settings.screenWidth - alien_width alien_space = 2 * alien_width number_aliens_x = int(space_x / alien_space) for alien_number in range(number_aliens_x): if reverse: alien = Alien(screen=screen, settings=settings, image=settings.alien_image_3) alien.x = settings.screenWidth + alien_space * alien_number settings.is_forward = False else: alien = Alien(screen=screen, settings=settings, image=settings.alien_image_4) alien.x = -alien_width - alien_space * alien_number settings.is_forward = True alien.rect.x = alien.x aliens.append(alien)
food_storage = pygame.sprite.Group() #holds food sprites fishies = pygame.sprite.Group() #holds fish sprites moneies = pygame.sprite.Group() #holds money sprites aliens = pygame.sprite.Group() #create objects player = Owner([kfc, pizza, icecream]) #allows user interaction introText = mpFont.render(''' HANI ICS3U P. Cugliari ''', 1, (0, 0, 0), (255, 255, 255)) #text at bottom of first screen #variables ct_speed = 30 #maximum frames per second '''The entire game is held in a while True loop so that players can play again.''' while True: aliens.add(Alien([alien1, alien2], 400, 200)) #creates an alien and adds to container fishies.add(Fish([guppy1, guppy2], 200, 200)) #creates a fish and adds to container '''These bools are used for breaking loops.''' alarm_s = True warning_s = True interval_s = False battle_coming = False a_w_interval = 0 shot = False time_paused = 0 clicked0 = False win = False '''First part - Introscreen ''' while True: for event in pygame.event.get():
#sounds #pygame.mixer.music.load(os.path.join("sounds", "music.mid")) sfx_slap = pygame.mixer.Sound(os.path.join("sounds", "slap.wav")) images = { 'f': pygame.image.load(os.path.join("images", "fish.png")).convert_alpha(), 'm': pygame.image.load(os.path.join("images", "mountain.png")).convert_alpha(), 'a': pygame.image.load(os.path.join("images", "alien.png")).convert_alpha(), 'b': pygame.image.load(os.path.join("images", "bird.png")).convert_alpha(), } Fish.getstuff((images['f'], None), sfx_slap) Mountain.getstuff((images['m'], None))#,sounds) Alien.getstuff((images['a'], None)) Bird.getstuff((images['b'], None)) Player.getstuff((images['b'], None)) Bullet.getstuff((images['f'], None), sfx_slap) player = Player.Player() fish = Fish.Fish((0,0)) mountains = pygame.sprite.Group() aliens = pygame.sprite.Group() pools = pygame.sprite.Group() birds = pygame.sprite.Group() bullets = pygame.sprite.Group() def newlevel(level):
def game_restart(aliens, bullets, ship, stats, settings, screen): aliens.empty() bullets.empty() stats.ResetStats() ship.center_ship() Alien.creat_aliens(settings, screen, aliens, ship)
def spawnAliens(self): # Spawns 3x6 aliens print("LEVEL: " + str(self.level)) if self.level % 6 == 0: #Spawns a boss at every sixth level self.boss = Alien('green', model=self.firstGreen.clone(), hp=self.power * 6) self.boss.setPosition(0, 0, 1, scale=.0025 * 3) self.speed = 1 / (self.power / 2) viz.playSound('bossSpawn.wav') elif not self.pause: x = -.6 #Spawns a 3x6 wave of aliens, each alien spawn is random for i in range(0, 6): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, 1) x += .25 x = -.6 for i in range(6, 12): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, .75) x += .25 x = -.6 for i in range(12, 18): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, .5) x += .25 viz.playSound('newWave.wav')
def spawnALiens(): row = [] for x in range(0, 5): a = Alien(x * 250, 50) row.append(a) alien_rows.append(row)
def __init__(self): # base class constructor viz.EventClass.__init__(self) self.callback(viz.KEYDOWN_EVENT, self.onKeyDown) # Callback for key press self.callback(viz.TIMER_EVENT, self.onTimer) # Callback for timers self.callback(viz.KEYUP_EVENT, self.onKeyUp) #Creates memory for bullets and alien spawns self.bulletlist = [] self.aliens = [None for x in range(0, 18)] self.alienbullets = list() # Default rotation for camera self.theta = 50 #Booleans for keys pressed self.leftUp = True self.rightUp = True self.Fire = False self.start = False self.pause = False self.start = False #Checks whether the game has started self.gameover = False self.title = True self.playerSpeed = .05 #Setup default camera view self.view = viz.MainView mat = viz.Matrix() mat.postAxisAngle(1, 0, 0, self.theta) mat.postTrans(0, 0, 0) self.view.setMatrix(mat) #Spawn the player self.playerShip = Player() self.playerShip.setPosition(0, 0, -.6) self.power = 3 self.level = 1 self.speed = 1 / self.power # Start timers self.starttimer(1, .05, viz.FOREVER) self.starttimer(2, .05, viz.FOREVER) self.starttimer(3, .001, viz.FOREVER) self.starttimer(4, self.speed, viz.FOREVER) self.starttimer(5, .5, viz.FOREVER) self.starttimer(6, .3, viz.FOREVER) #Initialize these models far off screen so they can be copied, thus these models only load once self.firstRed = Alien('red', modelLabel='redAlien.dae') self.firstRed.setPosition(0, 2000, 0) self.firstBlue = Alien('blue', modelLabel='blueAlien.dae') self.firstBlue.setPosition(0, 2000, 0) self.firstPurple = Alien('purple', modelLabel='tankAlien.dae') self.firstPurple.setPosition(0, 2000, 0) self.redbullet = Bullet(modelLabel='redBullet.dae') self.redbullet.setPosition(0, 2000, 0) self.greenbullet = Bullet(modelLabel='greenBullet.dae') self.greenbullet.setPosition(0, 2000, 0) self.firstOrange = Alien('orange', modelLabel='powerupAlien.dae') self.firstOrange.setPosition(0, 2000, 0) self.firstGreen = Alien('green', modelLabel='greenAlien.dae') self.firstGreen.setPosition(0, 2000, 0) #Boss object and where the boss can move self.boss = None self.bossRight = False self.bossLeft = True #Initial dynamic text strings self.levelText = None self.levelMsg = "Level: 1" self.hpText = None self.hpMsg = "HP: 1" self.scoreText = None self.scoreMsg = "Score: 0" self.score = 0 #Spawn the title screen self.titleScreen()
class Controller(viz.EventClass): # Constructor def __init__(self): # base class constructor viz.EventClass.__init__(self) self.callback(viz.KEYDOWN_EVENT, self.onKeyDown) # Callback for key press self.callback(viz.TIMER_EVENT, self.onTimer) # Callback for timers self.callback(viz.KEYUP_EVENT, self.onKeyUp) #Creates memory for bullets and alien spawns self.bulletlist = [] self.aliens = [None for x in range(0, 18)] self.alienbullets = list() # Default rotation for camera self.theta = 50 #Booleans for keys pressed self.leftUp = True self.rightUp = True self.Fire = False self.start = False self.pause = False self.start = False #Checks whether the game has started self.gameover = False self.title = True self.playerSpeed = .05 #Setup default camera view self.view = viz.MainView mat = viz.Matrix() mat.postAxisAngle(1, 0, 0, self.theta) mat.postTrans(0, 0, 0) self.view.setMatrix(mat) #Spawn the player self.playerShip = Player() self.playerShip.setPosition(0, 0, -.6) self.power = 3 self.level = 1 self.speed = 1 / self.power # Start timers self.starttimer(1, .05, viz.FOREVER) self.starttimer(2, .05, viz.FOREVER) self.starttimer(3, .001, viz.FOREVER) self.starttimer(4, self.speed, viz.FOREVER) self.starttimer(5, .5, viz.FOREVER) self.starttimer(6, .3, viz.FOREVER) #Initialize these models far off screen so they can be copied, thus these models only load once self.firstRed = Alien('red', modelLabel='redAlien.dae') self.firstRed.setPosition(0, 2000, 0) self.firstBlue = Alien('blue', modelLabel='blueAlien.dae') self.firstBlue.setPosition(0, 2000, 0) self.firstPurple = Alien('purple', modelLabel='tankAlien.dae') self.firstPurple.setPosition(0, 2000, 0) self.redbullet = Bullet(modelLabel='redBullet.dae') self.redbullet.setPosition(0, 2000, 0) self.greenbullet = Bullet(modelLabel='greenBullet.dae') self.greenbullet.setPosition(0, 2000, 0) self.firstOrange = Alien('orange', modelLabel='powerupAlien.dae') self.firstOrange.setPosition(0, 2000, 0) self.firstGreen = Alien('green', modelLabel='greenAlien.dae') self.firstGreen.setPosition(0, 2000, 0) #Boss object and where the boss can move self.boss = None self.bossRight = False self.bossLeft = True #Initial dynamic text strings self.levelText = None self.levelMsg = "Level: 1" self.hpText = None self.hpMsg = "HP: 1" self.scoreText = None self.scoreMsg = "Score: 0" self.score = 0 #Spawn the title screen self.titleScreen() def spawnAliens(self): # Spawns 3x6 aliens print("LEVEL: " + str(self.level)) if self.level % 6 == 0: #Spawns a boss at every sixth level self.boss = Alien('green', model=self.firstGreen.clone(), hp=self.power * 6) self.boss.setPosition(0, 0, 1, scale=.0025 * 3) self.speed = 1 / (self.power / 2) viz.playSound('bossSpawn.wav') elif not self.pause: x = -.6 #Spawns a 3x6 wave of aliens, each alien spawn is random for i in range(0, 6): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, 1) x += .25 x = -.6 for i in range(6, 12): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, .75) x += .25 x = -.6 for i in range(12, 18): num = random.randint(0, 3) if num == 0: self.aliens[i] = Alien('blue', model=self.firstBlue.clone(), hp=3) elif num == 1: self.aliens[i] = Alien('red', model=self.firstRed.clone()) elif num == 2: self.aliens[i] = Alien('purple', model=self.firstPurple.clone(), hp=3) elif num == 3: self.aliens[i] = Alien('orange', model=self.firstOrange.clone(), hp=2) self.aliens[i].setPosition(x, 0, .5) x += .25 viz.playSound('newWave.wav') def onKeyDown(self, key): #Movement keys if key == 'a' or key == viz.KEY_LEFT: self.leftUp = False if key == 'd' or key == viz.KEY_RIGHT: self.rightUp = False if key == "p": #Pause button if self.pause and not self.gameover: self.pause = False else: self.pause = True # Default Camera if key == '1': self.theta = 50 mat = viz.Matrix() mat.postTrans(0, 0, -2) mat.postAxisAngle(1, 0, 0, self.theta) self.view.setMatrix(mat) # Top Down View if key == '2': self.theta = 90 mat = viz.Matrix() mat.postAxisAngle(1, 0, 0, self.theta) mat.postTrans(0, 2, 0) self.view.setMatrix(mat) # Side View if key == '3': self.theta = 90 mat = viz.Matrix() mat.postAxisAngle(0, 1, 0, self.theta) mat.postTrans(-1.5, 0, 0) self.view.setMatrix(mat) # Side View if key == '4': self.theta = 270 mat = viz.Matrix() mat.postAxisAngle(0, 1, 0, self.theta) mat.postTrans(1.5, 0, 0) self.view.setMatrix(mat) #Player fires if key == " " and self.Fire and not self.pause: b = Bullet(model=self.greenbullet.clone()) b.setPosition(self.playerShip.getX() - .02, self.playerShip.getY() + .02, self.playerShip.getZ()) self.bulletlist.append(b) self.Fire = False viz.playSound('laser.wav') if key == 'q': self.title = False print(self.title) if key == viz.KEY_RETURN: if not self.start: #Change out the text on screen, disable the start text and setup dynamic text for the first time self.start = True self.description.remove() self.spawnAliens() self.levelMsg = "Level: 1" self.levelText = viz.addText(self.levelMsg, viz.SCREEN, pos=[.15, .95, 0]) self.levelText.fontSize(33) self.hpText = viz.addText(self.hpMsg, viz.SCREEN, pos=[.8, .95, 0]) self.hpText.fontSize(33) self.scoreText = viz.addText(self.scoreMsg, viz.SCREEN, pos=[.45, .95, 0]) self.scoreText.fontSize(33) def onKeyUp(self, key): #Controls booleans for key presses, reactions are done by timers if key == "a" or key == viz.KEY_LEFT: self.leftUp = True if key == "d" or key == viz.KEY_RIGHT: self.rightUp = True if key == " ": self.fire = False def onTimer(self, num): if num == 1 and not self.pause: # Moves the player left/right and controls the rotation of the ship if not self.leftUp and self.playerShip.canGoLeft(-0.25): self.playerShip.setPosition( self.playerShip.getX() - self.playerSpeed, self.playerShip.getY(), self.playerShip.getZ()) if self.playerShip.theta < 45 or self.playerShip.theta >= 315: self.playerShip.rotate(9) if not self.rightUp and self.playerShip.canGoRight(0.25): self.playerShip.setPosition( self.playerShip.getX() + self.playerSpeed, self.playerShip.getY(), self.playerShip.getZ()) if self.playerShip.theta > 315 and self.playerShip.theta <= 360 or self.playerShip.theta <= 45: self.playerShip.rotate(351) if num == 2 and not self.pause: #Controls passive rotation for if the player is not actively pressing buttons if self.leftUp and self.rightUp: if self.playerShip.theta <= 45 and self.playerShip.theta >= 0: self.playerShip.rotate(351) if self.playerShip.theta >= 315: self.playerShip.rotate(9) if num == 3 and not self.pause: #Move bullet for bullet in self.bulletlist: x = bullet.getX() vx = bullet.getVX() y = bullet.getY() vy = bullet.getVY() z = bullet.getZ() vz = bullet.getVZ() bullet.setPosition(x + vx, y + vy, z + vz) #Deallocate bullets if (bullet.getZ() > 2): bullet.delete() self.bulletlist.remove(bullet) # Check bullet to alien collison deadaliens = 0 for alien in self.aliens: if alien != None: if bullet.getX() > alien.getX() - .1 and bullet.getX( ) < alien.getX() + .1 and bullet.getZ() > alien.getZ( ) - .1 and bullet.getZ() < alien.getZ() + .1: bullet.delete() self.bulletlist.remove(bullet) alien.damage() viz.playSound('alienHit.wav') if alien.getHP() <= 0: alien.delete() deadalien = self.aliens.index(alien) self.aliens[deadalien] = None deadaliens += 1 if alien.getColor( ) == 'orange': #Orange aliens death triggers a powerup self.playerShip.powerUp() self.updateHPText() viz.playSound('powerup.wav') else: viz.playSound('explosion.wav') self.score += 100 self.updateScoreText() else: deadaliens += 1 if self.boss != None: #Check if boss alien is hit if bullet.getX() > self.boss.getX() - .3 and bullet.getX( ) < self.boss.getX() + .3 and bullet.getZ( ) > self.boss.getZ() - .3 and bullet.getZ( ) < self.boss.getZ() + .3: bullet.delete() self.bulletlist.remove(bullet) self.boss.damage() viz.playSound('alienHit.wav') if self.boss.getHP() <= 0: self.boss.delete() self.boss = None viz.playSound('explosion.wav') self.score += 100 self.updateScoreText() #Check to see if current wave is complete if len(self.aliens) == deadaliens and self.boss == None: self.power += 1 self.level += 1 self.updateLevelText() self.speed = 1 / self.power viz.killtimer(4) self.starttimer(4, self.speed, viz.FOREVER) self.spawnAliens() # TRANSLATE ALIEN BULLET for bullet in self.alienbullets: x = bullet.getX() vx = bullet.getVX() y = bullet.getY() vy = bullet.getVY() z = bullet.getZ() vz = bullet.getVZ() bullet.setPosition(x - vx, y - vy, z - vz) if (bullet.getZ() < -.8): bullet.delete() self.alienbullets.remove(bullet) if bullet.getX() > self.playerShip.getX() - .1 and bullet.getX( ) < self.playerShip.getX() + .1 and bullet.getZ( ) > self.playerShip.getZ() - .1 and bullet.getZ( ) < self.playerShip.getZ() + .1: bullet.delete() self.alienbullets.remove(bullet) self.playerShip.damage(math.floor(self.power / 2)) viz.playSound('playerHit.wav') if self.playerShip.getHP() <= 0: #GAME OVER self.gameover = True self.pause = True self.playerShip.delete() viz.playSound('playerDead.wav') self.updateHPText() if num == 4 and not self.pause: # Move aliens down the Z axis for alien in self.aliens: if alien != None: alien.setPosition(alien.getX(), alien.getY(), alien.getZ() - .001, alien.getScale()) if self.playerShip.getX() + .04 > alien.getX( ) - .1 and self.playerShip.getX() - .04 < alien.getX( ) + .1 and self.playerShip.getZ() + .06 > alien.getZ( ) - .1 and self.playerShip.getZ() - .06 < alien.getZ() + .1: self.playerShip.damage(1) if self.playerShip.getHP() <= 0: #GAME OVER self.gameover = True self.pause = True self.playerShip.delete() viz.playSound('collision.wav') self.updateHPText() if alien.isOffScreen( ): #Translate aliens back if off screen alien.setPosition(alien.getX(), alien.getY(), 1, alien.getScale()) if self.boss != None: #Move the boss around, the boss moves left right on the X axis instead of foward on the Z if self.boss.getX() > -1 and self.bossLeft: self.boss.setPosition(self.boss.getX() - .001, self.boss.getY(), self.boss.getZ(), self.boss.getScale()) else: self.bossLeft = False if self.boss.getX() < 1 and not self.bossLeft: self.boss.setPosition(self.boss.getX() + .001, self.boss.getY(), self.boss.getZ(), self.boss.getScale()) else: self.bossLeft = True if self.playerShip.getX() + .04 > self.boss.getX( ) - .1 and self.playerShip.getX() - .04 < self.boss.getX( ) + .1 and self.playerShip.getZ() + .06 > self.boss.getZ( ) - .1 and self.playerShip.getZ() - .06 < self.boss.getZ() + .1: self.playerShip.damage(1) if self.playerShip.getHP() <= 0: self.playerShip.delete() viz.playSound('explosion.wav') self.updateHPText() if self.boss.isOffScreen(): self.boss.setPosition(self.boss.getX(), self.boss.getY(), 1, self.boss.getScale()) if num == 5 and not self.pause: for alien in self.aliens: if alien != None: if alien.getColor() == 'red' or alien.getColor( ) == 'purple' or alien.getColor( ) == 'green': #Only red and purple ships can fire index = self.aliens.index( alien ) #Get the index of the current ship in our list #Checks for whether a ship exists in the two spots in front, False = No Ship, True = Ship Exists checkOne = False checkTwo = False if index < 6: if self.aliens[index + 6] != None: checkOne = True if self.aliens[index + 12] != None: checkTwo = True elif index < 12: if self.aliens[index + 6] != None: checkOne = True # FIRES ALIEN BULLETS, THESE CHECKS ARE REQUIRED TO ALLOW A SHIP TO FIRE, alien cannot fire if there is another ship in front of it if not checkOne and not checkTwo and self.playerShip.getX( ) <= alien.getX() + .1 and self.playerShip.getX( ) >= alien.getX() - .1 and not self.pause: b = Bullet(model=self.redbullet.clone()) b.setTheta(180) b.setPosition(alien.getX(), alien.getY(), alien.getZ()) self.alienbullets.append(b) viz.playSound('laser.wav') if self.boss != None: #The boss fires three bullets, one straight ahead and two at an angle b = Bullet(model=self.redbullet.clone()) b.setTheta(180) b.setPosition(self.boss.getX(), self.boss.getY(), self.boss.getZ(), 0) self.alienbullets.append(b) b = Bullet(model=self.redbullet.clone()) b.setTheta(180) b.setVXVY(.02, 0, .02) b.setPosition(self.boss.getX(), self.boss.getY(), self.boss.getZ()) self.alienbullets.append(b) b = Bullet(model=self.redbullet.clone()) b.setTheta(180) b.setVXVY(-.02, 0, .02) b.setPosition(self.boss.getX(), self.boss.getY(), self.boss.getZ(), 90) self.alienbullets.append(b) viz.playSound('laser.wav') if num == 6: #Allow player to fire self.Fire = True #Setup all possible dynamically changing text boxes def updateHPText(self): self.hpMsg = "HP: " + str(int(self.playerShip.getHP())) self.hpText.remove() self.hpText = viz.addText(self.hpMsg, viz.SCREEN, pos=[.8, .95, 0]) self.hpText.fontSize(33) def updateLevelText(self): self.levelText.remove() self.levelMsg = "Level: " + str(self.level) self.levelText = viz.addText(self.levelMsg, viz.SCREEN, pos=[.15, .95, 0]) self.levelText.fontSize(33) def updateScoreText(self): self.scoreText.remove() self.scoreMsg = "Score: " + str(self.score) self.scoreText = viz.addText(self.scoreMsg, viz.SCREEN, pos=[.45, .95, 0]) self.scoreText.fontSize(33) def titleScreen(self): #Commands to setup the title screen self.description = viz.addText3D( 'Make a last stand against an endless alien attack \n\n' + 'Use the A and D keys or left and right keys to move ship\n\n' + 'Press the spacebar to fire \n\n' + 'There are 5 different types of aliens\n\n' + 'Red: Shoots back at player\n\n' + 'Blue: Tank takes 3 hits to kill \n\n' + 'Purple: Has both the Blue and Red alien abilities\n\n' + 'Orange: Gives players an extra hitpoint when hit\n\n' + 'Green: Boss alien which will be a challenge to defeat\n\n' + 'Press enter when you are ready to begin!') self.description.font('Comic Sans MS') #Best font self.description.alignment(viz.ALIGN_CENTER) mat = viz.Matrix() mat.postScale(.05, .05, .05) mat.postAxisAngle(1, 0, 0, self.theta) mat.postTrans(0, .3, -.1) self.description.setMatrix(mat)
from Spaceship import * from Globals import * from Bullet import * from Alien import * pygame.init() #score = 0 spaceship = Spaceship() bullets = [] aliens = [] for n in xrange(5): aliens.append(Alien()) def reset(): global score global spaceship global bullets global aliens global GameOver global leftKeyPressed global rightKeyPressed global bulletKey GameOver = False leftKeyPressed = False rightKeyPressed = False bulletKey = False if score:
def spawnAlien(self): alien = Alien(self.screen, self, random.randint(10, 480), 0) self.aliens.append(alien) print("Un alien spawned")
displayHeight = 900 speed = 250 UP = 'up' DOWN = 'down' RIGHT = 'right' LEFT = 'left' LEVEL = 1 missleMap = [] enemyMap = [] tracker = 0 rocket = Rocket.Rocket() #test Alien alien = Alien.Alien(250, 30, 0) def runGame(): global missleMap speedUp = False movX, movY = 0, 0 s = "Score " + str(score) while True: playSound("Idle.wav") key = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN:
import random import sys import os import time import Spaceship import Alien import math import Missile import pygame from pygame.locals import * from random import randint from pygame.time import * from pygame.font import * spaceship = Spaceship.ship() alien = Alien.alien() missile1 = Missile.Missile1() missile2 = Missile.Missile2() class Board: def __init__(self): pygame.init() pygame.display.set_caption("Space Invaders") self.score = 0 alien.spawn() self.printboard() def printboard(self): screen = pygame.display.set_mode((600, 400))
def spawn_aliens(): for x in range(0, 5): aliens.append(Alien(x * 100, 100))
from star import * from Boss import * from Highscore import * ##largestNumber = 0 ##file = open('test.txt', 'r') ## ##for line in file: ## if line > largestNumber: ## largestNumber = line #print largestNumber boss_spawner = 0 pygame.init() screen = pygame.display.set_mode( [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]) ss = Spaceship() a = Alien(800, 100) direction_counter = 50 bullet_counter = 0 bullets = [] aliens = [a] stars = [] bosses = [] mode = "playing" lose = pygame.image.load('you-lose-i-win.jpg') lose = pygame.transform.scale( lose, (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT)) score = 0 score_font = pygame.font.SysFont("Times New Roman", 100) alien_spawner = 0
def update(self, delta_time): """ All the logic to move, and the game logic goes here. TODO: have ship explode each life, balance level design player invulnerability on respawn""" if self.current_state == GAME_RUNNING: # Collision Checking for Asteroid and Player, and bolt and player, and alien and player hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.asteroid_list) bolt_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.bolt_list) alien_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.alien_list) boss_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.boss_list) beam_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.beam_list) # Player timers self.player_sprite.timer = self.player_sprite.timer - 1 self.player_sprite.invul = self.player_sprite.invul - 1 # Player invulnerability coating if self.player_sprite.invul == 0: self.player_sprite.set_texture(0) elif self.player_sprite.invul == PLAYER_INVULNERABILITY - 1: self.player_sprite.set_texture(4) # Player Bounds Checking if self.player_sprite.center_x > SCREEN_WIDTH: self.player_sprite.center_x = 0 elif self.player_sprite.center_x < 0: self.player_sprite.center_x = SCREEN_WIDTH elif self.player_sprite.center_y > SCREEN_HEIGHT: self.player_sprite.center_y = 0 elif self.player_sprite.center_y < 0: self.player_sprite.center_y = SCREEN_HEIGHT # Checking player collisions if (hit_list or bolt_hit_list or alien_hit_list or boss_hit_list or beam_hit_list) \ and self.player_sprite.invul < 0: if self.lives > 1: self.player_sprite.center_x = SCREEN_WIDTH / 2 self.player_sprite.center_y = SCREEN_HEIGHT / 2 self.player_sprite.invul = PLAYER_INVULNERABILITY self.lives = self.lives - 1 self.score = self.score - 10 else: self.lives = 0 self.player_sprite.set_texture(1) self.player_sprite.movable = False self.player_sprite.stop() self.current_state = GAME_OVER # Creation of Powerups if self.numOfPow < 1 and random.randint(1, 10000) < 50: powType = 1 self.numOfPow = self.numOfPow + 1 self.powerup_list = Powerup.createPowerUp\ (self,self.powerup_list, powType, SCREEN_HEIGHT, SCREEN_WIDTH) pow_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.powerup_list) for pow in pow_hit_list: # Dealing with collision with player if self.pow == False: pow.kill() self.numOfPow = 0 if pow.type == 1: self.player_sprite.set_texture(2) self.laser = True self.pow = True elif pow.type == 2: self.player_sprite.set_texture(3) self.bb = 4 self.pow = True # Boss summoning if self.score > 1000 and self.numOfBoss < 1: self.boss_list = Alien.createBoss(MyGame, self.boss_list, SCREEN_HEIGHT, SCREEN_WIDTH) self.numOfBoss = 1 if self.numOfAliens > 0: for alien_left in self.alien_list: alien_left.kill() self.numOfAliens = 0 for boss in self.boss_list: boss.center_x = boss.center_x + boss.change_x boss.center_y = boss.center_y + boss.change_y boss.beamTimer = boss.beamTimer - 1 if self.player_sprite.center_x > boss.center_x: boss.change_x = 0.2 elif self.player_sprite.center_x < boss.center_x: boss.change_x = -0.2 # Boss Beaming if boss.beamTimer < 500 and not boss.beamActive: beam = arcade.Sprite("Resources/alienlaser.png", SPRITE_SCALING_BEAM) # Change to beam beam.height = SCREEN_HEIGHT / 1.2 beam.center_x = boss.center_x beam.center_y = boss.center_y - 350 boss.beamActive = True self.beam_list.append(beam) elif boss.beamTimer < 500 and boss.beamTimer > 0: for beam in self.beam_list: beam.center_x = boss.center_x beam.center_y = boss.center_y - 350 boss.beamTimer = boss.beamTimer - 1 elif boss.beamTimer <= 0: for beam in self.beam_list: beam.kill() boss.beamActive = False boss.beamTimer = 1000 # Boss Shooting if boss.shootTimer <= 0: for i in range(1, 6): bolt = arcade.Sprite("Resources/alienbolt.png", SPRITE_SCALING_BOLT) bolt.type = 0 bolt.center_x = boss.center_x - 100 + (30 * i) bolt.center_y = boss.center_y - 60 if i == 1: bolt.change_x = -2 elif i == 2: bolt.change_x = -1 elif i == 3: bolt.change_x = 0 elif i == 4: bolt.change_x = 1 elif i == 5: bolt.change_x = 2 bolt.change_y = -BOLT_SPEED * .35 self.bolt_list.append(bolt) boss.shootTimer = 50 else: boss.shootTimer = boss.shootTimer - 1 if self.numOfBoss < 1 or self.score > 5000: # Creation of Aliens (ultimately want to put on a timer) if self.score < 250: spawn = random.randint(1, 200) elif self.score < 500: spawn = random.randint(1, 100) else: spawn = random.randint(1, 50) if spawn == 1: alienType = random.randint(1, 4) self.alien_list, self.numOfAliens = Alien.createAlien\ (MyGame, self.alien_list, self.numOfAliens, alienType, SCREEN_HEIGHT, SCREEN_WIDTH) # Alien Movement for alien in self.alien_list: alien.center_x = alien.center_x + alien.change_x alien.center_y = alien.center_y + alien.change_y #Alien 3 follow pattern if alien.type == 3: if self.player_sprite.center_x > alien.center_x: alien.change_x = 2 elif self.player_sprite.center_x < alien.center_x: alien.change_x = -2 # # Aliens collide with asteroid # alien_hit_list = arcade.check_for_collision_with_list(alien, self.asteroid_list) # if alien_hit_list: # #TODO: Add result of alien death # alien.kill() # Alien shooting degreeOfSpace = 3 alien.timer = alien.timer - 1 if alien.center_x < self.player_sprite.center_x + degreeOfSpace \ and alien.center_x > self.player_sprite.center_x - degreeOfSpace \ and alien.center_y > self.player_sprite.center_y: if alien.type <= 3 and alien.timer < 0: alien.timer = 10 bolt = arcade.Sprite("Resources/alienbolt.png", SPRITE_SCALING_BOLT) bolt.type = 0 bolt.center_x = alien.center_x bolt.center_y = alien.center_y - 20 bolt.change_x = 0 bolt.change_y = -BOLT_SPEED * .65 self.bolt_list.append(bolt) if alien.type == 4 and alien.timer < 0: alien.timer = 10 bolt = arcade.Sprite("Resources/alienbolt.png", 5 * SPRITE_SCALING_BOLT) bolt.type = 1 bolt.center_x = alien.center_x bolt.center_y = alien.center_y - 60 bolt.change_x = 0 bolt.change_y = -BOLT_SPEED * .35 self.bolt_list.append(bolt) # Off Screen if alien.center_x > SCREEN_WIDTH: alien.center_x = 1 if alien.center_x < 0: alien.center_x = SCREEN_WIDTH - 1 if alien.center_y > SCREEN_HEIGHT: alien.kill() if alien.center_y < 0: alien.kill() # Asteroid Movement for asteroid in self.asteroid_list: asteroid.center_x = asteroid.center_x + asteroid.change_x asteroid.center_y = asteroid.center_y + asteroid.change_y asteroid_hit_list = arcade.check_for_collision_with_list( asteroid, self.asteroid_list) # Collision between asteroid physics for asteroid2 in asteroid_hit_list: if asteroid2 != asteroid: Asteroid.physics(asteroid, asteroid2) # Off Screen if asteroid.center_x - asteroid.collision_radius > SCREEN_WIDTH: asteroid.center_x = 10 - asteroid.collision_radius if asteroid.center_x + asteroid.collision_radius < 0: asteroid.center_x = SCREEN_WIDTH + asteroid.collision_radius if asteroid.center_y - asteroid.collision_radius > SCREEN_HEIGHT: asteroid.center_y = 10 - asteroid.collision_radius if asteroid.center_y + asteroid.collision_radius < 0: asteroid.center_y = SCREEN_HEIGHT + asteroid.collision_radius # Bolt Movement for bolt in self.bolt_list: bolt.center_x = bolt.center_x + bolt.change_x bolt.center_y = bolt.center_y + bolt.change_y # Collision with alien bolt_hit_list = arcade.check_for_collision_with_list( bolt, self.alien_list) for alien_hit in bolt_hit_list: alien_hit.kill() bolt.kill() self.numOfAliens = self.numOfAliens - 1 self.score = self.score + 50 # Collision with boss bolt_hit_list = arcade.check_for_collision_with_list( bolt, self.boss_list) for boss_hit in bolt_hit_list: if boss_hit.health > 0: if bolt.type == 0: boss_hit.health = boss_hit.health - 1 elif bolt.type == 1: boss_hit.health = boss_hit.health - 75 elif boss_hit.health <= 0: boss_hit.kill() self.numOfBoss = self.numOfBoss - 1 self.score = self.score + BOSSPOINTS bolt.kill() # Collision with asteroid bolt_hit_list = arcade.check_for_collision_with_list( bolt, self.asteroid_list) for asteroid_hit in bolt_hit_list: if asteroid_hit.health > 1: if bolt.type == 0: asteroid_hit.health = asteroid_hit.health - 1 elif bolt.type == 1: asteroid_hit.health = asteroid_hit.health - 75 bolt.kill() self.score = self.score + 1 if asteroid_hit.health <= .25 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(3) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .5 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(2) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .75 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(1) asteroid_hit._set_scale(asteroid_hit.scale) else: # Splits asteroid into two unless it is of smallest size if asteroid_hit.scale > SPRITE_MAX_SCALING_ASTEROID / 2: x1 = asteroid_hit.center_x + asteroid_hit.collision_radius / 2 y1 = asteroid_hit.center_y + asteroid_hit.collision_radius / 2 x2 = asteroid_hit.center_x - asteroid_hit.collision_radius / 2 y2 = asteroid_hit.center_y - asteroid_hit.collision_radius / 2 self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x1, y1, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x2, y2, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.numOfAsteroids = self.numOfAsteroids + 2 asteroid_hit.kill() bolt.kill() self.numOfAsteroids = self.numOfAsteroids - 1 self.score = self.score + 10 # Off Screen Deletion of Bolts if bolt.center_x > SCREEN_WIDTH or bolt.center_x < 0 \ or bolt.center_y > SCREEN_HEIGHT or bolt.center_y < 0: bolt.kill() for beam in self.beam_list: # Collision with asteroid laser_hit_list = arcade.check_for_collision_with_list( beam, self.asteroid_list) for asteroid_hit in laser_hit_list: if asteroid_hit.health > 1: asteroid_hit.health = asteroid_hit.health - 1 self.score = self.score + 1 if asteroid_hit.health <= .25 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(3) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .5 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(2) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .75 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(1) asteroid_hit._set_scale(asteroid_hit.scale) else: # Splits asteroid into two unless it is of smallest size if asteroid_hit.scale > SPRITE_MAX_SCALING_ASTEROID / 2: x1 = asteroid_hit.center_x + asteroid_hit.collision_radius / 2 y1 = asteroid_hit.center_y + asteroid_hit.collision_radius / 2 x2 = asteroid_hit.center_x - asteroid_hit.collision_radius / 2 y2 = asteroid_hit.center_y - asteroid_hit.collision_radius / 2 self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x1, y1, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x2, y2, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.numOfAsteroids = self.numOfAsteroids + 2 asteroid_hit.kill() for laser in self.laser_list: # Movement laserDistFromPlayer = laser.height / 2 + 25 if self.player_sprite.angle == 0: laser.center_x = self.player_sprite.center_x laser.center_y = self.player_sprite.center_y + laserDistFromPlayer laser.angle = 0 elif self.player_sprite.angle == 180: laser.center_x = self.player_sprite.center_x laser.center_y = self.player_sprite.center_y - laserDistFromPlayer laser.angle = 180 elif self.player_sprite.angle == 90: laser.center_x = self.player_sprite.center_x - laserDistFromPlayer laser.center_y = self.player_sprite.center_y laser.angle = 90 elif self.player_sprite.angle == 270: laser.center_x = self.player_sprite.center_x + laserDistFromPlayer laser.center_y = self.player_sprite.center_y laser.angle = 270 # Collision with alien laser_hit_list = arcade.check_for_collision_with_list( laser, self.alien_list) for alien_hit in laser_hit_list: alien_hit.kill() laser.health = laser.health - 1 self.numOfAliens = self.numOfAliens - 1 self.score = self.score + 50 if laser.health <= 0: laser.kill() # Collision with boss laser_hit_list = arcade.check_for_collision_with_list( laser, self.alien_list) for boss_hit in laser_hit_list: if boss_hit.health > 1: boss_hit.health = boss_hit.health - 1 laser.health = laser.health - 1 if laser.health <= 0: laser.kill() else: boss_hit.kill() self.score = self.score + BOSSPOINTS laser.health = laser.health - 1 if laser.health <= 0: laser.kill() self.numOfBoss = self.numOfBoss - 1 # Collision with asteroid laser_hit_list = arcade.check_for_collision_with_list( laser, self.asteroid_list) for asteroid_hit in laser_hit_list: if asteroid_hit.health > 1: asteroid_hit.health = asteroid_hit.health - 1 laser.health = laser.health - 1 if laser.health <= 0: laser.kill() self.score = self.score + 1 if asteroid_hit.health <= .25 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(3) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .5 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(2) asteroid_hit._set_scale(asteroid_hit.scale) elif asteroid_hit.health <= .75 * ( 5 * SPRITE_MAX_SCALING_ASTEROID): asteroid_hit.set_texture(1) asteroid_hit._set_scale(asteroid_hit.scale) else: # Splits asteroid into two unless it is of smallest size if asteroid_hit.scale > SPRITE_MAX_SCALING_ASTEROID / 2: x1 = asteroid_hit.center_x + asteroid_hit.collision_radius / 2 y1 = asteroid_hit.center_y + asteroid_hit.collision_radius / 2 x2 = asteroid_hit.center_x - asteroid_hit.collision_radius / 2 y2 = asteroid_hit.center_y - asteroid_hit.collision_radius / 2 self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x1, y1, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.asteroid_list = Asteroid.createMiniAsteroid( MyGame, self.asteroid_list, x2, y2, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) self.numOfAsteroids = self.numOfAsteroids + 2 asteroid_hit.kill() laser.health = laser.health - 1 if laser.health <= 0: laser.kill() self.numOfAsteroids = self.numOfAsteroids - 1 self.score = self.score + 10 # Laser Decay laser.health = laser.health - 1 if laser.health <= 0: laser.kill() self.laser = False self.pow = False # Creation of More Asteroids When One Is Destroyed extraAsteroid = round(self.score / 400) if self.numOfAsteroids < START_ASTEROID + extraAsteroid: self.asteroid_list, self.numOfAsteroids = Asteroid.createAsteroid( MyGame, True, self.asteroid_list, self.numOfAsteroids, SCREEN_HEIGHT, SCREEN_WIDTH, SPRITE_MAX_SCALING_ASTEROID, MAX_ASTEROID_SPEED) # End of Game when score > 1,000,000 if self.score >= 10000: self.current_state = GAME_WON self.physics_engine.update()