def test_animation_should_end_correctly(self): dummy_frames = ["0", "1", "2", "3", "4"] dummy_delay = 100 a = Animation(dummy_frames, dummy_delay) self.assertEqual(500, a.get_duration()) # start animation at 10_000-th millisecond a.start(10_000) self.assertFalse(a.is_over()) self.assertEqual("0", a.get_image(10_000)) self.assertEqual("0", a.get_image(10_050)) self.assertFalse(a.is_over()) self.assertEqual("1", a.get_image(10_100)) self.assertEqual("1", a.get_image(10_199)) self.assertFalse(a.is_over()) self.assertEqual("3", a.get_image(10_333)) self.assertEqual("3", a.get_image(10_366)) self.assertFalse(a.is_over()) self.assertEqual("4", a.get_image(10_400)) self.assertFalse(a.is_over()) self.assertEqual("4", a.get_image(10_500)) self.assertTrue(a.is_over()) self.assertEqual("4", a.get_image(22_222)) self.assertTrue(a.is_over())
def test_animator_should_not_initialize_with_bad_animations(self): dummy_frames = ["A", "B", "C"] dummy_delay = 100 a1 = Animation(dummy_frames, dummy_delay, loop=True) dummy_frames = ["E", "F", "G"] dummy_delay = 50 a2 = Animation(dummy_frames, dummy_delay, loop=True) dummy_frames = ["H", "I", "J"] dummy_delay = 10 a3 = Animation(dummy_frames, dummy_delay) dummy_frames = ["K", "L", "M"] dummy_delay = 2000 a4 = Animation(dummy_frames, dummy_delay) self.assertRaises(AnimationException, lambda: FallbackAnimator({ "0": a1, "1": a2 })) self.assertRaises(AnimationException, lambda: FallbackAnimator({ "2": a3, "3": a4 }))
def __init__(self, enemy): animations = { 'left': Animation(assets.images.enemies.krush, ('walk_left_1', 'walk_left_2', 'walk_left_3'), 100), 'right': Animation(assets.images.enemies.krush, ('walk_right_1', 'walk_right_2', 'walk_right_3'), 100) } MovingState.__init__(self, enemy, animations, .4, 0)
def __init__(self, player): animations = { 'left': Animation(assets.images.player, ('walk_left_1', 'walk_left_2'), 200), 'right': Animation(assets.images.player, ('walk_right_1', 'walk_right_2'), 200) } State.__init__(self, player, animations, .3, .5)
def __init__(self, player): animations = { 'left': Animation(assets.images.player, ('jump_left', )), 'right': Animation(assets.images.player, ('jump_right', )) } State.__init__(self, player, animations, .3, .5) self.name = None self.jumping_time = 0
class ShardSprite(pygame.sprite.Sprite): scene: 'GameScene' shard: Shard image: Surface rect: Rect hitbox: Rect animation: Animation def __init__(self, scene: 'GameScene', shard: Shard, *groups: AbstractGroup): super().__init__(*groups) self.scene = scene self.shard = shard scale_factor = self.scene.settings.scale_factor # load images and create looping animation frames = load_scaled_surfaces(ANIM_SHARD_IDLE, scale_factor) self.image = frames[0] self.animation = Animation(frames, 75, loop=True) self.animation.start(pygame.time.get_ticks()) center_of_first_tile = ((TILE_SIZE_PX // 2) * scale_factor, (TILE_SIZE_PX // 2) * scale_factor) # set rect and hitbox self.rect = self.image.get_rect(center=center_of_first_tile) self.hitbox = self.rect.copy() self.hitbox.inflate_ip(-3 * scale_factor, -3 * scale_factor) def update(self, *args, **kwargs) -> None: self._update_rectangle_based_on_current_position() self.image = self.animation.get_image(pygame.time.get_ticks()) def _update_rectangle_based_on_current_position(self): scale_factor = self.scene.settings.scale_factor position = self.shard.position x = (position.x * TILE_SIZE_PX) + (TILE_SIZE_PX // 2) x = x * scale_factor y = ((position.y - self.scene.vertical_shift) * TILE_SIZE_PX) + (TILE_SIZE_PX // 2) y = y * scale_factor self.rect.center = (x, y) self.hitbox.center = (x, y)
def __init__(self, enemy): animations = { 'left': Animation(assets.images.enemies.krush, ('flat_left_1', 'flat_left_2', 'flat_left_3'), 100), 'right': Animation(assets.images.enemies.krush, ('flat_right_1', 'flat_right_2', 'flat_right_3'), 100) } self.counter = 0 self.max_flat_time = 5000 MovingState.__init__(self, enemy, animations, .1, 0)
def __init__(self, settings, screen, images): """Initialize the blob""" super().__init__(settings, screen, images) # Override the start position self.dx = self.settings.enemy_blob_dx # Set the blob-specific animations self.animations[self.settings.anim_name_walk_left] = Animation([0, 1, 2, 1], 2) self.animations[self.settings.anim_name_walk_right] = Animation([3, 4, 5, 4], 2) self.animations[self.settings.anim_name_jump_down_left] = Animation([6], 1) self.animations[self.settings.anim_name_jump_down_right] = Animation([6], 1) self.animations[self.settings.anim_name_dead] = Animation([7], 60) self.current_animation = self.settings.anim_name_walk_right self.facing_left = False
def __init__(self, settings, screen, images, tile_map): """Initialize the animated blade and the particle generator for the map""" # AnimatedSprite init super().__init__(settings, screen, images) # store the map self.tile_map = tile_map # Set the location - at the bottom, in the tile with the 'drain' self.rect.move_ip(0, 0) self.rect.move_ip( self.screen_rect.width / 2 - settings.tile_width, self.tile_map.player_bounds_rect.bottom + self.settings.tile_height) # only 1 animation, could add a "bloody" one self.animations[self.settings.anim_name_exit] = Animation([0, 1], 1) self.current_animation = self.settings.anim_name_exit # Blob gibs # Leaving the callback out of this call 'self.generate_particles' will take the default behavior # which is randomized differently. Add a comment to see e.g. # ..., settings, settings.particle_gen_color, 0, 0)#, self.generate_particles) self.particle_gen = ParticleGenerator(screen, settings, settings.particle_gen_color, 0, 0, self.generate_particles) self.particle_gen.x = self.screen_rect.centerx - self.settings.tile_width / 2 self.particle_gen.y = self.screen_rect.bottom - self.settings.tile_width / 2 # This is the count of frames the generator will be active upon collision with a blob self.particles_frames_max = self.settings.particle_gen_max_frames # Override default update handling in the base self.bound_by_the_laws_of_physics = False self.bound_by_map = False
def __init__(self, enemy): animations = { 'moving': Animation(assets.images.enemies.turtle, ('shell_move_1', 'shell_move_2', 'shell_move_3'), 100) } MovingState.__init__(self, enemy, animations, .5)
def test_animator_should_be_initialized_correctly(self): dummy_frames = ["A", "B", "C"] dummy_delay = 100 a1 = Animation(dummy_frames, dummy_delay, loop=True) animator = FallbackAnimator({"0": a1}) animator.start(10_000) self.assertEqual("A", animator.get_image(10_000))
def __init__(self, settings, screen, images, initial_bounding_rect, tile_map): """Initialize the player sprite""" # Calls AnimatedSprite, which in turn will call pygame.Sprite __init_() super().__init__(settings, screen, images) self.tile_map = tile_map # Override the initial position self.initial_bounding_rect = initial_bounding_rect self.rect.bottom = initial_bounding_rect.bottom self.rect.left = self.screen.get_rect().width / 2 # Set the transparent margins self.margin_left = self.settings.player_sprite_horz_margin self.margin_right = self.settings.player_sprite_horz_margin self.margin_top = self.settings.player_sprite_top_margin # set the optional collision check callback self.collision_check = self.collided # These are specific to the player object self.air_jumps = 0 self.max_air_jumps = settings.player_max_air_jumps self.idle_top = False self.idle_counter = 0 self.won_level = False self.at_top = False # Add the animations for the player self.animations[self.settings.anim_name_idle_left] = Animation( [0, 1, 2, 3, 2, 1], 5) self.animations[self.settings.anim_name_idle_right] = Animation( [5, 6, 7, 8, 7, 6], 5) self.animations[self.settings.anim_name_walk_left] = Animation( [0, 10, 11, 10], 2) self.animations[self.settings.anim_name_walk_right] = Animation( [5, 12, 13, 12], 2) self.animations[self.settings.anim_name_jump_up_left] = Animation([15], 5) self.animations[self.settings.anim_name_jump_down_left] = Animation( [16], 5) self.animations[self.settings.anim_name_jump_up_right] = Animation( [17], 5) self.animations[self.settings.anim_name_jump_down_right] = Animation( [18], 5) self.animations[self.settings.anim_name_dead] = Animation([4], 5) self.current_animation = self.settings.anim_name_idle_left self.facing_left = True
def __init__(self, scene: 'GameScene', shard: Shard, *groups: AbstractGroup): super().__init__(*groups) self.scene = scene self.shard = shard scale_factor = self.scene.settings.scale_factor # load images and create looping animation frames = load_scaled_surfaces(ANIM_SHARD_IDLE, scale_factor) self.image = frames[0] self.animation = Animation(frames, 75, loop=True) self.animation.start(pygame.time.get_ticks()) center_of_first_tile = ((TILE_SIZE_PX // 2) * scale_factor, (TILE_SIZE_PX // 2) * scale_factor) # set rect and hitbox self.rect = self.image.get_rect(center=center_of_first_tile) self.hitbox = self.rect.copy() self.hitbox.inflate_ip(-3 * scale_factor, -3 * scale_factor)
def test_animator_should_animate_correctly(self): a1 = Animation(["A", "B"], 100, loop=True) a2 = Animation(["C", "D"], 10) animator = FallbackAnimator({"0": a1, "1": a2}) animator.start(10_000) self.assertEqual("A", animator.get_image(10_000)) self.assertEqual("B", animator.get_image(10_120)) # looping animation loops self.assertEqual("A", animator.get_image(10_210)) # start other animation animator.start_animation("1", 10_210) self.assertEqual("C", animator.get_image(10_210)) self.assertEqual("C", animator.get_image(10_219)) self.assertEqual("D", animator.get_image(10_225)) # fallback to looping animation self.assertEqual("A", animator.get_image(10_235)) self.assertEqual("A", animator.get_image(10_329)) self.assertEqual("B", animator.get_image(10_330))
def __init__(self, settings, screen, images, initial_bounding_rect, tile_map): """Inicialize o sprite do jogador""" # Calls AnimatedSprite, which in turn will call pygame.Sprite __init_() super().__init__(settings, screen, images) self.tile_map = tile_map # Substituir a posição inicial self.initial_bounding_rect = initial_bounding_rect self.rect.bottom = initial_bounding_rect.bottom self.rect.left = self.screen.get_rect().width / 2 # Defina as margens transparentes self.margin_left = self.settings.player_sprite_horz_margin self.margin_right = self.settings.player_sprite_horz_margin self.margin_top = self.settings.player_sprite_top_margin # definir o retorno de chamada de verificação de colisão opcional self.collision_check = self.collided # Estes são específicos para o objeto do jogador self.air_jumps = 0 self.max_air_jumps = settings.player_max_air_jumps self.idle_top = False self.idle_counter = 0 self.won_level = False self.at_top = False # Adicione as animações para o jogador self.animations[self.settings.anim_name_idle_left] = Animation([0, 1, 2, 3, 2, 1], 5) self.animations[self.settings.anim_name_idle_right] = Animation([5, 6, 7, 8, 7, 6], 5) self.animations[self.settings.anim_name_walk_left] = Animation([0, 10, 11, 10], 2) self.animations[self.settings.anim_name_walk_right] = Animation([5, 12, 13, 12], 2) self.animations[self.settings.anim_name_jump_up_left] = Animation([15], 5) self.animations[self.settings.anim_name_jump_down_left] = Animation([16], 5) self.animations[self.settings.anim_name_jump_up_right] = Animation([17], 5) self.animations[self.settings.anim_name_jump_down_right] = Animation([18], 5) self.animations[self.settings.anim_name_dead] = Animation([4], 5) self.current_animation = self.settings.anim_name_idle_left self.facing_left = True
def init_animation(event_queue): """Initialises the animation""" path = os.path.dirname(__file__) directories = [ os.path.join(path, p) for p in os.listdir(path) if os.path.isdir(os.path.join(path, p)) ] folder = directories[0] if directories else "" animation = Animation(folder) event_queue.subscribe("SET_FOLDER", animation.set_folder) event_queue.subscribe("SET_ALPHA", animation.set_alpha) event_queue.subscribe("SET_REPEAT", animation.set_repeating) event_queue.subscribe("SET_POSITION", animation.set_position) return animation
def launch_the_game(event): interface.new_playfield(width=200, height=80) floors = [] for y in range(0, 40): floors.append([(x, y, WalkableTerrain()) for x in range(0, 60)]) for f in sum(floors, []): x, y, ent = f ent.introduce_at(x, y, interface.playfield) walls = [(x, 20, Wall()) for x in range(0, 11)] for w in walls: x, y, ent = w ent.introduce_at(x, y, interface.playfield) player_char = Mobile(size=4, sigil=Sigil("@", priority=3), name="Player Character") player_char.introduce_at(10, 10, interface.playfield) interface.playfield.player_character = player_char interface.playfield.origin = (2, 2) interface.add_animation(7, 7, Animation(frames=[AnimationFrame(Sigil("\\"), 5), AnimationFrame(Sigil("|"), 5), AnimationFrame(Sigil("/"), 5), AnimationFrame(Sigil("-"), 5)], repeating=True)) blue_floor = WalkableTerrain(color=(50, 50, 255)) blue_floor.sigil = Sigil("!", priority=blue_floor.sigil.priority) blue_floor.introduce_at(12, 12, interface.playfield) # print(interface.playfield.get_cell(12, 12).sigils) interface.new_game_log(height=10, width=40) interface.print_to_log("This is a log tests!", color=(25, 250, 25)) interface.print_to_log("This is an exceptionally long log tests so we can see how well it handles multiples of these.") interface.print_to_log("This is another line.") interface.print_to_log("This is yet another line.") interface.print_to_log("This should bump the first line off of the screen.") menu.close_menu()
def __init__(self, enemy): animations = { 'shell': Animation(assets.images.enemies.turtle, ('shell_front',)) } State.__init__(self, enemy, animations)
def the_tsp_problem(): # Initialize modules start_timer("setup") x_large_data = "../data/TSP_Italy_16862.txt" big_data = "../data/TSP_Canada_4663.txt" middle_data = "../data/TSP_Uruguay_734.txt" small_data = "../data/TSP_WesternSahara_29.txt" actual_data = parse(middle_data) # Create Instance tsp = TSP(graph=actual_data, population_size=POP_SIZE, mating_pool_size=MATING_POOL_SIZE, mutation_rate=MUTATION_RATE, num_generations=NUM_GENERATIONS) # Initialize modules initializer = Initialization(tsp, INIT_METHOD) parent_selector = Parent_Selection(tsp, SELECT_METHOD) mutator = Mutation(tsp, MUTATION_METHOD) evaluator = Evaluation(tsp, EVALUATION_METHOD) recombinator = Recombination(tsp, CROSSOVER_METHOD, evaluator) survivor_selector = Survivor_Selection(tsp, SURVIVOR_METHOD) terminator = Termination(NUM_GENERATIONS, TIME_LIMIT, TERMINATOR_METHOD) # Initialize Population and fitness initializer.initialize() evaluator.evaluate() end_timer("setup") print("*" * 20) print("Initial Mean Fitness: {}\t Best Fitness:{}".format( tsp.fitness.mean(), tsp.fitness.max())) # print("Best initial member of Population:\n", tsp.population[np.argmax(tsp.fitness)]) print("*" * 20) current_time = 0 fitness = [] generation = [] while terminator.method(tsp.current_generation, current_time): # select parents and spawn children parent_selector.select() recombinator.recombine() # mutate population and children mutator.mutate_population() mutator.mutate_children() # re-evaluate children and population evaluator.evaluate(use_mask=True) evaluator.evaluate_children() # select from parents and children to form new population survivor_selector.select() # add history and print debugs every 10% tsp.add_history("mean_fitness", tsp.fitness.mean()) tsp.add_history("best_fitness", tsp.fitness.max()) std = tsp.fitness.std() tsp.add_history("std_dev", std) tsp.current_generation += 1 if not (tsp.current_generation % (tsp.num_generations // 10)): # print("Mutation Rate:",tsp.mutation_rate) print( "Generation {:<4} Mean Fitness: {:5.2f}\t Best Fitness:{:5.2f}\t STD DEV: {:.2f}" .format(tsp.current_generation, tsp.fitness.mean(), tsp.fitness.max(), std)) tsp.add_history("best_individual", tsp.population[np.argmax(tsp.fitness.max())]) fitness.append(tsp.fitness.max()) generation.append(tsp.current_generation) # If animation is set to true if ANIMATE: animator = Animation(actual_data, tsp.history["best_individual"], fitness, generation) animator.start() # finished, print results print("*" * 20) # print("Best Member of Population:\n", tsp.population[np.argmax(tsp.fitness)]) print("Final Mean Fitness: {}\t Best Fitness:{}".format( tsp.fitness.mean(), tsp.fitness.max())) print("*" * 10 + "\nFunction Times (in ms):\n") time_sum = 0 for k, v in get_times(): print("{:16}\t{:.2f}".format(k, v * 1000)) time_sum += v print("-" * 20) print("Total Time:\t{:.2f} seconds".format(time_sum)) # plot history tsp.plot_history("mean_fitness") tsp.plot_history("best_fitness") tsp.plot_history("std_dev")
def test_animation_should_loop_forever(self): dummy_frames = ["0", "1", "2"] dummy_delay = 10 a = Animation(dummy_frames, dummy_delay, loop=True) # start animation at 100-th millisecond a.start(100) self.assertFalse(a.is_over()) self.assertEqual("0", a.get_image(100)) self.assertEqual("0", a.get_image(101)) self.assertFalse(a.is_over()) self.assertEqual("2", a.get_image(120)) self.assertEqual("2", a.get_image(129)) self.assertFalse(a.is_over()) self.assertEqual("0", a.get_image(130)) self.assertFalse(a.is_over()) self.assertEqual("1", a.get_image(145)) self.assertFalse(a.is_over()) self.assertEqual("2", a.get_image(150)) self.assertFalse(a.is_over()) self.assertEqual("1", a.get_image(410)) self.assertFalse(a.is_over())
def __init__(self, player): animations = { 'left': Animation(assets.images.player, ('stand_left', )), 'right': Animation(assets.images.player, ('stand_right', )) } State.__init__(self, player, animations, .3, .5)
""" Make an animation of the simulated particle positions. Authors: Jonah Post """ from src.animation import Animation from src.utils import N_runs if __name__ == "__main__": # Get the first path in the list of length one path = N_runs(N=1, temperature=300, density=1.602, steps=5000, time_step=1e-2)[0] # Initialize animation class ani = Animation(path, frameskip=10) # Show the animation ani.run()