def get_game_setup_menu(self, values): #self.missionsList = missions.get_open_play_missions() self.battlefieldsList = battlefields.get_battlefields() self.bgColour = values.colours["Beige"] longPanelImage = resources.load_secondary_sprite("long_panel01.png") panel01Image = pygame.transform.scale(longPanelImage, (270, 595)) panel02Image = pygame.transform.scale(longPanelImage, (860, 595)) sprList = [ sprites.GameSprite(panel01Image, (50, 75, 270, 595)), sprites.GameSprite(panel02Image, (370, 75, 860, 595)), ] self.group.add(sprList) buttonImage = resources.load_secondary_sprite("button01.png") buttonImage01 = pygame.transform.scale(buttonImage, (150, 50)) button = sprites.Button(11, 0, buttonImage01, (225, 0, 150, 50), "Battlefields", values.font20, values) button = sprites.Button(12, 0, buttonImage01, (400, 0, 150, 50), "Armies", values.font20, values) button = sprites.Button(13, 0, buttonImage01, (575, 0, 150, 50), "Game Settings", values.font20, values) button = sprites.Button(14, 0, buttonImage01, (750, 0, 150, 50), "Start Game", values.font20, values) button = sprites.Button(15, 0, buttonImage01, (925, 0, 150, 50), "Back", values.font20, values) for button in values.buttons: self.group.add(button.sprites)
def __init__(self, stateManager, gameDisplay): super().__init__() self.stateManager = stateManager self.backgroundPosition = [0, 0] self.gameDisplay = gameDisplay self.backgroundImage = pygame.image.load("images/quit.jpg") self.buttons = [sprites.Button(400, 350), sprites.Button(700, 350)] self.labels = [ texts.Text("Are you sure?", 200, 100, 150), texts.Text("YES!", 450, 350, 80), texts.Text("NO", 775, 350, 80) ]
def title(): # Define functions.setup() title = public.fonts['large'].render('Flappe', True, public.YELLOW) hs_text = public.fonts['plain'].render( 'High score: ' + str(public.high_score), True, public.YELLOW) play_btn = sprites.Button( media.MEDIA['play_normal_texture'], media.MEDIA['play_pressed_texture'], public.menu_rects['tt_play'], public.menu_rects['tt_play_pressed'], public.all_sprites) settings_btn = sprites.Button( media.MEDIA['play_normal_texture'], media.MEDIA['play_pressed_texture'], public.menu_rects['tt_settings'], public.menu_rects['tt_settings_pressed'], public.all_sprites) # Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: functions.dump_hs() return 1 elif event.type == pygame.MOUSEBUTTONDOWN: if public.menu_rects['tt_play'].collidepoint(event.pos): game() return 1 # Logic functions.update_clouds() functions.update_floors() public.all_sprites.update() sorted_sprites = sorted( public.all_sprites.sprites(), key=lambda x: x.type) # Draw public.screen.fill(public.skycolor) for sprite in sorted_sprites: sprite.draw() public.screen.blit(title, (97, 150)) public.screen.blit(hs_text, ( (public.SWIDTH / 2) - hs_text.get_width() // 2, 290)) pygame.display.flip() public.clock.tick(public.FPS)
def respond_complete(self, tile=TILE_TYPE.NONE): can_complete = self.can_complete(tile) if can_complete: clicked = False btn_yes = sprites.Button((0, 255, 0), 100, 30) btn_yes.rect.x = 300 btn_yes.rect.y = 600 btn_no = sprites.Button((255, 0, 0), 100, 30) btn_no.rect.x = 500 btn_no.rect.y = 600 txt = sprites.Text(u'要胡吗', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) response = False def on_click_yes(): if btn_yes.alive(): nonlocal response, clicked btn_yes.kill() clicked = True txt.kill() response = True def on_click_no(): if btn_no.alive(): nonlocal response, clicked btn_no.kill() txt.kill() clicked = True response = False self._graphics.add_sprite(btn_yes) self._graphics.add_sprite(btn_no) self._graphics.add_sprite(txt) btn_yes.on_click = on_click_yes btn_no.on_click = on_click_no while not clicked: self._graphics.clear() self._graphics.draw_all() pygame.display.update() self._graphics.handle(pygame.event.get()) self._graphics.clock.tick(30) self._graphics.clear() self._graphics.draw_all() return response else: return False
def __init__(self, stateManager, gameDisplay): super().__init__() self.stateManager = stateManager self.backgroundPosition = [0, 0] self.gameDisplay = gameDisplay self.backgroundImage = [ pygame.image.load("images/hud.jpg"), pygame.image.load("images/controls.jpg"), pygame.image.load("images/points.jpg"), pygame.image.load("images/info.jpg") ] self.nextImage = 0 self.buttons = [sprites.Button(10, 10), sprites.Button(1020, 610)] self.buttonText = [ texts.Text("Main Menu", 20, 35, 45), texts.Text("Next", 1090, 625, 60) ]
def title(debug): pygame.display.set_caption('Contrast') pygame.display.set_icon(pygame.image.fromstring(bz2.decompress( dictionaries.MEDIA['icon']), (32, 32), 'RGBA')) info_text = public.FONT_LG.render( 'ENTER TO BEGIN', False, [public.WHITE] * 3) play_button = sprites.Button((343, 290), 'Play') music_button = sprites.Button((407, 290), 'Music') button_cover = pygame.Surface((public.SWIDTH, 10)) button_cover.fill([public.BLACK] * 3) if len(debug) != 1: public.music = False m = re.search('map_(.+?).tmx', debug[1]) if m: public.level = int(m.group(1)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return 0 public.all_sprites.update() if public.end_title: game() return 0 public.screen.fill([public.BLACK] * 3) public.screen.blit(dictionaries.IMAGES['Logo'], functions.center( dictionaries.IMAGES['Logo'])) for sprite in public.all_sprites: sprite.draw() public.screen.blit(button_cover, (0, 345)) pygame.display.flip() public.clock.tick(public.FPS)
def __init__(self, stateManager, gameDisplay): super().__init__() self.stateManager = stateManager self.backgroundPosition = [0, 0] self.gameDisplay = gameDisplay self.backgroundImage = pygame.image.load("images/background.jpg") self.buttons = [ sprites.Button(850, 100), sprites.Button(850, 250), sprites.Button(850, 400), sprites.Button(850, 550) ] self.labels = [ texts.Text("PLAY!", 860, 100, 80), texts.Text("How To Play!", 860, 275, 40), texts.Text("High Scores!", 860, 425, 40), texts.Text("Quit!", 860, 550, 80) ]
def set_up_battlefield_tab(self, values): widePanelImage = resources.load_secondary_sprite("wide_panel01.png") buttonImage = pygame.transform.scale(widePanelImage, (255, 25)) x = sprites.centre_x(255, 270, 50) y = 85 for b in self.battlefieldsList: if self.missionSettings.currentBattlefield != None: if b == self.missionSettings.currentBattlefield.storage: button = sprites.Button(17, 0, buttonImage, (x, y, 255, 25), b.name, values.font20, values, colour=values.colours["Lime"], storage=b) self.missionSettings.currentBattlefield = button else: button = sprites.Button(17, 0, buttonImage, (x, y, 255, 25), b.name, values.font20, values, storage=b) else: button = sprites.Button(17, 0, buttonImage, (x, y, 255, 25), b.name, values.font20, values, storage=b) y += 25 self.tabGroup.add(button.sprites) if self.missionSettings.currentBattlefield != None: self.get_battlefield_tab_display(values)
def set_up_armies_tab(self, values): widePanelImage = resources.load_secondary_sprite("wide_panel01.png") buttonImage = pygame.transform.scale(widePanelImage, (255, 25)) x = sprites.centre_x(255, 270, 50) y = 85 #load armies from save data db = sqlite3.connect('Save Data/save data') #connect to database cursor = db.cursor() cursor.execute( '''SELECT name, bossTrait, faction, totalSP, totalPoints, detachments FROM armies''' ) data = cursor.fetchall() self.armies = army.get_army_lists(data) #Set up buttons for list for a in self.armies: button = sprites.Button(18, 0, buttonImage, (x, y, 255, 25), a.name, values.font20, values, storage=a) y += 25 self.tabGroup.add(button.sprites) #Set up player army buttons button = sprites.Button(19, 0, buttonImage, (850, 100, 255, 25), "Player 1", values.font20, values) self.tabGroup.add(button.sprites) button = sprites.Button(20, 0, buttonImage, (850, 400, 255, 25), "Player 2", values.font20, values) self.tabGroup.add(button.sprites) #display current army setup if self.missionSettings.player1Army != None or self.missionSettings.player2Army != None: self.get_armies_tab_display(values)
def __init__(self, stateManager, gameDisplay): super().__init__() self.stateManager = stateManager self.backgroundPosition = [0, 0] self.gameDisplay = gameDisplay self.backgroundImage = pygame.image.load( "images/gameplayBackground.jpg") self.backButton = sprites.Button(10, 10) self.file = scorefile.HighscoreFile() self.labels = [ texts.Text("Main Menu", 20, 35, 45), texts.Text("High Scores", 450, 35, 80) ]
def respond_pung(self, tile): can_pung = self.can_pung(tile) if can_pung: print(tile) print(self._tiles) print(self._cnt) clicked = False btn = sprites.Button((255, 0, 0), 100, 30) btn.rect.x = 300 btn.rect.y = 600 txt = sprites.Text(u'要碰吗', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) def on_click(): if btn.alive(): nonlocal clicked, txt if len(self._chosen_tiles) == 0: btn.kill() txt.kill() clicked = True return if len(self._chosen_tiles) == 2 and int(self._chosen_tiles[0]) == int(self._chosen_tiles[1]) == int(tile): btn.kill() txt.kill() clicked = True return txt.kill() txt = sprites.Text(u'出牌不符合规定', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) self._graphics.add_sprite(txt) self._graphics.add_sprite(btn) self._graphics.add_sprite(txt) btn.on_click = on_click while not clicked: self._graphics.clear() self._graphics.draw_all() pygame.display.update() self._graphics.handle(pygame.event.get()) self._graphics.clock.tick(30) if len(self._chosen_tiles) > 0: self.remove(self._chosen_tiles) self._chosen_tiles.clear() self.refresh() return True return False
def get_main_menu(self, values): self.bgColour = values.colours["Beige"] image = values.font90.render("Wargame", True, values.colours["Black"]) x = sprites.centre_x(image.get_width(), values.settings.width, 0) spr = sprites.GameSprite( image, (x, 50, image.get_width(), image.get_height())) self.group.add(spr) image = values.font20.render(values.version, True, values.colours["Black"]) spr = sprites.GameSprite( image, (1190, 700, image.get_width(), image.get_height())) self.group.add(spr) image = resources.load_secondary_sprite("button01.png") image = pygame.transform.scale(image, (400, 100)) x = sprites.centre_x(400, values.settings.width, 0) button = sprites.Button(0, 0, image, (x, 200, 400, 100), "Same PC Mode", values.font60, values) button = sprites.Button(1, 0, image, (x, 325, 400, 100), "Server Mode", values.font60, values) button = sprites.Button(2, 0, image, (x, 450, 400, 100), "Direct Link Mode", values.font60, values) image = resources.load_secondary_sprite("button01.png") image = pygame.transform.scale(image, (300, 50)) x = sprites.centre_x(300, values.settings.width, 0) button = sprites.Button(5, 0, image, (x, 600, 300, 50), "Quit Game", values.font30, values) for button in values.buttons: self.group.add(button.sprites)
def get_play_menu(self, values): self.bgColour = values.colours["Beige"] image = values.font90.render("Wargame", True, values.colours["Black"]) x = sprites.centre_x(image.get_width(), values.settings.width, 0) spr = sprites.GameSprite( image, (x, 50, image.get_width(), image.get_height())) self.group.add(spr) image = values.font20.render(values.version, True, values.colours["Black"]) spr = sprites.GameSprite( image, (1190, 700, image.get_width(), image.get_height())) self.group.add(spr) image = resources.load_secondary_sprite("button01.png") image = pygame.transform.scale(image, (400, 100)) x = sprites.centre_x(400, values.settings.width, 0) button = sprites.Button(6, 0, image, (x, 200, 400, 100), "Create Game", values.font60, values) button = sprites.Button(7, 0, image, (x, 325, 400, 100), "Army Builder", values.font60, values) button = sprites.Button(8, 0, image, (x, 450, 400, 100), "Unused Button", values.font60, values) image = resources.load_secondary_sprite("button01.png") image = pygame.transform.scale(image, (300, 50)) x = sprites.centre_x(300, values.settings.width, 0) button = sprites.Button(9, 0, image, (x, 600, 300, 50), "Back", values.font30, values) for button in values.buttons: self.group.add(button.sprites)
def respond_chow(self, tile): can_chow, sols = self.can_chow(tile) if can_chow: clicked = False btn = sprites.Button((255, 0, 0), 100, 30) btn.rect.x = 300 btn.rect.y = 600 # txt = u'要吃吗' txt = sprites.Text(u'要吃吗', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) def on_click(): if btn.alive(): nonlocal clicked, txt, sols if len(self._chosen_tiles) == 0: btn.kill() txt.kill() clicked = True return for sol in sols: if sorted(self._chosen_tiles, key=lambda x: int(x)) == sorted(sol, key=lambda x: int(x)): btn.kill() txt.kill() clicked = True return txt.kill() txt = sprites.Text(u'出牌不符合规定', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) self._graphics.add_sprite(txt) # txt = u'出牌不符合规定' self._graphics.add_sprite(btn) self._graphics.add_sprite(txt) btn.on_click = on_click while not clicked: self._graphics.clear() self._graphics.draw_all() # self._graphics.show_text(txt) pygame.display.update() self._graphics.handle(pygame.event.get()) self._graphics.clock.tick(30) if len(self._chosen_tiles) > 0: self.remove(self._chosen_tiles) self._chosen_tiles.clear() self.refresh() return True return False
def title(): loop = True ticks = 0 all_sprites = pygame.sprite.Group() functions.generate_clouds(public.clouds, True) floor_bottom = sprites.Floor((0, 550), 0, public.floors) floor_top = sprites.Floor((0, 0), 1, public.floors) play_btn = sprites.Button((190, 300), 'Play', all_sprites) play_text = public.FONT_BIG.render(play_btn.type, True, (255, 255, 255)) while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: loop = False elif event.type == pygame.MOUSEBUTTONDOWN: if play_btn.rect.collidepoint(event.pos): main() return 1 # Game logic ticks += 1 if ticks == 150: functions.generate_clouds(public.clouds, False) ticks = 0 public.floors.update() public.clouds.update() # Game drawing public.screen.fill(public.BLUE) public.clouds.draw(public.screen) public.floors.draw(public.screen) public.screen.blit(dictionaries.MEDIA['title_texture'], (0, 105)) all_sprites.draw(public.screen) public.screen.blit(play_text, (play_btn.pos.x + 20, play_btn.pos.y + 11)) pygame.display.flip() public.clock.tick(public.FPS)
def instructions(): #The Entities bkgd = pygame.image.load('images\\instructions.png').convert() button = sprites.Button(3) allSprites = pygame.sprite.Group(button) clock = pygame.time.Clock() #Assign keepGoing = True while keepGoing: #Loop clock.tick(30) #TIME for event in pygame.event.get(): #Event Handling if event.type == pygame.QUIT: keepGoing = False exitstatus = 1 if button.get_pressed(): keepGoing = False exitstatus = 0 screen.blit(bkgd, (0, 0)) #Refresh The Screen allSprites.update() allSprites.draw(screen) pygame.display.flip() return exitstatus
def respond_normal(self): clicked = False btn = sprites.Button((255, 0, 0), 100, 30) btn.rect.x = 300 btn.rect.y = 600 txt = sprites.Text(u'请出牌', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) def on_click(): if btn.alive(): nonlocal clicked, txt if len(self._chosen_tiles) != 1: # txt = u'请出一张牌' txt.kill() txt = sprites.Text(u'请出一张牌', [self._graphics._width / 2 - 60, self._graphics._height / 2 - 15]) self._graphics.add_sprite(txt) return btn.kill() clicked = True txt.kill() self._graphics.add_sprite(btn) self._graphics.add_sprite(txt) btn.on_click = on_click while not clicked: self._graphics.clear() self._graphics.draw_all() # self._graphics.show_text(txt) pygame.display.update() self._graphics.handle(pygame.event.get()) self._graphics.clock.tick(30) tile = self._chosen_tiles[0] self.remove(tile) self._chosen_tiles.clear() self.refresh() return tile
def title_screen(): #Funtion for Title Screen bkgd = pygame.image.load('images\\title screen.jpg').convert() #Entities animations = [sprites.Animation(i) for i in range(2)] buttons = [sprites.Button(i) for i in range(3)] allSprites = pygame.sprite.Group(animations[0]) sfx = pygame.mixer.Sound('sounds\\menu.wav') #Song Played in Main menu sfx.play() clock = pygame.time.Clock() #Put the time keepGoing = True pygame.mouse.set_visible(True) while keepGoing: #Loop again clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False exitstatus = 2 if animations[0].get_done(): #Handles text animation allSprites.add(animations[1]) if animations[1].get_done(): allSprites.add(buttons) if buttons[0].get_pressed(): #Check if the player pressed any buttons keepGoing = False exitstatus = 0 elif buttons[1].get_pressed(): keepGoing = False exitstatus = 1 elif buttons[2].get_pressed(): keepGoing = False exitstatus = 2 screen.blit(bkgd, (0, 0)) #Refresh The Screen again allSprites.update() allSprites.draw(screen) pygame.display.flip() return exitstatus
def game_menu(): """The menu for the game""" pygame.mixer.music.stop() pygame.mixer.music.load("assets/audio/bensound-endlessmotion.wav") pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(-1) start_button = sprites.Button( G.SMALL_TEXT.render("Start", True, G.BLACK), ((G.DISPLAY_WIDTH * 0.16), (G.DISPLAY_HEIGHT * 0.65), 100, 50), G.GREEN, new_round.new_round, ) about_button = sprites.Button( G.SMALL_TEXT.render("About", True, G.BLACK), ((G.DISPLAY_WIDTH * 0.33), (G.DISPLAY_HEIGHT * 0.5), 100, 50), G.LIGHT_YELLOW, about_page, ) scores_button = sprites.Button( G.SMALL_TEXT.render("Scores", True, G.BLACK), ((G.DISPLAY_WIDTH * 0.53), (G.DISPLAY_HEIGHT * 0.5), 100, 50), G.GOLD, scores.scores_page, ) quit_button = sprites.Button( G.SMALL_TEXT.render("Quit", True, G.BLACK), ((G.DISPLAY_WIDTH * 0.70), (G.DISPLAY_HEIGHT * 0.65), 100, 50), G.RED, exit_game, ) text_surf_title, text_rect_title = text_objects( "RAstral Rampart", G.BIG_TEXT, G.WHITE, ((G.DISPLAY_WIDTH * 0.5), (G.DISPLAY_HEIGHT * 0.2)), ) text_surf_space, text_rect_space = text_objects( "Press Space To Shoot!", G.MEDIUM_TEXT, G.WHITE, ((G.DISPLAY_WIDTH * 0.5), (G.DISPLAY_HEIGHT * 0.32)), ) all_sprites_list = pygame.sprite.Group() projectile_list = pygame.sprite.Group() buttons_list = pygame.sprite.Group() all_sprites_list.add(start_button, about_button, quit_button, scores_button) buttons_list.add(start_button, about_button, quit_button, scores_button) gun = sprites.Gun((G.DISPLAY_WIDTH * 0.5, G.DISPLAY_HEIGHT * 0.875)) all_sprites_list.add(gun) G.DIFFICULTY = 1 G.SCORE = 0 G.PERMANENT_POWER_UPS["higher_max_health"] = 0 G.PERMANENT_POWER_UPS["higher_max_ammo"] = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: pygame.mixer.Sound.play(G.SHOOT_FX) projectile = sprites.Projectile( gun.rect.center, gun.angle, gun.image.get_height() * 0.5, ) all_sprites_list.add(projectile) projectile_list.add(projectile) all_sprites_list.update() for projectile in projectile_list: hit_button_list = pygame.sprite.spritecollide( projectile, buttons_list, False) for button in hit_button_list: button.function() if projectile.off_screen(): projectile.kill() G.SCREEN.fill(G.WHITE) G.SCREEN.blit(G.BACKGROUND_2.image, G.BACKGROUND_2.rect) G.SCREEN.blit(text_surf_title, text_rect_title) G.SCREEN.blit(text_surf_space, text_rect_space) all_sprites_list.draw(G.SCREEN) pygame.display.update() G.CLOCK.tick(60)
def gameover(): gameover_title = public.fonts['large'].render( 'Game Over', True, public.YELLOW) score_text = public.fonts['plain'].render( 'Score: ' + str(public.score), True, public.YELLOW) playagain_btn = sprites.Button( media.MEDIA['playagain_normal_texture'], media.MEDIA['playagain_pressed_texture'], public.menu_rects['go_playagain'], public.menu_rects['go_playagain_pressed'], public.all_sprites) title_btn = sprites.Button( media.MEDIA['title_normal_texture'], media.MEDIA['title_pressed_texture'], public.menu_rects['go_title'], public.menu_rects['go_title_pressed'], public.all_sprites) exit_btn = sprites.Button( media.MEDIA['exit_normal_texture'], media.MEDIA['exit_pressed_texture'], public.menu_rects['go_exit'], public.menu_rects['go_exit_pressed'], public.all_sprites) # Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: functions.dump_hs() return 1 elif event.type == pygame.MOUSEBUTTONDOWN: if public.menu_rects['go_playagain'].collidepoint( event.pos): functions.generate_floors() game() return 1 elif public.menu_rects['go_title'].collidepoint(event.pos): title() return 1 elif public.menu_rects['go_exit'].collidepoint(event.pos): functions.dump_hs() return 1 # Logic functions.update_clouds() functions.update_floors() public.all_sprites.update() sorted_sprites = sorted( public.all_sprites.sprites(), key=lambda x: x.type) # Draw public.screen.fill(public.skycolor) for sprite in sorted_sprites: sprite.draw() public.screen.blit(gameover_title, (19, 150)) public.screen.blit(public.hs_surf, (185, 305)) public.screen.blit(score_text, ( (public.SWIDTH / 2) - score_text.get_width() // 2, 270)) pygame.display.flip() public.clock.tick(public.FPS)
def main(): """This is the main function.""" pygame.init() # Load background music if not pygame.mixer: print('Warning: Sound disabled') music = load_sound('Africa.wav') music.set_volume(0.05) # Create pygame display window screen = pygame.display.set_mode((480, 640)) pygame.display.set_caption('pbc fly') # Load background image background, _ = load_image('background1.png', scale=(480, 640)) background1_rect = pygame.Rect(0, 0, 480, 640) background2_rect = pygame.Rect(0, 0, 480, 640) # Set the font of the score score_font = pygame.font.SysFont('arial', 25) start_button = sprites.Button('start.png', 'start_down.png', (240, 320)) again_button = sprites.Button('game_again.png', 'game_again_down.png', (240, 390)) leave_button = sprites.Button('leave_game.png', 'leave_game_down.png', (240, 480)) gameover_image, _ = load_image('gameover.png', colorkey=-1, scale=(400, 150)) # Create sprites plane = sprites.Plane() allsprites = pygame.sprite.RenderPlain((plane)) # Create 10 missiles and store them in the class variable pool sprites.Missile.pool = pygame.sprite.Group( [sprites.Missile() for _ in range(10)]) sprites.Missile.allsprites = allsprites # Create enemies sprites.EnemyMissile.pool = pygame.sprite.Group( [sprites.EnemyMissile() for _ in range(10)]) sprites.EnemyMissile.allsprites = allsprites enemies = pygame.sprite.Group() sprites.ExplosionEnemy.allsprites = allsprites sprites.ExplosionBoss.allsprites = allsprites sprites.Enemy.all_images = [ load_image('enemy{}.png'.format(i), colorkey=-1, scale=(32, 34))[0] for i in range(1, 6) ] # Add boss group bosses = pygame.sprite.Group() sprites.Boss.all_images = [ load_image('boss{}.png'.format(i), colorkey=-1, scale=(96, 102))[0] for i in range(1, 6) ] # Create falling objects sprites.FallingItem.allsprites = allsprites hp_pack = sprites.HpPack() powerup = sprites.PowerUp() # Create HP bar and let it track plane's hp attr hp_bar = sprites.HpBar(plane) # Create the clock object clock = pygame.time.Clock() music.play(loops=-1) # Looping play background music # Enter starting view while True: clock.tick(60) # Max FPS = 60 # Event handling (somehow this needs to be here to make get the mouse position work) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.quit() return screen.blit(background, (0, background1_rect.y)) screen.blit(background, (0, background2_rect.y)) start_button.render(screen) if start_button.pressed: start_button.pressed = False break pygame.display.update() keep_playing = True game = 0 while keep_playing: game += 1 # Re-position the plane plane.place_at_bottom_center() # Clearing the view by emptying all the groups allsprites.empty() allsprites.add(plane) bosses.empty() enemies.empty() # Also empty those 'active' groups to avoid invisible missiles collide # with our plane or enemies sprites.Missile.pool.add(sprites.Missile.active) sprites.Missile.active.empty() sprites.EnemyMissile.pool.add(sprites.EnemyMissile.active) sprites.EnemyMissile.active.empty() # Reinitialize the HP and battle constant values of all class and objects plane.hp = INITIAL_HP sprites.Enemy.initial_hp = sprites.HP_ENEMY sprites.Boss.initial_hp = sprites.HP_BOSS fire_period = 20 boss_fire_period = 70 mark = False # to identify whether enemy adds hp after 1 boss is defeated (enemy level up) initial_boss_appear = True # to identify the first appearance of boss boss_number_appear = 1 # the number of boss that has appeared including this one # Reinitialize loop counter and scores score = 0 frame = 0 frame_record = 0 # Enter the main game loop while True: frame += 1 # Loop counter score += 1 / 30 clock.tick(60) # Max FPS = 60 # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.quit() return # Check if arrow key is pressed, and tell the plane to move plane.key_pressed() # The plane fires every constant period (frames) if not frame % fire_period: plane.fire() # Randomly put a powerup item on the top of the screen if it is not # already on the screen if powerup not in allsprites and random.random() <= POWER_UP_PROB: powerup.appear() # Randomly put a HP pack item on the top of the screen if it is not # already on the screen if hp_pack not in allsprites and random.random() <= HP_PACK_PROB: hp_pack.appear() # Enemy's appearnce if not frame % 100: if len(bosses) == 0: new_enemy = sprites.Enemy() new_enemy.number_appear = boss_number_appear % 5 new_enemy.appearnce() # determine the image it appears if mark: # enemy's hp increases since player has entered next level new_enemy.revival() mark = False new_enemy.add(allsprites, enemies) # Enemy fires missile for a_enemy in enemies: a_enemy.fire() # Increase missiles fired at once if collided with powerup item if powerup in allsprites and pygame.sprite.collide_rect( plane, powerup): plane.powerup() powerup.kill() # Recover HP if collided with HP pack item if hp_pack in allsprites and pygame.sprite.collide_rect( plane, hp_pack): plane.hp += HP_INCREMENT hp_pack.kill() # Another boss appears 25 seconds after the previous one is defeated if frame == frame_record + 1500: new_boss = sprites.Boss() new_boss.number_appear = boss_number_appear % 5 new_boss.appearnce() # determine the image it appears if not initial_boss_appear: # Boss has already appeared more than 1 time new_boss.revival() # boss' hp increases new_boss.add(allsprites, bosses) # Boss fires missile if not frame % boss_fire_period: for a_boss in bosses: a_boss.fire() # Check if enemy collide with our plane for a_enemy in enemies: if pygame.sprite.collide_circle(plane, a_enemy): plane.hp -= COLLIDE_HP_DROP plane.remove_powerup() a_enemy.kill() # Check if enemy's missile hit our plane for missile in sprites.EnemyMissile.active: if pygame.sprite.collide_circle(plane, missile): missile.recycle() plane.hp -= HIT_HP_DROP plane.remove_powerup() # Check if our plane's missile hit enemy for a_enemy in enemies: for missile in sprites.Missile.active: if pygame.sprite.collide_circle(a_enemy, missile): missile.recycle() a_enemy.hp -= HIT_HP_DROP if a_enemy.hp <= 0: score += 40 # Check if boss collide with our plane for a_boss in bosses: if pygame.sprite.collide_circle(plane, a_boss): plane.hp -= COLLIDE_HP_DROP plane.remove_powerup() # Check if our plane's missile hit boss for a_boss in bosses: for missile in sprites.Missile.active: if pygame.sprite.collide_circle(a_boss, missile): missile.recycle() a_boss.hp -= HIT_HP_DROP if a_boss.hp <= 0: score += 200 a_boss.die() mark = True # player entering next level initial_boss_appear = False # launch revival method every time a new boss appears boss_number_appear += 1 frame_record = frame # to record the number of frames when a boss is defeated # End the game if the HP goes to 0 if plane.hp <= 0: break # Update all sprite object's positions allsprites.update() # Update the score score_text = score_font.render('Score : %6d' % score, True, (225, 225, 225)) # Scroll the background background1_rect.y += SCROLLING_SPEED if background2_rect.y + background1_rect.y > 640: background1_rect.y = 0 background2_rect.bottom = background1_rect.y # Draw Everything screen.blit(background, (0, background1_rect.y)) screen.blit(background, (0, background2_rect.y)) hp_bar.draw() screen.blit(score_text, (10, 5)) allsprites.draw(screen) pygame.display.flip() # The end of game view, asking the player to choose if they want to continue while True: clock.tick(60) # Max FPS = 60 # Event handling (somehow this needs to be here to make get the mouse position work) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.quit() return screen.blit(background, (0, background1_rect.y)) screen.blit(background, (0, background2_rect.y)) screen.blit(gameover_image, (40, 150)) screen.blit(score_text, (10, 5)) again_button.render(screen) leave_button.render(screen) if again_button.pressed: again_button.pressed = False break if leave_button.pressed: keep_playing = False leave_button.pressed = False break pygame.display.update() pygame.quit()