def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.bottom, speedy=8, image=laser_enemy_img) all_sprites.add(bullet) enemies.add(bullet)
def shoot(self): temp_bullets = [] temp_bullets.append(Bullet(self.rect.centerx, self.rect.top)) if variables.scores >= 10: temp_bullets.append( Bullet(self.rect.centerx - 10, self.rect.top, speedx=-5, image=pygame.transform.rotate(laser_img, 32))) temp_bullets.append( Bullet(self.rect.centerx + 10, self.rect.top, speedx=5, image=pygame.transform.rotate(laser_img, -32))) for bullet in temp_bullets: all_sprites.add(bullet) bullets.add(bullet) shoot_sound.play()
def run(self): mainloop = True while mainloop: self.clock.tick(50) self.screen.fill([0, 0, 0]) self.screen.blit(self.bg, self.bg_rect) # Close the game when the red cross is clicked for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Keyboard Events keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.spaceship.sprite.x -= 10 if self.spaceship.shooting is False: self.bullet.sprite.x -= 10 elif keys[pygame.K_RIGHT]: self.spaceship.sprite.x += 10 if self.spaceship.shooting is False: self.bullet.sprite.x += 10 elif keys[pygame.K_SPACE]: self.spaceship.shoot = True elif keys[pygame.K_ESCAPE]: # Go back to the game menu mainloop = False self.escape_selected = True pygame.mixer.music.rewind() if self.spaceship.shoot is True: self.laser_sound.play() if self.bullet.sprite.y > 0 and self.invader_exploding is False: self.spaceship.shooting = True self.bullet.sprite = self.bullet.sprite.move([0, -6]) else: self.laser_sound.fadeout(1000) self.bullet.sprite.x, self.bullet.sprite.y = ( self.spaceship.sprite.x + self.spaceship.sprite.width / 2, self.spaceship.sprite.y) self.spaceship.shoot = False self.spaceship.shooting = False self.invader_exploding = False item_to_remove = None # Invader Colision + Vertical Movement # Allow slowly vertical movement if self.timecount_m > self.nasty_move_time: self.invaders_moving = True else: self.invaders_moving = False self.timecount_m += self.clock.get_time() if len(self.invaders) > 0: for i, invader in enumerate(self.invaders): if invader.sprite.collidepoint(self.bullet.sprite.x, self.bullet.sprite.y): item_to_remove = i self.invader_exploding = True else: if self.invaders_moving and not self.game_over: invader.sprite.y += 15 self.timecount_m = 0 self.screen.blit(invader.image, invader.sprite) # Remove dead invaders: if item_to_remove is not None: del self.invaders[item_to_remove] if not self.has_already_chosen: # Select random invader among survivor invaders if len(self.invaders) > 0 and not self.game_over: if len(self.invaders) is not 1: self.randinvader = self.invaders[randint( 1, len(self.invaders) - 1)] else: self.randinvader = self.invaders[0] self.has_already_chosen = True posx = self.randinvader.sprite.x width = self.randinvader.sprite.width height = self.randinvader.sprite.height posy = self.randinvader.sprite.y self.ennemybullet = Bullet( (posx + width / 2, posy + height)) else: self.victory = True self.timecount += self.clock.get_time() # Handle the bullet shot by the random invader if self.timecount > self.nasty_shoot_time and self.has_already_chosen: self.timecount = 0 self.has_already_chosen = False elif self.timecount < self.nasty_shoot_time and self.has_already_chosen: if self.ennemybullet.sprite.y < self.scr_height: self.ennemybullet.sprite = self.ennemybullet.sprite.move( [0, 6]) self.screen.blit(self.ennemybullet.image, self.ennemybullet.sprite) # Shuttle Displaying and Colision if self.spaceship.sprite.collidepoint( self.ennemybullet.sprite.x, self.ennemybullet.sprite.y ) and self.spaceship.exploding is False: self.timecount = self.nasty_shoot_time self.has_already_chosen = False self.spaceship.exploding = True else: self.screen.blit(self.bullet.image, self.bullet.sprite) self.screen.blit(self.spaceship.image, self.spaceship.sprite) # Life Management and Displaying if self.spaceship.exploding: self.spaceship.exploding = False if len(self.lifes) > 0: self.lifes.pop() else: self.game_over = True self.spaceship.exploding = False # Remaining lifes pygame.draw.rect(self.screen, (255, 255, 255), [self.scr_width - 120, 0, 120, 40], 1) for life in self.lifes: self.screen.blit(life.image, life.sprite) if self.victory: self.screen.blit(self.label_victory, (self.scr_width / 2 - self.label_victory.get_rect().width / 2, self.scr_height / 2 - self.label_victory.get_rect().height / 2)) if self.game_over: self.screen.blit(self.label_game_over, (self.scr_width / 2 - self.label_game_over.get_rect().width / 2, self.scr_height / 2 - self.label_game_over.get_rect().height / 2)) pygame.display.flip() if self.game_over or self.victory: pygame.time.delay(4000) mainloop = False
def __init__(self, screen): self.screen = screen self.scr_width = self.screen.get_rect().width self.scr_height = self.screen.get_rect().height self.screen_size = self.scr_width, self.scr_height # Background Game self.bg = pygame.image.load("resources/images/starsbackground.jpg") self.bg_rect = self.bg.get_rect() # Sound Game self.laser_sound = pygame.mixer.Sound( 'resources/sounds/laser_shot.wav') self.laser_sound.set_volume(0.2) # Labels self.font = pygame.font.SysFont(None, 100) self.label_game_over = self.font.render("Game Over", 1, (255, 255, 255)) self.label_victory = self.font.render("Victory is yours", 1, (255, 255, 255)) # Life Bar self.lifes = [] self.lifes_number = 3 # Invaders self.invaders = [] self.invaders_number = 10 # Spaceship and bullets self.spaceship = Spaceship(self.screen_size) self.init_pos_bullet = (self.spaceship.sprite.x + self.spaceship.sprite.width / 2, self.spaceship.sprite.y) self.bullet = Bullet(self.init_pos_bullet) self.game_over = False self.victory = False self.escape_selected = False # Objects initialisation self.randinvader = () self.ennemybullet = () # Invaders self.has_already_chosen = False # Go down every second self.nasty_move_time = 1000 # Invader shoot duration self.nasty_shoot_time = 1000 self.invaders_moving = False self.invader_exploding = False # Time Variables self.clock = pygame.time.Clock() # Timer for invaders vertical moving self.timecount_m = 0 # Time for invader bullet vertical moving self.timecount = 0 # Init Invaders self.init_x = 10 for i in range(self.invaders_number): self.invaders.append(Invader((self.init_x, 10))) self.init_x += 50 # Init life bar self.init_life_x = self.scr_width - 120 for i in range(self.lifes_number): self.lifes.append(Life((self.init_life_x, 0))) self.init_life_x += 40
def main(): """ Main Program """ # Call this function so the Pygame library can initialize itself pygame.init() # Create a 500x500 sized screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE) pygame.display.set_caption("my-py-game") # Create the player paddle object player = Player(64, 64) # List of moving sprites moving_sprites = pygame.sprite.Group() moving_sprites.add(player) # List of all sprites all_sprites_list = pygame.sprite.Group() # List of all bullets bullet_list = pygame.sprite.Group() level_changed = True current_level_x = 0 current_level_y = 0 font = pygame.font.Font(None, 30) clock = pygame.time.Clock() done = False while not done: # --- Event Processing --- for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # if event.type == pygame.VIDEORESIZE: # old_screen_saved = screen # screen = pygame.display.set_mode((event.w, event.h), # pygame.RESIZABLE) # # On the next line, if only part of the window # # needs to be copied, there's some other options. # screen.blit(old_screen_saved, (0, 0)) # del old_screen_saved if event.type == pygame.MOUSEBUTTONDOWN: # Fire a bullet if the user clicks the mouse button # Get the mouse position pos = pygame.mouse.get_pos() mouse_x = pos[0] mouse_y = pos[1] # Create the bullet based on where we are, and where we want to go. bullet = Bullet(player.rect.centerx, player.rect.centery, mouse_x, mouse_y) # Add the bullet to the lists all_sprites_list.add(bullet) bullet_list.add(bullet) moving_sprites.add(bullet) if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.changespeed(-PLAYER_SPEED, 0) player.set_direction('left') if event.key == pygame.K_d: player.changespeed(PLAYER_SPEED, 0) player.set_direction('right') if event.key == pygame.K_w: player.changespeed(0, -PLAYER_SPEED) if event.key == pygame.K_s: player.changespeed(0, PLAYER_SPEED) if event.type == pygame.KEYUP: if event.key == pygame.K_a: player.changespeed(PLAYER_SPEED, 0) if event.key == pygame.K_d: player.changespeed(-PLAYER_SPEED, 0) if event.key == pygame.K_w: player.changespeed(0, PLAYER_SPEED) if event.key == pygame.K_s: player.changespeed(0, -PLAYER_SPEED) # --- Game Logic --- if level_changed: if current_level_x == 0 and current_level_y == 0: # print('Entering level 1') current_level = Level(1) else: # print('Entering level 2') current_level = Level(2) current_level.draw_bg_tiles(screen) current_level.draw_walls(screen) pygame.display.flip() level_changed = False # Dirty rects are all the rects that need to be updated at the end of this frame dirty_rects = [] # get tiles intersecting player bg_to_draw = [] for bg_tile in current_level.bg_tiles: if bg_tile.rect.colliderect(player.rect): bg_to_draw.append(bg_tile) for bullet in bullet_list: if bg_tile.rect.colliderect(bullet.rect): bg_to_draw.append(bg_tile) # add those tiles to dirty rects dirty_rects.extend([bg_tile.rect for bg_tile in bg_to_draw]) dirty_rects.append(player.rect) player.move(current_level.wall_tiles) # Changing between levels if player.rect.y < -TILE_WIDTH / 2 and current_level_y == 0: level_changed = True current_level_y += 1 player.rect.y = SCREEN_HEIGHT - TILE_WIDTH / 2 - 1 if player.rect.y > SCREEN_HEIGHT - TILE_WIDTH / 2 and current_level_y > 0: level_changed = True current_level_y -= 1 player.rect.y = -TILE_WIDTH / 2 + 1 for bullet in bullet_list: bullet.update(current_level.wall_tiles) # --- Drawing --- # draw walls and player for bg_tile in bg_to_draw: bg_tile.draw_to_screen(screen) for bullet in bullet_list: screen.blit(bullet.image, bullet.rect) screen.blit(player.image, player.rect) # print(dirty_rects) if SHOW_FPS: fps = font.render(str(int(clock.get_fps())), True, pygame.Color('white')) fps_bg_image = pygame.Surface([32, 32]) fps_bg_image.fill(BLACK) screen.blit(fps_bg_image, (0, 0)) screen.blit(fps, (0, 0)) dirty_rects.append(fps_bg_image.get_rect()) pygame.display.update(dirty_rects) clock.tick(60) pygame.quit()
def fire_bullet(ai_settings, screen, ship, bullets): """Fire a bullet if limit is not reached yet.""" # Create a new bullet and add it to the bullets group if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullets(settings, screen, ship, bullets): new_bullet = Bullet(settings, screen, ship) bullets.add(new_bullet)
def shoot(self): if self.coolDownCounter == 0: bullet = Bullet(self.x, self.y, self.bulletImg) self.bullets.append(bullet) self.coolDownCounter = 1
def fire_bullet(bullets, setting, screen, ship): # 创建新子弹,限制最大子弹数 if len(bullets) < setting.bullet_allow: new_bullet = Bullet(setting, screen, ship) bullets.add(new_bullet)
def test_can_create_a_valid_bullet(self): bullet = Bullet(self.get_size()) self.check_instance(bullet.image, pygame.Surface)
def fire_bullet(screen, ai_settings, ship, bullets): if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def shoot(self, KEYS, K_space, Screen, S_height): """Create the bullets and append it""" if KEYS[K_space]: B = Bullet(self.x + self.width / 2, self.y, Screen) self.bullets.append(B)
def logic(exp_number=None): """ Main logic of the simulation. Here, initialization and movement of agents is happening. exp_number: An integer that will be used for the name of the text file for the results. If it's set to None, results text file is not going to be created. """ if not sys.warnoptions: warnings.simplefilter("ignore") """Set PyGame settings""" # To show counter, font needs to be initialized pygame.font.init() # Set window width/height and name of window WIDTH, HEIGHT = 1000, 800 # The main window to show the running simulation WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Agent Simulation") # Using the font to display surviving agents main_font = pygame.font.SysFont("comicsans", int(WIDTH / 25)) """Load everything needed for the simulation""" # Load JSON file json_service_obj = JsonService() CONFIG_DICT = json_service_obj.get_json_dict() print(CONFIG_DICT) random.seed(CONFIG_DICT['random_seed']) # Get directory of current file SOURCE_FILE_DIR = os.path.dirname(os.path.abspath(__file__)) print(SOURCE_FILE_DIR) # Load assets ASSETS_DIR = os.path.join(SOURCE_FILE_DIR, "assets") # Drone RED_AGENT = pygame.transform.scale( pygame.image.load(os.path.join(ASSETS_DIR, "pixel_ship_red_small.png")), (40, 30)) # Lasers RED_LASER = pygame.transform.scale( pygame.image.load(os.path.join(ASSETS_DIR, "pixel_laser_red.png")), (50, 40)) # Backgrond BG = pygame.transform.scale( pygame.image.load(os.path.join(ASSETS_DIR, "background-black.png")), (WIDTH, HEIGHT)) waves_of_bullets = 0 tick_counter = 0 agents_to_wave = dict() comp_time_to_wave = dict() ms1 = int(round(time.time() * 1000)) run = True # To make the main loop run FPS = 120 # Pygame FPS survived_agents = 0 # Count the number of agents surviving agents = [] # List to store all the agents on screen bullets = [] # List to store all the bullets on the screen # An object to help track time, will be used to run pygame on specific FPS clock = pygame.time.Clock() bullet_time = 500 / CONFIG_DICT['sim_speed'] # milisecond xpos = 40 xxpos = int((WIDTH - xpos * 2) / (CONFIG_DICT['wave_length'] - 1)) number_waves = CONFIG_DICT['no_of_waves'] just_once = False bool_loc, bool_config, bool_perm_config, bool_move = True, True, True, True def redraw_window(): """ This function can only be called in "main" Function. Basically updates window every frame blit draws the image on the background at the given coordinates. """ WIN.blit(BG, (0, 0)) # Drawing counter on the screen counter_label = main_font.render(f"Agents Survived: {survived_agents}", 1, (255, 255, 255)) WIN.blit(counter_label, (10, 10)) pygame.draw.line(WIN, (255, 0, 0), (0, 150), (WIDTH, 150), 2) for agent in agents: # Every screen update, draw the agents present in the agents[] list # on the screen agent.draw(WIN) for bullet in bullets: # Every screen update, draw the bullets present in the bullets[] # list on screen bullet.draw(WIN) # Updates the entire surface/screen every loop pygame.display.update() while run: # Means that for every second at most "FPS" frames should pass. Here, clock.tick(FPS) start_while_time = datetime.now() agents_to_wave[tick_counter] = survived_agents + len(agents) tick_counter += 1 xpos = 40 # x-Position of the initial agent. Hard coded. # Logic states, If there is no agent on the screen and the required # number of waves have not gone already, send in the next wave if len(agents) == 0 and number_waves > 0: # initialising to run the loop "length" number of times to create # the required number of agents for i in range(CONFIG_DICT['wave_length']): agent = Agent(x=xpos, y=random.randrange(HEIGHT - 100, HEIGHT), config_dict=CONFIG_DICT, ship_img=RED_AGENT) # Add the new initialized agent to the agent list agents.append(agent) xpos += xxpos # Incresing Xpos value for next agent number_waves -= 1 # Decreasing value after each wave sent ms2 = int(round(time.time() * 1000)) xpos = 40 # Since we're using a grid patern, bullets should start at the same point as agents # Logic states, if there is no bullet present on screen and if there # are still some surviving agents, make new bullets if ms2 - ms1 > bullet_time and len(agents) != 0: waves_of_bullets += 1 ms1 = ms2 just_once = True for i in range( CONFIG_DICT['wave_length'] ): # Create same number of bullets as number of agents # Start them at the same Xpos, but subtract its own size so it # centres on the grid and in the straight line with the agent bullet = Bullet(x=xpos, y=0, bullet_img=RED_LASER) # This line is used to send in a random wave of bullets every # time if (random.randrange(0, 100)) % 2 == 0: # The bullet is only appended to the bullet_list. # "bullets[]" if the condition is met. bullets.append(bullet) # It is done so that we can have random number of bullets # at random places every wave of bullets xpos += xxpos # Increase Xpos value for next bullet for event in pygame.event.get(): # In case someone presses a button if event.type == pygame.QUIT: # If the button pressebd is "X" in the top right to close the window, then the simulation should stop pygame.quit() sys.exit() run = False # Stop the main while loop on closing if len(agents) == 0 and len(bullets) == 0: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and just_once == False: agents[0].health = 1 agents[4].health = 1 just_once = True survived_agents = move_agents(agents, survived_agents, CONFIG_DICT['agent_vel']) for bullet in bullets: # Similar loop description as for agents but for bullets bullet.move(CONFIG_DICT['bullet_vel']) if bullet.y > HEIGHT: # If bullet goes offscreen when moving downwards, then # Remove the bullet from the list of bullets bullets.remove(bullet) # And since we're in the loop of moving all bullets, we check # if they collide with an agent for agent in agents: # Checking for all agents in one go try: if collide( agent, bullet ): # If two objects (agent object and bullet object) collide as defined in the function above # print("Hit") # #Print console log "Hit" for testing # Once the bullet hits, we remove it from the # simulation bullets.remove(bullet) # And the agent that the bullet hit gets 1 minus # health. agent.health -= 1 if agent.health == 0: # We check if the agent has 0 hp, that means the agent died. # If agent is dead, we remove it from the screen agents.remove(agent) except ValueError: pass if CONFIG_DICT['communication'] == 'centralized' or CONFIG_DICT[ 'communication'] == 'decentralized': if CONFIG_DICT['communication'] == 'centralized': agents, bool_loc, bool_config, bool_perm_config, bool_move = centralized_logic( agents, xxpos, CONFIG_DICT, bool_loc, bool_config, bool_perm_config, bool_move) for agent in agents[:]: for tnega in agents: if agent != tnega: if abs(agent.x - tnega.x) < CONFIG_DICT[ 'cover_radius'] and agent.health == 1 and agent.cover == False and tnega.health != 1 and CONFIG_DICT[ 'to_cover'] == True and tnega.cost != 0: cover(agent, tnega) agent.cover = True tnega.cost -= 1 # Finally, redraw_window function is called to update every object on # the screen for the next frame redraw_window() end_while_time = datetime.now() comp_time = end_while_time - start_while_time # Saving in microseconds comp_time_to_wave[tick_counter] = comp_time.microseconds if len(agents) == 0: pygame.quit() run = False del agents_to_wave[0] results_service_obj = ResultService(config_dict=CONFIG_DICT, num_survived_agents=survived_agents, exp_number=exp_number, waves_of_bullets=waves_of_bullets, agents_to_wave=agents_to_wave, comp_time_to_wave=comp_time_to_wave) results_service_obj.save_results()
isStopped = False while run: if isStopped: show_start_screen() isStopped = False clock.tick(FPS) # проверка пункта 1 for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keystate = pygame.key.get_pressed() if keystate[pygame.K_SPACE]: if isBulletActive == False: isBulletActive = True bullet = Bullet(all_zombies.sprites()[0]) all_sprites.add(bullet) player.score -= 1 if keystate[pygame.K_ESCAPE]: isStopped = True hits = pygame.sprite.spritecollide(player, all_zombies, False) for hit in hits: player.hit() if (player.hp <= 0): run = False hits = pygame.sprite.spritecollide(player, all_walls, False) for hit in hits: player.hitwall(wall, keystate)