def animate(self, x): """ Move everything """ self.frame_count += 1 if self.frame_count % 60 == 0: print(self.frame_count) if not self.game_over: self.all_sprites_list.update() for bullet in self.bullet_list: asteroids = \ arcade.check_for_collision_with_list(bullet, self.asteroid_list) for asteroid in asteroids: self.split_asteroid(asteroid) asteroid.kill() bullet.kill() if not self.player_sprite.respawning: asteroids = \ arcade.check_for_collision_with_list(self.player_sprite, self.asteroid_list) if len(asteroids) > 0: if self.lives > 0: self.lives -= 1 self.player_sprite.respawn() self.split_asteroid(asteroids[0]) asteroids[0].kill() self.ship_life_list.pop().kill() print("Crash") else: self.game_over = True print("Game over")
def animate(self, x): self.physics_engine.update() q = WINDOW_WIDTH / 4 if self.player_sprite.center_x - self.ortho_left > q * 3: self.ortho_left = self.player_sprite.center_x - q * 3 arcade.set_viewport(self.ortho_left, WINDOW_WIDTH + self.ortho_left, 0, WINDOW_HEIGHT) if self.player_sprite.center_x - self.ortho_left < q: self.ortho_left = self.player_sprite.center_x - q arcade.set_viewport(self.ortho_left, WINDOW_WIDTH + self.ortho_left, 0, WINDOW_HEIGHT) coins_hit = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) for coin in coins_hit: coin.kill() self.score += 1 arcade.draw_text("Score: {}".format(self.score), 5, 5, arcade.color.BLACK, 14)
def animate(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this # example though.) self.all_sprites_list.update() # Loop through each bullet for bullet in self.bullet_list: # Check this bullet to see if it hit a coin hit_list = arcade.check_for_collision_with_list(bullet, self.coin_list) # If it did, get rid of the bullet if len(hit_list) > 0: bullet.kill() # For every coin we hit, add to the score and remove the coin for coin in hit_list: coin.kill() self.score += 1 # Hit Sound arcade.sound.play_sound(self.hit_sound) # If the bullet flies off-screen, remove it. if bullet.bottom > SCREEN_HEIGHT: bullet.kill()
def animate(self, delta_time): """ Movement and game logic """ self.all_sprites_list.update() self.all_sprites_list.update_animation() # Generate a list of all sprites that collided with the player. hit_list = \ arcade.check_for_collision_with_list(self.player, self.coin_list) # Loop through each colliding sprite, remove it, and add to the score. for coin in hit_list: coin.kill() self.score += 1
def animate(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this # example though.) self.all_sprites_list.update() # Generate a list of all sprites that collided with the player. hit_list = \ arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each colliding sprite, remove it, and add to the score. for coin in hit_list: coin.kill() self.score += 1
def animate(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this # example though.) self.all_sprites_list.update() # Generate a list of all sprites that collided with the player. hit_list = \ arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each colliding sprite, change it, and add to the score. for coin in hit_list: # Have we collected this? if not coin.changed: # No? Then do so coin.texture = arcade.load_texture("images/bumper.png") coin.changed = True coin.width = 30 coin.height = 30 self.score += 1
def on_update(self, delta_time): self.frame_count += 1 self.shoot_delay -= 1 self.physics_engine.update() changed = False if arcade.check_for_collision_with_list( self.player_sprite, self.thunder_list) or arcade.check_for_collision_with_list( self.player_sprite, self.bullet_list): self.player_sprite.change_x = 0 self.player_sprite.change_y = 0 self.player_sprite.center_x = player_start_x self.player_sprite.center_y = player_start_y self.view_bottom = 0 changed = True self.ammo_count = 3 self.score = 0 self.reset_map(self.current_level) if arcade.check_for_collision_with_list(self.player_sprite, self.finishing_line_list): self.player_sprite.change_x = 0 self.player_sprite.change_y = 0 self.player_sprite.center_x = player_start_x self.player_sprite.center_y = player_start_y self.view_bottom = 0 changed = True self.score += self.ammo_count * 5 self.ammo_count = 3 self.level += 1 self.current_level = f"Map_{self.level}.tmx" self.reset_map(self.current_level) clip_list = arcade.check_for_collision_with_list( self.player_sprite, self.ammo_list) for clip in clip_list: clip.remove_from_sprite_lists() self.ammo_count += 1 top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed = True bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed = True if changed: self.view_bottom = int(self.view_bottom) arcade.set_viewport(0, SCREEN_WIDTH, self.view_bottom, SCREEN_HEIGHT + self.view_bottom) for enemy in self.plane_list: start_x = enemy.center_x start_y = enemy.center_y dest_x = self.player_sprite.center_x dest_y = self.player_sprite.center_y x_diff = dest_x - start_x y_diff = dest_y - start_y if math.sqrt((x_diff * x_diff) + (y_diff * y_diff)) < 700: angle = math.atan2(y_diff, x_diff) enemy.angle = math.degrees(angle) + 90 if self.frame_count % 120 == 0: bullet = arcade.Sprite("Sprites\Bullet\Bullet.png") bullet.center_x = start_x bullet.center_y = start_y bullet.angle = math.degrees(angle) - 90 bullet.change_x = math.cos(angle) * BULLET_SPEED * 5 bullet.change_y = math.sin(angle) * BULLET_SPEED * 5 self.bullet_list.append(bullet) for bullet in self.bullet_list: if math.sqrt(( (self.player_sprite.center_x - bullet.center_x) * (self.player_sprite.center_x - bullet.center_x)) + ( (self.player_sprite.center_y - bullet.center_y) * (self.player_sprite.center_y - bullet.center_y))) > 800: bullet.remove_from_sprite_lists() hit_list = arcade.check_for_collision_with_list( bullet, self.thunder_list) if len(hit_list) > 0: bullet.remove_from_sprite_lists() for thunder in hit_list: thunder.remove_from_sprite_lists() self.bullet_list.update() self.player_bullet_list.update() for player_bullet in self.player_bullet_list: hit_list = arcade.check_for_collision_with_list( player_bullet, self.plane_list) if len(hit_list) > 0: player_bullet.remove_from_sprite_lists() for plane in hit_list: plane.remove_from_sprite_lists() self.score += 10
def update_friction(self, oil_list): if arcade.check_for_collision_with_list(self, oil_list): self.friction_current = self.friction_base / 5 else: self.friction_current = self.friction_base
def update(self, other_player, powerups, window): self.sprite_list.update() # Update Player sprite (spaceship) self.mines.update() # Update mines self.bullets.update() # Update bullets # Burst Emitter for e in self.emitters: e.update() # Cool down laser self.cooldown += 1 # Cool down mine self.m_cooldown += 1 # Calculate distance between players used below dx = self.sprite.center_x - other_player.sprite.center_x # x difference dy = self.sprite.center_y - other_player.sprite.center_y # y difference d = np.sqrt(np.square(dx) + np.square(dy)) # distance - credit goes to Pythagoras # AI actions # Is it single player mode with AI enemy? if self.isAI: if dy != 0: if constants.AI_PREDICTIVE == 0: a = np.rad2deg(np.arctan( dx / dy)) # Calc angle to aim in degrees else: # Predictive calc angle to aim taking into account player velocity t = d / constants.BULLET_SPEED # Approx. time bullet will travel # Difference taking into account opponent speed vectors dx1 = self.sprite.center_x - ( other_player.sprite.center_x + other_player.sprite.change_x * t) dy1 = self.sprite.center_y - ( other_player.sprite.center_y + other_player.sprite.change_y * t) a = np.rad2deg(np.arctan( dx1 / dy1)) # Calc predicted angle to aim if dy < 0: self.sprite.angle = -a # Set AI player's sprite angle else: self.sprite.angle = -a + 180 # Set AI player's sprite angle # Accelerate if distance > 300 for close combat action if d > 300: self.accelerate() else: self.coast() # Shoot lasers randomly if not randint(0, constants.AI_SHOOT_PACE): self.shoot() # Drop mine randomly if not randint(0, constants.AI_SHOOT_PACE): self.mine() # END AI actions # PLAYER TO PLAYER COLLISION # Player 1 vs Player 2 collision # See above dx, dy, and d used in below calculations # Collision logic is explained in Collisions.ipynb and Collisions.xlsx under data folder # Check if we are not overlapping P1 and P2 and turn on collision for players if d > self.sprite.width / 2 + other_player.sprite.width / 2 and \ d > self.sprite.height / 2 + other_player.sprite.height / 2: self.collision_on = True # If players have collided and collision flag is on for both players: if arcade.check_for_collision(self.sprite, other_player.sprite) and \ self.collision_on and other_player.collision_on: # Turn off collisions to avoid multiple collision events at the same time self.collision_on = False vn1 = self.sprite.speed[0] * dx / d + self.sprite.speed[1] * dy / d vt1 = -self.sprite.speed[0] * dy / d + self.sprite.speed[1] * dx / d vn2 = other_player.sprite.speed[ 0] * dx / d + other_player.sprite.speed[1] * dy / d vt2 = -other_player.sprite.speed[ 0] * dy / d + other_player.sprite.speed[1] * dx / d self.sprite.speed[0] = vn2 * dx / d - vt1 * dy / d self.sprite.speed[1] = vn2 * dy / d + vt1 * dx / d other_player.sprite.speed[0] = vn1 * dx / d - vt2 * dy / d other_player.sprite.speed[1] = vn1 * dy / d + vt2 * dx / d # END COLLISION CHECKS # Check if player hits mine ship_hits = arcade.check_for_collision_with_list( self.sprite, other_player.mines) for hit in ship_hits: hit.remove_from_sprite_lists() # Get rid of the lucky mine self.boom() # Explosion self.health -= constants.MINE_DAMAGE # Do damage decreasing health # Check if any bullets have landed onto Players # Check Player 1 first ship_hits = arcade.check_for_collision_with_list( self.sprite, other_player.bullets) for hit in ship_hits: hit.remove_from_sprite_lists() # Get rid of the lucky bullet self.boom() # Explosion self.health -= constants.HIT_DAMAGE # Do damage decreasing health # DEATH IS INEVITABLE # If Player is out of health if self.health <= 0: if self.isAI == 0 and other_player.isAI == 0: # 2 Player game, other player wins game_over_view = menus.GameOverView(other_player.name + " wins!") elif self.isAI == 0 and other_player.isAI == 1: # Single player game, player loose game_over_view = menus.GameOverView("You loose! :(") else: # Single player game, player wins game_over_view = menus.GameOverView("You won! :)") window.show_view(game_over_view) # Check if player hit power-up ship_hits = arcade.check_for_collision_with_list(self.sprite, powerups) for hit in ship_hits: hit.remove_from_sprite_lists() # Get rid of the power up if self.bullet_cooldown > constants.POWERUP_EFFECT: self.bullet_cooldown -= constants.POWERUP_EFFECT # Upgrade - decrease laser cool down time # Drop new powerup powerup = arcade.Sprite( utils.resource_path(os.path.join('data', 'powerup.png')), 0.3) powerup.center_x = randint(0 + 20, constants.SCREEN_WIDTH - 20) powerup.center_y = randint(0 + 20, constants.SCREEN_HEIGHT - 20) powerup.change_x = 0 powerup.change_y = 0 powerup.change_angle = -5 powerups.append(powerup) # Get rid of bullets that flew out of the screen for bullet in self.bullets: if bullet.top < 0 or bullet.bottom > constants.SCREEN_HEIGHT or \ bullet.right < 0 or bullet.left > constants.SCREEN_WIDTH: bullet.remove_from_sprite_lists()
def on_update(self, delta_time: float): """movement and game logic""" # move player with physics! self.physics_engine.update() # coin hit check coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # remove collected coins for coin in coin_hit_list: # get coin cost if 'Points' not in coin.properties: print("Warning! no coin cost!") print(coin) else: cost = int(coin.properties['Points']) self.score += cost coin.remove_from_sprite_lists() arcade.play_sound(self.coin_collect_sfx) # key hit check key_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.key_list) # remove collected key for key in key_hit_list: key.remove_from_sprite_lists() arcade.play_sound(self.key_collect_sfx) self.keys += 1 # handle scrolling changed = False # scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed = True # scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed = True # scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed = True # scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed = True if changed: self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def setup(self): self.wall_list = arcade.SpriteList() self.player_list = arcade.SpriteList() # Create cave system using a 2D grid dg = RLDungeonGenerator(GRID_WIDTH, GRID_HEIGHT) dg.generate_map() # Create sprites based on 2D grid if not MERGE_SPRITES: # This is the simple-to-understand method. Each grid location # is a sprite. for row in range(dg.height): for column in range(dg.width): value = dg.dungeon[row][column] if value == '#': wall = arcade.Sprite("images/grassCenter.png", WALL_SPRITE_SCALING) wall.center_x = column * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2 wall.center_y = row * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2 self.wall_list.append(wall) else: # This uses new Arcade 1.3.1 features, that allow me to create a # larger sprite with a repeating texture. So if there are multiple # cells in a row with a wall, we merge them into one sprite, with a # repeating texture for each cell. This reduces our sprite count. for row in range(dg.height): column = 0 while column < dg.width: while column < dg.width and dg.dungeon[row][column] != '#': column += 1 start_column = column while column < dg.width and dg.dungeon[row][column] == '#': column += 1 end_column = column - 1 column_count = end_column - start_column + 1 column_mid = (start_column + end_column) / 2 wall = arcade.Sprite("images/grassCenter.png", WALL_SPRITE_SCALING, repeat_count_x=column_count) wall.center_x = column_mid * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2 wall.center_y = row * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2 wall.width = WALL_SPRITE_SIZE * column_count self.wall_list.append(wall) # Set up the player self.player_sprite = arcade.Sprite("images/character.png", PLAYER_SPRITE_SCALING) self.player_list.append(self.player_sprite) # Randomly place the player. If we are in a wall, repeat until we aren't. placed = False while not placed: # Randomly position self.player_sprite.center_x = random.randrange(AREA_WIDTH) self.player_sprite.center_y = random.randrange(AREA_HEIGHT) # Are we in a wall? walls_hit = arcade.check_for_collision_with_list( self.player_sprite, self.wall_list) if len(walls_hit) == 0: # Not in a wall! Success! placed = True self.physics_engine = arcade.PhysicsEngineSimple( self.player_sprite, self.wall_list)
def update(self, delta_time): # Start update timer start_time = timeit.default_timer() self.player_list.update() if self.player.center_x < 0 and self.player.change_x < 0: self.player.change_x *= -1 if self.player.center_y < 0 and self.player.change_y < 0: self.player.change_y *= -1 if self.player.center_x > SCREEN_WIDTH and self.player.change_x > 0: self.player.change_x *= -1 if self.player.center_y > SCREEN_HEIGHT and self.player.change_y > 0: self.player.change_y *= -1 coin_hit_list = arcade.check_for_collision_with_list( self.player, self.coin_list) for coin in coin_hit_list: coin.center_x = random.randrange(SCREEN_WIDTH) coin.center_y = random.randrange(SCREEN_HEIGHT) # Save the time it took to do this. self.processing_time = timeit.default_timer() - start_time # Total time program has been running total_program_time = int(timeit.default_timer() - self.program_start_time) # Print out stats, or add more sprites if total_program_time > self.last_fps_reading: self.last_fps_reading = total_program_time # It takes the program a while to "warm up", so the first # few seconds our readings will be off. So wait some time # before taking readings if total_program_time > 5: # We want the program to run for a while before taking # timing measurements. We don't want the time it takes # to add new sprites to be part of that measurement. So # make sure we have a clear second of nothing but # running the sprites, and not adding the sprites. if total_program_time % 2 == 1: output = f"{total_program_time}, {len(self.coin_list)}, {self.fps.get_fps():.1f}, " \ f"{self.processing_time:.4f}, {self.draw_time:.4f}\n" print(output, end="") self.results_file.write(output) if len(self.coin_list) >= STOP_COUNT: pyglet.app.exit() return # Take timings print( f"{total_program_time}, {len(self.coin_list)}, {self.fps.get_fps():.1f}, " f"{self.processing_time:.4f}, {self.draw_time:.4f}") self.sprite_count_list.append(len(self.coin_list)) self.fps_list.append(round(self.fps.get_fps(), 1)) self.processing_time_list.append(self.processing_time) self.drawing_time_list.append(self.draw_time) # Now add the coins self.add_coins()
def on_update(self, delta_time): """ Movement and game logic """ # Move the player with the physics engine self.physics_engine.update() # Update animations if self.physics_engine.can_jump(): self.player_sprite.can_jump = False else: self.player_sprite.can_jump = True if self.physics_engine.is_on_ladder() and not self.physics_engine.can_jump(): self.player_sprite.is_on_ladder = True self.process_keychange() else: self.player_sprite.is_on_ladder = False self.process_keychange() self.coin_list.update_animation(delta_time) self.background_list.update_animation(delta_time) self.player_list.update_animation(delta_time) # Update walls, used with moving platforms self.wall_list.update() # See if the moving wall hit a boundary and needs to reverse direction. for wall in self.wall_list: if wall.boundary_right and wall.right > wall.boundary_right and wall.change_x > 0: wall.change_x *= -1 if wall.boundary_left and wall.left < wall.boundary_left and wall.change_x < 0: wall.change_x *= -1 if wall.boundary_top and wall.top > wall.boundary_top and wall.change_y > 0: wall.change_y *= -1 if wall.boundary_bottom and wall.bottom < wall.boundary_bottom and wall.change_y < 0: wall.change_y *= -1 # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Figure out how many points this coin is worth if 'Points' not in coin.properties: print("Warning, collected a coin without a Points property.") else: points = int(coin.properties['Points']) self.score += points # Remove the coin coin.remove_from_sprite_lists() arcade.play_sound(self.collect_coin_sound) # Track if we need to change the viewport changed_viewport = False # --- Manage Scrolling --- # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed_viewport = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed_viewport = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed_viewport = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed_viewport = True if changed_viewport: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def update(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this example, though.) self.physics_engine.update() # Figure out whether or not we should face left, right (or up/down, etc) # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Check to see if we've come into contact with any mates mate_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.mate_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Remove the coin coin.remove_from_sprite_lists() # Play a sound arcade.play_sound(self.collect_coin_sound) # Add one to the score self.score += 1 # Loop through any mate we come into contact with (if any) and remove it for mate in mate_hit_list: # Remove the coin mate.remove_from_sprite_lists() self.player_sprite.set_texture(TEXTURE_MATED) # Play a sound arcade.play_sound(self.victory_theme) # Add one to the score self.score += 1 # --- Manage Scrolling --- # Track if we need to change the viewport changed = False ### NOTE: ALL OF THIS IS CURRENTLY WORKING CORRECTLY, BUT SOMETHING'S WRONG WITH WINDOW SIZING; FIX THIS TO MAKE SCROLLING WORK PROPERLY ### # Solved the above by inreasing the right viewport margin (in "constants" section above initializer) # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed = True if changed: # Only scroll to integers--otherwise we end up with pixels # that don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the sscrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def update(self, delta_time): self.time_elapsed += delta_time #movimento esquerda = abs(self.car.position[1]-esqYpos) if(esquerda>SCALE): esquerda=SCALE #print(esquerda) direita = abs(self.car.position[1]-dirYpos) if(direita>SCALE): direita=SCALE sensE=SENS_SCALE sensD=SENS_SCALE for cone in self.cone_list: if(cone.position[0]>self.car.position[0]-55): if(cone.position[1]>self.car.position[1]): #print("cone a esquerda") sensE_ = math.sqrt((self.car.position[0]-cone.position[0])**2+(self.car.position[1]-cone.position[1])**2) if(sensE_<sensE): sensE=sensE_ else: #print("cone a direita") sensD_ = math.sqrt((self.car.position[0]-cone.position[0])**2+(self.car.position[1]-cone.position[1])**2) if(sensD_<sensD): sensD=sensD_ ''' senHit = arcade.check_for_collision_with_list(self.sensorE, self.cone_list) if senHit: for cone in senHit: if(cone.position[1]>self.car.position[1]): print("cone a esquerda") sensE_ = math.sqrt((self.car.position[0]-cone.position[0])**2+(self.car.position[1]-cone.position[1])**2) if(sensE_<sensE): sensE=sensE_ senHit = arcade.check_for_collision_with_list(self.sensorD, self.cone_list) if senHit: for cone in senHit: if(cone.position[1]<self.car.position[1]): print("cone a direita") sensD_ = math.sqrt((self.car.position[0]-cone.position[0])**2+(self.car.position[1]-cone.position[1])**2) if(sensD_<sensD): sensD=sensD_ ''' direita/=SCALE esquerda/=SCALE self.entrada=[[esquerda,direita,sensE/SENS_SCALE,sensD/SENS_SCALE]] saida = otimizador.predict(self.entrada) self.spdX_ = saida[0][0] self.spdY_esq = saida[0][1] self.spdY_dir = saida[0][2] #print("testando") speedX = TOP_SPEED*self.spdX_ self.car.center_x = self.car.position[0]+speedX self.sensorD.center_x = self.sensorD.position[0]+speedX self.sensorE.center_x = self.sensorE.position[0]+speedX self.distance_car+=speedX if(self.car.position[0]>500): self.car.center_x = self.car.position[0]-speedX self.sensorD.center_x = self.sensorD.position[0]-speedX self.sensorE.center_x = self.sensorE.position[0]-speedX self.distance_map+speedX for cone in self.cone_list: cone.center_x = cone.position[0]-speedX if(cone.center_x<=20): cone.kill() speedY = TOP_SPEED_TURNING*(self.spdY_esq-self.spdY_dir) self.car.center_y = self.car.position[1]+speedY self.sensorD.center_y = self.sensorD.position[1]+speedY self.sensorE.center_y = self.sensorE.position[1]+speedY hit = arcade.check_for_collision_with_list(self.car, self.barreira_list) #colidiu com parede/fundo if hit: print("colidiu") self.reset_log() #learn y_dir = self.spdY_dir y_esq = self.spdY_esq x_ = self.spdX_ for fundo in hit: if(fundo.center_y==esqYpos):#esquerda print("esquerda") y_esq = 0 y_dir = 0.7 elif(fundo.center_y==dirYpos):#direita print("direita") y_esq = 0.7 y_dir = 0 elif(fundo.center_y==300):#fundo print("fundo") x_ = 0.7 y_esq=self.spdY_esq y_dir=self.spdY_dir #print(f"{self.spdX_} {self.spdY_esq-self.spdY_dir}") if(x_<0.4): x_=0.7 #print(x_) y_esperado = [[x_,y_esq,y_dir]] print(f"{self.entrada} {y_esperado}") otimizador.train(self.entrada,y_esperado) #reset position self.resetCount+=1 self.car.center_x = 80 self.car.center_y = 300 self.sensorD.center_x = 160 self.sensorD.center_y = 285 self.sensorE.center_x = 160 self.sensorE.center_y = 315 self.distance_car=0 self.trained = True for cone in self.cone_list: cone.kill() hit = arcade.check_for_collision_with_list(self.car, self.cone_list) if hit:#colidiu com cone print("colidiu") self.reset_log() #learn y_dir = self.spdY_dir y_esq = self.spdY_esq x_ = self.spdX_ for cone in hit: if(cone.center_y>=self.car.position[1]):#esquerda print("cone - esquerda") #if() #se estava no canto direito y_esq = 0.0 y_dir = 0.8 #x_ = 0.5 elif(cone.center_y<self.car.position[1]):#direita print("cone - direita") #if(esquerda<40): #se estava no canto esquerdo y_esq = 0.8 y_dir = 0.0 #x_ = 0.5 if(x_<0.3): x_=0.7 y_esperado = [[x_,y_esq,y_dir]] #print("{self.entrada} {y_esperado}") otimizador.train(self.entrada,y_esperado) #reset position self.resetCount+=1 self.car.center_x = 80 self.car.center_y = 300 self.distance_car=0 self.trained = True self.sensorD.center_x = 160 self.sensorD.center_y = 285 self.sensorE.center_x = 160 self.sensorE.center_y = 315 for cone in self.cone_list: cone.kill() ''' #trigger de 1.5s if(self.time_elapsed>self.last): self.trigger=True self.last+=1.5 ''' #se nao treinou e ativou o trigger #if(self.trigger==True and self.trained==False): #if(self.trigger==True): if(abs(self.distance_car-self.last_checkUpX)<MIN_SPEED and (sensE>=SENS_SCALE or sensD>= SENS_SCALE)):#checa se "parou" print("parou") self.reset_log() #learn x_ = 0.8 y_esq = self.spdY_esq y_dir = self.spdY_dir y_esperado = [[x_,y_esq,y_dir]] #print("{self.entrada} {y_esperado}") otimizador.train(self.entrada,y_esperado) #reset position self.car.center_x = 80 self.car.center_y = 300 self.sensorD.center_x = 160 self.sensorD.center_y = 285 self.sensorE.center_x = 160 self.sensorE.center_y = 315 self.resetCount+=1 self.distance_car=0 for cone in self.cone_list: cone.kill() else: self.last_checkUpX = self.distance_car #self.trained = False #self.trigger=False ''' if(self.resetCount>=self.save): storage.save(nn, filepath=f"Saves/Rede1_4-3/motorista{amostra}_{CODINOME}_g{self.save}_d{self.maxDistance:.0f}.hdf5") self.save+= SAVE_SPAN ''' if(self.coneTimer>=CONE_TIMER and self.car.position[0]>400): cone = arcade.Sprite("cone.png",SPRITE_SCALING_CONE) cone.center_x = 900 cone.center_y = randint(int(self.car.position[1]-50),int(self.car.position[1]+50)) if(len(self.cone_list)<5): self.cone_list.append(cone) self.coneTimer=0 else: self.coneTimer+=1 if(self.distance_car>self.maxDistance): self.maxDistance = self.distance_car if(self.car.position[0]<400): for cone in self.cone_list: cone.kill() #self.car.center_x = x #self.car.center_y = y #self.car.center_x = self.car.position[0]+distX #self.car.center_y = self.car.position[1]+distY #self.car.change_x = 10 #self.physics_engine.update() """ All the logic to move, and the game logic goes here. """ pass
def setup(self): """ Set up the game and initialize the variables. """ # Sprite lists self.all_sprites_list = arcade.SpriteList() self.wall_list = arcade.SpriteList() self.coin_list = arcade.SpriteList() # Set up the player self.player_sprite = arcade.Sprite("images/character.png", SPRITE_SCALING) self.player_sprite.center_x = 50 self.player_sprite.center_y = 64 # -- Set up the walls # Create a series of horizontal walls for y in range(0, 800, 200): for x in range(100, 700, 64): wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING) wall.center_x = x wall.center_y = y self.wall_list.append(wall) # -- Randomly place coins where there are no walls # Create the coins for i in range(NUMBER_OF_COINS): # Create the coin instance # Coin image from kenney.nl coin = arcade.Sprite("images/coin_01.png", SPRITE_SCALING_COIN) # --- IMPORTANT PART --- # Boolean variable if we successfully placed the coin coin_placed_successfully = False # Keep trying until success while not coin_placed_successfully: # Position the coin coin.center_x = random.randrange(SCREEN_WIDTH) coin.center_y = random.randrange(SCREEN_HEIGHT) # See if the coin is hitting a wall wall_hit_list = arcade.check_for_collision_with_list( coin, self.wall_list) # See if the coin is hitting another coin coin_hit_list = arcade.check_for_collision_with_list( coin, self.coin_list) if len(wall_hit_list) == 0 and len(coin_hit_list) == 0: # It is! coin_placed_successfully = True # Add the coin to the lists self.coin_list.append(coin) # --- END OF IMPORTANT PART --- self.physics_engine = arcade.PhysicsEngineSimple( self.player_sprite, self.wall_list) # Set the background color arcade.set_background_color(arcade.color.AMAZON)
def update(self, delta_time): self.score_timeout += delta_time self.frame += delta_time self.score = int(self.score_timeout) % 60 self.player_list.update() for player in self.player_list : #fix angle if player.angle > 90 : player.angle = -280 if player.angle * -1 > 280 : player.angle = 91 collision = arcade.check_for_collision_with_list(player, self.wall_list) if len(collision) > 0 and not DEBUG: self.kill(player) line_top, line_botton, line_left, line_right = Util.calc_angle(player) #fitness func player.reward = self.reward[player.bottonx][player.rightx] * player.position[1] hidden_state, output = self.perceptron.run([ player.speed, line_top, line_botton, line_left, line_right ], player.weights1, player.weights2) A = np.array(output) H = np.array(hidden_state) hidden = np.where(H==max(hidden_state))[0][0] action = np.where(A==max(output))[0][0] if player.reward >= self.better_count : self.index = player.index self.better_count = player.reward if(player.index == self.index) : self.neuron_action = [hidden, action] self.lines_action = [line_top, line_botton, line_left, line_right] if not DEBUG and player.stop == 0: Util.action_reliase(player,action) if(self.score > self.MAX_TIME and not DEBUG) : self.score_timeout = 0 print('--------- MAX_TIME OVER --------') print('start genoma - player_list:', len(self.player_list)) self.better = Genome.get_better(self.better, self.player_list ) #apply crossover self.genoma_list = [] self.genoma_list.append( self.better ) GEN = True while GEN : tmp = Genome.crossover( self.player_list ) self.genoma_list.extend( tmp ) if len(tmp) > 0 and len(self.genoma_list) < MAX and len(self.player_list) > 3 : GEN = True else: GEN = False print('end genoma - genoma_list:', len(self.genoma_list)) count_final = 0 while len(self.player_list) > 0: for player in self.player_list: if player.reward >= self.better_count : count_final += 1 player.kill() self.player_tmp = [] self.player_tmp.append( self.better ) for player in self.genoma_list: self.player_tmp.append( player ) print( 'new players crossover', len(self.player_tmp) ) print('follow', count_final) self.better_count = 0 self.startnewgame()
def update(self, delta_time): """ All the logic to move, and the game logic goes here. Normally, you'll call update() on the sprite lists that need it. """ spheres_hit_list = [] # Handle multiple keys and keys held down if self.right_arrow == True: print('Right Arrow held down') self.player_sprite.center_x += 1 self.player_sprite_list.update() if self.left_arrow == True: print('Left Arrow held down') self.player_sprite.center_x -= 1 self.player_sprite_list.update() self.friendlies_list.update() self.hostiles_list.update() # Handle Bombs # Generate a list of all friendly spheres that collided with walls for bomb in self.spheres_list: spheres_hit_list = arcade.check_for_collision_with_list( bomb, self.walls_list) # Loop through each colliding sprite, remove it, and add to the score. for collision in spheres_hit_list: collision.hp -= 1000 if collision.hp < 0: collision.kill() bomb.kill() self.score += 1 # Generate a list of all hostile spheres that collided with walls for bomb in self.hostile_spheres_list: spheres_hit_list = arcade.check_for_collision_with_list( bomb, self.walls_list) # Loop through each colliding sprite, remove it, and add to the score. for collision in spheres_hit_list: collision.hp -= 1000 if collision.hp < 0: collision.kill() bomb.kill() self.score += 1 # Handle Cubes # Generate a list of all friendly spheres that collided with walls for cube in self.cubes_list: cubes_hit_list = arcade.check_for_collision_with_list( cube, self.walls_list) # Loop through each colliding sprite, set its movement to 0 for collision in cubes_hit_list: cube.change_x = 0 self.score += 1 # Generate a list of all hostile spheres that collided with walls for cube in self.hostile_cubes_list: cubes_hit_list = arcade.check_for_collision_with_list( cube, self.walls_list) # Loop through each colliding sprite, set its movement to 0 for collision in cubes_hit_list: cube.change_x = 0 self.score += 1 # Handle Tris # Generate a list of all friendly tris that collided with walls for tri in self.tris_list: tris_hit_list = arcade.check_for_collision_with_list( tri, self.walls_list) # Loop through each colliding sprite, remove it, and add to the score. for collision in tris_hit_list: tri.change_x = 0 self.score += 1 tris_hit_list = arcade.check_for_collision_with_list( tri, self.friendlies_list) for collision in tris_hit_list: collision.change_y = 0 collision.center_x = tri.center_x collision.center_y = tri.center_y + 50 collision.floating = True self.score += 1 # Generate a list of all hostile tris that collided with walls for tri in self.hostile_tris_list: tris_hit_list = arcade.check_for_collision_with_list( tri, self.walls_list) # Loop through each colliding sprite, remove it, and add to the score. for collision in tris_hit_list: tri.change_x = 0 self.score += 1 tris_hit_list = arcade.check_for_collision_with_list( tri, self.hostiles_list) for collision in tris_hit_list: collision.change_y = 0 collision.center_x = tri.center_x collision.center_y = tri.center_y + 50 collision.floating = True self.score += 1
def update(self, delta_time): self.crosshair_list.update() self.health_list.update() self.player_health() self.slime_list.update() self.spider_list.update() self.rogue_list.update() self.door_list.update() self.fireball_list.update() self.fireball_list.update_animation() self.bolt_list.update() self.bolt_list.update_animation() self.player_list.update() self.player_list.update_animation() self.slime_spawn_timer += delta_time self.spider_spawn_timer += delta_time self.rogue_spawn_timer += delta_time if self.fireball_timer > 0: self.fireball_timer -= delta_time if self.bolt_timer > 0: self.bolt_timer -= delta_time if self.stage_timer > 0: self.stage_timer -= delta_time if self.loading_screen_timer > 0: self.loading_screen_timer -= delta_time #animation_clocks self.animation_timer_2 -= delta_time if self.animation_timer_2 < 0.75 and self.animation_timer_2 > 0.5: self.animation_clock_2 = 1 self.animation_timer_2 = 1.5 if self.animation_timer_2 < 1.25 and self.animation_timer_2 > 1: self.animation_clock_2 = 2 self.animation_timer_2 = 1 self.animation_timer_3 -= delta_time if self.animation_timer_3 < 0.75 and self.animation_timer_3 > 0.5: self.animation_clock_3 = 1 self.animation_timer_3 = 1.5 if self.animation_timer_3 < 1.25 and self.animation_timer_3 > 1: self.animation_clock_3 = 2 self.animation_timer_3 = 2 if self.animation_timer_3 < 1.75 and self.animation_timer_3 > 1.5: self.animation_clock_3 = 3 self.animation_timer_3 = 1 #fireball_cast_animation if self.fireball_cast_timer > 0: self.fireball_cast_timer -= delta_time if self.fireball_cast_timer < 0.1 and self.player_move == False and self.shoot_cd == True: self.player.stand_right_textures.clear() self.player.stand_right_textures.append( arcade.load_texture("images/Mage_3.png", scale=self.player_scale)) self.player.stand_left_textures.clear() self.player.stand_left_textures.append( arcade.load_texture("images/Mage_3.png", scale=self.player_scale, mirrored=True)) self.fireball_cast_timer = 1 if self.fireball_cast_timer < 0.87 and self.fireball_cast_timer > 0.5 and self.player_move == False and self.shoot_cd == True: self.player.stand_right_textures.clear() self.player.stand_right_textures.append( arcade.load_texture("images/Mage_4.png", scale=self.player_scale)) self.player.stand_left_textures.clear() self.player.stand_left_textures.append( arcade.load_texture("images/Mage_4.png", scale=self.player_scale, mirrored=True)) self.fireball_cast_timer = 1.5 if self.fireball_cast_timer < 1.37 and self.fireball_cast_timer > 1 and self.player_move == False and self.shoot_cd == True: self.player.stand_right_textures.clear() self.player.stand_right_textures.append( arcade.load_texture("images/Mage_5.png", scale=self.player_scale)) self.player.stand_left_textures.clear() self.player.stand_left_textures.append( arcade.load_texture("images/Mage_5.png", scale=self.player_scale, mirrored=True)) self.fireball_cast_timer = 2 if self.fireball_cast_timer < 1.87 and self.fireball_cast_timer > 1.5 and self.player_move == False and self.shoot_cd == True: self.fireball() self.player.stand_right_textures.clear() self.player.stand_right_textures.append( arcade.load_texture("images/Mage_1.png", scale=self.player_scale)) self.player.stand_left_textures.clear() self.player.stand_left_textures.append( arcade.load_texture("images/Mage_1.png", scale=self.player_scale, mirrored=True)) self.fireball_cast_timer = 0 self.shoot_cd = False #animations for slime in self.slime_list: self.animation(slime, "slime", 2, self.slime_scale) for fireball in self.fireball_list: self.animation(fireball, "fireball", 3, self.fireball_scale) for spider in self.spider_list: if spider.center_x > self.player.center_x: self.animation(spider, "spider", 3, self.spider_scale, True) else: self.animation(spider, "spider", 3, self.spider_scale, False) #slime_movement + spawn if self.slime_spawn_timer > 2: self.slime_enemy() self.slime_spawn_timer = 0 for slime in self.slime_list: if self.player.center_x > slime.center_x: slime.change_x = 1 else: slime.change_x = -1 if self.player.center_y > slime.center_y: slime.change_y = 1 else: slime.change_y = -1 #spider movement & spawn if self.spider_spawn_timer > 5: self.spider_enemy() self.spider_spawn_timer = 0 try: ab = abs(x2) / x2 except ZeroDivisionError: ab = 0 x1 = x2 - self.evasion_cooldown * ab y1 = y2 - self.evasion_cooldown * ab for spider in self.spider_list: d1 = self.player.center_x - spider.center_x d2 = self.player.center_y - spider.center_y if d1 > 0: spider.change_x = 2 + x1 elif d1 == 0: spider.change_x = 2 + x1 else: spider.change_x = -2 + x1 if d2 > 0: spider.change_y = 2 + y1 elif d2 == 0: spider.change_y = 2 + y1 else: spider.change_y = -2 + y1 if x2 == 0: self.evasion_cooldown = 0 else: self.evasion_cooldown += 2 * delta_time if self.evasion_cooldown >= 4: self.evasion_cooldown = 4 if self.rogue_spawn_timer > 8: self.rogue_enemy() self.rogue_spawn_timer = 0 try: ab = abs(x4) / x4 except ZeroDivisionError: ab = 0 x3 = x4 - self.evasion_cooldown2 * ab y3 = y4 - self.evasion_cooldown2 * ab for rogue in self.rogue_list: if self.bolt_timer <= 0: self.bolt(rogue.center_x, rogue.center_y) d1 = self.player.center_x - rogue.center_x d2 = self.player.center_y - rogue.center_y d3 = (d1**2 + d2**2)**(1 / 2) f = 0 if d3 > 400: f = 0 if d3 > 350 and f == 0: if d1 > 0: rogue.change_x = 1 + x3 elif d1 == 0: rogue.change_x = 1 + x3 else: rogue.change_x = -1 + x3 if d2 > 0: rogue.change_y = 1 + y3 elif d2 == 0: rogue.change_y = 1 + y3 else: rogue.change_y = -1 + y3 else: f = 1 xc = self.player.center_x yc = self.player.center_y xr = rogue.center_x yr = rogue.center_y ac = math.atan2(yc - yr, xc - xr) rogue.change_x = math.sin(ac) * (-2) * (1 + x3) rogue.change_y = math.cos(ac) * 2 * (1 + y3) if x4 == 0: self.evasion_cooldown2 = 0 else: self.evasion_cooldown2 += 2 * delta_time if self.evasion_cooldown2 >= 2: self.evasion_cooldown2 = 2 #door if self.stage_timer < 0.01: if self.onetime_door == True: self.door() self.onetime_door = False door_hit_with_player = arcade.check_for_collision_with_list( self.player, self.door_list) for door in door_hit_with_player: self.stage += 1 self.player.center_x = screen_resolution_int(200) self.player.center_y = SCREEN_HEIGHT // 2 door.kill() self.stage_timer = 13 self.onetime_door = True self.slime_list = arcade.SpriteList() self.fireball_list = arcade.SpriteList() self.spider_list = arcade.SpriteList() self.loading_screen_on = 1 self.loading_screen_timer = 3 if self.loading_screen_timer > 2.8 and self.loading_screen_timer < 2.9: arcade.pause(2) self.loading_screen_on = 0 self.background = arcade.load_texture( file_name="images/background.png") self.animation_timer_2 = 4 self.animation_timer_3 = 4 #game_over if self.player_life < 1: arcade.close_window() print("Noob, you lost.") #hitboxes enemy_hit_with_player = arcade.check_for_collision_with_list( self.player, self.enemy_list) for enemy in enemy_hit_with_player: self.player_life -= 1 self.enemy_life -= 1 for enemy in self.enemy_list: enemy_hit_with_projectile = arcade.check_for_collision_with_list( enemy, self.fireball_list) for enemy_hit in enemy_hit_with_projectile: self.enemy_life -= 1 for enemy in self.enemy_list: if enemy.bottom > SCREEN_HEIGHT - screen_resolution_int( 150) or enemy.top < screen_resolution_int( 150) or enemy.right < screen_resolution_int( 150 ) or slime.left > SCREEN_WIDTH - screen_resolution_int( 150): self.enemy_life -= 1 #slime hitbox slime_hit_with_player = arcade.check_for_collision_with_list( self.player, self.slime_list) for slime in slime_hit_with_player: self.player_life -= 1 slime.kill() for slime in self.slime_list: slime_hit_with_projectile = arcade.check_for_collision_with_list( slime, self.fireball_list) for slime_hit in slime_hit_with_projectile: slime.kill() for slime in self.slime_list: if slime.bottom > SCREEN_HEIGHT - screen_resolution_int( 150) or slime.top < screen_resolution_int( 150) or slime.right < screen_resolution_int( 150 ) or slime.left > SCREEN_WIDTH - screen_resolution_int( 150): slime.kill() #spider hitbox spider_hit_with_player = arcade.check_for_collision_with_list( self.player, self.spider_list) for spider in spider_hit_with_player: self.player_life -= 1 spider.kill() for spider in self.spider_list: spider_hit_with_projectile = arcade.check_for_collision_with_list( spider, self.fireball_list) for spider_hit in spider_hit_with_projectile: spider.kill() for spider in self.spider_list: if spider.bottom > SCREEN_HEIGHT - screen_resolution_int( 150) or spider.top < screen_resolution_int( 150 ) or spider.right < screen_resolution_int( 150 ) or spider.left > SCREEN_WIDTH - screen_resolution_int( 150): spider.kill() #rogue hitbox rogue_hit_with_player = arcade.check_for_collision_with_list( self.player, self.rogue_list) for rogue in rogue_hit_with_player: self.player_life -= 1 rogue.kill() for rogue in self.rogue_list: rogue_hit_with_projectile = arcade.check_for_collision_with_list( rogue, self.fireball_list) for rogue_hit in rogue_hit_with_projectile: rogue.kill() for rogue in self.rogue_list: if rogue.bottom > SCREEN_HEIGHT - 150 or rogue.top < 150 or rogue.right < 150 or rogue.left > SCREEN_WIDTH - 150: rogue.kill() #wall_hitbox wall_down_hit_list = arcade.check_for_collision_with_list( self.player, self.wall_down_list) for wall in wall_down_hit_list: self.player.center_y += screen_resolution_int(5) wall_up_hit_list = arcade.check_for_collision_with_list( self.player, self.wall_up_list) for wall in wall_up_hit_list: self.player.center_y -= screen_resolution_int(5) wall_left_hit_list = arcade.check_for_collision_with_list( self.player, self.wall_left_list) for wall in wall_left_hit_list: self.player.center_x += screen_resolution_int(5) wall_right_hit_list = arcade.check_for_collision_with_list( self.player, self.wall_right_list) for wall in wall_right_hit_list: self.player.center_x -= screen_resolution_int(5) #fireball_hitbox for fireball in self.fireball_list: if fireball.bottom > SCREEN_HEIGHT - screen_resolution_int( 150) or fireball.top < screen_resolution_int( 150 ) or fireball.right < screen_resolution_int( 150 ) or fireball.left > SCREEN_WIDTH - screen_resolution_int( 150): fireball.kill() for bolt in self.bolt_list: if bolt.bottom > SCREEN_HEIGHT - 200 or bolt.top < 200 or bolt.right < 200 or bolt.left > SCREEN_WIDTH - 200: bolt.kill() #bolt_hitbox bolt_hit_with_player = arcade.check_for_collision_with_list( self.player, self.bolt_list) for bolt in bolt_hit_with_player: self.player_life -= 1 bolt.kill() for bolt in self.bolt_list: bolt_hit_with_projectile = arcade.check_for_collision_with_list( bolt, self.fireball_list) for bolt_hit in bolt_hit_with_projectile: bolt.kill()
def update(self, delta_time): if self.attack_delay_true_or_false == True: self.attack_delay += 1 if self.attack_delay == 25: self.attack_delay = 0 self.attack_delay_true_or_false = False if self.player_A_L_sprite.center_x != self.player_L_sprite.center_x - 70: self.player_A_L_sprite.change_x = ( self.player_L_sprite.center_x - 70) - self.player_A_L_sprite.center_x if self.player_A_R_sprite.center_x != self.player_R_sprite.center_x + 55: self.player_A_R_sprite.change_x = ( self.player_R_sprite.center_x + 55) - self.player_A_R_sprite.center_x if self.game_over == False: zombie_slayer.body_disposal(self) if self.damage_points > 0: self.damage_points -= 1 zombie_slayer.move_zombie(self) zombie_slayer.move_player(self) zombie_slayer.update_my_physics_engine(self) if self.space == True: if self.face_right == True: self.kill_zombie = arcade.check_for_collision_with_list( self.player_A_R_sprite, self.zombie_list) for i in self.kill_zombie: self.killed_zombies[self.my_zombie_list.index(i)] = i self.zombie_move_true_or_false[ self.my_zombie_list.index(i)] = False elif self.space == False: zombie_attack_list = arcade.check_for_collision_with_list( self.player_R_sprite, self.zombie_list) for i in zombie_attack_list: self.zombie_attack_true_or_false[self.my_zombie_list.index( i)] = True if len(zombie_attack_list) == 0: for i in range(len(self.zombie_attack_true_or_false)): self.zombie_attack_true_or_false[i] = False else: for i in range(len(self.zombie_attack_true_or_false)): if self.zombie_attack_true_or_false[i] == True: if self.my_zombie_list[i] in zombie_attack_list: self.zombie_attack_true_or_false[i] == True else: self.zombie_attack_true_or_false[i] == False for i in range(len(self.zombie_attack_true_or_false)): if self.zombie_attack_true_or_false[ i] == True and self.killed_zombies[i] == '': self.damage_points += 4 "***********************************************************" if self.game_over == False: zombie_slayer.body_disposal(self) if self.damage_points > 0: self.damage_points -= 1 if self.space == True: if self.face_right == False: self.kill_zombie = arcade.check_for_collision_with_list( self.player_A_L_sprite, self.left_zombie_list) for i in self.kill_zombie: self.left_killed_zombies[ self.left_my_zombie_list.index(i)] = i self.left_zombie_move_true_or_false[ self.left_my_zombie_list.index(i)] = False elif self.space == False: zombie_attack_list1 = arcade.check_for_collision_with_list( self.player_L_sprite, self.left_zombie_list) for i in zombie_attack_list1: self.left_zombie_attack_true_or_false[ self.left_my_zombie_list.index(i)] = True if len(zombie_attack_list1) == 0: for i in range(len(self.left_zombie_attack_true_or_false)): self.left_zombie_attack_true_or_false[i] = False else: for i in range(len(self.left_zombie_attack_true_or_false)): if self.left_zombie_attack_true_or_false[i] == True: if self.left_my_zombie_list[ i] in zombie_attack_list: self.left_zombie_attack_true_or_false[ i] == True else: self.left_zombie_attack_true_or_false[ i] == False for i in range(len(self.left_zombie_attack_true_or_false)): if self.left_zombie_attack_true_or_false[ i] == True and self.left_killed_zombies[i] == '': self.damage_points += 4 if self.damage_points >= 900: self.game_over = False self.you_lose = True self.killed_zombies_combined = [] + self.killed_zombies + self.left_killed_zombies for i in self.killed_zombies_combined: if i == True: self.score += 1 if self.score == 10: self.you_win = False self.score = 0 "***********************************************************"
def update(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this # example though.) self.physics_engine.update() # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Remove the coin coin.remove_from_sprite_lists() # Play a sound arcade.play_sound(self.collect_coin_sound) # Add one to the score self.score += 1 # Track if we need to change the viewport changed_viewport = False # Did the player fall off the map? if self.player_sprite.center_y < -100: self.player_sprite.center_x = PLAYER_START_X self.player_sprite.center_y = PLAYER_START_Y # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True arcade.play_sound(self.game_over) # Did the player touch something they should not? if arcade.check_for_collision_with_list(self.player_sprite, self.dont_touch_list): self.player_sprite.center_x = PLAYER_START_X self.player_sprite.center_y = PLAYER_START_Y # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True arcade.play_sound(self.game_over) # See if the user got to the end of the level if self.player_sprite.center_x >= self.end_of_map: # Advance to the next level self.level += 1 # Load the next level self.setup(self.level) # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True # --- Manage Scrolling --- # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed_viewport = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed_viewport = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed_viewport = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed_viewport = True if changed_viewport: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def on_update(self, delta_time: float): """Update the positions and statuses of all game objects If we're paused, do nothing Once everything has moved, check for collisions between the player and the list of enemies Arguments: delta_time {float} -- Time since the last update """ self.bullet_list.update() for bullet in self.bullet_list: # Check this bullet to see if it hit a coin hit_list = arcade.check_for_collision_with_list(bullet, self.enemies_list) # If it did, get rid of the bullet if len(hit_list) > 0: bullet.remove_from_sprite_lists() for enemy in hit_list: enemy.remove_from_sprite_lists() self.score += 1 # If the bullet flies off-screen, remove it. if bullet.bottom > SCREEN_WIDTH: bullet.remove_from_sprite_lists() if self.HP == 0: time.sleep(2) arcade.close_window() # Did we collide with something earlier? If so, update our timer if self.collided: for enemy in self.enemies_list: enemy_hit = arcade.check_for_collision_with_list(self.player_sprite, self.enemies_list) if len(enemy_hit) > 0: enemy.remove_from_sprite_lists() for enemy in enemy_hit: enemy.remove_from_sprite_lists() self.collided = False self.HP -= 1 #self.collision_timer += delta_time # If we've paused for two seconds, we can quitw #if self.collision_timer > 2.0: #arcade.close_window() # Stop updating things as well return # If we're paused, don't update anything if self.paused: return # Did we hit anything? If so, end the game if self.player_sprite.collides_with_list(self.enemies_list): self.collided = True self.collision_timer = 0.0 # Update everything for sprite in self.all_sprites: sprite.center_x = int( sprite.center_x + sprite.change_x * delta_time ) sprite.center_y = int( sprite.center_y + sprite.change_y * delta_time ) # Keep the player on screen if self.player_sprite.top > self.height: self.player_sprite.top = self.height if self.player_sprite.right > self.width: self.player_sprite.right = self.width if self.player_sprite.bottom < 0: self.player_sprite.bottom = 0 if self.player_sprite.left < 0: self.player_sprite.left = 0
def falon_all(self, fal_lista): return not arcade.check_for_collision_with_list(self, fal_lista) == []
def on_update(self, delta_time): #This is a 60 fps game, so this function is called 60 times each second for enemy in self.enemy_list: #If enemy flies off screen, it reappers on the top. Also increments misses by 1 if enemy.center_y < 0: enemy.center_y = TOP_LIMIT if not self.gameOver: self.misses += 1 if len(self.enemy_list) == 0: #Check which level we are in and spawn enemies accordingly if (self.score <= 50): self.spawnEnemies() else: self.spawnEnemiesLevel2() if not self.gameOver: #loop through each enemy we have and have them shoot for enemy in self.enemy_list: if random.randrange(self.probability) == 0: bullet = BulletSprite( ":resources:images/space_shooter/laserBlue01.png", 1) bullet.center_x = enemy.center_x bullet.angle = -90 bullet.top = enemy.bottom bullet.change_y = -2 self.bullet_list.append(bullet) #Check for bullet collisions with enemies for bullet in self.player_bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.enemy_list) if len(hit_list) > 0: self.createExplosion(hit_list) bullet.remove_from_sprite_lists() for enemy in hit_list: self.score += 1 enemy.remove_from_sprite_lists() arcade.sound.play_sound(self.hit_sound) #Check for bullet collisions with player if (not self.player.respawning) and (not self.player.shield): for bullet in self.bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.player_list) if len(hit_list) > 0: self.createExplosion(hit_list) bullet.remove_from_sprite_lists() if self.lives > 0: self.lives -= 1 self.player.respawn() self.ship_life_list.pop().remove_from_sprite_lists( ) else: self.stopGame() #Check for collisions between player and enemy if (not self.player.respawning) and (not self.player.shield): for enemy in self.enemy_list: hit_list = arcade.check_for_collision_with_list( enemy, self.player_list) if len(hit_list) > 0: self.createExplosion(hit_list) enemy.remove_from_sprite_lists() if self.lives > 0: self.lives -= 1 self.player.respawn() self.ship_life_list.pop().remove_from_sprite_lists( ) else: self.stopGame() self.bullet_list.update() self.player_bullet_list.update() self.player_list.update() self.enemy_list.update() self.explosions_list.update()
def update(self, dt): # Update main sprites self.player.update() self.player.update_animation(dt) if self.game_background.center_x < 0: self.game_background.center_x += self.game_background.width / 2 * RESOLUTION_SCALING for obstacle in self.obstacles_list: if obstacle.center_x < -obstacle.width * 2: obstacle.remove_from_sprite_lists() obstacle.update() obstacle.update_animation(dt) # Update powerup collectibles for powerup_bar in self.powerup_holder_list: powerup_bar.update() for powerup in self.powerup_sprite_list: if powerup.center_x < -powerup.width * 2: powerup.remove_from_sprite_lists() powerup.update() for powerup_enabled in self.powerup_enabled_sprite_list: if powerup_enabled.center_x < -powerup_enabled.width * 2: powerup_enabled.remove_from_sprite_lists() powerup_enabled.update() # Update powerup sprites for shockwave in self.player.shockwave_sprite_list: shockwave.update() for time_warp in self.player.time_warp_sprite_list: time_warp.update() for timer_hand in self.player.timer_hand_sprite_list: timer_hand.angle = self.player.timer_hand_rotation timer_hand.update() # Update achievements for achievement_dropdown in self.achievement_dropdown_list: if achievement_dropdown.finished: achievement_dropdown.remove_from_sprite_lists() else: achievement_dropdown.update() i = 0 for achievement_icon in self.achievement_dropdown_icon_list: if len(self.achievement_dropdown_list) == 0: achievement_icon.remove_from_sprite_lists() else: achievement_icon.center_x = self.achievement_dropdown_list[ i].center_x achievement_icon.center_y = self.achievement_dropdown_list[i].center_y - \ self.achievement_dropdown_list[i].height / 5 achievement_icon.update() i += 1 i = 0 for text_label in self.achievement_dropdown_text_list: if len(self.achievement_dropdown_list) == 0: self.achievement_dropdown_text_list.clear() else: text_label.x = self.achievement_dropdown_list[i].center_x text_label.y = self.achievement_dropdown_list[i].center_y + \ self.achievement_dropdown_list[i].height / 5 i += 1 self.game_background.update() self.game_background.change_x = -Globals.GLOBAL_SCROLL_SPEED # Game logic for i in range(len(self.obstacle_initial_textures)): obstacle_generator = np.random.randint(0, 20000) if ((self.time > self.new_object_spawn_values[i]) and (obstacle_generator - self.time) < 100): obstacle = Obstacle(None, SPRITE_SCALING) obstacle.type = i + 1 obstacle.texture = self.obstacle_initial_textures[i] obstacle.center_x = SCREEN_WIDTH + obstacle.width * 2 obstacle.center_y = GROUND_LEVEL obstacle.change_x = -Globals.GLOBAL_SCROLL_SPEED obstacle.init_animation_textures() self.obstacles_list.append(obstacle) for i in range(len(self.powerups_permanent_scores)): if self.time > self.powerups_permanent_scores[i]: self.powerup_spawns_enabled_list[i] = True else: break # Powerup bar lengths for i in range(NUM_POWERUPS_PERMANENT): bar_length_temp = (POWERUP_BAR_LENGTH * (self.player.powerup_time_since_used[i] / self.player.powerup_recharge_time_list[i])) bar_length = np.minimum(bar_length_temp, POWERUP_BAR_LENGTH) self.powerup_bar_lengths[i] = bar_length # Spawn powerups for i in range(NUM_POWERUPS_PERMANENT): # Generate powerup enabled sprites powerup_enabled_generator = np.random.randint(0, 7200) if ((self.time > self.powerups_permanent_scores[i]) and (powerup_enabled_generator < 60) and self.player.powerups_enabled_list[i] is False): powerup_enabled_sprite = PowerupEnabled( self.powerup_enabled_path_list[i], SPRITE_SCALING) powerup_enabled_sprite.center_x = SCREEN_WIDTH + powerup_enabled_sprite.width * 2 powerup_enabled_sprite.center_y = GROUND_LEVEL powerup_enabled_sprite.change_x = -SCROLL_SPEED powerup_enabled_sprite.type = i + 1 self.powerup_enabled_sprite_list.append(powerup_enabled_sprite) # Gemerate powerup upgrades powerup_generator = np.random.randint(0, 7200) if ((self.time > self.new_object_spawn_values[i]) and (powerup_generator < 60) and (self.player.powerup_level_list[i] < POWERUP_MAX_LEVEL) and (self.player.powerups_enabled_list[i])): powerup = Powerup(self.powerup_sprite_path_list[i], SPRITE_SCALING) powerup.type = i + 1 powerup.center_x = SCREEN_WIDTH + powerup.width * 2 powerup.center_y = GROUND_LEVEL powerup.change_x = -Globals.GLOBAL_SCROLL_SPEED self.powerup_sprite_list.append(powerup) # Check for collisions for shield in self.player.shield_list: collisions = arcade.check_for_collision_with_list( shield, self.obstacles_list) for obstacle in collisions: if obstacle.dead is False: self.player.shield_hit = True obstacle.dead = True for slime_blast in self.player.slime_blast_sprite_list: collisions = arcade.check_for_collision_with_list( slime_blast, self.obstacles_list) for obstacle in collisions: if obstacle.dead is False: obstacle.dead = True self.score += 10 for shockwave in self.player.shockwave_sprite_list: collisions = arcade.check_for_collision_with_list( shockwave, self.obstacles_list) for obstacle in collisions: if obstacle.dead is False: obstacle.dead = True self.score += 10 powerup_hit_list = arcade.check_for_collision_with_list( self.player, self.powerup_sprite_list) for powerup in powerup_hit_list: next_level = self.player.powerup_level_list[powerup.type - 1] + 1 self.player.powerup_level_list[powerup.type - 1] = np.minimum( next_level, POWERUP_MAX_LEVEL) self.player.powerup_recharge_time_list[powerup.type - 1] = ( POWERUP_RECHARGE_TIMES[powerup.type - 1] * (1 - (self.player.powerup_level_list[powerup.type - 1] / (2 * POWERUP_MAX_LEVEL)))) powerup.remove_from_sprite_lists() powerup_enabled_hit_list = arcade.check_for_collision_with_list( self.player, self.powerup_enabled_sprite_list) for powerup_enabled in powerup_enabled_hit_list: self.player.powerups_enabled_list[powerup_enabled.type - 1] = True powerup_enabled.remove_from_sprite_lists() powerup_enabled.update() for i in range(len(ACHIEVEMENT_SCORES)): if self.score > ACHIEVEMENT_SCORES[i] and not GameData.data[ 'achievements_complete'][i]: path = os.path.join(SPRITES_PATH, 'achievement_dropdown.png') path_icon = os.path.join( SPRITES_PATH, 'achievement_icon_' + str(i + 1) + '.png') achievement_dropdown = AchievementDropdown( path, SPRITE_SCALING) achievement_icon = arcade.Sprite(path_icon, SPRITE_SCALING) achievement_icon.center_x = achievement_dropdown.center_x achievement_icon.center_y = achievement_dropdown.center_y + achievement_dropdown.height / 5 text_label = arcade.gui.TextLabel( ACHIEVEMENT_NAMES[i], achievement_dropdown.center_x, achievement_dropdown.center_y - achievement_dropdown.height / 5, arcade.color.BLACK, font_size=20) self.achievement_dropdown_list.append(achievement_dropdown) self.achievement_dropdown_icon_list.append(achievement_icon) self.achievement_dropdown_text_list.append(text_label) GameData.data['achievements_complete'][i] = True GameData.save_data() for i in range(len(ACHIEVEMENT_DISTANCES)): if self.distance > ACHIEVEMENT_DISTANCES[i] and not GameData.data[ 'achievements_complete'][i + 4]: GameData.data['achievements_complete'][i + 4] = True GameData.save_data() object_hit_list = arcade.check_for_collision_with_list( self.player, self.obstacles_list) for object in object_hit_list: if obstacle.dead is False: self.player.health -= 1 if self.player.health <= 0: self.init_game_over() self.time += dt self.distance += dt * 60 self.score += dt * 60
def update(self, delta_time): """All the logic to move, and the game logic goes here. """ global explode, explode_x, explode_y, fps, position_y_1, position_y_2, level, prompt, prompt_time, boss_hp, boss_hp_current global up_pressed, down_pressed, left_pressed, right_pressed, laser_bomb, laser_effect, laser_fps, laser_counter, laser_counter_update global boss_create_fps, boss_sound_on, game_sound_on, game_sound_1, game_sound_2, game_sound_3, boss_sound_1, boss_sound_2, boss_sound_3, game_sound, boss_sound_4 if self.current_state != GAME_RUNNING and self.frame_count % 3480 == 0: try: arcade.play_sound(background_sound) except Exception as e: print("Error playing sound.", e) pass if self.current_state == GAME_RUNNING: try: arcade.stop_sound(background_sound) except Exception as e: print("Error pausing sound.", e) pass if level == 4: self.current_state = WIN return if self.current_state == GAME_RUNNING: if self.boss and boss_sound_on == 0: boss_sound_on = 1 try: if level == 0: arcade.stop_sound(game_sound) arcade.play_sound(boss_sound_1) if level == 1: game_sound_1.pause() arcade.play_sound(boss_sound_2) if level == 2: game_sound_2.pause() arcade.play_sound(boss_sound_3) if level == 3: game_sound_3.pause() arcade.play_sound(boss_sound_4) except Exception as e: print("Error pausing sound.", e) pass if not self.boss: try: if level == 0: boss_sound_1.pause() if level == 1: boss_sound_2.pause() if level == 2: boss_sound_3.pause() if level == 3: boss_sound_4.pause() except Exception as e: print("Error pausing sound.", e) pass boss_sound_on = 0 # if (self.frame_count - fps) == 180 and fps != 0: # game_sound_on = 0 if game_sound_on == 0: try: if level == 0: arcade.play_sound(game_sound) if level == 1: arcade.play_sound(game_sound_1) if level == 2: arcade.play_sound(game_sound_2) if level == 3: arcade.play_sound(game_sound_3) except Exception as e: print("Error playing sound.", e) pass game_sound_on = 1 # update remaining laser based on current score laser_counter = Score // 1000 + 1 if laser_counter + laser_counter_update == 1: arcade.play_sound(missile_sound_1) self.laser_player += 1 laser_counter_update -= 1 if self.hp <= 0: game_sound_on = 10 try: arcade.stop_sound(game_sound) # game_sound_1.pause() # game_sound_2.pause() # game_sound_3.pause() # boss_sound_1.pause() # boss_sound_2.pause() # boss_sound_3.pause() # boss_sound_4.pause() except Exception as e: print("Error pausing sound.", e) self.dead() else: # drop hp bonus every 60s if self.frame_count % 3600 == 3599: bonus_hp = arcade.Sprite("images/hp_bonus.png", 0.45) bonus_hp.center_x = random.randrange(0, SCREEN_WIDTH) bonus_hp.center_y = random.randrange( SCREEN_HEIGHT, SCREEN_HEIGHT * 1.25) self.bonus.append(bonus_hp) if self.frame_count % 240 == 0 and not self.boss and not 1 <= explode <= 4: for _ in range(2 + level): # generate randomly enemy planes of different levels ranNum = random.randint(0, 1000) if ranNum < 500: enemy = Enemy("images/plane_small.png", 0.8, 2, 10, 4, False) elif ranNum < 850: enemy = Enemy("images/bigplane0.png", 0.7, 3, 50, 3, False) else: enemy = Enemy("images/boss0.png", 0.35, 5, 100, 2, False) enemy.center_x = random.randrange(0, SCREEN_WIDTH) enemy.center_y = random.randrange( SCREEN_HEIGHT, SCREEN_HEIGHT * 1.25) enemy.angle = 180 self.enemy_list.append(enemy) # create a boss and ensure no small enemies appear during the boss battle elif self.frame_count - fps == ( 1799 * (level + 1)) and not self.boss and not 1 <= explode <= 4: # 提示 boss_create_fps = self.frame_count prompt = True prompt_time = self.frame_count # update boss image based on game level if level == 0: enemy = Enemy("images/boss_2.png", 0.8, 25, 500, 2, True) elif level == 1: enemy = Enemy("images/boss_4.png", 0.8, 35, 1000, 3, True) elif level == 2: enemy = Enemy("images/boss_1.png", 0.8, 50, 2000, 3, True) elif level == 3: enemy = Enemy("images/boss_5.png", 0.8, 70, 4000, 3, True) enemy.center_x = random.randrange(0, SCREEN_WIDTH) enemy.center_y = SCREEN_HEIGHT * 2 enemy.angle = 180 self.enemy_list.append(enemy) self.boss = True boss_hp = enemy.ehp # set time for boss prompt to be 3s if self.frame_count - prompt_time == 180 and prompt: prompt = False # update player's hp based on different damage levels from boss for boss in self.enemy_list: if 1 <= laser_effect <= 6: # realize the disappearance of self bullet when it hits boss for e in self.bullet_self_list: if boss.center_x - 20 <= e.center_x <= boss.center_x + 20: e.kill() # calculate different damage levels of laser from boss if level == 0: if self.player.center_x - 36 < boss.center_x < self.player.center_x + 36: self.hp = max(0, self.hp - 0.8) if level == 1: if self.player.center_x - 36 < boss.center_x < self.player.center_x + 36: self.hp = max(0, self.hp - 0.9) if level == 2: if self.player.center_x - 36 < boss.center_x - 45 < self.player.center_x + 36 or self.player.center_x - 36 < boss.center_x + 15 < self.player.center_x + 36: self.hp = max(0, self.hp - 1) if level == 3: if self.player.center_x - 36 < boss.center_x - 45 < self.player.center_x + 36 or self.player.center_x - 36 < boss.center_x < self.player.center_x + 36 or self.player.center_x - 36 < boss.center_x + 15 < self.player.center_x + 36: self.hp = max(0, self.hp - 1.1) # update the background position position_y_1 -= 1 position_y_2 -= 1 if position_y_1 == -300: position_y_1 = 900 if position_y_2 == -300: position_y_2 = 900 # collision with bullet bullet_collide_list = arcade.check_for_collision_with_list( self.player, self.bullet_list) for collide_bullet in bullet_collide_list: collide_bullet.kill() self.hp = max(0, self.hp - 5) # collision with enemy enemy_collide_list = arcade.check_for_collision_with_list( self.player, self.enemy_list) for collide_enemy in enemy_collide_list: collide_enemy.kill() if self.boss: self.hp = 0 self.hp = max(0, self.hp - 30) # calculate different damage of player's bullet or bomb makes on enemy or boss for e in self.enemy_list: if e.boss: boss_hp_current = e.ehp bullet_hit_list = arcade.check_for_collision_with_list( e, self.bullet_self_list) for bullet_hit in bullet_hit_list: bullet_hit.kill() boss_hit = e.hitted(1) if boss_hit[0] == 1: self.boss = False explode = 1 explode_x = boss_hit[1] explode_y = boss_hit[2] fps = self.frame_count for bomb in self.assist: bullet_hit_list = arcade.check_for_collision_with_list( bomb, self.bullet_list) for b in bullet_hit_list: b.kill() for e in self.enemy_list: if e.boss: boss_hp_current = e.ehp bullet_hit_list = arcade.check_for_collision_with_list( e, self.assist) for bullet_hit in bullet_hit_list: boss_hit = e.hitted(0.3) if boss_hit[0] == 1: self.boss = False explode = 1 explode_x = boss_hit[1] explode_y = boss_hit[2] fps = self.frame_count # boss explode animation if explode == 1 and self.frame_count - fps == 20: arcade.play_sound(bomb_sound) explode += 1 elif explode == 2 and self.frame_count - fps == 40: explode += 1 elif explode == 3 and self.frame_count - fps == 60: explode += 1 elif explode == 4 and self.frame_count - fps == 180: explode += 1 level += 1 # bomb_sound.pause() game_sound_on = 0 # use loop to make all enemies facing to the player for enemy in self.enemy_list: # First, calculate the angle to the player. We could do this # only when the bullet fires, but in this case we will rotate # the enemy to face the player each frame, so we'll do this # each frame. # Position the start at the enemy's current location start_x = enemy.center_x start_y = enemy.center_y # list_1[i][2]Get the destination location for the bullet dest_x = self.player.center_x dest_y = self.player.center_y # Do math to calculate how to get the bullet to the destination. # Calculation the angle in radians between the start points # and end points. This is the angle the bullet will travel. x_diff = dest_x - start_x y_diff = dest_y - start_y angle = math.atan2(y_diff, x_diff) # use if statement to exclude the boss angle if enemy.boss: enemy.angle = 0 else: enemy.angle = math.degrees(angle) - 270 # determine the shooting characteristics of enemy / boss planes if enemy.boss and self.frame_count % ( (120 - 20 * level) // 2) == 0: bullet = arcade.Sprite("images/boss_bullet.png", 0.5) bullet.center_x = start_x bullet.center_y = start_y bullet.angle = 0 bullet.change_x = 0 bullet.change_y = -BULLET_SPEED * (level // 3 + 1) self.bullet_list.append(bullet) elif self.frame_count % (120 - 20 * level) == 0: bullet = arcade.Sprite("images/enemy_bullet.png", 0.5) bullet.center_x = start_x bullet.center_y = start_y bullet.angle = math.degrees(angle) bullet.change_x = math.cos(angle) * BULLET_SPEED * ( level // 3 + 1) bullet.change_y = math.sin(angle) * BULLET_SPEED * ( level // 3 + 1) self.bullet_list.append(bullet) # determine the shooting frequency of the player airplane if self.frame_count % (15 - 2 * level) == 0: bullet = arcade.Sprite("images/Bomb2.png", 0.7) bullet.center_x = self.player.center_x bullet.center_y = self.player.center_y # Angle the bullet sprite bullet.angle = 0 # Taking into account the angle, calculate our change_x # and change_y. Velocity is how fast the bullet travels. bullet.change_x = 0 bullet.change_y = BULLET_SPEED * 3 self.bullet_self_list.append(bullet) # arcade.play_sound(bullet_sound) # use loops to remove the bullet when it flies off-screen for bullet in self.bullet_self_list: if bullet.bottom > 600: bullet.kill() for bullet in self.assist: if bullet.bottom > 600: bullet.kill() for bullet in self.bullet_list: if bullet.top < 0: bullet.kill() # use loops to control the dropping of hp_bonus for hp_bonus in self.bonus: hp_bonus.center_y -= 5 # update player's hp when it catches hp_bonus if arcade.check_for_collision(self.player, hp_bonus): self.hp = min(100, self.hp + 30) arcade.play_sound(hp_bonus_sound) hp_bonus.kill() # remove hp_bonus when it gets out of windows if hp_bonus.top < 0: hp_bonus.kill() # keyboard control the movement of the player if up_pressed: self.player.center_y = min(552, self.player.center_y + 5) if down_pressed: self.player.center_y = max(48, self.player.center_y - 5) if left_pressed: self.player.center_x = max(36, self.player.center_x - 5) if right_pressed: self.player.center_x = min(764, self.player.center_x + 5) # trigger the missile if laser_bomb and self.laser_player > 0 and len( self.assist) <= 1: assist_bomb = arcade.Sprite("images/assisent1_1.png", 1) assist_bomb.center_x = self.player.center_x - 25 assist_bomb.center_y = self.player.center_y assist_bomb.angle = 0 assist_bomb.change_x = 0 assist_bomb.change_y = 10 self.assist.append(assist_bomb) assist_bomb = arcade.Sprite("images/assisent1_1.png", 1) assist_bomb.center_x = self.player.center_x + 25 assist_bomb.center_y = self.player.center_y assist_bomb.angle = 0 assist_bomb.change_x = 0 assist_bomb.change_y = 10 self.assist.append(assist_bomb) self.laser_player -= 1 # use if statement to set the laser shooting period to be 8s if self.boss and (self.frame_count - boss_create_fps) % 480 == 0 and ( self.frame_count - boss_create_fps) != 0: laser_effect = 1 laser_fps = self.frame_count # use if statement to animate laser if laser_effect == 1 and self.frame_count - laser_fps == 20: laser_effect += 1 elif laser_effect == 2 and self.frame_count - laser_fps == 40: laser_effect += 1 elif laser_effect == 3 and self.frame_count - laser_fps == 60: laser_effect += 1 elif laser_effect == 4 and self.frame_count - laser_fps == 80: laser_effect += 1 elif laser_effect == 5 and self.frame_count - laser_fps == 100: laser_effect += 1 elif laser_effect == 6 and self.frame_count - laser_fps == 120: laser_effect += 1 # realize the dropping of boss and enemy planes for e in self.enemy_list: e.drop() if level == 4: self.current_state = WIN self.set_mouse_visible(True) self.bullet_list.update() self.bullet_self_list.update() self.assist.update() # update the frame_count self.frame_count += 1
def update(self, level): """ Movement and game logic """ for i in self.player.deck().blocks(): self.wall_list.append(i) self.player.deck().clean_blocks() # Move the player with the physics engine self.player.update_animation() self.physics_engine.update() # See if we hit any coins key_hit_list = arcade.check_for_collision_with_list( self.player.player_sprite, self.key_list) damage_hit_list = arcade.check_for_collision_with_list( self.player.player_sprite, self.damage_list) # Loop through each coin we hit (if any) and remove it for key in key_hit_list: # Remove the coin key.remove_from_sprite_lists() # Add score self.player.state().score = 50 self.player.state().isWithKey = True arcade.play_sound(self.collect_sound) # Track if we need to change the viewport changed_viewport = False # Is the player dead? for key in damage_hit_list: key.remove_from_sprite_lists if self.player.state().isSave == True: self.player.state( ).countSave = self.player.state().countSave - 10 self.player.player_sprite.change_y = self.controlador.PLAYER_JUMP_SPEED if self.player.state().countSave == 0: self.player.state().isSave = False else: self.setup(self.level, self.player.state().savex, self.player.state().savey) self.player.state().score = -20 # Is the player in the portal? if arcade.check_for_collision_with_list(self.player.player_sprite, self.portal_list): if self.player.state().isWithKey: self.player.state().isInPortal = True self.level += 1 if self.level == 10: ini_view = self.controlador.finish_view( "Você terminou o jogo") self.window.show_view(ini_view) else: self.setup(self.level) # See if the user got to the end of the level if self.player.player_sprite.center_x >= self.end_of_map: # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True
def update(self, delta_time): # Count Number of Main Game-Loop Iterations if self.iteration < 40: self.iteration = self.iteration + 1 else: self.iteration = 1 # Reset Number Every 333000 Iterations (prevents number from getting too large) # Prevent Defender From Moving Off Screen or "Out of Bounds" defenderPosition = self.defender_sprite.get_position() if self.leftButtonDown == True and defenderPosition[ 0] < self.LEFT_BOUNDARY_X: self.defender_sprite.change_x = 0 elif self.rightButtonDown == True and defenderPosition[ 0] > self.RIGHT_BOUNDARY_X: self.defender_sprite.change_x = 0 # MOVE INVADERS # First, Move Invaders Left 10 times if (self.iteration == 2 or self.iteration == 4 or self.iteration == 6 or self.iteration == 8 or self.iteration == 10): for x in range(len(self.invader_list)): # Flip Image of Invader if self.invader_list[x].facing == "left": self.invader_list[x].texture = self.invader_list[ x].texture_right self.invader_list[x].facing = "right" else: self.invader_list[x].texture = self.invader_list[ x].texture_left self.invader_list[x].facing = "left" # Move Invader (Horizontally) if self.invaderDirection == "left": self.invader_list[x].change_x = -50 # When Invaders Reach Left Border, Move Invaders Down for x in range(len(self.invader_list)): if self.iteration == 10: self.invader_list[x].change_y = -25 # Next, March Invaders Right 20 Times elif (self.iteration == 12 or self.iteration == 14 or self.iteration == 16 or self.iteration == 18 or self.iteration == 20 or self.iteration == 22 or self.iteration == 24 or self.iteration == 26 or self.iteration == 28 or self.iteration == 30): for x in range(len(self.invader_list)): # Flip Image of Invader if self.invader_list[x].facing == "left": self.invader_list[x].texture = self.invader_list[ x].texture_right self.invader_list[x].facing = "right" else: self.invader_list[x].texture = self.invader_list[ x].texture_left self.invader_list[x].facing = "left" # Move Invader (Horizontally) if self.invaderDirection == "left": self.invader_list[x].change_x = 50 # When Invaders Reach Right Border, Move Invaders Down for x in range(len(self.invader_list)): if self.iteration == 30: self.invader_list[x].change_y = -25 # Last, March Invaders Left Right 10 Times Back To The Center of the Screen elif (self.iteration == 32 or self.iteration == 34 or self.iteration == 36 or self.iteration == 38 or self.iteration == 40): for x in range(len(self.invader_list)): # Flip Image of Invader if self.invader_list[x].facing == "left": self.invader_list[x].texture = self.invader_list[ x].texture_right self.invader_list[x].facing = "right" else: self.invader_list[x].texture = self.invader_list[ x].texture_left self.invader_list[x].facing = "left" # Move Invader (Horizontally) if self.invaderDirection == "left": self.invader_list[x].change_x = -50 else: for x in range(len(self.invader_list)): self.invader_list[x].change_x = 0 self.invader_list[x].change_y = 0 # LAZER BEAM CODE GOES HERE self.lazer_list.update() for lazer in self.lazer_list: # Check this bullet to see if it hit a coin hit_list = arcade.check_for_collision_with_list( lazer, self.invader_list) # If it did, get rid of the bullet if len(hit_list) > 0: lazer.kill() # For every coin we hit, add to score and remove the coin for invader in hit_list: invader.kill() # If the bullet flies off-screen, remove it. if lazer.bottom > self.FULL_SCREEN_HEIGHT: lazer.kill() # END LAZER BEAM CODE # If Joystick is Available, Move Player When Joystick Moved # NOTICE: The code to move the player when a keyboard button # is pressed is contained in the on_key_press and on_key_release # methods, but the code to move the player when the joystick is # moved is contained here, in the update method. if self.joystick: joystick_input = self.joystick.x * MOVEMENT_MULTIPLIER # When the joystick is in the "left" position, and the player has not # gone out of bounds on the left side of the screen, move defender left. if joystick_input < 0 and defenderPosition[ 0] > self.LEFT_BOUNDARY_X: # Set a "dead zone" to prevent drive from a centered joystick if abs(joystick_input) < DEAD_ZONE: self.defender_sprite.change_x = 0 else: self.defender_sprite.change_x = joystick_input # When the joystick is in the "right" position, and the player has not # gone out of bounds on the right side of the screen, move defender right. elif joystick_input > 0 and defenderPosition[ 0] < self.RIGHT_BOUNDARY_X: # Set a "dead zone" to prevent drive from a centered joystick if abs(joystick_input) < DEAD_ZONE: self.defender_sprite.change_x = 0 else: self.defender_sprite.change_x = joystick_input # Else, stop the defender so that he does not go off the screen else: self.defender_sprite.change_x = 0 # Call update on all sprites (The sprites don't do much in this # example though.) self.defender_list.update() self.invader_list.update()
def _move_sprite(moving_sprite: Sprite, walls: SpriteList, ramp_up: bool): # start_time = time.time() # See if we are starting this turn with a sprite already colliding with us. if len(check_for_collision_with_list(moving_sprite, walls)) > 0: _circular_check(moving_sprite, walls) original_x = moving_sprite.center_x original_y = moving_sprite.center_y original_angle = moving_sprite.angle # --- Rotate rotating_hit_list = [] if moving_sprite.change_angle: # Rotate moving_sprite.angle += moving_sprite.change_angle # Resolve collisions caused by rotating rotating_hit_list = check_for_collision_with_list(moving_sprite, walls) if len(rotating_hit_list) > 0: max_distance = (moving_sprite.width + moving_sprite.height) / 2 # Resolve any collisions by this weird kludge _circular_check(moving_sprite, walls) if get_distance(original_x, original_y, moving_sprite.center_x, moving_sprite.center_y) > max_distance: # Ok, glitched trying to rotate. Reset. moving_sprite.center_x = original_x moving_sprite.center_y = original_y moving_sprite.angle = original_angle # --- Move in the y direction moving_sprite.center_y += moving_sprite.change_y # Check for wall hit hit_list_x = check_for_collision_with_list(moving_sprite, walls) # print(f"Post-y move {hit_list_x}") complete_hit_list = hit_list_x # If we hit a wall, move so the edges are at the same point if len(hit_list_x) > 0: if moving_sprite.change_y > 0: while len(check_for_collision_with_list(moving_sprite, walls)) > 0: moving_sprite.center_y -= 1 # print(f"Spot X ({self.player_sprite.center_x}, {self.player_sprite.center_y})" # f" {self.player_sprite.change_y}") elif moving_sprite.change_y < 0: # Reset number of jumps for item in hit_list_x: while check_for_collision(moving_sprite, item): # self.player_sprite.bottom = item.top <- Doesn't work for ramps moving_sprite.center_y += 0.25 if item.change_x != 0: moving_sprite.center_x += item.change_x # print(f"Spot Y ({self.player_sprite.center_x}, {self.player_sprite.center_y})") else: pass # TODO: The code below can't execute, as "item" doesn't # exist. In theory, this condition should never be arrived at. # Collision while player wasn't moving, most likely # moving platform. # if self.player_sprite.center_y >= item.center_y: # self.player_sprite.bottom = item.top # else: # self.player_sprite.top = item.bottom moving_sprite.change_y = min(0.0, hit_list_x[0].change_y) # print(f"Spot D ({self.player_sprite.center_x}, {self.player_sprite.center_y})") moving_sprite.center_y = round(moving_sprite.center_y, 2) # print(f"Spot Q ({self.player_sprite.center_x}, {self.player_sprite.center_y})") # end_time = time.time() # print(f"Move 1 - {end_time - start_time:7.4f}") # start_time = time.time() loop_count = 0 # --- Move in the x direction if moving_sprite.change_x: # Keep track of our current y, used in ramping up almost_original_y = moving_sprite.center_y # Strip off sign so we only have to write one version of this for # both directions direction = math.copysign(1, moving_sprite.change_x) cur_x_change = abs(moving_sprite.change_x) upper_bound = cur_x_change lower_bound = 0 cur_y_change = 0 exit_loop = False while not exit_loop: loop_count += 1 # print(f"{cur_x_change=}, {upper_bound=}, {lower_bound=}, {loop_count=}") # Move sprite and check for collisions moving_sprite.center_x = original_x + cur_x_change * direction collision_check = check_for_collision_with_list(moving_sprite, walls) # Update collision list for sprite in collision_check: if sprite not in complete_hit_list: complete_hit_list.append(sprite) # Did we collide? if len(collision_check) > 0: # We did collide. Can we ramp up and not collide? if ramp_up: cur_y_change = cur_x_change moving_sprite.center_y = original_y + cur_y_change collision_check = check_for_collision_with_list(moving_sprite, walls) if len(collision_check) > 0: cur_y_change -= cur_x_change else: while(len(collision_check) == 0) and cur_y_change > 0: # print("Ramp up check") cur_y_change -= 1 moving_sprite.center_y = almost_original_y + cur_y_change collision_check = check_for_collision_with_list(moving_sprite, walls) cur_y_change += 1 collision_check = [] if len(collision_check) > 0: # print(f"Yes @ {cur_x_change}") upper_bound = cur_x_change - 1 if upper_bound - lower_bound <= 0: cur_x_change = lower_bound exit_loop = True # print(f"Exit 2 @ {cur_x_change}") else: cur_x_change = (upper_bound + lower_bound) // 2 else: lower_bound = cur_x_change if upper_bound - lower_bound <= 0: exit_loop = True # print(f"Exit 1 @ {cur_x_change}") else: # No collision. Keep this new position and exit lower_bound = cur_x_change if upper_bound - lower_bound <= 0: # print(f"Exit 3 @ {cur_x_change}") exit_loop = True else: # print(f"No @ {cur_x_change}") cur_x_change = (upper_bound + lower_bound) // 2 + (upper_bound + lower_bound) % 2 # print(cur_x_change * direction, cur_y_change) moving_sprite.center_x = original_x + cur_x_change * direction moving_sprite.center_y = almost_original_y + cur_y_change # print(f"({moving_sprite.center_x}, {moving_sprite.center_y}) {cur_x_change * direction}, {cur_y_change}") # Add in rotating hit list for sprite in rotating_hit_list: if sprite not in complete_hit_list: complete_hit_list.append(sprite) # end_time = time.time() # print(f"Move 2 - {end_time - start_time:7.4f} {loop_count}") return complete_hit_list
def on_update(self, delta_time): """ Movement and game logic """ # Move the player with the physics engine self.physics_engine.update() # Update animations if self.physics_engine.can_jump(): self.player_sprite.can_jump = False else: self.player_sprite.can_jump = True if self.physics_engine.is_on_ladder() and not self.physics_engine.can_jump(): self.player_sprite.is_on_ladder = True self.process_keychange() else: self.player_sprite.is_on_ladder = False self.process_keychange() self.coin_list.update_animation(delta_time) self.background_list.update_animation(delta_time) self.player_list.update_animation(delta_time) # Update walls, used with moving platforms self.wall_list.update() # Update bullets. self.bullet_list.update() # Update explosions self.explosions_list.update() # Loop through each bullet for bullet in self.bullet_list: # Check this bullet to see if it hit a coin hit_list = arcade.check_for_collision_with_list(bullet, self.coin_list) # If it did, get rid of the bullet if len(hit_list) > 0: bullet.remove_from_sprite_lists() # For every coin we hit, add to the score and remove the coin for coin in hit_list: # Make an explosion for i in range(PARTICLE_COUNT): particle = Particle(self.explosions_list) particle.position = coin.position self.explosions_list.append(particle) smoke = Smoke(50) smoke.position = coin.position self.explosions_list.append(smoke) coin.remove_from_sprite_lists() self.score += 1 arcade.play_sound(self.collect_coin_sound) # If the bullet flies off-screen, remove it. if bullet.bottom < self.view_bottom \ or bullet.top > SCREEN_HEIGHT + self.view_bottom \ or bullet.right > self.view_left + SCREEN_WIDTH \ or bullet.left < self.view_left: bullet.remove_from_sprite_lists() # If the bullet hits a platform, remove it. # Check this bullet to see if it hit a wall hit_list = arcade.check_for_collision_with_list(bullet, self.wall_list) # If it did, get rid of the bullet if len(hit_list) > 0: # Make an explosion for i in range(PARTICLE_COUNT): particle = Particle(self.explosions_list) particle.position = bullet.position self.explosions_list.append(particle) smoke = Smoke(50) smoke.position = bullet.position self.explosions_list.append(smoke) arcade.play_sound(self.explosion_sound) bullet.remove_from_sprite_lists() # See if the moving wall hit a boundary and needs to reverse direction. for wall in self.wall_list: if wall.boundary_right and wall.right > wall.boundary_right and wall.change_x > 0: wall.change_x *= -1 if wall.boundary_left and wall.left < wall.boundary_left and wall.change_x < 0: wall.change_x *= -1 if wall.boundary_top and wall.top > wall.boundary_top and wall.change_y > 0: wall.change_y *= -1 if wall.boundary_bottom and wall.bottom < wall.boundary_bottom and wall.change_y < 0: wall.change_y *= -1 # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Figure out how many points this coin is worth if 'Points' not in coin.properties: print("Warning, collected a coin without a Points property.") else: points = int(coin.properties['Points']) self.score += points # Remove the coin coin.remove_from_sprite_lists() arcade.play_sound(self.collect_coin_sound) # See if we hit any coins do_not_touch_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.do_not_touch_list) if len(do_not_touch_hit_list) > 0: # Player died. view = GameOverView("You touched something you shouldn't.") self.window.show_view(view) # Track if we need to change the viewport changed_viewport = False # --- Manage Scrolling --- # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed_viewport = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed_viewport = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed_viewport = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed_viewport = True if changed_viewport: self.change_viewport() # Check if the player died. if self.player_sprite.bottom < -1000: view = GameOverView("You fell out of the world.") self.window.show_view(view)
def setup(self): self.wall_list = arcade.SpriteList(use_spatial_hash=True) self.player_list = arcade.SpriteList() # Create cave system using a 2D grid self.grid = create_grid(GRID_WIDTH, GRID_HEIGHT) initialize_grid(self.grid) for step in range(NUMBER_OF_STEPS): self.grid = do_simulation_step(self.grid) # Create sprites based on 2D grid if not MERGE_SPRITES: # This is the simple-to-understand method. Each grid location # is a sprite. for row in range(GRID_HEIGHT): for column in range(GRID_WIDTH): if self.grid[row][column] == 1: wall = arcade.Sprite( ":resources:images/tiles/grassCenter.png", SPRITE_SCALING) wall.center_x = column * SPRITE_SIZE + SPRITE_SIZE / 2 wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2 self.wall_list.append(wall) else: # This uses new Arcade 1.3.1 features, that allow me to create a # larger sprite with a repeating texture. So if there are multiple # cells in a row with a wall, we merge them into one sprite, with a # repeating texture for each cell. This reduces our sprite count. for row in range(GRID_HEIGHT): column = 0 while column < GRID_WIDTH: while column < GRID_WIDTH and self.grid[row][column] == 0: column += 1 start_column = column while column < GRID_WIDTH and self.grid[row][column] == 1: column += 1 end_column = column - 1 column_count = end_column - start_column + 1 column_mid = (start_column + end_column) / 2 wall = arcade.Sprite( ":resources:images/tiles/grassCenter.png", SPRITE_SCALING, repeat_count_x=column_count) wall.center_x = column_mid * SPRITE_SIZE + SPRITE_SIZE / 2 wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2 wall.width = SPRITE_SIZE * column_count self.wall_list.append(wall) # Set up the player self.player_sprite = arcade.Sprite( ":resources:images/animated_characters/female_person/femalePerson_idle.png", SPRITE_SCALING) self.player_list.append(self.player_sprite) # Randomly place the player. If we are in a wall, repeat until we aren't. placed = False while not placed: # Randomly position max_x = GRID_WIDTH * SPRITE_SIZE max_y = GRID_HEIGHT * SPRITE_SIZE self.player_sprite.center_x = random.randrange(max_x) self.player_sprite.center_y = random.randrange(max_y) # Are we in a wall? walls_hit = arcade.check_for_collision_with_list( self.player_sprite, self.wall_list) if len(walls_hit) == 0: # Not in a wall! Success! placed = True self.physics_engine = arcade.PhysicsEngineSimple( self.player_sprite, self.wall_list)
def on_update(self, delta_time): """ Movement and game logic """ # Start timing how long this takes start_time = timeit.default_timer() # Move the player with the physics engine self.physics_engine.update() # Update animations if self.physics_engine.can_jump(): self.player_sprite.can_jump = False else: self.player_sprite.can_jump = True if self.physics_engine.is_on_ladder( ) and not self.physics_engine.can_jump(): self.player_sprite.is_on_ladder = True self.process_keychange() else: self.player_sprite.is_on_ladder = False self.process_keychange() self.coin_list.update_animation(delta_time) self.background_list.update_animation(delta_time) self.player_list.update_animation(delta_time) # Update walls, used with moving platforms self.wall_list.update() # See if the moving wall hit a boundary and needs to reverse direction. for wall in self.wall_list: if wall.boundary_right and wall.right > wall.boundary_right and wall.change_x > 0: wall.change_x *= -1 if wall.boundary_left and wall.left < wall.boundary_left and wall.change_x < 0: wall.change_x *= -1 if wall.boundary_top and wall.top > wall.boundary_top and wall.change_y > 0: wall.change_y *= -1 if wall.boundary_bottom and wall.bottom < wall.boundary_bottom and wall.change_y < 0: wall.change_y *= -1 # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.coin_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Figure out how many points this coin is worth if 'Type' not in coin.properties: print("Warning, collected an item without a Type property.") else: trigger = int(coin.properties['Type']) print("Triggered:", trigger) for wall in self.wall_list: if "Type" not in wall.properties: pass else: if int(wall.properties['Type']) == trigger: wall.remove_from_sprite_lists() # Remove the coin coin.remove_from_sprite_lists() arcade.play_sound(self.collect_coin_sound) # Track if we need to change the viewport changed_viewport = False # Did the player fall off the map? if self.player_sprite.center_y < -100: self.player_sprite.center_x = PLAYER_START_X self.player_sprite.center_y = PLAYER_START_Y self.score -= 1 if self.score <= 0: view = GameOverView() self.window.show_view(view) # Set the camera to the start # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True arcade.play_sound(self.game_over) # Did the player touch something they should not? if arcade.check_for_collision_with_list(self.player_sprite, self.dont_touch_list): self.player_sprite.change_x = 0 self.player_sprite.change_y = 0 self.player_sprite.center_x = PLAYER_START_X self.player_sprite.center_y = PLAYER_START_Y # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True arcade.play_sound(self.game_over) self.score -= 1 if self.score <= 0: view = GameOverView() self.window.show_view(view) # See if the user got to the end of the level if arcade.check_for_collision_with_list(self.player_sprite, self.do_touch_list): # Advance to the next level if self.level == 1: self.tutorial_num += 1 self.level += 1 # Load the next level if self.level > LEVEL_MAX: view = GameOverView() self.level = LEVEL_MAX self.window.show_view(view) else: view = LevelOverView(self) self.setup(self.level) self.left_pressed = False self.right_pressed = False self.up_pressed = False self.down_pressed = False self.window.show_view(view) # Set the camera to the start self.view_left = 0 self.view_bottom = 0 changed_viewport = True # --- Manage Scrolling --- # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed_viewport = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed_viewport = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed_viewport = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed_viewport = True if changed_viewport: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom) # Stop the draw timer, and calculate total on_draw time. self.processing_time = timeit.default_timer() - start_time
def update(self, delta_time): """ Movement and game logic """ if self.score == 3: ctypes.windll.user32.MessageBoxW(0, "You Win!", "You Win!", 1) # Call update on all sprites (The sprites don't do much in this # example though.) self.physics_engine.update() # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.coin_list) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Remove the coin coin.remove_from_sprite_lists() # Add one to the score self.score += 1 # --- Manage Scrolling --- # Track if we need to change the viewport changed = False # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed = True if changed: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def on_update(self, delta_time): self.player_list.update_animation() self.player_list.update() self.physics_engine.update() self.time -= delta_time #zabraňuje padání mimo mapu if self.player.right < 100 or self.player.right > 15000: self.player.change_x = 0 elif self.player.top > 600: self.player.change_y = -1 #pohyb protivníka for one_rival in self.rival: if int(self.time) % 2 == 0: one_rival.right += 2 else: one_rival.right -= 2 #pohyb coin for one_coin in self.coin: if int(self.time) % 2 == 0: one_coin.angle += 0.5 else: one_coin.angle -= 0.5 scroll_map = False #nastavení posunu mapy - pravá right_boundary = self.view_left + WIDTH - RIGHT_SCROLL if self.player.right > right_boundary: if self.player.right < 6900: self.view_left += self.player.right - right_boundary scroll_map = True #nastavení posunu mapy - levá left_boundary = self.view_left + 20 if self.player.left < left_boundary: if self.player.right < 6900: self.view_left -= left_boundary - self.player.left scroll_map = True #nastavení posunu mapy - nahoru top_boundary = self.view_bottom + HEIGHT - 40 if self.player.top > top_boundary: self.view_bottom += self.player.top - top_boundary scroll_map = True #nastavení posunu mapy - dolů bottom_boundary = self.view_bottom + 150 if self.player.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player.bottom #aby se neposouvala mapa pod vodu if self.view_bottom < 0: self.view_bottom = 0 scroll_map = True if scroll_map == True: self.view_left = int(self.view_left) arcade.set_viewport(self.view_left, WIDTH + self.view_left, self.view_bottom, HEIGHT + self.view_bottom) #pokud spadne postava do vody water_hit = arcade.check_for_collision_with_list(self.player, self.water) if water_hit: arcade.play_sound(self.lose_sound) time.sleep(0.3) view = End_lose() self.window.show_view(view) #pokud narazí do tanku rival_hit = arcade.check_for_collision_with_list(self.player, self.rival) if rival_hit: arcade.play_sound(self.lose_sound) time.sleep(0.3) view = End_lose() self.window.show_view(view) #sbírání peněz coin_hit = arcade.check_for_collision_with_list(self.player, self.coin) for coin in coin_hit: self.count_score += 1 coin.kill() arcade.play_sound(self.coin_sound) #pokud dojde do domečku house_end = arcade.check_for_collision_with_list(self.player, self.house) for house in house_end: if self.level < 3: self.level += 1 self.load_level(self.level) self.player.center_x = 200 self.player.center_y = 200 self.player.change_x = 0 self.player.change_y = 0 arcade.set_viewport(0, WIDTH, 0, HEIGHT) self.time = 50 arcade.play_sound(self.win_sound) else: time.sleep(0.9) view = End_win() self.window.show_view(view) arcade.play_sound(self.win_sound) #pokud vyprší čas if int(self.time) % 60 == 0: arcade.play_sound(self.lose_sound) time.sleep(0.3) view = End_lose() self.window.show_view(view)
def updaate(self,delta_time): self.coin_sprite_list.update hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_sprite_list) for coin in hit_list: coin.kill() self.score+=1
def on_update(self, delta_time): """ Movement and game logic """ if self.player_sprite.right >= self.end_of_map: self.game_over = True # Call update on all sprites (The sprites don't do much in this # example though.) if not self.game_over: self.physics_engine.update() light_source = arcade.LightSource(200, 50, 200) self.wall_list.light_list = [light_source] self.coin_list.light_list = [light_source] self.player_list.light_list = [light_source] self.wall_list._calculate_sprite_buffer() coins_hit = arcade.check_for_collision_with_list( self.player_sprite, self.coin_list) for coin in coins_hit: coin.remove_from_sprite_lists() self.score += 1 # --- Manage Scrolling --- # Track if we need to change the view port changed = False # Scroll left left_bndry = self.view_left + VIEWPORT_LEFT_MARGIN if self.player_sprite.left < left_bndry: self.view_left -= left_bndry - self.player_sprite.left changed = True # Scroll right right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_RIGHT_MARGIN if self.player_sprite.right > right_bndry: self.view_left += self.player_sprite.right - right_bndry changed = True # Scroll up top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN_TOP if self.player_sprite.top > top_bndry: self.view_bottom += self.player_sprite.top - top_bndry changed = True # Scroll down bottom_bndry = self.view_bottom + VIEWPORT_MARGIN_BOTTOM if self.player_sprite.bottom < bottom_bndry: self.view_bottom -= bottom_bndry - self.player_sprite.bottom changed = True # If we need to scroll, go ahead and do it. if changed: self.view_left = int(self.view_left) self.view_bottom = int(self.view_bottom) arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def animate(self, delta_time): """ Movement and game logic """ # Only move and do things if the game is running. if self.current_state == GAME_RUNNING: # Call update on all sprites (The sprites don't do much in this # example though.) self.all_sprites_list.update() # Generate a list of all sprites that collided with the player. hit_list = \ arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # Loop through each colliding sprite, remove it, and add to the # score. for coin in hit_list: coin.kill() self.score += 1 # If we've collected all the games, then move to a "GAME_OVER" # state. if len(self.coin_list) == 0: self.current_state = GAME_OVER self.set_mouse_visible(True)