def fire(self, projectiles): if self.ammo_count > 0: self.ammo_count -= 1 projectiles.append( Bullet(self.barrel_1_exit_pos, self.current_aim_vector, self.per_bullet_damage, self.explosion_sprite_sheet)) projectiles.append( Bullet(self.barrel_2_exit_pos, self.current_aim_vector, self.per_bullet_damage, self.explosion_sprite_sheet))
def fire_key_held(self, dt, player, projectiles): if self.fire_rate_acc > self.fire_rate: self.fire_rate_acc = 0.0 projectiles.append( Bullet(player, player.position, player.aim_angle, self.weapon_force)) else: self.fire_rate_acc += dt
def update_screen(screen, game_settings, background, zombies, squares, plants, bullets, tick, icons): ''' 更新(画)游戏图形 ''' screen.blit(background.image, background.rect) for icon in icons: screen.blit(icon.image, icon.rect) if game_settings.highlighted_square != 0: pygame.draw.rect(screen, (255, 215, 0), (game_settings.highlighted_square.rect.left, game_settings.highlighted_square.rect.top, game_settings.squares['square_width'], game_settings.squares['square_height']), 5) # 画僵尸 for zombie in zombies.sprites(): if game_settings.game_active: zombie.update_me() zombie.draw_me() if zombie.rect.left <= zombie.screen_rect.left: game_settings.game_active = False zombie.moving = True # 画植物 for plant in plants: plant.draw_me() should_shoot = time.time() - plant.last_shot > plant.shoot_speed can_shoot = plant.can_shoot in_my_row = game_settings.zombie_in_row[plant.yard_row] > 0 if should_shoot and in_my_row and can_shoot: bullets.add(Bullet(screen, plant)) plant.last_shot = time.time() can_make_sun = plant.can_make_sun should_make_sun = time.time() - plant.last_sun > plant.sun_speed if can_make_sun and should_make_sun: plant.make_sun(game_settings) plant.last_sun = time.time() for bullet in bullets.sprites(): bullet.update_me() bullet.draw_me() score_font = pygame.font.SysFont("monospace", 36) # render a font takes 3 params: # 1. What text. # 2. I cant remember # 3. Color score_render = score_font.render( "Killed: " + str(game_settings.zombies_killed) + "!", 1, (255, 215, 0)) screen.blit(score_render, (100, 20)) sun_render = score_font.render( "Sun: " + str(game_settings.total_sun) + "!", 1, (255, 215, 0)) screen.blit(sun_render, (100, 40))
def __init__(self): self.enemy = Enemy() self.bullet = Bullet() self.player = Player() self.num_enemy = 6 self.enemies = [] for i in range(self.num_enemy): self.enemies.append(Enemy())
def setup(self): """ Set up the game and initializes variables. Args: self (Gameview): an instance of Gameview Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre """ self.tanks = Run() self.ground = Ground() self.bullet = Bullet() self.power = SpawnRandom() self.explosions_list = arcade.SpriteList() self.physics_engine = arcade.PhysicsEngineSimple( self.tanks.player1, self.ground.ground_sprite_list) self.physics_engine2 = arcade.PhysicsEngineSimple( self.tanks.player2, self.ground.ground_sprite_list) self.physics_engine3 = arcade.PhysicsEngineSimple( self.tanks.player1, self.tanks.sprite_list)
def __init__(self): self.e_X = random.randint(0, 400) self.e_Y = random.randint(50, 150) self.enemy_die = pygame.mixer.Sound("sounds/invaderkilled.wav") self.player_die = pygame.mixer.Sound("sounds/explosion.wav") self.velocidade = 10 self.direcao = 1 self.e_IMG = pygame.image.load('imgs/enemy.png') # chama os objetos self.player = Player() self.bullet = Bullet()
def create_fired_bullets(self, bullets): if self.should_fire_bullet: self.should_fire_bullet = False fire_power = self.lerp(100.0, 600.0, self.power_level) heading = math.radians(90.0 - float(self.current_turret_angle)) heading_vector = [-math.cos(heading), -math.sin(heading)] vel_heading_vector = [ heading_vector[0] * fire_power, heading_vector[1] * fire_power ] # we want to start bullets a little in front of the tank so they don't # immediately overlap with the tank that fires them and blow it up tank_front = [self.position[0], self.position[1]] tank_front[0] += heading_vector[0] * 32.0 tank_front[1] += heading_vector[1] * 32.0 bullet = Bullet(tank_front, vel_heading_vector, self.power_ups, True) bullets.append(bullet) self.owned_bullets.append(bullet) self.power_level = 0.0 return bullets
def shoot(self): bullet = Bullet(self.screen, self, 15) self.bullets.add(bullet)
def _fire_bullet(self): if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)
def shoot(self): bul = Bullet(self.screen, self) self.bullets.add(bul)
def shoot(self): """飞机射击""" self.bullets.add(Bullet(self, 15))
def update_movement_and_collision(self, bullets, lives_board, time_delta, explosions): if self.charging_power: self.power_level += time_delta self.power_gauge.update_power_level(self.power_level) if self.power_level >= 1.0: self.power_level = 1.0 for explosion in explosions: if self.test_explosion_collision(explosion): self.should_die = True for bullet in bullets: if self.test_bullet_collision(bullet): bullet.should_die = True self.should_die = True self.owned_bullets[:] = [ bullet for bullet in self.owned_bullets if not bullet.should_die ] if self.should_detonate_or_split: self.should_detonate_or_split = False oldest_bullet_life = 10000.0 oldest_bullet = None for bullet in self.owned_bullets: if bullet.life_time < oldest_bullet_life: oldest_bullet = bullet if oldest_bullet is not None: if oldest_bullet.can_split and self.power_ups.clusters_per_shell > 0: cluster_direction = 1 for cluster_index in range( 0, self.power_ups.clusters_per_shell + 1): new_vector = oldest_bullet.current_vector new_vector[0] += (cluster_index * 20 * cluster_direction) bullet = Bullet(oldest_bullet.position, new_vector, self.power_ups, False) bullets.append(bullet) self.owned_bullets.append(bullet) if cluster_direction == 1: cluster_direction = -1 else: cluster_direction = 1 oldest_bullet.should_die = True if self.should_move_left or self.should_move_right: if self.should_move_right: if self.current_turret_angle < -90.0: self.current_turret_angle = -90.0 else: self.move_left_acceleration = 0.0 self.move_right_acceleration += time_delta * 0.75 # 1.5 seconds ish to max speed if self.move_right_acceleration > 1.0: self.move_right_acceleration = 1.0 self.current_turret_angle -= time_delta * self.lerp( self.min_rotate_speed, self.max_rotate_speed, self.move_right_acceleration) if self.should_move_left: if self.current_turret_angle > 90.0: self.current_turret_angle = 90.0 else: self.move_right_acceleration = 0.0 self.move_left_acceleration += time_delta * 0.75 # 1.5 seconds ish to max speed if self.move_left_acceleration > 1.0: self.move_left_acceleration = 1.0 self.current_turret_angle += time_delta * self.lerp( self.min_rotate_speed, self.max_rotate_speed, self.move_left_acceleration) self.turret_barrel.image = pygame.transform.rotate( self.turret_barrel.original_turret_image, self.current_turret_angle) self.turret_barrel.rect = self.turret_barrel.image.get_rect() self.turret_barrel.rect.center = self.rot_point([ self.position[0], self.position[1] + self.turret_barrel.turret_y_offset ], self.position, -self.current_turret_angle) else: self.move_left_acceleration = 0.0 self.move_right_acceleration = 0.0 for lives in lives_board: if lives.player_id == self.player_id: lives.lives = self.current_lives lives.explosion_power = self.power_ups.explosion_size lives.clusters = self.power_ups.clusters_per_shell lives.shots = self.power_ups.max_shots
def fire_bullet(ai_settings, screen, ship, bullets): """if in the limit of allowed ,it will launch a bullet""" if len(bullets) < ai_settings.bullets_allowed: # create a bullet,and add to bullets's Group new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def update_shooting(self, time_delta, monsters, projectiles): # time gap between shots if self.fire_rate_acc < self.fire_rate: self.fire_rate_acc += time_delta else: self.can_fire = True if self.current_target is None or self.current_target.should_die or self.target_distance > self.radius: self.current_target, self.target_distance = self.get_closest_monster_in_radius( monsters) if self.current_target is not None: # aim at the monster self.target_distance = self.calc_distance_to_target( self.current_target) results = self.calculate_aiming_vector(self.current_target, self.target_distance) self.target_vector = results[0] target_pos = results[1] relative_angle_to_target = self.rotate_current_angle_to_target( time_delta) # fire some bullets if self.can_fire and abs(relative_angle_to_target) < math.pi / 8: self.fire_rate_acc = 0.0 self.can_fire = False gun_pos1 = [ self.position[0] + (self.current_vector[1] * 6), self.position[1] - (self.current_vector[0] * 6) ] bullet_vec1_x = target_pos[0] - gun_pos1[0] bullet_vec1_y = target_pos[1] - gun_pos1[1] bullet1_dist = math.sqrt((bullet_vec1_x**2) + (bullet_vec1_y**2)) bullet_vec1 = [ bullet_vec1_x / bullet1_dist, bullet_vec1_y / bullet1_dist ] gun_pos2 = [ self.position[0] - (self.current_vector[1] * 6), self.position[1] + (self.current_vector[0] * 6) ] bullet_vec2_x = target_pos[0] - gun_pos2[0] bullet_vec2_y = target_pos[1] - gun_pos2[1] bullet2_dist = math.sqrt((bullet_vec2_x**2) + (bullet_vec2_y**2)) bullet_vec2 = [ bullet_vec2_x / bullet2_dist, bullet_vec2_y / bullet2_dist ] projectiles.append( Bullet(gun_pos1, bullet_vec1, target_pos, self.per_bullet_damage, self.projectile_speed, self.explosions_sprite_sheet, self.image_atlas, self.collision_grid)) projectiles.append( Bullet(gun_pos2, bullet_vec2, target_pos, self.per_bullet_damage, self.projectile_speed, self.explosions_sprite_sheet, self.image_atlas, self.collision_grid))
ufo_music=pygame.mixer.Sound("C:/Users/acer/Desktop/music/bgm_maoudamashii_neorock82-_1_.wav") gameover_music=pygame.mixer.Sound("C:/Users/acer/Desktop/music/zth070516_aigei_com.wav") bullet_sound.set_volume(0.5) fire_sound.set_volume(0.5) supply_sound.set_volume(0.8) other_dead_sound.set_volume(0.9) myairplane_dead_sound.set_volume(0.9) boss_dead_sound.set_volume(1) win_music.set_volume(1) ufo_music.set_volume(0.1) gameover_music.set_volume(1) u=Ufo(gameDisplay,"D:/python practice/ufo.png",(143,-700)) l=Light("D:/python practice/light.png",(325,120)) ublist=[] ubgroup=pygame.sprite.Group() ub=Bullet("D:/python practice/bulletufo.png",200,116) ub2=Bullet("D:/python practice/bulletufo.png",320,150) ub3=Bullet("D:/python practice/bulletufo.png",485,150) ub5=Bullet("D:/python practice/bulletufo.png",611,116) ublist=[ub,ub2,ub3,ub5] for ufobullet in ublist: ubgroup.add(ufobullet) clock=pygame.time.Clock() def game_over(): pygame.mixer.music.pause() LargeText=pygame.font.SysFont("comicsansms",115) Textsurface=LargeText.render("Game Over!",True,white) Textrect=Textsurface.get_rect() Textrect.center=(400,300) over=True while over:
def fire(self): if self.bullet_cd_timer <= 0: self.bullets.append(Bullet(self.player.p_X)) self.bullet_cd_timer = self.bullet_cd_time
def shoot(self): ''' 飞机发射子弹 ''' bullet = Bullet(self.screen, self, 15) self.bullets.add(bullet)
def shoot(self): """ 发射子弹 """ bullet = Bullet(self.screen, self, 20) self.bullets.add(bullet)
def fire_bullet(setting, screen, ship, bullets): if len(bullets) < setting.bullet_count: new_bullet = Bullet(setting, screen, ship) bullets.add(new_bullet)
class GameView(arcade.View): """ Game view for Tank Wars. The responsibility of this class of objects is to control the sequence of play Stereotype: Coordinator, Structurer, Service Provider Attributes: _score (Score): initalizes the score class texture (arcade.load_texture): load background texture game_ending (Boolean): triggers final game actions name (String): name of losing player physicis_engine (None): declares physics engine variable physics_engine2 (None): declares physics engine 2 variable physics_engine3 (None): declares physics engine 2 variable physics_engine4 (None): declares physics engine 2 variable bullet_list (None): declares bullet list variable explosion_list (None): declares explosion list variable explosion_texture_list (List): declares texture list used for explosion Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre Juliano Nascimiento """ def __init__(self): """ Declares variables for the GameView class Args: self (Gameview): an instance of Gameview Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre Juliano Nascimiento """ super().__init__() self._score = Score() self.texture = arcade.load_texture(constants.BACKGROUND) self.game_ending = False self.name = "" # physics engines self.physics_engine = None self.physics_engine2 = None self.physics_engine3 = None self.physics_engine4 = None # sprite lists self.bullet_list = None self.explosions_list = None self.explosion_texture_list = [] # sounds self.powerup_sound = arcade.load_sound(constants.POWERUPS_SOUND) self.powerdown_sound = arcade.load_sound(constants.POWERDOWN_SOUND) self.tank_explode = arcade.load_sound(constants.EXPLOSION_SOUND) # explosion details self.columns = 16 self.count = 8 self.sprite_width = 256 self.sprite_height = 256 self.file_name = ":resources:images/spritesheets/explosion.png" self.explosion_texture_list = arcade.load_spritesheet( self.file_name, self.sprite_width, self.sprite_height, self.columns, self.count) def setup(self): """ Set up the game and initializes variables. Args: self (Gameview): an instance of Gameview Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre """ self.tanks = Run() self.ground = Ground() self.bullet = Bullet() self.power = SpawnRandom() self.explosions_list = arcade.SpriteList() self.physics_engine = arcade.PhysicsEngineSimple( self.tanks.player1, self.ground.ground_sprite_list) self.physics_engine2 = arcade.PhysicsEngineSimple( self.tanks.player2, self.ground.ground_sprite_list) self.physics_engine3 = arcade.PhysicsEngineSimple( self.tanks.player1, self.tanks.sprite_list) def on_draw(self): """ Draws the game screen. Args: self (Gameview): an instance of Gameview Contributors: Reed Hunsaker Adrianna Lund Jordan McIntyre Isabel Aranguren """ arcade.start_render() self.wrap() self.texture.draw_sized(constants.SCREEN_WIDTH / 2, constants.SCREEN_HEIGHT / 2, constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT) self.tanks.sprite_list.draw() for tank in self.tanks.sprite_list: tank.draw_life_bar() tank.draw_life_number() self.ground.ground_sprite_list.draw() self.power.sprite_list.draw() if self.bullet.bullet_sprite_list is not None: self.bullet.bullet_sprite_list.draw() if self.explosions_list is not None: self.explosions_list.draw() def on_update(self, delta_time: float): """ Updates the game screen. Args: self (Gameview): instance of Gameview delta_time: essential for updates to run Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre """ # if game is ending - update the last explosion, then go to the game over view if self.game_ending: self.explosions_list.update() if not self.explosions_list: self.switch_game_over_view(self.name) return self.physics_engine.update() self.physics_engine2.update() self.physics_engine3.update() self.explosions_list.update() # handle bullet collisions bullets = len(self.bullet.bullet_sprite_list) if bullets > 0: for bullet in self.bullet.bullet_sprite_list: hit_list_wall = arcade.check_for_collision_with_list( bullet, self.ground.ground_sprite_list) hit_list_tank = arcade.check_for_collision_with_list( bullet, self.tanks.sprite_list) self.bullet_shooting_update(bullet, bullets, hit_list_tank, hit_list_wall) # powerups powers = len(self.power.sprite_list) if powers > 0: for power in self.power.sprite_list: hit_list_wall = arcade.check_for_collision_with_list( power, self.ground.ground_sprite_list) hit_list_tank = arcade.check_for_collision_with_list( power, self.tanks.sprite_list) hit_list_bullet = arcade.check_for_collision_with_list( power, self.bullet.bullet_sprite_list) if len(hit_list_wall) > 0: power.kill() powers -= 1 self.power = SpawnRandom() # Paired with checker above in bullet collision checks. should destroy/block bullet if len(hit_list_bullet) > 0: if self.power.sprite_list[-1].get_value() == 2: for angle in range(0, 360, 60): self.bullet.shoot_bullet( self.power.sprite_list[-1]._get_center_x(), self.power.sprite_list[-1]._get_center_y(), angle) power.kill() powers -= 1 self.power = SpawnRandom() for tank in hit_list_tank: if self.power.sprite_list[-1].get_value() == 0: tank.set_life(-25) arcade.play_sound(self.powerdown_sound, .8) elif self.power.sprite_list[-1].get_value() == 1: tank.set_life(50) arcade.play_sound(self.powerup_sound) elif self.power.sprite_list[-1].get_value() == 2: for angle in range(0, 360, 60): bullets += 1 self.bullet.shoot_bullet(tank._get_center_x(), tank._get_center_y(), (tank.angle + angle)) power.kill() powers -= 1 self.power = SpawnRandom() # check tank health & set final explosion for tank in self.tanks.sprite_list: alive = tank.is_alive() if alive == False: self.game_ending = True self.count = 50 self.explosion_texture_list = arcade.load_spritesheet( self.file_name, self.sprite_width, self.sprite_height, self.columns, self.count) explosion = Explosion(self.explosion_texture_list) # set explosion center to location of first hit in list explosion.center_x = tank.center_x explosion.center_y = tank.center_y # update explosion (sets first image) explosion.update() self.explosions_list.append(explosion) self.name = tank.name tank.kill() def bullet_shooting_update(self, bullet, bullets, hit_list_tank, hit_list_wall): """ Updates bullets and explosions. Args: bullet: the length of the sprite list bullets: individual bullet objects hit_list_tank: list of tanks that were hit hit_list_wall: list of bullets that hit a wall Contributors: Reed Hunsaker Adrianna Lund Isabel Aranguren Jordan McIntyre """ if len(hit_list_wall) > 0: self.bullet.bullet_bounce(bullet, bullet.angle) if len(hit_list_tank) > 0: for tank in self.tanks.sprite_list: life = tank.get_life() explosion = Explosion(self.explosion_texture_list) # set explosion center to location of first hit in list explosion.center_x = hit_list_tank[0].center_x explosion.center_y = hit_list_tank[0].center_y # update explosion (sets first image) explosion.update() self.explosions_list.append(explosion) # if bullet leaves screen, kill it elif bullet.bottom > constants.SCREEN_HEIGHT or bullet.top < 0 or bullet.right < 0 or bullet.left > constants.SCREEN_WIDTH: bullet.kill() bullets -= 1 # play sound and kill bullet from hit lists for tank in hit_list_tank: tank.set_life(-25) arcade.play_sound(self.tank_explode, .5) bullet.kill() bullets -= 1 def wrap(self): """Keeps players on screen and kills bullets off screen and updates sprite movement. Args: self (Gameview): an instance of Gameview Contributors: Adrianna Lund Jordan McIntyre """ # Check player1 for out-of-bounds if self.tanks.player1.left < 0: self.tanks.player1.left = 0 elif self.tanks.player1.right > constants.SCREEN_WIDTH - 1: self.tanks.player1.right = constants.SCREEN_WIDTH - 1 if self.tanks.player1.bottom < 0: self.tanks.player1.bottom = 0 elif self.tanks.player1.top > constants.SCREEN_HEIGHT - 1: self.tanks.player1.top = constants.SCREEN_HEIGHT - 1 # Check player2 for out of bounds if self.tanks.player2.left < 0: self.tanks.player2.left = 0 elif self.tanks.player2.right > constants.SCREEN_WIDTH - 1: self.tanks.player2.right = constants.SCREEN_WIDTH - 1 if self.tanks.player2.bottom < 0: self.tanks.player2.bottom = 0 elif self.tanks.player2.top > constants.SCREEN_HEIGHT - 1: self.tanks.player2.top = constants.SCREEN_HEIGHT - 1 # Update animations/sprites self.tanks.player1.update() self.tanks.player2.update() if self.bullet.bullet_sprite_list is not None: self.bullet.bullet_sprite_list.update() self.bullet.bullet_sprite_list.update_animation() if self.explosions_list is not None: self.explosions_list.update() def on_key_press(self, key, modifiers): """Called whenever a key is pressed. Args: self (Explosion): an instance of GameView key: the key that was pressed modifiers: modifier keys that were pressed Contributors: Adrianna Lund Reed Hunsaker """ # Forward/back - PLAYER 1 if key == arcade.key.DOWN: self.tanks.player1.speed = constants.TANK_SPEED elif key == arcade.key.UP: self.tanks.player1.speed = -constants.TANK_SPEED elif key == arcade.key.SPACE: self.bullet.shoot_bullet(self.tanks.player1._get_center_x(), self.tanks.player1._get_center_y(), self.tanks.player1.angle) # Forward/back - PLAYER 2 elif key == arcade.key.S: self.tanks.player2.speed = constants.TANK_SPEED elif key == arcade.key.W: self.tanks.player2.speed = -constants.TANK_SPEED elif key == arcade.key.Q: self.bullet.shoot_bullet(self.tanks.player2._get_center_x(), self.tanks.player2._get_center_y(), self.tanks.player2.angle) # Rotate left/right - PLAYER 1 elif key == arcade.key.LEFT: self.tanks.player1.change_angle = constants.TANK_ANGLE_SPEED elif key == arcade.key.RIGHT: self.tanks.player1.change_angle = -constants.TANK_ANGLE_SPEED # Rotate left/right - PLAYER 2 elif key == arcade.key.A: self.tanks.player2.change_angle = constants.TANK_ANGLE_SPEED elif key == arcade.key.D: self.tanks.player2.change_angle = -constants.TANK_ANGLE_SPEED # Quit key elif key == arcade.key.ESCAPE: quit() def on_key_release(self, key, modifiers): """Called when the user releases a key. Args: self (Explosion): an instance of GameView key: the key that was pressed modifiers: modifier keys that were pressed Contributors: Adrianna Lund Reed Hunsaker """ # Resets speed/angle on key release - PLAYER 1 if key == arcade.key.UP or key == arcade.key.DOWN: self.tanks.player1.speed = 0 elif key == arcade.key.LEFT or key == arcade.key.RIGHT: self.tanks.player1.change_angle = 0 # Resets speed/angle on key release - PLAYER 2 elif key == arcade.key.W or key == arcade.key.S: self.tanks.player2.speed = 0 elif key == arcade.key.A or key == arcade.key.D: self.tanks.player2.change_angle = 0 def switch_game_over_view(self, loser): """ Call the game over screen. Args: self (Explosion): an instance of GameView loser: 0 or 1 to pass the winner Contributors: Reed Hunsaker """ game_over = GameOverView(loser) self.window.show_view(game_over)
def fire_bullet(ai_settings, screen, ship, bullets): """Dispara um projétil se o limite ainda não foi alcançado.""" # Cria um novo projétil e o adiciona ao grupo de projéteis if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def shoot(self): """ shoot bullet """ bullet = Bullet(self.screen, self, 40) self.bullets.add(bullet)
def shoot(self): #飞机发射子弹 bullet = Bullet(self.screen, self, 15) #实现子弹类,屏幕 飞机 速度 self.bullets.add(bullet)
def fire_bullet(ai_settings, screen, ship, bullets): """如果还没有达到限制,就发射一颗子弹""" # 创建一颗子弹,并将其加入到编组bullets中 if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def shoot(self, speed=10): """ 飞机发射子弹 """ bullet = Bullet(self.screen, self, speed) self.bullets.add(bullet)
def update_movement_and_collision(self, time_delta, time_multiplier, player, new_explosions, tiled_level, projectiles, pick_up_spawner): for explosion in new_explosions: if self.test_explosion_collision(explosion): self.take_damage(explosion.damage.amount) if self.health <= 0: self.should_die = True distance_to_player = 100000000.0 if not player.should_die: x_dist = float(player.position[0]) - float(self.position[0]) y_dist = float(player.position[1]) - float(self.position[1]) distance_to_player = math.sqrt((x_dist * x_dist) + (y_dist * y_dist)) # idle AI state if self.is_wandering_aimlessly: # self.moveSpeed = self.idleMoveSpeed if distance_to_player < 512.0: self.is_wandering_aimlessly = False elif self.random_target_change_acc < self.random_target_change_time: self.random_target_change_acc += time_delta else: self.random_target_change_acc = 0.0 self.random_target_change_time = random.uniform(3.0, 15.0) self.next_way_point = self.get_random_point_on_screen() x_dist = float(self.next_way_point[0]) - float( self.position[0]) y_dist = float(self.next_way_point[1]) - float( self.position[1]) # self.distance_to_next_way_point = math.sqrt((x_dist * x_dist) + (yDist * yDist)) self.current_vector = [ x_dist / self.distance_to_next_way_point, y_dist / self.distance_to_next_way_point ] self.rotate_sprite() # preparing to shoot AI state if not self.is_wandering_aimlessly: if distance_to_player > 700.0: self.is_wandering_aimlessly = True if distance_to_player > 0.0: self.current_vector = [ x_dist / distance_to_player, y_dist / distance_to_player ] self.rotate_sprite() if self.attack_time_acc < self.attack_time_delay: self.attack_time_acc += time_delta * time_multiplier else: self.attack_time_acc = random.random( ) / 10.0 # add a small random amount to the reload delay self.is_time_to_start_attack = True if self.is_time_to_start_attack and self.has_line_of_sight_to_player: self.is_time_to_start_attack = False self.is_attacking = True if self.id == "rifle": x_forward_offset = self.current_vector[ 0] * self.barrel_forward_offset x_side_offset = self.current_vector[ 1] * self.barrel_side_offset y_forward_offset = self.current_vector[ 1] * self.barrel_forward_offset y_side_offset = self.current_vector[ 0] * self.barrel_side_offset barrel_x_pos = self.position[ 0] + x_forward_offset - x_side_offset barrel_y_pos = self.position[ 1] + y_forward_offset + y_side_offset self.barrel_exit_pos = [barrel_x_pos, barrel_y_pos] projectiles.append( Bullet(self.barrel_exit_pos, self.current_vector, self.per_bullet_damage, self.explosions_sprite_sheet, True)) elif self.id == "shotgun": barrel_forward_offset = 32 barrel_side_offset1 = 4 barrel_side_offset2 = 8 x_forward_offset = self.current_vector[ 0] * barrel_forward_offset y_forward_offset = self.current_vector[ 1] * barrel_forward_offset x_side_offset1 = self.current_vector[ 1] * barrel_side_offset1 y_side_offset1 = self.current_vector[ 0] * barrel_side_offset1 x_side_offset2 = self.current_vector[ 1] * barrel_side_offset2 y_side_offset2 = self.current_vector[ 0] * barrel_side_offset2 barrel1_x_pos = self.position[ 0] + x_forward_offset - x_side_offset1 barrel1_y_pos = self.position[ 1] + y_forward_offset + y_side_offset1 barrel1_exit_pos = [barrel1_x_pos, barrel1_y_pos] barrel2_x_pos = self.position[ 0] + x_forward_offset - x_side_offset2 barrel2_y_pos = self.position[ 1] + y_forward_offset + y_side_offset2 barrel2_exit_pos = [barrel2_x_pos, barrel2_y_pos] projectiles.append( Bullet(barrel1_exit_pos, self.current_vector, self.per_bullet_damage, self.explosions_sprite_sheet, True)) projectiles.append( Bullet(barrel2_exit_pos, self.current_vector, self.per_bullet_damage, self.explosions_sprite_sheet, True)) elif self.id == "launcher": barrel_forward_offset = 28 barrel_side_offset = 11 missile_damage = 100 barrel_x_forward_vector = self.current_vector[ 0] * barrel_forward_offset barrel_x_side_vector = self.current_vector[ 1] * barrel_side_offset barrel_y_forward_vector = self.current_vector[ 1] * barrel_forward_offset barrel_y_side_vector = self.current_vector[ 0] * barrel_side_offset barrel_x_pos = self.position[ 0] + barrel_x_forward_vector - barrel_x_side_vector barrel_y_pos = self.position[ 1] + barrel_y_forward_vector + barrel_y_side_vector barrel_exit_pos = [barrel_x_pos, barrel_y_pos] projectiles.append( Missile(barrel_exit_pos, self.current_vector, missile_damage, self.explosions_sprite_sheet, True)) # shooting/reloading if self.is_attacking: self.attack_anim_acc += time_delta * time_multiplier if self.attack_anim_acc > self.attack_anim_total_time: self.attack_anim_acc = 0.0 self.is_attacking = False # time to check LOS to player? if self.los_check_acc >= self.los_check_timer: self.los_check_acc = 0.0 self.has_line_of_sight_to_player = True if not player.should_die: if distance_to_player < 550.0: self.line_of_sight = LOSLine(self.screen_position, player.screen_position) for tile_x in range(tiled_level.zero_tile_x, tiled_level.end_tile_x): if self.has_line_of_sight_to_player: for tile_y in range(tiled_level.zero_tile_y, tiled_level.end_tile_y): tile = tiled_level.tile_grid[tile_x][tile_y] if self.has_line_of_sight_to_player: for collision_shape in tile.tile_data.collision_shapes: if collision_shape[0] == "circle": pass elif collision_shape[0] == "rect": rect = collision_shape[2] if self.line_of_sight.is_rect_collided( rect): self.has_line_of_sight_to_player = False else: break else: break else: self.line_of_sight = None self.has_line_of_sight_to_player = False else: self.los_check_acc += time_delta * time_multiplier self.update_screen_position(self.tiled_level.position_offset) self.rect.center = self.screen_position if self.should_die: self.all_monster_sprites.remove(self) if self.active_flash_sprite: self.all_monster_sprites.remove(self.flash_sprite) self.active_flash_sprite = False self.try_pick_up_spawn(pick_up_spawner)
def shoot(self): """飞机发射子弹""" bullet = Bullet(self.screen, self, 15) self.bullets.add(bullet)
def fire(cfg, screen, ship, bullets): if len(bullets) < cfg.bullets_allowed: # 限制子弹数量 new_bullet = Bullet(cfg, screen, ship) bullets.add(new_bullet)
def gameloop(): x=800*0.5 y=600*0.8 n=600*0.8 delay=120 index=0 index1=0 index2=0 index3=0 bg_x=0 bg_y=0 bg_x1=0 bg_y1=-600 otherairplanes=pygame.sprite.Group() imagename="D:/python practice/otherairplane.png" x1=random.randint(0,380) y1=-80 o=Otherairplane(imagename,x1,y1,3) #小敵機 x2=random.randint(410,775) y2=-80 o1=Otherairplane(imagename,x2,y2,3) otherairplanes.add(o) otherairplanes.add(o1) imagename1="D:/python practice/otherairplane1.png" bossname="D:/python practice/bossairplane.png" boss=Bossairplane(gameDisplay,bossname,(400,-600),1) #大敵機 for enemy in range(0,3): x3=random.randint(0,775) y3=random.randint(-250,-150) otherairplanes.add(Otherairplane(imagename1,x3,y3,3)) bomb=Bombs(gameDisplay,(0,0)) #爆炸 bomb1=Bombs(gameDisplay,(0,0)) airplanegroups=pygame.sprite.Group() name="D:/python practice/airplane.png" name1="D:/python practice/airplane1.png" a=Airplane(gameDisplay,name,(x,y),10) #我方飛機 a1=Airplane(gameDisplay,name1,(x,y),10) airplanegroups.add(a) airplanegroups.add(a1) filename1="D:/python practice/bullet.png" filename2="D:/python practice/firebullet.png" bullets=pygame.sprite.Group() b=Bullet(filename1,x+25,n) #子彈物件(我方飛機) fire_b=Bullet(filename2,x-25,n) #火彈(子彈) fire_b1=Bullet(filename2,x+41,n) bullets.add(fire_b) bullets.add(fire_b1) b1=Bullet(filename1,400,1) #子彈(大敵機) b2=Bullet(filename1,585,1) s=Supplies(filename2) #補給物(火彈) s1=Supplies("D:/python practice/supply.png") #補給物(補血) bullet_group=pygame.sprite.Group() bullet_group.add(b1) bullet_group.add(b2) pygame.mixer.music.load("C:/Users/acer/Desktop/music/reckless_abandon (1).mp3") pygame.mixer.music.play(-1) UFOEVENT=pygame.USEREVENT+1 pygame.time.set_timer(UFOEVENT,90000) game_start=True a.Y_bolen=False a.X_bolen=False b.btbolen=False a_image=True a_image1=True a_image2=True launch=True launch1=True u_appear=False while game_start: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() if event.type==pygame.KEYDOWN: if event.key==pygame.K_LEFT: a.Leftmove() a.Y_bolen=False if event.key==pygame.K_RIGHT: a.Rightmove() a.Y_bolen=False if event.key==pygame.K_UP: a.Upmove() if event.key==pygame.K_DOWN: a.Downmove() if event.key==pygame.K_z: b.move() if event.type==pygame.KEYUP: if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT or event.key==pygame.K_UP or event.key==pygame.K_DOWN or event.key==pygame.K_z: a.X_bolen=False a.Y_bolen=False b.btbolen=False if event.type==UFOEVENT: u_appear=True u.appeared=True gameDisplay.blit(bg,bg_rect) if not u.appeared: #當飛碟沒出現時,畫面滾動 bg_y+=1 bg_y1+=1 gameDisplay.blit(bg,(bg_x,bg_y)) gameDisplay.blit(bg,(bg_x1,bg_y1)) if bg_y > 600: bg_y=-600 if bg_y1 > 600: bg_y1=-600 if u_appear: #當飛碟事件觸發時 pygame.mixer.music.pause() ufo_music.play(-1) ufoappear() s.reset1() #當補給物(火彈)被吃掉時,過一段時間會再出現 s1.reset1() #同上(補血) if s.visible: #補給物(火彈) gameDisplay.blit(s.image,s.rect) s.rect[1]+=s.supply_speed if s.rect[1] > 600: s.reset() if s1.visible: #補給物(補血) gameDisplay.blit(s1.image,s1.rect) s1.rect[1]+=s1.supply_speed if s1.rect[1] > 600: s1.reset() #飛機的生命值顯示(*3) if a_image2: gameDisplay.blit(pygame.transform.scale(a.image,(41,56)),(120,0)) if a_image1: gameDisplay.blit(pygame.transform.scale(a.image,(41,56)),(181,0)) if a_image: gameDisplay.blit(pygame.transform.scale(a.image,(41,56)),(242,0)) a.health(gameDisplay,red,0,0) #飛機血條 if a.active: #如果飛機存活 if a.X_bolen: a.rect[0]+=a.airplane_speedx b.rect[0]=a.rect[0]+25 fire_b.rect[0]=a.rect[0]-25 fire_b1.rect[0]=a.rect[0]+41 if a.rect[0]+71 > 800: a.rect[0]=729 if a.rect[0] < 0: a.rect[0]=0 if a.Y_bolen: a.rect[1]+=a.airplane_speedy if a.rect[1]+86 > 600: a.rect[1]=514 if a.rect[1] < 0: a.rect[1]=0 #使飛機有噴氣效果 if a.switch_name: gameDisplay.blit(a.image,a.rect) else: gameDisplay.blit(a1.image,a.rect) if not (delay%5): #延時效果,每五幀換一次 a.switch_name=not a.switch_name delay-=1 if not delay: delay=120 else: #飛機死亡 if bomb1.visible: myairplane_dead_sound.play() bomb1.draw(a.rect) bomb1.action() #飛機的生命值減掉 if index1==0: gameDisplay.blit(bg,(242,0),(242,0,41,56)) a_image=False if index1==1: gameDisplay.blit(bg,(181,0),(181,0,41,56)) a_image1=False if index1==2: gameDisplay.blit(bg,(120,0),(120,0,41,56)) a_image2=False game_start=False u.reset((143,-700)) l.reset((325,120)) u.appeared=False u.health=10000 ufo_music.stop() pygame.mixer.music.pause() gameover_music.play() game_over() if bomb1.otherairplane_alive: #爆炸播放完畢後 a.reset((x-300,y)) #飛機復位 a.airplane_speedy=0 b.rect[0]=x-300+25 #子彈復位 b.rect[1]=y fire_b.rect[0]=x-300-25 #火彈復位 fire_b1.rect[0]=x-300+61 fire_b.rect[1]=fire_b1.rect[1]=y index1+=1 if boss.rect[1] > -100: #如果大敵機的高度大於-100時,會出現補給物 if s.visible: #補給物(火彈) gameDisplay.blit(s.image,s.rect) s.rect[1]+=s.supply_speed if s.rect[1] > 600: s.reset() if s1.visible: #補給物(補血) gameDisplay.blit(s1.image,s1.rect) s1.rect[1]+=s1.supply_speed if s1.rect[1] > 600: s1.reset() #飛機與敵機,大敵機,補給物,飛碟的碰撞檢測 if pygame.sprite.spritecollide(a,otherairplanes,False,pygame.sprite.collide_rect_ratio(0.5)): if u.appeared==False: a.blood_len-=1 if a.blood_len <= 0: a.active=False bomb1.visible=True a.blood_len=100 if pygame.sprite.spritecollide(a,bullet_group,False,pygame.sprite.collide_rect_ratio(0.5)): if u.appeared==False: a.blood_len-=1 if a.blood_len <= 0: a.active=False bomb1.visible=True a.blood_len=100 if pygame.sprite.collide_rect_ratio(0.5)(boss,a): if u.appeared==False: a.blood_len-=5 if a.blood_len <= 0: a.active=False bomb1.visible=True a.blood_len=100 if pygame.sprite.collide_mask(a,s1): supply_sound.play() s1.visible=False a.blood_len+=50 if a.blood_len >= 100: a.blood_len=100 s1.reset() #補給物復位 if pygame.sprite.collide_mask(a,s): supply_sound.play() s.visible=False fire_b.fire_btbolen=True s.reset() #補給物復位 if pygame.sprite.collide_rect(a,l): if u.rect[1]==-74: a.Y_bolen=True a.airplane_speedy=-8 if pygame.sprite.collide_mask(a,u): if u.rect[1]==-74: a.blood_len-=40 if a.blood_len <= 0: a.active=False bomb1.visible=True a.blood_len=100 if pygame.sprite.spritecollide(a,ubgroup,False,pygame.sprite.collide_rect_ratio(0.4)): if u.ub_visible==True: a.blood_len-=15 if a.blood_len <= 0: a.active=False bomb1.visible=True a.blood_len=100 if b.btbolen: #按下z鍵發射子彈 bullet_sound.play() if launch: #當我方飛機不是在初始位置發射時,子彈的初始高度(y)存取我方飛機的高度 b.rect[1]=a.rect[1] launch=False gameDisplay.blit(b.image,b.rect) b.rect[1]+=b.bullet_speed if b.rect[1]<-60: b.rect[1]=a.rect[1] #子彈復位 gameDisplay.blit(b.image,b.rect) if fire_b.fire_btbolen: #發射火彈 fire_sound.play() if launch1: #同launch的作法 fire_b.rect[1]=a.rect[1] fire_b1.rect[1]=a.rect[1] launch1=False gameDisplay.blit(fire_b.image,fire_b.rect) gameDisplay.blit(fire_b1.image,fire_b1.rect) fire_b.rect[1]+=fire_b.fire_speed fire_b1.rect[1]+=fire_b1.fire_speed if fire_b.rect[1] < -60 or fire_b1.rect[1] < -60: fire_b.rect[1]=a.rect[1] #火彈復位 fire_b1.rect[1]=a.rect[1] index2+=1 if index2==500: #火彈持續時間 fire_b.fire_btbolen=False index2=0 #子彈與敵機的碰撞檢測 result=pygame.sprite.spritecollide(b,otherairplanes,False,pygame.sprite.collide_mask) if result: if b.btbolen: #子彈發射後 for r in result: r.active=False bombposition=r.rect bomb.visible=True bomb.otherairplane_alive=False if not u.appeared: for p in otherairplanes: if p.rect[1]>600: p.active=False bomb.otherairplane_alive=True if boss.add_other_speed: #當boss被打敗時,所有小敵機速度加2 p.o_speed+=2 for i in otherairplanes: if i.active: #如果敵機存活 gameDisplay.blit(i.image,i.rect) i.rect[1]+=i.o_speed else: #敵機死亡 if bomb.visible: other_dead_sound.play() bomb.draw(bombposition) bomb.action() if bomb.otherairplane_alive: i.reset(random.randint(0,775),random.randint(-250,-150)) #敵機復位 #子彈與大敵機的碰撞檢測 result1=pygame.sprite.collide_mask(b,boss) if result1: if u.appeared==False: if b.btbolen: b.rect[1]=a.rect[1] #打中之後,子彈復位 index+=1 if index==140: #打中一百四十發後大敵機死亡 boss.active=False boss.bombhappen=True boss.boss_relive=False index=0 #子彈與飛碟的碰撞檢測 if pygame.sprite.collide_rect_ratio(0.67)(b,u): if b.btbolen: b.rect[1]=a.rect[1] u.health-=3 if u.health <= 0: u.active=False u.bombhappen=True u.health=10000 #火彈與小敵機的碰檢 result3=pygame.sprite.groupcollide(otherairplanes,bullets,False,False,pygame.sprite.collide_mask) if result3: if fire_b.fire_btbolen: #火彈發射後 for rr in result3: rr.active=False bombposition=rr.rect bomb.visible=True bomb.otherairplane_alive=False #火彈與大敵機的碰撞檢測 result4=pygame.sprite.spritecollide(boss,bullets,False,pygame.sprite.collide_mask) if result4: if fire_b.fire_btbolen: fire_b.rect[1]=a.rect[1] fire_b1.rect[1]=a.rect[1] index3+=30 #火彈的殺傷力 if index3 >= 780: boss.active=False boss.bombhappen=True boss.boss_relive=False index3=0 #火彈與飛碟的碰撞檢測 if pygame.sprite.spritecollide(u,bullets,False,pygame.sprite.collide_rect_ratio(0.67)): if fire_b.fire_btbolen: fire_b.rect[1]=a.rect[1] fire_b1.rect[1]=a.rect[1] u.health-=70 if u.health <= 0: u.active=False u.bombhappen=True u.health=15000 if not u.appeared: if boss.rect[1] > 600: boss.reset((random.randint(0,500),-600)) b1.rect[0]=boss.rect[0] b2.rect[0]=boss.rect[0]+185 index=0 index3=0 s.visible=True #當大敵機活著飛到高度大於600時,會再度出現補給物s,s1 s1.visible=True if boss.active: #如果大敵機存活 boss.add_other_speed=False #關掉速度加1 gameDisplay.blit(boss.image,boss.rect) boss.rect[1]+=boss.boss_speed if boss.rect[1] > 0: #當大敵機出現時發射子彈 bullet_sound.play() gameDisplay.blit(b1.image,b1.rect) gameDisplay.blit(b2.image,b2.rect) b1.rect[1]+=b1.bullet_speed b2.rect[1]+=b2.bullet_speed if b1.rect[1] > 660 or b2.rect[1] > 660: b1.rect[1]=boss.rect[1] b2.rect[1]=boss.rect[1] else: #大敵機死亡 b.rect[1]=a.rect[1] if boss.bombhappen: boss_dead_sound.play() boss.draw(boss.rect) boss.action() if boss.boss_relive: boss.reset((random.randint(0,500),-600)) b1.rect[0]=boss.rect[0] b2.rect[0]=boss.rect[0]+185 s1.visible=True #出現補給物(補血) pygame.display.update() #畫面刷新 clock.tick(60) #遊戲幀率60幀
def _fire_bullet(self): """ Create a new bullet and add it to the bullets group """ if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)