def take_damage(self, explosion): self.all_sprites.remove(explosion) if self.lives > 0: self.goto_checkpoint() self.lives -= 1 else: gameover = GameOver(self.screen.get_width() * 0.2, self.screen.get_height() * 0.2, int(self.screen.get_width() * 0.6), int(self.screen.get_height() * 0.6), self.highest_score, self.reset) self.all_sprites.add(gameover)
def update_screen(self): for s in self.sprites: s.update_status() if not s.ai: #update player s.update() if not s.status==8 and not self.player.off_screen(): s.check_mapcollisions(self.blocks) trig = s.check_trigcollisions(self.map.triggers) if trig: if trig.name=="exit": self.player.exiting = 1 elif trig.name=="dtrigger": self.show_dialog(trig.params) if trig.params=="tut08": self.player.exiting = -1 self.player.set_image(GLOBALS["nanji"]["idle"][0]) else: player_data["health"] = 9 player_data["lives"] -= 1 if player_data["lives"] > 0: next = Level(self.map_filename, prev=self.prev) else: next = GameOver() self.next = FadeState(self.screen, next.background, next) self.quit() else: #update ai if s.ai_update(self): #throw shuriken? self.bullets.add(Shuriken(s, self.camera)) self.bullets.update() self.camera.update() #draw bg #self.scroll_bg.update(self.player.vel[0]) self.background.blit(self.bg, (0,0)) #draw map and sprites self.lvl_layer.fill((255,0,255)) self.lvl_layer.blit(self.lvl_img, self.camera.pos, [self.camera.pos, GLOBALS["screen_size"]]) self.lvl_layer.set_colorkey((255,0,255)) self.bullets.draw(self.lvl_layer) self.sprites.draw(self.lvl_layer) #pygame.draw.rect(self.lvl_layer, (255,255,0), self.player.colrect, 1) #draw collision rect of nanji if self.player.exiting: #draw semi-black image over dojo entry while entering self.lvl_layer.blit(GLOBALS["objects"]["dojo_entry"], self.map.dojo_pos) self.background.blit(self.lvl_layer, (0,0), [self.camera.pos, GLOBALS["screen_size"]]) self.ui_layer.draw(self.background) self.screen.blit(self.background, (0,0)) pygame.display.flip()
def __init__(self, ai_settings, screen): self.ai_settings = ai_settings self.screen = screen self.display_start = True self.display_high_score = False self.start_screen = StartScreen(ai_settings=ai_settings, screen=screen) self.stats = GameStats(ai_settings=self.ai_settings) self.sb = Scoreboard(ai_settings=self.ai_settings, screen=self.screen, stats=self.stats) self.ship = Ship(ai_settings=self.ai_settings, screen=self.screen) self.high_score = High_Score(self.ai_settings, self.screen) self.gameover = GameOver(self.ai_settings, self.screen) self.quit = False self.alien1 = Alien1(ai_settings=self.ai_settings, screen=self.screen) self.alien2 = Alien2(ai_settings=self.ai_settings, screen=self.screen) self.alien3 = Alien3(ai_settings=self.ai_settings, screen=self.screen) self.aliens = [self.alien1, self.alien2, self.alien3] self.UFO = UFO(ai_settings=self.ai_settings, screen=self.screen) self.faster = False self.bullets = Group() self.enemy_bullets = Group() self.alien_group = Group() self.play_music = 'sounds/play.mp3' self.play_music_faster = 'sounds/play-faster.mp3' self.missile_sound = pygame.mixer.Sound('sounds/missile.wav') self.bunker = Group() self.create_bunker()
def main(): pygame.init() screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH) pygame.display.set_caption("Snowy Slopes") pygame.display.set_icon(load.load_image("sledderFullsize")) init() timer = pygame.time.Clock() while True: timer.tick(60) selection = Menu(screen).run() if selection == Menu.NEWGAME: selection = Menu(screen, gameSelection=True).run() if selection == Menu.GAME: score = Game(screen, timer).run() elif selection == Menu.DRAW: numPlatforms = Draw(screen).run() if isinstance(numPlatforms, list): platformType = numPlatforms score = Game(screen, timer, custom=platformType).run() elif isinstance(numPlatforms, int): score = Game(screen, timer, custom=numPlatforms).run() else: main() elif selection == Menu.BACK: main() elif selection == Menu.HELP: Help(screen, timer).run() score = Game(screen, timer).run() elif selection == Menu.QUIT: pygame.quit() sys.exit() # runs after game is over newSelection = GameOver(screen, score).run() if newSelection == GameOver.QUIT: pygame.quit() sys.exit() elif newSelection == GameOver.REPLAY: main() # resets the game
while not run and not man.living and not man.win and not difficultyScreen: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if singlePlayer.collidePt(event.pos): man.living = True run = True elif difficulty.collidePt(event.pos): difficultyScreen = True elif exit.collidePt(event.pos): exit.clicked = True sys.exit() screen.fill([0, 0, 0]) banner = GameOver("rsc/Menus/titlebanner.png", [25, 25], screenSize) screen.blit(banner.surface, banner.rect) screen.blit(singlePlayer.surface, singlePlayer.rect) screen.blit(difficulty.surface, difficulty.rect) screen.blit(exit.surface, exit.rect) pygame.display.flip() #---------------------Difficulty------------------------------------ while not run and not man.living and not man.win and difficultyScreen: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if easy.collidePt(event.pos): maxZombies = 5 maxRobots = 5
def __init__(self,gamestate,score,ammo): # Konfuguracja random.seed() #inicjalizaja pygame.init() self.SCREEN_SIZE = (1280, 720) # grafiki dopasowane do tego self.screen = pygame.display.set_mode(self.SCREEN_SIZE) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.shot = 0.0 self.supertime = -2 self.player = Player(self) self.aliens = [] self.opp = 10 self.bullets = [] self.alienbulets = [] self.lives = Lives(self) self.lives_number = 3 self.score = Score(self) self.score_number = 0 + score self.ammo = Ammo(self) self.walls = [] self.gameover = GameOver(self) self.gamestate = gamestate self.ammo_number = ammo + 5 self.nextlevel = NextLevel(self) self.tps_max = 300.0 self.superalien = [] self.tooClose = False self.pauseSign = Pause(self) self.pause = 1 for i in range(0,self.opp): self.aliens.append(Alien(self, i * 100 + 100, 100,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 150,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 200,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 250,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 300,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 350,self.gamestate-1)) self.rand_opp = 6*self.opp for i in range(0,5): self.walls.append(Wall(self,80+i*340)) channel_game = pygame.mixer.Channel(1) channel_game2 = pygame.mixer.Channel(2) channel_game3 = pygame.mixer.Channel(3) self.background = pygame.image.load("tlo3.jpg") self.text = open("score").readline() while self.gamestate !=0: if self.rand_opp != 0: los = random.randrange(self.rand_opp) else: los = 0 # obsługa zdarzen for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player.pos[0]+23,self.player.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) elif (self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose == True) and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate = 0 elif len(self.aliens) == 0 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate += 1 Game(self.gamestate,self.score_number,self.ammo_number) self.text = open("score").readline() self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and self.pause == -1: self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_p and self.pause == -1: self.pause *= -1 #ticking self.tps_delta += self.tps_clock.tick() / 1000.0 self.shot += self.tps_clock.tick()+0.000000003*(self.gamestate-1) / 1.0 self.supertime += self.tps_clock.tick() / 1.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max while(self.shot >= 0.001 / self.tps_max and len(self.aliens)!=0 and (self.lives_number != 0 and self.ammo_number > 0) and self.tooClose == False and self.pause == 1): self.shot = 0 channel_game.play(pygame.mixer.Sound("shot.wav")) channel_game.set_volume(0.5) self.alienbulets.append(AlienBullet(self,self.aliens[los].x,self.aliens[los].y)) while self.supertime >= 0.001 / self.tps_max: self.supertime = -2 if(len(self.superalien)==0 and self.tooClose == False and self.lives_number !=0 and self.ammo_number > 0 and self.pause == 1): self.superalien.append(SuperAlien(self)) channel_game2.play(pygame.mixer.Sound("supersound.wav")) channel_game2.set_volume(0.3) #rendering self.screen.fill((0, 0, 0)) self.screen.blit(self.background, (0, 0)) self.draw() pygame.display.flip()
class Game(object): def __init__(self,gamestate,score,ammo): # Konfuguracja random.seed() #inicjalizaja pygame.init() self.SCREEN_SIZE = (1280, 720) # grafiki dopasowane do tego self.screen = pygame.display.set_mode(self.SCREEN_SIZE) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.shot = 0.0 self.supertime = -2 self.player = Player(self) self.aliens = [] self.opp = 10 self.bullets = [] self.alienbulets = [] self.lives = Lives(self) self.lives_number = 3 self.score = Score(self) self.score_number = 0 + score self.ammo = Ammo(self) self.walls = [] self.gameover = GameOver(self) self.gamestate = gamestate self.ammo_number = ammo + 5 self.nextlevel = NextLevel(self) self.tps_max = 300.0 self.superalien = [] self.tooClose = False self.pauseSign = Pause(self) self.pause = 1 for i in range(0,self.opp): self.aliens.append(Alien(self, i * 100 + 100, 100,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 150,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 200,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 250,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 300,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 350,self.gamestate-1)) self.rand_opp = 6*self.opp for i in range(0,5): self.walls.append(Wall(self,80+i*340)) channel_game = pygame.mixer.Channel(1) channel_game2 = pygame.mixer.Channel(2) channel_game3 = pygame.mixer.Channel(3) self.background = pygame.image.load("tlo3.jpg") self.text = open("score").readline() while self.gamestate !=0: if self.rand_opp != 0: los = random.randrange(self.rand_opp) else: los = 0 # obsługa zdarzen for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player.pos[0]+23,self.player.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) elif (self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose == True) and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate = 0 elif len(self.aliens) == 0 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate += 1 Game(self.gamestate,self.score_number,self.ammo_number) self.text = open("score").readline() self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and self.pause == -1: self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_p and self.pause == -1: self.pause *= -1 #ticking self.tps_delta += self.tps_clock.tick() / 1000.0 self.shot += self.tps_clock.tick()+0.000000003*(self.gamestate-1) / 1.0 self.supertime += self.tps_clock.tick() / 1.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max while(self.shot >= 0.001 / self.tps_max and len(self.aliens)!=0 and (self.lives_number != 0 and self.ammo_number > 0) and self.tooClose == False and self.pause == 1): self.shot = 0 channel_game.play(pygame.mixer.Sound("shot.wav")) channel_game.set_volume(0.5) self.alienbulets.append(AlienBullet(self,self.aliens[los].x,self.aliens[los].y)) while self.supertime >= 0.001 / self.tps_max: self.supertime = -2 if(len(self.superalien)==0 and self.tooClose == False and self.lives_number !=0 and self.ammo_number > 0 and self.pause == 1): self.superalien.append(SuperAlien(self)) channel_game2.play(pygame.mixer.Sound("supersound.wav")) channel_game2.set_volume(0.3) #rendering self.screen.fill((0, 0, 0)) self.screen.blit(self.background, (0, 0)) self.draw() pygame.display.flip() def tick(self): if (self.lives_number != 0 and self.ammo_number > 0 and len(self.aliens) !=0 and self.tooClose == False and self.pause == 1): self.edge = False self.player.tick() for i in range(0,len(self.aliens)): self.aliens[i].move() if (self.aliens[i].x >= self.SCREEN_SIZE[0]-50) or (self.aliens[i].x <= 0): self.edge = True if self.edge: for i in range(0, len(self.aliens)): if self.aliens[i].x >= self.SCREEN_SIZE[0]-100: for j in range(0, len(self.aliens)): self.aliens[j].x -= 3 elif self.aliens[i].x < 50: for j in range(0, len(self.aliens)): self.aliens[j].x += 3 self.aliens[i].shiftDown() self.edge = False if (self.aliens[i].y > 600 ): self.tooClose = True for i in range(0,len(self.bullets)): self.bullets[i].tick() for i in range(0,len(self.alienbulets)): self.alienbulets[i].tick() for i in range(0,len(self.superalien)): self.superalien[i].move() def draw(self): self.player.draw() self.lives.draw(self.lives_number) self.score.draw(self.score_number) self.ammo.draw(self.ammo_number) for i in range(0,len(self.walls)-1): self.walls[i].draw() for i in range(0,len(self.bullets)): self.bullets[i].draw() for j in range(0, len(self.aliens)): if(self.bullets[i].hits(self.aliens[j])): self.aliens[j].destroy() self.bullets[i].destroy() self.score_number +=10 #self.ammo_number += 1 for j in range(0, len(self.walls)): if (self.bullets[i].hits_wall(self.walls[j])): self.bullets[i].destroy() self.ammo_number -=1 if (self.walls[j].state > 0): self.walls[j].state -= 1 else: self.walls[j].destroy() for j in range(0,len(self.superalien)): if(self.bullets[i].hits_super(self.superalien[j])): self.superalien[j].destroy() self.bullets[i].destroy() self.score_number +=100 self.ammo_number += 5 if(self.bullets[i].y <= 0): self.bullets[i].destroy() self.ammo_number -= 1 for i in range(0,len(self.aliens)): self.aliens[i].draw() for i in range(len(self.bullets)-1,-1,-1): if(self.bullets[i].toDestroy): self.bullets.pop(i) for i in range(len(self.aliens)-1,-1,-1): if(self.aliens[i].toDestroy): self.aliens.pop(i) self.rand_opp -= 1 for i in range(len(self.walls)-1,-1,-1): if(self.walls[i].toDestroy): self.walls.pop(i) for i in range(len(self.alienbulets)-1,-1,-1): if(self.alienbulets[i].toDestroy): self.alienbulets.pop(i) for i in range(len(self.superalien)-1,-1,-1): if(self.superalien[i].toDestroy): self.superalien.pop(i) for i in range(0,len(self.superalien)): self.superalien[i].draw() if self.superalien[i].x < -65: self.superalien[i].destroy() for i in range(0,len(self.alienbulets)): self.alienbulets[i].draw() if(self.alienbulets[i].hits(self.player) and len(self.aliens) != 0): self.alienbulets[i].destroy() self.lives_number -= 1 self.ammo_number -= 4*(self.gamestate) self.score_number -= 100 for j in range(0,len(self.walls)): if(self.alienbulets[i].hits_wall(self.walls[j])): self.alienbulets[i].destroy() if(self.walls[j].state>0): self.walls[j].state -=1 else: self.walls[j].destroy() if (self.alienbulets[i].y >= 720): self.alienbulets[i].destroy() if self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose: self.gameover.draw() if len(self.aliens) == 0: self.nextlevel.draw() if self.pause == -1: self.pauseSign.draw() if(self.score_number > int(self.text)): self.cel = open("score", "w") self.cel.write(self.text.replace(self.text,str(self.score_number))) self.cel.close()
def on_render(self, screen, clock): if self.dead == True: currFrame = self.frame triggerFrame = currFrame + 100 d = "dead" while currFrame != triggerFrame: self.p1.update(d, screen, self.board) self.p2.update(d, screen, self.board) currFrame += 1 pygame.display.flip() pygame.time.delay(700) self.switch_to_scene(GameOver(self.menuObject)) if pygame.key.get_pressed()[pygame.K_w] or pygame.key.get_pressed()[ pygame.K_UP]: direction = 'up' elif pygame.key.get_pressed()[pygame.K_a] or pygame.key.get_pressed()[ pygame.K_LEFT]: direction = 'left' elif pygame.key.get_pressed()[pygame.K_s] or pygame.key.get_pressed()[ pygame.K_DOWN]: direction = 'down' elif pygame.key.get_pressed()[pygame.K_d] or pygame.key.get_pressed()[ pygame.K_RIGHT]: direction = 'right' else: direction = 'idle' screen.fill((255, 255, 255)) screen.blit(self.get_image(self.path + self.background), (0, 0)) screen.blit( self.get_image(self.path + '/animation/label_level' + str(self.level) + '.png'), (0, 560)) for i in range(len(self.tiles)): screen.blit(self.get_image(self.path + self.tiles[i].path), self.tiles[i].getRealXY()) p1_status = self.p1.update(direction, screen, self.board) p2_status = self.p2.update(direction, screen, self.board) if p1_status[0] == "dead" or p2_status[0] == "dead": self.p1 = DeadPlayer(self.path + '/animation/character1/', p1_status[1], p1_status[2]) self.p2 = DeadPlayer(self.path + '/animation/character2/', p2_status[1], p2_status[2]) self.dead = True # self.switch_to_scene(GameOver(self.menuObject)) if p1_status[0] == "victory": print("Victory player 1") self.victory_count += 1 self.p1 = Victor(self.path + '/animation/character3/', p1_status[1], p1_status[2]) if p2_status[0] == "victory": print("Victory player 2") self.victory_count += 1 self.p2 = Victor(self.path + '/animation/character4/', p2_status[1], p2_status[2]) if self.victory_count == 2: pygame.time.delay(500) self.switch_to_scene(WonLevel(self.menuObject)) if p1_status[0] == "moving": fallingCoin = Animator(self.path + '/animation/coin/', p1_status[1], p1_status[2]) fallingCoin.realX += 12.5 fallingCoin.realY += 30 self.fallingCoins.append([fallingCoin, 0]) if p2_status[0] == "moving": fallingCoin = Animator(self.path + '/animation/coin/', p2_status[1], p2_status[2]) fallingCoin.realX += 12.5 fallingCoin.realY += 30 self.fallingCoins.append([fallingCoin, 0]) for i in range(len(self.fallingCoins) - 1, -1, -1): self.fallingCoins[i][1] += 0.3 self.fallingCoins[i][0].realY += self.fallingCoins[i][1] self.fallingCoins[i][0].update(screen) if self.fallingCoins[i][0].realY > 600: del self.fallingCoins[i] if self.frame % 3 == 0: self.particles.append( [random.randrange(0, 800), 610, random.randrange(1, 6)]) for i in range(len(self.particles) - 1, -1, -1): pygame.draw.circle(screen, (255, 255, 255, 100), (self.particles[i][0], self.particles[i][1]), self.particles[i][2], 1) self.particles[i][1] -= self.particles[i][2] if self.particles[i][1] < -10: del self.particles[i] for i in range(len(self.anims)): self.anims[i].update(screen) self.frame += 1 pygame.display.flip()
class PlayScreen: def __init__(self, ai_settings, screen): self.ai_settings = ai_settings self.screen = screen self.display_start = True self.display_high_score = False self.start_screen = StartScreen(ai_settings=ai_settings, screen=screen) self.stats = GameStats(ai_settings=self.ai_settings) self.sb = Scoreboard(ai_settings=self.ai_settings, screen=self.screen, stats=self.stats) self.ship = Ship(ai_settings=self.ai_settings, screen=self.screen) self.high_score = High_Score(self.ai_settings, self.screen) self.gameover = GameOver(self.ai_settings, self.screen) self.quit = False self.alien1 = Alien1(ai_settings=self.ai_settings, screen=self.screen) self.alien2 = Alien2(ai_settings=self.ai_settings, screen=self.screen) self.alien3 = Alien3(ai_settings=self.ai_settings, screen=self.screen) self.aliens = [self.alien1, self.alien2, self.alien3] self.UFO = UFO(ai_settings=self.ai_settings, screen=self.screen) self.faster = False self.bullets = Group() self.enemy_bullets = Group() self.alien_group = Group() self.play_music = 'sounds/play.mp3' self.play_music_faster = 'sounds/play-faster.mp3' self.missile_sound = pygame.mixer.Sound('sounds/missile.wav') self.bunker = Group() self.create_bunker() def create_bunker(self): for x in range(3): bunk = Bunker(ai_settings=self.ai_settings, screen=self.screen, centerx=x * 400 + 200, centery=self.ai_settings.screen_height - 100) self.bunker.add(bunk) def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self.check_keydown_events(event) elif event.type == pygame.KEYUP: self.check_keyup_events(event) def check_keyup_events(self, event): if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def check_keydown_events(self, event): if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_SPACE: self.fire_bullet() elif event.key == pygame.K_q: sys.exit() def new_game(self): self.ai_settings.initialize_dynamic_settings() pygame.mouse.set_visible(False) self.stats.reset_stats() self.stats.game_active = True self.sb.prep_score() self.sb.prep_ships() self.alien_group.empty() self.bullets.empty() self.enemy_bullets.empty() # create fleet self.create_fleet() self.create_bunker() self.ship.center_ship() def fire_bullet(self): if len(self.bullets) < self.ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings=self.ai_settings, screen=self.screen, ship=self.ship) self.bullets.add(new_bullet) self.missile_sound.play() def fire_enemy_bullet(self): if random.random() < self.ai_settings.probability_to_fire: if len(self.enemy_bullets ) < self.ai_settings.enemy_bullets_allowed: alien = random.choice(list(self.alien_group.spritedict.keys())) new_bullet = Bullet(ai_settings=self.ai_settings, screen=self.screen, ship=alien, enemy=True) self.enemy_bullets.add(new_bullet) self.missile_sound.play() def get_number_aliens_x(self): alien_width = self.aliens[0].rect.width available_space_x = self.ai_settings.screen_width - (2 * alien_width) number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def get_number_rows(self): alien_height = self.aliens[0].rect.height available_space_y = (self.ai_settings.screen_height - (3 * alien_height) - self.ship.rect.height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows def create_alien(self, which_alien, row_number, alien_number): one_alien = None if which_alien == 0: one_alien = Alien1(ai_settings=self.ai_settings, screen=self.screen) elif which_alien == 1: one_alien = Alien2(ai_settings=self.ai_settings, screen=self.screen) elif which_alien == 2: one_alien = Alien3(ai_settings=self.ai_settings, screen=self.screen) alien_width = one_alien.rect.width one_alien.x = alien_width + 2 * alien_width * alien_number one_alien.rect.x = one_alien.x one_alien.rect.y = one_alien.rect.height + 2 * one_alien.rect.height * row_number self.alien_group.add(one_alien) def create_fleet(self): rows = self.get_number_rows() aliens_per_row = self.get_number_aliens_x() for row_number in range(rows): which_alien = int(row_number / 2) for alien_number in range(aliens_per_row): self.create_alien(which_alien=which_alien, row_number=row_number, alien_number=alien_number) def check_bullet_alien_collisions(self): collisions = pygame.sprite.groupcollide(self.bullets, self.alien_group, True, True) pygame.sprite.groupcollide(self.alien_group, self.bunker, False, True) if self.UFO.alive: if pygame.sprite.spritecollideany(self.UFO, self.bullets): self.UFO.explode() self.UFO.dead() self.stats.score += self.ai_settings.ufo_points self.sb.prep_score() if collisions: for aliens in collisions.values(): for alien in aliens: for x in range(len(self.aliens)): if type(alien) == type(self.aliens[x]): self.stats.score += self.ai_settings.alien_points[ x] self.sb.prep_score() alien.explode() sleep(0.05) alien.explosion_timer.reset() # needs to update settings for alien points if len(self.alien_group) < 11 and not self.faster: self.play_game_music(faster=True) if len(self.alien_group) == 0 and not self.UFO.alive: self.bullets.empty() self.ai_settings.increase_speed() self.stats.level += 1 self.sb.prep_level() self.create_fleet() self.UFO.reset() self.play_game_music(faster=False) bunker_collision = pygame.sprite.groupcollide( groupa=self.bunker, groupb=self.enemy_bullets, dokilla=False, dokillb=True, collided=pygame.sprite.collide_rect_ratio(2)) def ship_hit(self): self.stats.ships_left -= 1 print(self.stats.ships_left) if self.stats.ships_left > 0: # Update the scoreboard self.sb.prep_ships() # Empty list of aliens and bullets self.alien_group.empty() self.bullets.empty() self.enemy_bullets.empty() # create_fleet self.create_fleet() self.ship.center_ship() self.create_bunker() # Pause sleep(0.5) else: for i in range(6): self.ship.explode() sleep(0.3) self.ship.explosion_timer.reset() self.stats.game_active = False pygame.mouse.set_visible(True) self.high_score.update_score(self.stats.score) def update_screen(self): self.screen.fill(self.ai_settings.bg_color) self.bullets.draw(self.screen) self.enemy_bullets.draw(self.screen) self.ship.blitme() for alien in self.alien_group: alien.blitme() if self.UFO.alive: self.UFO.blitme() for bunker in self.bunker: bunker.draw() self.sb.show_score() pygame.display.flip() def start_screen_play(self): self.start_screen.play_music() while self.display_start: for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit() elif e.type == pygame.MOUSEBUTTONDOWN: _mouse_x, _mouse_y = pygame.mouse.get_pos() if self.start_screen.check_play_button(_mouse_x, _mouse_y): self.display_start = False continue if self.start_screen.check_high_score_button( _mouse_x, _mouse_y): self.display_high_score = True elif e.type == pygame.KEYDOWN: if e.key == pygame.K_SPACE: self.display_high_score = False if self.display_high_score: self.high_score.draw() else: self.start_screen.draw() pygame.display.flip() pygame.mixer.music.stop() def gameOver_play(self): self.gameover.draw() for e in pygame.event.get(): if e.type == pygame.KEYDOWN: if e.type == pygame.QUIT: sys.exit() if e.type == pygame.MOUSEBUTTONDOWN: _mouse_x, _mouse_y = pygame.mouse.get_pos() if self.gameover.check_play_button(_mouse_x=_mouse_x, _mouse_y=_mouse_y): self.new_game() self.stats.game_active = True elif self.gameover.check_quit_button(_mouse_x=_mouse_x, _mouse_y=_mouse_y): self.quit = True def play_game_music(self, faster): pygame.mixer.music.stop() if faster: pygame.mixer.music.load(self.play_music_faster) self.faster = True else: pygame.mixer.music.load(self.play_music) self.faster = False pygame.mixer.music.play(-1, 0.0) def update_bullets(self): self.bullets.update() self.enemy_bullets.update() for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) for bullet in self.enemy_bullets.copy(): if bullet.rect.top >= self.ai_settings.screen_height: self.enemy_bullets.remove(bullet) self.fire_enemy_bullet() if pygame.sprite.spritecollideany(self.ship, self.enemy_bullets): self.ship_hit() self.check_bullet_alien_collisions() def change_fleet_direction(self): for alien in self.alien_group: alien.rect.y += self.ai_settings.fleet_drop_speed self.ai_settings.fleet_direction *= -1 def check_fleet_edges(self): for alien in self.alien_group: if alien.check_edges(): self.change_fleet_direction() break def check_aliens_bottom(self): screen_rect = self.screen.get_rect() for alien in self.alien_group: if alien.rect.bottom >= screen_rect.bottom: self.ship_hit() break def update_aliens(self): self.check_fleet_edges() self.alien_group.update() if pygame.sprite.spritecollideany(self.ship, self.alien_group): self.ship_hit() if self.UFO.alive: self.update_UFO() self.check_aliens_bottom() def update_UFO(self): if self.UFO.check_edges(): self.ai_settings.UFO_direction *= -1 self.UFO.update() def play(self): self.start_screen_play() self.new_game() self.play_game_music(faster=False) while not self.quit: if self.stats.game_active: self.check_events() self.ship.update() self.update_bullets() self.update_aliens() self.update_screen() else: self.gameOver_play() pygame.display.flip()
def game_over(self): gameover = GameOver(self.screen, self.MAP_POS, self.MAP_SIZE) return gameover.main_loop()
def play(self): state = constants.STATE_START score_board = Score(location=(constants.WINDOW_WIDTH - 30, 20)) play_button = Play( location=(int((constants.WINDOW_WIDTH - constants.PLAY_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.PLAY_HEIGHT) / 2))) pause_button = Pause(location=(20, 20)) welcome_message = Welcome(location=( int((constants.WINDOW_WIDTH - constants.MESSAGE_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.MESSAGE_HEIGHT) / 2))) gameover_message = GameOver(location=( int((constants.WINDOW_WIDTH - constants.GAMEOVER_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.GAMEOVER_HEIGHT) / 3))) collided = False done = False while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.KEYDOWN: if state == constants.STATE_START: if event.key == pygame.K_SPACE: state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() elif state == constants.STATE_RUN: if event.key == pygame.K_SPACE: self.agent.flap() elif event.key == pygame.K_ESCAPE: state = constants.STATE_PAUSE elif state == constants.STATE_PAUSE: if event.key == pygame.K_SPACE: if collided: state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() else: self.agent.resume(fps=self.fps) state = constants.STATE_RUN elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = event.pos # gets mouse position if state == constants.STATE_RUN: if pause_button.rect.collidepoint(mouse_pos): state = constants.STATE_PAUSE else: self.agent.flap() elif state == constants.STATE_START and welcome_message.rect.collidepoint( mouse_pos): state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() elif state == constants.STATE_PAUSE: if gameover_message.rect.collidepoint(mouse_pos): state = constants.STATE_START collided = False elif play_button.rect.collidepoint(mouse_pos): self.agent.resume(fps=self.fps) state = constants.STATE_RUN if state == constants.STATE_START: self.redraw_screen(move=False) self.screen.blit(welcome_message.image, welcome_message.rect) elif state == constants.STATE_RUN: out_of_bounds = self.agent.move() self.meter_counts[1] += constants.SPEED if self.meter_counts[1] - self.meter_counts[ 0] > constants.PIPE_WIDTH: self.meter_counts[0] = self.meter_counts[1] self.update_pipes() collided, _ = self.check_collision() collided = collided or out_of_bounds if collided: state = constants.STATE_PAUSE score_board.update(score=self.score) self.redraw_screen() self.screen.blit(pause_button.image, pause_button.rect) self.screen.blit(score_board.surface, score_board.rect) elif state == constants.STATE_PAUSE: self.redraw_screen(move=False) if collided: self.screen.blit(gameover_message.image, gameover_message.rect) else: self.screen.blit(play_button.image, play_button.rect) # Limit the number of frames per second fps = self.fps if state == constants.STATE_RUN else int(self.fps / 2) self.clock.tick(fps) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()