def play(self): while self.isRunning: # collisions if collide_any(self.player.body, self.enemies): self.isRunning = False for enemy in group_collide(self.enemies, self.bullets, True, True): Splat(enemy.box.muz[:2], (self.all_sprites, self.splats)) for splat in get_collided(self.player.body, self.splats): self.splat_count[0] += 1 Splat_Collect(splat.box.muz[:2], (-.85, -.8), (self.all_sprites, self.splats_collect)) splat.kill() for tornado in get_collided(self.player.body, self.tornados): if tornado.is_rainbow: self.player.embiggen() else: self.isRunning = False # input for event in pg.event.get(): if (event.type == KEYDOWN and event.key == K_ESCAPE) or event.type == QUIT: self.isRunning = False if event.type == self.ADDENEMY: Enemy((self.all_sprites, self.enemies)) if event.type == self.NEWTORNADO: Tornado((self.all_sprites, self.tornados)) if event.type == KEYDOWN and event.key == K_SPACE: PlayerBullet(*self.player.body.box.mux[:2], (self.bullets)) if (event.type == MOUSEBUTTONDOWN and self.loot_button.rollover() or (event.type == KEYDOWN and event.key == K_TAB)): self.loot.open() # draw frame for splat in self.splats: splat.draw() for splat in self.splats_collect: splat.draw() self.player.draw() self.loot_button.draw() for bullet in self.bullets: bullet.draw() for enemy in self.enemies: enemy.draw() for tornado in self.tornados: tornado.draw() pg.display.flip() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.background.draw() self.clock.tick(60)
def spawn_enemies(self): self.enemies = [ Enemy(100, 50, 10) for _ in range(self.get_enemy_count()) ] index_of_enemy = 0 for index_row, row in enumerate(self.map): for index_cell, cell in enumerate(row): if cell == 'E': enemy = self.enemies[index_of_enemy] enemy.x_coord = index_cell enemy.y_coord = index_row self.map[index_row][index_cell] = enemy index_of_enemy += 1
def allocate_enemy(self, x, y, amountOfMutations): if len(self.enemiesNotInUse) > 0: print() newEnemy = self.game.enemiesNotInUse.pop() newEnemy.init(x, y) self.game.enemiesInUse.append(newEnemy) elif len(self.enemiesInUse) < self.POOL_SIZE: newEnemy = Enemy(self.game) newEnemy.init(x, y) self.game.enemiesInUse.append(newEnemy) else: return None
def newEnemy(self,health,speed): """generates a new enemy on a random platform in the level""" platform = self.level[floor(len(self.level)*random())] #create new a new Enemy until it is sufficiently far from the player while True: enemy = Enemy(self.SCALE*(platform[2] + platform[0]*random())+self.current_level.world_shift_x,self.SCALE*(platform[3]-10)+self.current_level.world_shift_y,self.current_level,self.player,health,(self.SCREEN_HEIGHT,self.SCREEN_WIDTH)) enemy.speed = speed p_pos = np.array((self.player.rect.x,self.player.rect.y)) e_pos = np.array((enemy.rect.x,enemy.rect.y)) if np.linalg.norm(p_pos-e_pos) > 100 and abs(p_pos[0]-e_pos[0]) > 50: break return enemy
def makeEnemies(level): for i in range(NUM_ENEMIES): image_name = "images/enemy%d.png" % (i % 4) mod = (i % 4) row = mod if i < 4: col = 1 elif i < 8: col = 2 elif i < 12: col = 3 elif i < 16: col = 4 elif i < 20: col = 5 elif i < 24: col = 6 enemy = Enemy(image_name, row, col, level) enemies.add(enemy)
def initialize(self): # initialize all variables and do all the setup for a new game EnemyNum = 0 self.all_sprites = pg.sprite.Group() self.walls = pg.sprite.Group() self.gates = pg.sprite.Group() self.action_area = pg.sprite.Group() self.destroyable_objects = pg.sprite.Group() self.bullets = pg.sprite.Group() self.enemy_bullets = pg.sprite.Group() self.enemies = pg.sprite.Group() self.background = [] # for y in range(0, 2500, BACKGROUND_IMG_SIZE[1]): # for x in range(0, 5000, BACKGROUND_IMG_SIZE[0]): # self.background.append(Background(self, self.img_folder + "/" + BACKGROUND_IMG, [x, y])) # self.background = Background(self, self.img_folder + "/" + BACKGROUND_IMG, [0,0]) self.player_dead = False self.camera = Camera(self.map.width, self.map.height) for row, tiles in enumerate(self.map.data): for col, tile in enumerate(tiles): if tile == '1': Wall(self, col, row) if tile == 'S': self.player = Player(self, col, row, self.camera) if tile == 'W': self.woodbox = WoodBox(self, col, row) if tile == 'T': self.tree = Tree(self, col, row) if tile == 'G': self.gate = Gate(self, col, row) if tile == 'A': self.a_area = ActionArea(self, col, row) if tile == 'C': self.control_box = ControlBox(self, col, row) if tile == 'E': EnemyNum += 1 self.enemy = Enemy(self, col, row, EnemyNum) sound_background = pg.mixer.music.load(self.sound_folder + "/" + SOUND_BACKGROUND) pg.mixer.music.set_volume(0.5) pg.mixer.music.play(-1)
def add_new_enemy(self, sid, data): class_list = [ "Baby", "Girl", "Woman", "Pregnant", "Boy", "Man", "Granda" ] if self.boss_fight: enemy_class = "Boss" logger.debug(f"SPAWNING BOSS") else: enemy_class = random.choice(class_list) if enemy_class == "Enemy": newEnemy = Enemy(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Baby": newEnemy = Baby(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Girl": newEnemy = Girl(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Woman": newEnemy = Woman(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Pregnant": newEnemy = Pregnant(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Boy": newEnemy = Boy(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Man": newEnemy = Man(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Granda": newEnemy = Granda(sid, 100, 50, velocity=(0, 0)) elif enemy_class == "Boss": newEnemy = Boss(sid, 100, 50, velocity=(0, 0)) else: logger.error(f"add_new_enemy: could not find class {enemy_class}") return False # self.enemies[sid] = data while self.flushingEnemies: pass self.new_enemies.append((sid, newEnemy))
def start(self, screen, map_path=None, difficulty_path=None): # 读取游戏难度对应的参数 with open(difficulty_path, 'r') as f: difficulty_dict = json.load(f) self.money = difficulty_dict.get('money') self.health = difficulty_dict.get('health') self.max_health = difficulty_dict.get('health') difficulty_dict = difficulty_dict.get('enemy') # 每60s生成一波敌人 GenEnemiesEvent = pygame.constants.USEREVENT + 0 pygame.time.set_timer(GenEnemiesEvent, 60000) # 生成敌人的flag和当前已生成敌人的总次数 genEnemiesFlag = False genEnemiesNum = 0 # 每0.5秒出一个敌人 GenEnemyEvent = pygame.constants.USEREVENT + 1 pygame.time.set_timer(GenEnemyEvent, 500) genEnemyFlag = False # 防止变量未定义 enemyRange = None numEnemy = None # 是否手动操作箭塔射击 Manualshot = False has_control = False while True: if self.health <= 0: return for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONUP: # 左键选物品 if event.button == 1: # 鼠标点击在地图上 if self.map_rect.collidepoint(event.pos): if self.mouseCarried: if self.mouseCarried[0] == 'turret': self.buildTurret(event.pos) elif self.mouseCarried[0] == 'XXX': self.sellTurret(event.pos) # 鼠标点击在工具栏 elif self.toolbar_rect.collidepoint(event.pos): for button in self.buttons: if button.rect.collidepoint(event.pos): if button.text == 'T1': button.onClick() elif button.text == 'T2': button.onClick() elif button.text == 'T3': button.onClick() elif button.text == 'XXX': button.onClick() elif button.text == 'Pause': button.onClick(screen) elif button.text == 'Quit': button.onClick() # 显然只能有一个按钮被点击 break # 右键释放物品 if event.button == 3: self.mouseCarried = [] # 按中间键手动控制炮塔射箭方向一次,否则自由射箭 if event.button == 2: Manualshot = True if event.type == GenEnemiesEvent: genEnemiesFlag = True if event.type == GenEnemyEvent: genEnemyFlag = True # 生成敌人 # 生成的敌人随当前已生成敌人的总次数的增加而变强变多 if genEnemiesFlag: genEnemiesFlag = False genEnemiesNum += 1 idx = 0 for key, value in difficulty_dict.items(): idx += 1 if idx == len(difficulty_dict.keys()): enemyRange = value['enemyRange'] numEnemy = value['numEnemy'] break if genEnemiesNum <= int(key): enemyRange = value['enemyRange'] numEnemy = value['numEnemy'] break if genEnemyFlag and numEnemy: genEnemyFlag = False numEnemy -= 1 enemy = Enemy.Enemy(random.choice(range(enemyRange))) self.EnemiesGroup.add(enemy) # 射箭 for turret in self.builtTurretGroup: if not Manualshot: position = turret.position[0] + self.elementSize // 2, turret.position[1] arrow = turret.shot(position) else: position = turret.position[0] + self.elementSize // 2, turret.position[1] mouse_pos = pygame.mouse.get_pos() angle = math.atan((mouse_pos[1]-position[1]) / (mouse_pos[0]-position[0] + 1e-6)) arrow = turret.shot(position, angle) has_control = True if arrow: self.arrowsGroup.add(arrow) else: has_control = False if has_control: has_control = False Manualshot = False # 移动箭和碰撞检测 for arrow in self.arrowsGroup: arrow.move() points = [(arrow.rect.left, arrow.rect.top), (arrow.rect.left, arrow.rect.bottom), (arrow.rect.right, arrow.rect.top), (arrow.rect.right, arrow.rect.bottom)] if (not self.map_rect.collidepoint(points[0])) and (not self.map_rect.collidepoint(points[1])) and \ (not self.map_rect.collidepoint(points[2])) and (not self.map_rect.collidepoint(points[3])): self.arrowsGroup.remove(arrow) del arrow continue for enemy in self.EnemiesGroup: if pygame.sprite.collide_rect(arrow, enemy): enemy.life_value -= arrow.attack_power self.arrowsGroup.remove(arrow) del arrow break self.draw(screen, map_path)
def setup(self, level, score): self.level = level self.score = score self.player_list = arcade.SpriteList() self.bullet_list = arcade.SpriteList() self.donut_list = arcade.SpriteList() self.enemy_bullet_list = arcade.SpriteList() self.wall_list = arcade.SpriteList() self.enemy_list = arcade.SpriteList() self.player_sprite = Player("assets/player.png", SPRITE_SCALING * 2) self.player_sprite.center_x = 50 self.player_sprite.center_y = 50 self.player_list.append(self.player_sprite) for _ in range((self.level + 1) * 2): donut = arcade.Sprite("assets/donut.png", 1) donut_placed = False while not donut_placed: donut.center_x = random.randrange(SCREEN_WIDTH) donut.center_y = random.randrange(SCREEN_HEIGHT) donut_hit_list = arcade.check_for_collision_with_list( donut, self.donut_list ) wall_hit_list = arcade.check_for_collision_with_list( donut, self.wall_list ) donut_placed = len(donut_hit_list) == 0 and len(wall_hit_list) == 0 self.donut_list.append(donut) for _ in range(25): wall = arcade.Sprite("assets/wall.png", 1) wall_placed = False # Keep trying until success while not wall_placed: wall.center_x = random.randrange(SCREEN_WIDTH) wall.center_y = random.randrange(SCREEN_HEIGHT) wall_hit_list = arcade.check_for_collision_with_list( wall, self.wall_list ) if len(wall_hit_list) == 0: wall_placed = True self.wall_list.append(wall) self.enemy_engines = [] for _ in range(self.level + 1): enemy = Enemy("assets/enemy.png", 1) enemy_placed = False # Keep trying until success while not enemy_placed: enemy.center_x = random.randrange(SCREEN_WIDTH) enemy.center_y = random.randrange(SCREEN_HEIGHT) enemy_hit_list = arcade.check_for_collision_with_list( enemy, self.enemy_list ) if len(enemy_hit_list) == 0: enemy_placed = True engine = arcade.PhysicsEngineSimple(enemy, self.wall_list) self.enemy_engines.append(engine) self.enemy_list.append(enemy) self.physics_engine = arcade.PhysicsEngineSimple( self.player_sprite, self.wall_list )
def game_window(window): clock = pygame.time.Clock() assets = load_assets() # Key do mapa para a direita aumenta n0, para cima aumenta n1 # Para cima, os mapas têm final 2 e, para baixo, final 0 map_k = {"map_n0": 1, "map_n1": 1} # Pontuação e HP iniciais score = 0 health = 5 # Estados do gamerun RUNNING = 0 PAUSED = 1 # Fonte para os scores e o HP myfont = pygame.font.SysFont("monospace", 16) # Grupos das sprites e para as mascaras dos mapas all_sprites = pygame.sprite.Group() all_arrows = pygame.sprite.Group() all_enemies = pygame.sprite.Group() chests = pygame.sprite.Group() map_masks = pygame.sprite.Group() groups = {} groups['all_sprites'] = all_sprites groups['all_arrows'] = all_arrows groups['all_enemies'] = all_enemies groups['chests'] = chests # Criando sprite do jogador e adicionando-a ao grupo player = Char(groups, assets) all_sprites.add(player) # Definição dos mapas e seus parâmetros (quais possuem mapas e variável para spawn de mobs (True para permitir spawn e False para bloquear o spawn)) MASK = MapMask(map_def(player, map_k, assets)[1]) map_masks.add(MASK) MAP = assets['maps']['map1.1'] spawn = False map_w_chest = [ assets['maps']['map1.1'], assets['maps']['map2.2'], assets['maps']['map3.0'], assets['maps']['map5.0'], assets['maps']['map5.2'] ] wave = 6 # Variável para guardar o número da wave de mobs do último mapa # Loop principal gamerun = RUNNING pygame.mixer.music.load(path.join(SOUND_DIR, 'background.mp3')) pygame.mixer.music.play(loops=-1) while True: clock.tick(FPS) # Ações do personagem e da interface do jogo: andar, atirar e sair do jogo for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.delta["left"] = 1 if event.key == pygame.K_d: player.delta["right"] = 1 if event.key == pygame.K_w: player.delta["up"] = 1 if event.key == pygame.K_s: player.delta["down"] = 1 if event.key == pygame.K_SPACE: player.shoot() if event.type == pygame.KEYUP: if event.key == pygame.K_a: player.delta["left"] = 0 if event.key == pygame.K_d: player.delta["right"] = 0 if event.key == pygame.K_w: player.delta["up"] = 0 if event.key == pygame.K_s: player.delta["down"] = 0 # Atualiza todas as sprites all_sprites.update() all_enemies.update(player) # Redefinição de mapa: # O programa verifica se o mapa mudou ou se continua o mesmo. Para isso, ele refaz a máscara do mapa e redefine a variável do mapa caso necessário MASK.kill() new_map = map_def(player, map_k, assets)[0] if new_map != MAP: spawn = True MAP = new_map if MAP in map_w_chest: # Caso o mapa novo seja um mapa que possua baú, o baú é desenhado if len(chests) > 1: for chest in chests: chest.kill() chest = chest_spawn(assets, MAP, chests, player) chests.add(chest) else: for chest in chests: # Apaga o baú caso o mapa não possua baú chest.kill() for enemy in all_enemies: # A cada mudança de mapa, todos os inimigos desaparecem enemy.kill() else: spawn = False # O ultimo mapa apresenta uma mecanica de waves, que o jogador deve derrotar para vencer o jogo. if MAP == assets['maps']['map6.2'] and wave != 0 and len( all_enemies) == 0: spawn = True # Entrando no mapa, os mobs podem spawnar caso ainda restem waves e não haja inimigos vivos if spawn == True: # Caso os inimigos possam nascer, são gerados de 3 a 8 inimigos no mapa se este não for o mapa 1.1 (zona segura) if MAP != assets['maps']['map1.1']: if MAP == assets['maps'][ 'map6.2']: # Aqui implementa-se o sistema de waves para o mapa 6.2 if wave != 0 and len(all_enemies) == 0: n = random.randint(3, 8) for i in range(n): xy = random.randint(50, 400) enemy = Enemy(groups, assets, player, [xy, xy]) all_enemies.add(enemy) wave -= 1 else: # Geraçao normal de mobs para os demais mapas n = random.randint(3, 8) for i in range(n): xy = random.randint(50, 400) enemy = Enemy(groups, assets, player, [xy, xy]) all_enemies.add(enemy) spawn = False if MAP == assets['maps']['map1.1'] or MAP == assets['maps'][ 'map4.1']: # Para que os mobs não sigam o jogador, se este entrar nos mapas 1.1 ou 4.2, os mobs morrem for enemy in all_enemies: enemy.kill() MASK = MapMask(map_def(player, map_k, assets)[1]) map_masks.add(MASK) # Colisões map_collide = pygame.sprite.spritecollide( player, map_masks, False, pygame.sprite.collide_mask ) # Colisão do jogador com as máscaras do mapa hits = pygame.sprite.groupcollide( all_enemies, all_arrows, True, True, pygame.sprite.collide_mask) # Colisão das flechas com os inimigos impact = pygame.sprite.groupcollide( all_enemies, all_sprites, True, False, pygame.sprite.collide_mask) # Colisão dos inimigos com o jogador item_collect = pygame.sprite.spritecollide( player, chests, True) # Colisão do jogador com os baús if item_collect: # Ao colidir com o baú, o jogador ganha 200 pontos score += 200 if health < 5: health += 1 assets['point'].play() if map_collide: # Ao colidir com o mapa, o jogador para de se mover player.undo() if hits: # Ao matar um inimigo, o jogador ganha 10 pontos e, a cada 200 pontos ganhos, o jogador ganha mais uma vida, caso tenha perdido alguma assets['elemental_dying'].play() score += 10 if score % 200 == 0 and health < 5: health += 1 if impact: # Quando um inimigo toca em um jogador, o inimigo morre e o jogador perde uma vida health -= 1 # Desenhando o mapa e as sprites window.blit(MAP, (0, 0)) chests.draw(window) all_sprites.draw(window) all_arrows.draw(window) all_enemies.draw(window) # Desenhando Health e Score text_surface = assets['score_font'].render( chr(9829) * health, True, (255, 0, 0)) text_rect = text_surface.get_rect() text_rect.bottomleft = (10, HEIGHT - 10) window.blit(text_surface, text_rect) text_surface = assets['score_font'].render("Score:{:0d}".format(score), True, (255, 255, 255)) text_rect = text_surface.get_rect() text_rect.topleft = (10, 10) window.blit(text_surface, text_rect) # Caso a vida acabe, o jogo entra na tela de game over if health == 0 or wave == 0: gamerun = PAUSED # Tela de game over if gamerun == PAUSED: # Na tela de game over, o jogador pode escolher se para ou recomeça o jogo pygame.mixer.music.pause() window.blit(assets['over_screen'], (0, 0)) text_surface = assets['score_font'].render( "Score:{:0d}".format(score), True, (255, 255, 255)) text_rect = text_surface.get_rect() text_rect = ((WIDTH / 2 - 125), (HEIGHT / 2 + 15)) window.blit(text_surface, text_rect) gamerun = PAUSED if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: # Caso aperte Enter, o jogo recomeça no primeiro mapa, o estado volta pra RUNNING, a vida para 5 e os pontos zeram for chest in chests: chest.kill() wave = 6 pygame.mixer.music.play(loops=-1) map_k["map_n0"] = 1 map_k["map_n1"] = 1 gamerun = RUNNING health = 5 score = 0 window.blit(MAP, (0, 0)) elif event.key == pygame.K_ESCAPE: # Caso aperte Esc, o jogo fecha pygame.quit() pygame.display.flip() continue pygame.display.update()
def __init__(self, fps=1): pyxel.image(0).load(0, 0, "assets/villagers-export.png") pyxel.image(1).load(0, 0, "assets/16X16-export.png") self._init_space() lines = [] body = pymunk.Body(body_type=pymunk.Body.STATIC) for x in [z for z in range(0, 41)] + [z for z in range(158, 166)]: lines.append(pymunk.Segment(body, (0, x), (255, x), 30)) lines.append(pymunk.Segment(body, (-25, 0), (-25, 144), 30)) # lines.append(pymunk.Segment(body, (265, 0), (265, 144), 30)) for line in lines: self.space.add(line) death_wall = Enemy(0, xpos=0, ypos=0, imagebank=0, spritesheet_positions=[(3, 57)], attack_sprite_position=(0, 0), width=1, height=settings.canvas_y, spritesheet_keycol=0, mass=100, momentum=1, velocity=(0, 0), player_num=1) death_wall.attack_frames = pymunk.inf death_wall.health = pymunk.inf death_wall.poly = pymunk.Segment(body, (0, 0), (0, 144), 10) death_wall.poly.collision_type = 1 death_wall.body = pymunk.Segment(body, (0, 0), (0, 144), 10) death_wall.body.sprite = death_wall self.space.add(death_wall.body, death_wall.poly) logger.info("game initialized.") start_y = 50 self.players = { "Anna": Player("Anna", 18, start_y, spritesheet_positions=[(0, 0)], velocity=(0, 0), player_num=1), "Betrice": Player("Betrice", 48, start_y, spritesheet_positions=[(0, 48)], velocity=(0, 0), player_num=2), "Candice": Player("Candice", 78, start_y, spritesheet_positions=[(0, 96)], velocity=(0, 0), player_num=3), "Derp": Player("Derp", 108, start_y, spritesheet_positions=[(0, 144)], velocity=(0, 0), player_num=4) } self.dead_grannys = [] self.enemies = {} self.new_enemies = [] for player in self.players.values(): self.space.add(player.body, player.poly) self.boss_fight = False self.boss_dead = False self.running = False
if game_over: screen.blit(endgame_screen, (0, 0)) bullet.try_reload_bullet() if not bullet.prepared: bullet.move() bullet.y -= bullet.Y_change player.move() pygame.display.update() if __name__ == '__main__': bullet = Bullet(screen, pygame.image.load('assets/img/bullet/bullet1.png')) player = Player(screen, pygame.image.load('assets/img/player/player1.png')) enemies = [] for i in range(1,6): enemy = Enemy(screen, pygame.image.load('assets/img/enemy/enemy1.png')) enemy.x = random.randint(0, 736) enemy.y = random.randint(50, 150) enemy.X_change = 4 enemy.Y_change = 40 enemies.append(enemy) run()
def game(): EXPLODING = 2 RUNNING = 1 QUIT = 0 state = RUNNING side = STILL assets = load_assets() all_sprites = pygame.sprite.Group() all_enemies = pygame.sprite.Group() all_bullets = pygame.sprite.Group() all_platforms = pygame.sprite.Group() groups = {} groups['all_sprites'] = all_sprites groups['all_meteors'] = all_enemies groups['all_bullets'] = all_bullets groups['all_platforms'] = all_platforms camera = Camera(assets) player = Hero(groups, assets, side) enemy = Enemy(assets) platform1 = Platform(assets, 700, 650) all_sprites.add(camera) all_sprites.add(player) all_sprites.add(platform1) score = 0 lives = 15 number_of_enemies = 2 keys_down = {} for i in range(number_of_enemies): enemy = Enemy(assets) all_sprites.add(enemy) all_enemies.add(enemy) while state != QUIT: for event in pygame.event.get(): if event.type == pygame.QUIT: state = QUIT if event.type == pygame.KEYDOWN: keys_down[event.key] = True if event.key == pygame.K_ESCAPE: pause() if event.key == pygame.K_UP or event.key == pygame.K_w: player.jump() if event.key == pygame.K_LEFT or event.key == pygame.K_a: camera.speedx += 2 enemy.speedx += 2 if camera.rect.left <= 0 or camera.rect.right >= window_width: platform1.speedx += 2 else: platform1.speed = 0 player.side = Bullet.side = LEFT if event.key == pygame.K_RIGHT or event.key == pygame.K_d: camera.speedx -= 2 enemy.speedx -= 2 if camera.rect.left <= 0 or camera.rect.right >= window_width: platform1.speedx -= 2 else: platform1.speed = 0 player.side = Bullet.side = RIGHT if event.key == pygame.K_SPACE: player.shoot() if event.type == pygame.KEYUP: if event.key in keys_down and keys_down[event.key]: if event.key == pygame.K_LEFT or event.key == pygame.K_a: camera.speedx -= 2 enemy.speedx -= 2 if camera.rect.left <= 0 or camera.rect.right >= window_width: platform1.speedx -= 2 else: platform1.speed = 0 player.side = Bullet.side = LEFT if event.key == pygame.K_RIGHT or event.key == pygame.K_d: camera.speedx += 2 enemy.speedx += 2 if camera.rect.left <= 0 or camera.rect.right >= window_width: platform1.speedx += 2 else: platform1.speed = 0 player.side = Bullet.side = RIGHT all_sprites.update() if state == RUNNING: hits = pygame.sprite.groupcollide(all_enemies, all_bullets, True, True, pygame.sprite.collide_mask) for enemy in hits: assets['destroy_sound'].play() e = Enemy(assets) all_sprites.add(e) all_enemies.add(e) explosion = Explosion(enemy.rect.center, assets) all_sprites.add(explosion) score += 100 if score % 1000 == 0: lives += 1 hits = pygame.sprite.spritecollide(player, all_enemies, True, pygame.sprite.collide_mask) if len(hits) > 0: assets['boom_sound'].play() player.kill() lives -= 1 explosion = Explosion(player.rect.center, assets) all_sprites.add(explosion) state = EXPLODING keys_down = {} explosion_tick = pygame.time.get_ticks() explosion_duration = explosion.frame_ticks * len(explosion.explosion_anim) + 50 hits = pygame.sprite.spritecollide(player, all_platforms, False, pygame.sprite.collide_mask) if hits: player.speedy = 0 player.rect.pos.y = hits[0].rect.top keys_down = {} elif state == EXPLODING: now = pygame.time.get_ticks() camera.speedx = 0 platform1.speedx = 0 keys_down = {} if now - explosion_tick > explosion_duration: if lives == 0: game_over() else: state = RUNNING player = Hero(groups, assets, side) enemy = Enemy(assets) all_sprites.add(player) all_sprites.add(enemy) all_enemies.add(enemy) all_sprites.draw(window) text_surface = assets['score_font'].render('{:08d}'.format(score), True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (window_width / 2, 10) window.blit(text_surface, text_rect) text_surface = assets['score_font'].render(chr(9829) * lives, True, INSPER_RED) text_rect = text_surface.get_rect() text_rect.topleft = (10, 10) window.blit(text_surface, text_rect) pygame.display.update() clock.tick(FPS) pygame.quit() pygame.mixer.quit()
def update(self): self.all_sprites.update() # спавн врагов по времени now = pg.time.get_ticks() if now - self.enemy_count > 6000 + random.choice( [-1000, -500, 0, 500, 1000]): self.enemy_count = now Enemy(self) # поставить игрока на платформу при падении if self.player.vel.y > 0: hits = pg.sprite.spritecollide(self.player, self.platforms, False) if hits: object = hits[0] for hit in hits: if hit.rect.bottom > object.rect.bottom: object = hit if self.player.pos.x < object.rect.right + 10 and \ self.player.pos.x > object.rect.left - 10: if self.player.pos.y < object.rect.bottom + object.rect.height: self.player.pos.y = object.rect.top # добавить к скорости игрока скорость платформы на которой он стоит if hits[0].color == GREEN: self.player.pos.x += hits[0].vel self.player.vel.y = 0 self.player.OnGround = True else: self.player.OnGround = False # смещение мира по отношению к игроку (камера) if self.player.pos.y <= HEIGHT // 3 + 100: self.player.pos.y += abs(self.player.vel.y) self.background1.rect.y += abs(int(self.player.vel.y * 0.4)) self.background2.rect.y += abs(int(self.player.vel.y * 0.4)) for i in self.enemies: i.rect.y += abs(self.player.vel.y) # удаление врага за экраном if i.rect.top >= HEIGHT: i.kill() for i in self.platforms: i.rect.y += abs(self.player.vel.y) # удаление платформ за экраном if i.rect.top >= HEIGHT: i.kill() self.score += abs(int(self.player.vel.y)) # добавление новых платформ self.add_new_platform(-20) # соприкосновение с бонусом powerup_hits = pg.sprite.spritecollide(self.player, self.powerups, True, pg.sprite.collide_mask) for powerup in powerup_hits: if powerup.type == 'big jump': self.powerup_sound.play() self.player.vel.y = -POWERUP_JUMP self.player.jumping = False elif powerup.type == 'small gravity': self.powerup_sound.play() self.gravity_count = 0 self.gravity_on_off = False self.gravity = PLAYER_GRAVITY if self.gravity_on_off else POWERUP_GRAVITY if not self.gravity_on_off: self.gravity_count += 1 if self.gravity_count >= 600: self.gravity_count = 0 self.gravity_on_off = True # соприкосновение с врагом enemy_hits = pg.sprite.spritecollide(self.player, self.enemies, False, pg.sprite.collide_mask) if enemy_hits: self.death_sound.play() self.playing = False # смерть игрока if self.player.rect.top > HEIGHT: if self.death is False: self.death = True self.death_sound.play() # если герой вышел за экран внизу, # то все предметы улетают наверх с его же скоростью for i in self.all_sprites: i.rect.y -= self.player.vel.y if i.rect.bottom < 0: i.kill() if len(self.platforms) == 0: self.playing = False
def game_screen(window): clock = pygame.time.Clock() assets = load_assets() # Criando um grupo de inimigos all_sprites = pygame.sprite.Group() all_enemies = pygame.sprite.Group() all_bullets = pygame.sprite.Group() groups = {} groups['all_sprites'] = all_sprites groups['all_enemies'] = all_enemies groups['all_bullets'] = all_bullets # Criando o jogador player = Hero(groups, assets) all_sprites.add(player) # Status DONE = 0 PLAYING = 1 EXPLODING = 2 status = PLAYING keys_down = {} score = 0 lives = 5 # Criando os inimigos for j in range(4): enemy = Enemy(assets) all_sprites.add(enemy) all_enemies.add(enemy) # ===== Loop principal ===== pygame.mixer.music.play(loops=-1) while status != DONE: clock.tick(FPS) # ----- Trata eventos for event in pygame.event.get(): # ----- Verifica consequências if event.type == pygame.QUIT: status = DONE # Verifica teclado modo de jogo if status == PLAYING: # Verifica se apertou alguma tecla if event.type == pygame.KEYDOWN: keys_down[event.key] = True if event.key == pygame.K_LEFT: player.speedx -= 10 if event.key == pygame.K_RIGHT: player.speedx += 10 if event.key == pygame.K_SPACE: player.shoot() if event.key == pygame.K_UP: player.jump() # Verifica se soltou alguma tecla if event.type == pygame.KEYUP: if event.key in keys_down and keys_down[event.key]: if event.key == pygame.K_LEFT: player.speedx += 10 if event.key == pygame.K_RIGHT: player.speedx -= 10 # ----- Atualiza o estado do jogo all_sprites.update() if status == PLAYING: hits = pygame.sprite.groupcollide(all_enemies, all_bullets, True, True) for hit in hits: # Inimigo morto precisa de recriação assets[BOOM_SOUND].play() assets[ENEMY_DEATH_SOUND].play() m = Enemy(assets) all_sprites.add(m) all_enemies.add(m) # No lugar do inimigo antigo, adicionar uma explosão explosao = Explosion(hit.rect.center, assets) all_sprites.add(explosao) # Pontos recebidos pela eliminação do inimigo score += 100 if score % 1000 == 0: lives += 1 hits = pygame.sprite.spritecollide(player, all_enemies, True) if len(hits) > 0: # Som da colisão assets[HERO_DAMAGE_SOUND].play() assets[ENEMY_DEATH_SOUND].play() player.kill() lives -= 1 explosao = Explosion(player.rect.center, assets) all_sprites.add(explosao) status = EXPLODING keys_down = {} explosion_tick = pygame.time.get_ticks() explosion_duration = explosao.frame_ticks * len( explosao.explosion_anim) elif status == EXPLODING: now = pygame.time.get_ticks() if now - explosion_tick > explosion_duration: if lives == 0: assets[GAME_OVER_SOUND].play() time.sleep(5) status = DONE else: status = PLAYING player = Hero(groups, assets) all_sprites.add(player) enemy = Enemy(assets) all_sprites.add(enemy) all_enemies.add(enemy) # ----- Gera saídas window.fill((0, 0, 0)) window.blit(assets['background'], (0, 0)) # Desenhando os sprites all_sprites.draw(window) # Desenhando o score text_surface = assets['score_font'].render('{:08d}'.format(score), True, (255, 255, 0)) text_rect = text_surface.get_rect() text_rect.midtop = (WIDTH / 2, 10) window.blit(text_surface, text_rect) # Desenhando as vidas text_surface = assets['score_font'].render( chr(9829) * lives, True, (255, 0, 0)) text_rect = text_surface.get_rect() text_rect.bottomleft = (10, HEIGHT - 10) window.blit(text_surface, text_rect) pygame.display.update() # Mostra um novo frame