def load_sprites(filename, row, col, grid_mapping): grid = TextureGrid(ImageGrid(load_image(filename), row, col)) sprites = {} index = 0 for item in grid_mapping: if isinstance(item, Img): grid_index = get_grid_index(index, row, col) sprites[item.name] = grid[grid_index] index += 1 elif isinstance(item, Anim): sprites[item.name] = Animation.from_image_sequence( [ grid[get_grid_index(index + offset, row, col)] for offset in range(item.nb_frame) ], item.period, item.loop, ) index += item.nb_frame elif isinstance(item, Skip): index += item.skip_nb else: raise WrongGridMappingError(item) return sprites
def __init__(self, src: str, background: tuple = None, speed: Union[int, float] = 1, damage: Union[int, float] = 1, acceleration: Union[int, float] = 0, animated: bool = False, animation_rows: int = None, animation_columns: int = None, animation_item_width: int = None, animation_item_height: int = None, animation_period: float = 0.1, animation_main_frame: int = 0, *args, **kwargs) -> None: """ :param src: File of the image to load :param background: A tuple representing RGBA values for the background :param speed: Speed at which the projectile will move :param damage: Damage the projectile will deal :param acceleration: Acceleration in m/s^2 :param animated: Flag saying if the projectile uses an animation :param animation_rows: The number of rows in the animation sequence source :param animation_columns: The number of columns in the animation sequence source :param animation_item_width: The width of each frame of the animation in the source :param animation_item_height: The height of each frame in the source :param animation_period: Time to show each frame :param animation_main_frame: The frame in which the hitbox bounds will be calculated :param args: :param kwargs: """ if animated: image = load(src) image_seq = ImageGrid(image, rows=animation_rows, columns=animation_columns, item_width=animation_item_width, item_height=animation_item_height) image_texture = TextureGrid(image_seq) img = Animation.from_image_sequence(image_texture[0:], period=animation_period, loop=True) # self.src = image_array = cv.imread(src) x1 = animation_item_width * animation_main_frame x2 = x1 + animation_item_width self.np = image_array[:, x1:x2] # The numpy array used for the collision test will be the slice else: img = load(src) self.np = cv.imread(src) # The whole image will be read self.src = img self.background = background self.speed = speed self.acceleration = acceleration self.damage = damage super().__init__(img, *args, **kwargs) self.radians = 0 # self.anchor if animated: for frame in self.image.frames: frame.image.anchor_x = image.width / animation_columns / 2 frame.image.anchor_y = image.height / animation_rows / 2 else: self.image.anchor_x = self.image.width / 2 self.image.anchor_y = self.image.height / 2 self.init_time = time.time() self.update(x=self.x, y=self.y) self.refresh_threshold() if self.background: self.rectangle = Rectangle(x=self.get_left_bound(), y=self.get_bot_bound(), width=self.width, height=self.height, color=self.background)
def collide(self, node): if node is not None: for other in self.man_col.iter_colliding(node): if self.children.count((1, other)) != 0: other.kill() if isinstance(other, Enemigo): self.HUD.puntos += 10 self.HUD.update() if self.children.count((1, node)) != 0: node.kill() seq = ImageGrid(load('Explosion.png'), 1, 1) anim = Animation.from_image_sequence(seq, 0.05, False) self.sprite = Sprite(anim, (other.x, other.y)) self.add(self.sprite) self.do(Delay(0.8) + CallFunc(self.sprite.kill))
def load_tileset(cls, tileset): filename = tileset["image"] if not filename in cls.__independant_tilesets: try: img = pyglet.resource.image(filename) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) except IOError: print "[resource manager error] unable to load image '%s'" % filename return None img.anchor_x = 0 img.anchor_y = 0 if "nbtile_width" in tileset: tilewidth = img.width / tileset["nbtile_width"] #assert tilewidth >= 1 elif "tilewidth" in tileset: tilewidth = tileset["tilewidth"] else: tilewidth = img.width if "nbtile_height" in tileset: tileheight = img.height / tileset["nbtile_height"] #assert tileheight >= 1 elif "tileheight" in tileset: tileheight = tileset["tileheight"] else: tileheight = img.height rx = img.width / tilewidth ry = img.height / tileheight img_grid = ImageGrid(img, ry, rx) for _img in img_grid: _img.anchor_x = 0 _img.anchor_y = 0 tileset["frames"] = TextureGrid(img_grid) tileset["tilewidth"] = tilewidth tileset["tileheight"] = tileheight cls.__independant_tilesets[filename] = tileset return cls.__independant_tilesets[filename]
def load_animation(imgage): seq = ImageGrid(load(imgage), 2, 1) return Animation.from_image_sequence(seq, 0.5)
class Image: resource.path.append("../res/image") resource.reindex() try: background = resource.image("background.png") menu = resource.image("menu.png") mario = resource.image("mario.png") sprite_set = resource.image("sprite_set.png") except resource.ResourceNotFoundException: raise SystemExit("cannot find images!") sprite_set_small = ImageGrid(sprite_set, 20, 20) sprite_set_big = ImageGrid(sprite_set, 10, 20) # mario mario_walk_right_small = [sprite_set_small[(18, 0)], sprite_set_small[(18, 1)], sprite_set_small[(18, 2)]] mario_walk_left_small = [image.get_transform(flip_x=True) for image in mario_walk_right_small] mario_walk_right_big = [sprite_set_big[(8, 0)], sprite_set_big[(8, 1)], sprite_set_big[(8, 2)]] mario_walk_left_big = [image.get_transform(flip_x=True) for image in mario_walk_right_big] mario_walk_right_fire = [sprite_set_big[(7, 0)], sprite_set_big[(7, 1)], sprite_set_big[(7, 2)]] mario_walk_left_fire = [image.get_transform(flip_x=True) for image in mario_walk_right_fire] mario_walk = [[mario_walk_right_small, mario_walk_left_small], [mario_walk_right_big, mario_walk_left_big], [mario_walk_right_fire, mario_walk_left_fire]] mario_jump_right_small = sprite_set_small[(18, 4)] mario_jump_left_small = mario_jump_right_small.get_transform(flip_x=True) mario_jump_right_big = sprite_set_big[(8, 4)] mario_jump_left_big = mario_jump_right_big.get_transform(flip_x=True) mario_jump_right_fire = sprite_set_big[(7, 4)] mario_jump_left_fire = mario_jump_right_fire.get_transform(flip_x=True) mario_jump = [[mario_jump_right_small, mario_jump_left_small], [mario_jump_right_big, mario_jump_left_big], [mario_jump_right_fire, mario_jump_left_fire]] mario_stand_right_small = sprite_set_small[(18, 6)] mario_stand_left_small = mario_stand_right_small.get_transform(flip_x=True) mario_stand_right_big = sprite_set_big[(8, 6)] mario_stand_left_big = mario_stand_right_big.get_transform(flip_x=True) mario_stand_right_fire = sprite_set_big[(7, 6)] mario_stand_left_fire = mario_stand_right_fire.get_transform(flip_x=True) mario_stand = [[mario_stand_right_small, mario_stand_left_small], [mario_stand_right_big, mario_stand_left_big], [mario_stand_right_fire, mario_stand_left_fire]] mario_die = sprite_set_small[(18, 5)] mario_walk_to_castle = [Animation.from_image_sequence(mario_walk_right_small, 0.1), Animation.from_image_sequence(mario_walk_right_big, 0.1), Animation.from_image_sequence(mario_walk_right_fire, 0.1)] mario_lower_flag_small = [sprite_set_small[(18, 7)], sprite_set_small[(18, 8)]] mario_lower_flag_big = [sprite_set_big[(8, 7)], sprite_set_big[(8, 8)]] mario_lower_flag_fire = [sprite_set_big[(7, 7)], sprite_set_big[(7, 8)]] mario_lower_flag = [Animation.from_image_sequence(mario_lower_flag_small, 0.2), Animation.from_image_sequence(mario_lower_flag_big, 0.2), Animation.from_image_sequence(mario_lower_flag_fire, 0.2)] mario_lower_flag_turn_around = [sprite_set_small[(18, 8)].get_transform(flip_x=True), sprite_set_big[(8, 8)].get_transform(flip_x=True), sprite_set_big[(7, 8)].get_transform(flip_x=True)] # prop normal_mushroom = sprite_set_small[(7, 0)] life_mushroom = sprite_set_small[(7, 1)] frames = [sprite_set_small[(5, 0)], sprite_set_small[(5, 1)]] fire_flower_blink = Animation.from_image_sequence(frames, 0.3) # enemy frames = [sprite_set_small[(10, 7)], sprite_set_small[(10, 8)]] goomba_move = Animation.from_image_sequence(frames, 0.3) goomba_die = sprite_set_small[(10, 9)] frames = [sprite_set_big[(5, 0)], sprite_set_big[(5, 1)]] koopa_move = Animation.from_image_sequence(frames, 0.3) koopa_die = sprite_set_small[(10, 4)] # others # cliff is a total transparent image cliff = sprite_set_small[(2, 2)] coin = sprite_set_big[(3, 4)] flag = sprite_set_small[(0, 0)] castle_flag = sprite_set_small[(2, 0)] normal_brick = sprite_set_small[(0, 3)] unknown_brick = sprite_set_small[(0, 6)] try: normal_brick2 = load("../res/image/brick.png") except Exception as e: raise SystemExit(e)
''' 程序:动画演示 作者:苏秦@小海豚科学馆公众号 来源:图书《Python趣味编程:从入门到人工智能》 ''' import pyglet from pyglet.image import ImageGrid from pyglet.image import Animation game_win = pyglet.window.Window(width=1024, height=768) image = pyglet.resource.image('fish2.png') img_seq = ImageGrid(image, 8, 1) print(len(img_seq)) animation = Animation.from_image_sequence(img_seq[:3:-1], 0.2) fish = pyglet.sprite.Sprite(animation, 500, 300) @game_win.event def on_draw(): game_win.clear() img_seq[0].blit(0, 0) fish.draw() if __name__ == '__main__': pyglet.app.run()
def __init__(self, enable_neat=False, *args, **kwargs): # Inherit the pyglet window super().__init__(*args, **kwargs) # Save the configuration that determines if the NEAT algorithm is used self.enable_neat = enable_neat # Generate the font style pyglet.font.add_file('data/fonts/press_start_2p.ttf') pyglet.font.load("Press Start 2P") # Save and draw the FPS self.frame_rate = 1/60 self.fps_display = FPSDisplay(self) self.fps_display.label.x = self.width - 10 self.fps_display.label.y = 10 self.fps_display.label.anchor_x = "right" self.fps_display.label.font_name = "Press Start 2P" self.fps_display.label.font_size = 20 self.fps_display.label.color = (192, 192, 192, 192) # Set the FPS pyglet.clock.schedule_interval(self.update, self.frame_rate) # Control the horizontal velocity of the obstacles self.obstacle_velx = -600 # Create batches self.bg_batch = pyglet.graphics.Batch() self.main_batch = pyglet.graphics.Batch() if self.enable_neat: self.neat_batch = pyglet.graphics.Batch() else: self.game_over_batch = pyglet.graphics.Batch() # Preload the images into memory and save them game_sprites = self.preload_image("sprites.png") self.terrain_img = game_sprites.get_region(2, 0, 2402, 27) self.dinosaur_run_animation = Animation.from_image_sequence( ImageGrid( game_sprites.get_region(1854, 33, 176, 95), 1, 2, item_width=88, item_height=96 ), 0.3, loop=True ) self.dinosaur_duck_animation = Animation.from_image_sequence( ImageGrid( game_sprites.get_region(2203, 33, 240, 61), 1, 2, item_width=118, item_height=62 ), 0.3, loop=True ) self.dinosaur_jump_img = game_sprites.get_region(1678, 33, 88, 95) self.dinosaur_collision_img = game_sprites.get_region(2030, 33, 88, 95) self.cacti_imgs = ( game_sprites.get_region(446, 58, 34, 70), # Small cacti 1 game_sprites.get_region(480, 58, 68, 70), # Small cacti 2 game_sprites.get_region(548, 58, 102, 70), # Small cacti 3 game_sprites.get_region(652, 32, 50, 98), # Large cacti 1 game_sprites.get_region(702, 32, 100, 98), # Large cacti 2 game_sprites.get_region(802, 30, 150, 98), # Large cacti 3 ) self.bird_animation = Animation.from_image_sequence( ImageGrid( game_sprites.get_region(260, 48, 184, 80), 1, 2, item_width=92, item_height=80 ), 0.3, loop=True ) self.cloud_img = game_sprites.get_region(165, 100, 95, 28) self.moon_phases = cycle(( game_sprites.get_region(1234, 47, 40, 82), game_sprites.get_region(1194, 47, 40, 82), game_sprites.get_region(1154, 47, 40, 82), game_sprites.get_region(1074, 47, 80, 82), game_sprites.get_region(1034, 47, 40, 82), game_sprites.get_region(994, 47, 40, 82), game_sprites.get_region(954, 47, 40, 82) )) self.reset_button_img = game_sprites.get_region(2, 63, 72, 65) # Score and label self.score = 0 self.score_label = pyglet.text.Label( f"{self.score:05}", font_name="Press Start 2P", font_size=20, x=self.width - 10, y=self.height - 10, anchor_x="right", anchor_y="top", batch=self.bg_batch ) # Game over label (only if the user plays the game manually) if not self.enable_neat: self.game_over_label = pyglet.text.Label( "G A M E O V E R", font_name="Press Start 2P", font_size=30, x=self.width / 2, y=self.height / 2 + 100, anchor_x="center", anchor_y="center", batch=self.game_over_batch ) # Initialize the sprites self.terrain_1 = GameSprite( self.terrain_img, 0, 50, velx=self.obstacle_velx, batch=self.bg_batch ) self.terrain_2 = GameSprite( self.terrain_img, 2400, 50, velx=self.obstacle_velx, batch=self.bg_batch ) self.moon = GameSprite(next(self.moon_phases), 2920, 275, velx=-20, batch=self.main_batch) self.clouds = [] # Elements will be randomly generated as the game progresses self.obstacles = [] # Elements will be randomly generated as the game progresses # Reset button is only available when the user plays manually if not self.enable_neat: self.reset_button = GameSprite( self.reset_button_img, 564, 150, batch=self.game_over_batch ) # Generate the user's dinosaur if the user plays manually if not self.enable_neat: self.dinosaur = Dinosaur(self.dinosaur_run_animation, 65, 45, batch=self.main_batch) # Set variables to track user inputs self.trigger_duck = False self.trigger_jump = False # Keep track of any user collisions self.user_collision = False # Add a delays to control when events happen self.next_score_increment = 0.1 self.next_cloud_spawn = 3 * random() + 1 self.next_obstacle_spawn = 2 * random() + 1 self.next_velocity_increase = 1 # Set up the NEAT algorithm if true. Otherwise, let the user play manually if self.enable_neat: # Locate the NEAT configuration file config_file = os.path.join(os.path.dirname(__file__), 'config-feedforward.txt') # Configure the NEAT algorithm config = neat.config.Config( neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file ) # Generate the population population = neat.Population(config) # Add a reporter to show progress in the terminal population.add_reporter(neat.StdOutReporter(True)) population.add_reporter(neat.StatisticsReporter()) # Generation label self.generation = -1 self.generation_label = pyglet.text.Label( f"GENERATION: {self.generation:02}", font_name="Press Start 2P", font_size=20, x=10, y=self.height - 10, anchor_x="left", anchor_y="top", batch=self.neat_batch ) # Number of dinosaurs label self.number_of_dinosaurs = 0 self.number_of_dinosaurs_label = pyglet.text.Label( f"DINOSAURS: {self.number_of_dinosaurs:03}", font_name="Press Start 2P", font_size=20, x=10, y=self.height - 40, anchor_x="left", anchor_y="top", batch=self.neat_batch ) # Run the NEAT algorithm and find the best "player" winner = population.run(self.eval_genomes, 25) else: # Run the main loop and play the game manually pyglet.app.run()
def load_animation(image): # 2 rows, 1 column on sprite sheet seq = ImageGrid(load(image), 2, 1) # show each image for half a second return Animation.from_image_sequence(seq, 0.5)
def load_animation(imgage): """ Animation for each image """ seq = ImageGrid(load(imgage), 2, 1) return Animation.from_image_sequence(seq, 0.5)
def __init__(self): self.map = None self.layout = None self.end_staircase = None self.stage = 1 self.game_window = None self.pc = None self.next_stage = False self.move_timeout = True self.timeout_limit = 1 # sekundy self.enemies = set() self.consumables = set() self.equippables = set() self.sprites = Batch() self.items = Batch() self.stages = 5 self.cell_size = 5 self.width = 45 # w tile-ach, wielokrotność 3*sell_size self.height = 30 # wielokrotność cell_size self.status_bar = None self.difficulty = 0 self.groups = [OrderedGroup(0), OrderedGroup(1)] self.tileset = TextureGrid(ImageGrid(load_image('img/tiles.png'), 5, 5)) self.tile_textures = { 'floor': self.tileset.get(4, 0).get_image_data(), 'wall': self.tileset.get(4, 1).get_image_data(), 'bars': self.tileset.get(4, 2).get_image_data(), 'rubble': self.tileset.get(4, 3).get_image_data(), 'stairs': self.tileset.get(4, 4).get_image_data(), } self.sprite_textures = { 'bandit_dig': self.tileset.get(0, 0), 'bandit_disg': self.tileset.get(0, 1), 'bandit_fierce': self.tileset.get(0, 2), 'bandit_wander': self.tileset.get(0, 3), 'bandit_wary': self.tileset.get(0, 4), 'bandit_aggr': self.tileset.get(1, 2), 'bandit_coward': self.tileset.get(1, 3), 'bandit_def': self.tileset.get(1, 4), 'guard_glass': self.tileset.get(1, 0), 'guard_unlk': self.tileset.get(1, 1), 'guard': self.tileset.get(2, 0), 'guard_angry': self.tileset.get(2, 1), 'guard_blnk': self.tileset.get(2, 2), 'guard_chase': self.tileset.get(2, 3), 'guard_def': self.tileset.get(2, 4), 'player': self.tileset.get(3, 0), 'player_h': self.tileset.get(3, 1), 'player_d': self.tileset.get(3, 2), 'player_dh': self.tileset.get(3, 3), 'item': self.tileset.get(3, 4), } self.sounds = { 'player_hit': StaticSource(load_media('sound/player_hit.wav')), 'bandit_hit': StaticSource(load_media('sound/bandit_hit.wav')), 'guard_hit': StaticSource(load_media('sound/guard_hit.wav')), }
def load_animation(self, imgage, delay): seq = ImageGrid(load(imgage), 1, 6) return Animation.from_image_sequence(seq, delay, loop=False)
def load_animation(imgage): #載入動畫 seq = ImageGrid(load(imgage), 2, 1) #載入一個圖片網格 return Animation.from_image_sequence(seq, 0.5) #每0.5秒變換一次圖片
def load_animation(self, imgage, delay): seq = ImageGrid(load(imgage), 4, 1) return Animation.from_image_sequence(seq, delay)
from pyglet.image import load, ImageGrid, Animation from itertools import cycle # Constant values WINDOW_WIDTH = 1200 WINDOW_HEIGHT = 400 GENERATIONS = 25 FONT_NAME = os.path.join(os.path.dirname(__file__), "data/fonts/press_start_2p.ttf") # Sprites GAME_SPRITES = load(os.path.join(os.path.dirname(__file__), "data/images/sprites.png")) TERRAIN_IMG = GAME_SPRITES.get_region(2, 0, 2402, 27) DINOSAUR_RUN_ANIMATION = Animation.from_image_sequence( ImageGrid(GAME_SPRITES.get_region(1854, 33, 176, 95), 1, 2, item_width=88, item_height=96), 0.3, loop=True ) DINOSAUR_DUCK_ANIMATION = Animation.from_image_sequence( ImageGrid(GAME_SPRITES.get_region(2203, 33, 240, 61), 1, 2, item_width=118, item_height=62), 0.3, loop=True ) DINOSAUR_JUMP_IMG = GAME_SPRITES.get_region(1678, 33, 88, 95) DINOSAUR_COLLISION_IMG = GAME_SPRITES.get_region(2030, 33, 88, 95) CACTI_IMGS = ( GAME_SPRITES.get_region(446, 58, 34, 70), # Small cacti 1 GAME_SPRITES.get_region(480, 58, 68, 70), # Small cacti 2 GAME_SPRITES.get_region(548, 58, 102, 70), # Small cacti 3 GAME_SPRITES.get_region(652, 32, 50, 98), # Large cacti 1
import pyglet from pyglet.image import ImageGrid pyglet.resource.path = ["/home/clayton/Pictures/sprites"] pyglet.resource.reindex() player = pyglet.resource.image("player.png") enemy = pyglet.resource.image("enemy.png") dimple = pyglet.resource.image("dimple.png") boss = pyglet.resource.image("boss.png") bird = pyglet.resource.image("atlas/bird.png") bird_seq = ImageGrid(bird, 3, 5) bird_seq = bird_seq[10:] + bird_seq[5:10] + bird_seq[:4] # Fix order