def place_enemy(self, x, y): for enemy in self.game.layers["ENEMIES"]: if self.distance_squared( (x, y), (enemy.pos.x, enemy.pos.y)) < self.enemy_min_distance: return enemy_type = random.randint(0, 3) sprites.Enemy(self.game, x, y, enemy_type)
def startup(self): # TODO: overworld grid should consist of multiple maps # TODO: the grid construction should be done from json data maps = [ tilemaps.Map(self.game, self.game.map_files[2]), tilemaps.Map(self.game, self.game.map_files[3]), tilemaps.Map(self.game, self.game.map_files[4]) ] self.game.overworld_grid = tilemaps.Grid(self.game, name='overworld', width=2, height=2) self.game.overworld_grid.insert_grid(maps[0], 0, 0) self.game.overworld_grid.insert_grid(maps[1], 1, 0) self.game.overworld_grid.insert_grid(maps[2], 0, 1) self.game.map = maps[0] self.game.map.create_map() # put the player somewhere on the map self.game.player = spr.Player(self.game, { 'x': 182, 'y': 136, 'width': 16, 'height': 16 }) self.game.inventory = inter.Inventory(self.game) self.game.inventory.active = True # TODO: Testing self.game.inventory.add_item(items.Sword, 0, 0) self.game.inventory.add_item(items.Test, 0, 1) self.game.camera = utils.Camera(self.game, self.game.map.size.x, self.game.map.size.y, 'FOLLOW') self.game.camera.update(self.game.player) t = inter.Textbox(self.game, self.game.world_screen_rect.center, self.game.texts['demo_dialog'], lambda: self.game.change_state('InGame')) #t.activate() spr.Enemy(self.game, {'x': 300, 'y': 100, 'width': 16, 'height': 16}) self.game.select_menu = inter.Base_menu(self.game, rect=None, anchor_x='centerx') e1 = inter.Menu_entry('Resume Game', self.game.select_menu.deactivate) e2 = inter.Menu_entry('Go To Title Screen', lambda: self.game.change_state('TitleScreen')) e3 = inter.Menu_entry('Exit Program', self.game.exit_game) self.game.select_menu.add_entries(e1, e2, e3) self.done = True
def simulate(self, time_delta): self.run_time += time_delta while self.next_spawn <= self.run_time: sprites.Enemy(self, self.next_x) self.next_spawn, self.next_x = next(self.spawn) super().simulate(time_delta) player = self.groups[sprites.Player.group] bullets = self.groups[sprites.Bullet.group] enemies = self.groups[sprites.Enemy.group] groupcollide(player, enemies, True, True) groupcollide(enemies, bullets, True, True)
def place_enemies(level): x = 0 y = 0 for row in level: for column in row: if column == "E": s.Enemy(x, y) if column == "B": s.Boss(x, y) x += i.tileWidth x = 0 y += i.tileHeight
def render(self, DISPLAYSURF): # Drawing/updating code DISPLAYSURF.fill(WHITE) self.cat_list.draw(DISPLAYSURF) #draws cat self.enemy_list.draw(DISPLAYSURF) # draws enemy self.enemy_list.update() # makes enemies move self.bullet_list.draw(DISPLAYSURF) # draws the bullets self.bullet_list.update() # ensures the bullets move self.ebullet_list.draw(DISPLAYSURF) self.ebullet_list.update() DISPLAYSURF.blit(self.font.render(self.text, True, BLACK), (32, 48)) DISPLAYSURF.blit( self.font.render(str(self.score).rjust(4), True, BLACK), (DISPLAYSURF.get_width() - 50, 48)) # Enemy Creation Code. Everytime it updates it creates an enemy and ebullet enemy = sprites.Enemy() enemybullet = sprites.EnemyBullet() if random.randint(1, 10) <= self.level: enemy.spawn(DISPLAYSURF) self.enemy_list.add(enemy) enemybullet.spawn(enemy.getmidx(), enemy.getmidy()) self.ebullet_list.add(enemybullet) #enemy reshooting code for enemy in self.enemy_list: if enemy.shoot(DISPLAYSURF) == True: enemybullet.spawn(enemy.getmidx(), enemy.getmidy()) self.ebullet_list.add(enemybullet) # Bullet creation code. Everytime it updates it'll create a bullet bullet = sprites.Bullet() bullet.spawn(self.mousex, self.mousey) self.bullet_list.add(bullet) enemy.remove(self.enemy_list, self.cat_list, DISPLAYSURF) enemybullet.remove(self.ebullet_list, self.cat_list, DISPLAYSURF) self.score = bullet.remove(self.bullet_list, self.enemy_list, self.score) pass
def makeEnemy(self, pos1, pos2, speed, scale=1, offset=vector.Vector(0, 0)): sprite = sprites.Enemy(self.game, pos1 * scale + offset, pos2 * scale + offset, speed * scale, scale) self.game.all.add(sprite) self.game.enemies.add(sprite) return sprite
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()
def gameplay(): # creating screen and clock objects screen = pg.display.set_mode((WIDTH, HEIGHT)) clock = pg.time.Clock() # sprite groups orated here all_sprites = pg.sprite.Group() enemy_sprites = pg.sprite.Group() blast_sprites = pg.sprite.Group() # player sprite created here player = sprites.Player() all_sprites.add(player) # enemy sprite created here for x in range(10): enemy = sprites.Enemy() enemy_sprites.add(enemy) all_sprites.add(enemy) global game_score game_score = 0 background_image1 = pg.image.load('field background.jpg') click_sound = pg.mixer.Sound("8-bit-laser.aiff") playing = True while playing: #--- Main event loop for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): #if user clicked close started = False #Flag that user is done and exit loop if event.type == pg.KEYDOWN and event.key == pg.K_SPACE: marshmellow = sprites.Bullet() marshmellow.rect.bottom = player.rect.top marshmellow.rect.centerx = player.rect.centerx blast_sprites.add(marshmellow) all_sprites.add(marshmellow) click_sound.play() screen.fill(BLACK) #set screen background color screen.blit(background_image1, [0, 0]) #text = font.render("Score: " + str(score), True, RED) #update all_sprites.update() hits = pg.sprite.spritecollide(player, enemy_sprites, False) if hits: playing = False hits2 = pg.sprite.groupcollide(blast_sprites, enemy_sprites, True, True) for hit in hits2: enemy = sprites.Enemy() enemy_sprites.add(enemy) all_sprites.add(enemy) game_score += 10 # --- DRAWING CODE--- ############################################################################################### scoredisplay(game_score) all_sprites.draw(screen) #screen.blit(text, [10, 10]) ##################################################################################################################### #waits to display the screen until the program has finished drawing, # then "flips" the graphics drawn to the screen pg.display.flip() # Limit framerate to (FPS) frames per second clock.tick(FPS)
for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif gameover == True: pass elif event.type == MOUSEMOTION: mousex, mousey = event.pos cat.update(mousex, mousey) elif event.type == MOUSEBUTTONUP: pass elif event.type == MOUSEBUTTONDOWN: pass # Enemy Creation Code. Everytime it updates it creates an enemy enemy = sprites.Enemy() enemy.spawn() enemy_list.add(enemy) # Bullet creation code. Everytime it updates it'll create a bullet bullet = sprites.Bullet() bullet.spawn(mousex, mousey) bullet_list.add(bullet) # Removes Bullet sprite when it goes off the screen for bullet in bullet_list: hit_list = pygame.sprite.spritecollide(bullet, enemy_list, True) for enemy in hit_list: bullet_list.remove(bullet) enemy_list.remove(enemy)
def level1(): #Our level 1 '''main game''' player = sprites.Player() #Entities / Players tank = sprites.Tank() playerGrp = pygame.sprite.Group(tank, player) current_player = player clean_bkgd = pygame.image.load('images\\bkgd.png').convert() #Background bkgd = sprites.Background(player) wall = sprites.Platform(((1438, 380), (1, 100))) #Map Objects platforms = pygame.sprite.Group([ sprites.Platform(dimension) for dimension in (((0, 366), (1400, 1)), ((1438, 450), (2507, 1)), ((1845, 342), (110, 1)), ((2032, 260), (348, 1)), ((2380, 342), (130, 1)), ((2510, 260), (290, 1)), ((2915, 260), (345, 1)), ((3260, 342), (150, 1))) ]) pBulletsGrp = pygame.sprite.Group() #Projectiles (bullets and grenades) eBulletsGrp = pygame.sprite.Group() grenadeGrp = pygame.sprite.Group() scoreboard = sprites.ScoreBoard(player, tank) #Scoreboard enemiesGrp = pygame.sprite.Group([ sprites.Enemy(midbottom) for midbottom in ( #Enemies (500, 366), (800, 366), (1000, 366), (1100, 366), (1200, 366), (1300, 366), (1700, 450), (1800, 450), (1900, 450), (2300, 450), (2400, 450), (2500, 450), (2600, 450), (2700, 450), (2800, 450), (2900, 450), (3000, 450), (3100, 450), (3200, 450), (3400, 450), (3500, 450), (3600, 450), (3800, 450), (1880, 342), (2040, 260), (2200, 260), (2400, 342), (2550, 260), (2700, 260), (2950, 260), (3100, 260), (3280, 342)) ]) pygame.mixer.music.load('sounds\\music.mp3') #Music pygame.mixer.music.play(-1) allSprites = pygame.sprite.OrderedUpdates(enemiesGrp, playerGrp, eBulletsGrp, pBulletsGrp, grenadeGrp) clock = pygame.time.Clock() keepGoing = True pygame.mouse.set_visible(False) while keepGoing: #Another While Loop clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False exitstatus = 2 if not current_player.get_dying(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_e: if pygame.sprite.collide_rect( player, #Enter the TANK tank ) and current_player == player and not tank.get_dying( ): current_player = tank player.kill() elif current_player == tank: #Exit the TANK player.respawn(tank) playerGrp.add(player) allSprites.add(playerGrp) current_player = player tank.die() elif event.key == pygame.K_l: if current_player == tank: #Fire Cannon from the TANK if tank.shoot_cannon(): grenadeGrp.add(sprites.TankShell(tank)) allSprites.add(grenadeGrp) elif player.get_grenades(): #Player throw grenade player.throw_grenade() grenadeGrp.add(sprites.Grenade(player)) allSprites.add(grenadeGrp) if not current_player.get_dying(): keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_d] and keys_pressed[ pygame.K_a]: #In game movement, left and right pass elif keys_pressed[pygame.K_a]: current_player.move(-1) elif keys_pressed[pygame.K_d]: current_player.move(1) if keys_pressed[pygame.K_j]: #In game action, Jump current_player.jump() if current_player == tank: #Tank Controls if keys_pressed[pygame.K_k]: #Tank shooting Machine Gun tank.shoot_mg() pBulletsGrp.add(sprites.TankBullet(bkgd, tank)) allSprites.add(pBulletsGrp) if keys_pressed[pygame.K_w] and keys_pressed[ pygame.K_s]: #The machine gun rotation pass elif keys_pressed[pygame.K_w]: tank.rotate(5) elif keys_pressed[pygame.K_s]: tank.rotate(-5) else: #Player Control if keys_pressed[pygame.K_k]: if player.get_weapon(): #Player shoot Machine Gun pBulletsGrp.add( sprites.MGBullet(bkgd, player, player.shoot())) allSprites.add(pBulletsGrp) for item in (player, tank): #Collision Detection if pygame.sprite.collide_rect(item, wall): #Collision with wall item.collide_wall(wall) collision = pygame.sprite.spritecollide( item, platforms, False) #Collision with platform if collision: item.land(max(platform.rect.top for platform in collision)) #Find lowest platform to step on else: item.fall() for bullet in pygame.sprite.spritecollide( current_player, eBulletsGrp, False): #Bullet collision with player if not current_player.get_dying(): bullet.kill() current_player.hurt(50) for enemy in pygame.sprite.spritecollide( tank, enemiesGrp, False): #The tank collision with enemies enemy.die() for bullet, enemy in pygame.sprite.groupcollide( pBulletsGrp, enemiesGrp, False, False).items(): #Bullet colision with enemies if enemy and not enemy[0].get_dying(): bullet.kill() enemy[0].die() for grenade, enemy in pygame.sprite.groupcollide( grenadeGrp, enemiesGrp, False, True).items(): #Grenade collision with enemies if enemy: grenade.explode() for i in enemy: i.die() for grenade, platform in pygame.sprite.groupcollide( grenadeGrp, platforms, False, False).items(): #Grenade collision with the platform if platform: grenade.explode() for enemy in enemiesGrp: #Enemy shooting if enemy.get_shooting(): eBulletsGrp.add(sprites.EnemyBullet(enemy, current_player)) allSprites.add(eBulletsGrp) if tank.get_dying( ): #If the tank is destroyed, respawn the player to the current status player.respawn(tank) playerGrp.add(player) allSprites.add(playerGrp) current_player = player if player.get_dying() == 2: #Exit game loop when player died keepGoing = False exitstatus = 1 if current_player.rect.right >= bkgd.image.get_width( ): #Checking if the player has defeated the boss keepGoing = False exitstatus = 0 # REFRESH SCREEN # We draws all of the sprites in the background bkgd.image.blit(clean_bkgd, (0, 0)) allSprites.update(current_player) allSprites.draw(bkgd.image) # Update the background based on the position of the player bkgd.update(current_player) screen.blit(bkgd.image, bkgd.rect) # Update the scoreboard scoreboard.update(current_player) screen.blit(scoreboard.image, scoreboard.rect) pygame.display.flip() pygame.mixer.music.stop() if tank.get_dying(): return exitstatus, player return exitstatus, player, tank
def main(): screen = pg.display.set_mode(screen_size) clock = pg.time.Clock() font = pg.font.SysFont("comicsansms", 32) frames = 0 points = 0 text = font.render(f"Enemigos asesinados: {points}", True, (0, 0, 0)) sky = pg.Surface(screen_size) sky = sky.convert() sky.fill((80, 140, 210)) screen.blit(sky, (0, 0)) ground_group = createGround("ice.png") player = sprites.Player(screen, ground_group) player_group = pg.sprite.Group(player) sword = sprites.Sword(player) sword_group = pg.sprite.Group(sword) enemies_group = pg.sprite.Group() scene_start(screen, clock) while True: clock.tick(framerate) frames += 1 # Escuchar eventos for event in pg.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN: if event.key == K_w: player.jump() if event.key == K_SPACE: sword.toDraw(frames) keys = pg.key.get_pressed() if keys[pg.K_d]: player.move_right() if keys[pg.K_a]: player.move_left() # Actualizar estados de juego player_group.update() sword_group.update(frames) enemies_group.update() if sword.drawn: if pg.sprite.spritecollide(sword, enemies_group, True): points += 1 text = font.render(f"Enemigos asesinados: {points}", True, (0, 0, 0)) if pg.sprite.groupcollide(enemies_group, player_group, False, False): scene_end(screen, clock, points) if frames % 60 == 0: enemies_group.add(sprites.Enemy(player)) # Pintar screen.blit(sky, (0, 0)) ground_group.draw(screen) player_group.draw(screen) if sword.drawn: sword_group.draw(screen) enemies_group.draw(screen) screen.blit(text, (10, 10)) pg.display.flip()