def get_animation(self): """ Import all video frames into memory. An empty animation will be returned if the source has no video. Otherwise, the animation will contain all unplayed video frames (the entire source, if it has not been queued on a player). After creating the animation, the source will be at EOS (end of stream). This method is unsuitable for videos running longer than a few seconds. .. versionadded:: 1.1 Returns: :class:`pyglet.image.Animation` """ from pyglet.image import Animation, AnimationFrame if not self.video_format: # XXX: This causes an assertion in the constructor of Animation return Animation([]) else: frames = [] last_ts = 0 next_ts = self.get_next_video_timestamp() while next_ts is not None: image = self.get_next_video_frame() if image is not None: delay = next_ts - last_ts frames.append(AnimationFrame(image, delay)) last_ts = next_ts next_ts = self.get_next_video_timestamp() return Animation(frames)
def __init__(self): super(TestLayer, self).__init__() x, y = director.get_window_size() assets = "../assets/" hole_img = pyglet.image.load(assets + 'hole.png') hole_seq1 = pyglet.image.ImageGrid(hole_img, 2, 9) hole_seq2 = pyglet.image.ImageGrid(hole_img, 4, 9) anis = {} anis['T'] = Animation.from_image_sequence(hole_seq1[9 * 0:9 * 0 + 9], 0.1) anis['t'] = Animation.from_image_sequence(hole_seq1[9 * 1:9 * 1 + 9], 0.1) flats = [] flats.append(hole_seq2[9 * 2 + 8]) flats.append(hole_seq2[9 * 3 + 8]) flats.append(hole_seq2[9 * 0 + 8]) anis['F'] = Animation.from_image_sequence(flats, 1) self.anis = anis self.ani_keys = ['T', 't', 'F'] self.ani_idx = 0 self.sprite = Sprite(anis[self.ani_keys[self.ani_idx]]) #self.sprite = Sprite(runner_seq[8]) self.sprite.position = x // 3, y // 3 self.add(self.sprite)
def __init__(self): super( TestLayer, self ).__init__() x,y = director.get_window_size() assets = "../assets/" runner = pyglet.image.load(assets + 'runner.png') runner_seq = pyglet.image.ImageGrid(runner, 3, 9) anis = {} anis['W'] = Animation.from_image_sequence(runner_seq[9*2:9*2+3], 0.5) anis['w'] = Animation.from_image_sequence(runner_seq[9*2+3:9*2+6], 0.5) anis['U'] = Animation.from_image_sequence(runner_seq[9*2+6:9*2+8], 0.5) anis['D'] = runner_seq[9*2+8] anis['d'] = runner_seq[8] anis['R'] = Animation.from_image_sequence(runner_seq[9*0:9*0+3], 0.5) anis['r'] = Animation.from_image_sequence(runner_seq[9*0+3:9*0+6], 0.5) anis['H'] = runner_seq[9*0+6] anis['h'] = runner_seq[9*0+7] self.anis = anis self.ani_keys=['W','w','U','D','d','R','r','H','h'] self.ani_idx = 0 self.sprite = Sprite(anis[self.ani_keys[self.ani_idx]]) #self.sprite = Sprite(runner_seq[8]) self.sprite.position = x//3, y//3 self.add( self.sprite )
def __init__(self, x, y): super(Player, self).__init__('assets/runner1.png', x, y) self.speed_h = eu.Vector2(200, 0) self.speed_v = eu.Vector2(0, 200) assets = "assets/" runner = pyglet.image.load(assets + 'runner.png') self.runner_stand = pyglet.image.load(assets + 'runner1.png') runner_seq = pyglet.image.ImageGrid(runner, 3, 9) anis = {} dur = 0.01 anis['W'] = Animation.from_image_sequence(runner_seq[9 * 2:9 * 2 + 3], dur) anis['w'] = Animation.from_image_sequence( runner_seq[9 * 2 + 3:9 * 2 + 6], dur) anis['U'] = Animation.from_image_sequence( runner_seq[9 * 2 + 6:9 * 2 + 8], dur) anis['D'] = runner_seq[9 * 2 + 8] anis['d'] = runner_seq[8] anis['R'] = Animation.from_image_sequence(runner_seq[9 * 0:9 * 0 + 3], dur) anis['r'] = Animation.from_image_sequence( runner_seq[9 * 0 + 3:9 * 0 + 6], dur) anis['H'] = runner_seq[9 * 0 + 6] anis['h'] = runner_seq[9 * 0 + 7] self.anis = anis self.last_move = "" self.move_act = { 'd': self.anis['W'], 'a': self.anis['w'], 'w': self.anis['U'], 's': self.runner_stand }
def get_animation(self): '''Import all video frames into memory as an `Animation`. An empty animation will be returned if the source has no video. Otherwise, the animation will contain all unplayed video frames (the entire source, if it has not been queued on a player). After creating the animation, the source will be at EOS. This method is unsuitable for videos running longer than a few seconds. :since: pyglet 1.1 :rtype: `pyglet.image.Animation` ''' from pyglet.image import Animation, AnimationFrame if not self.video_format: return Animation([]) else: # Create a dummy player for the source to push its textures onto. frames = [] last_ts = 0 next_ts = self.get_next_video_timestamp() while next_ts is not None: image = self.get_next_video_frame() assert image is not None delay = next_ts - last_ts frames.append(AnimationFrame(image, delay)) last_ts = next_ts next_ts = self.get_next_video_timestamp() return Animation(frames)
def set_animation(self, item={}): '''设置动画''' image = pyglet.resource.image(item['file']) img_seq = pyglet.image.ImageGrid(image, item['rows'], 1) for img in img_seq: self.set_image_center(img) self.alive_img = Animation.from_image_sequence(img_seq[:3:-1], 0.2) self.dead_img = Animation.from_image_sequence(img_seq[3::-1], 0.2)
def __init__(self, prefix, numFrames): self.prefix = prefix imgs, flipImgs = self.loadImgsAndFlipImgs(False, numFrames, self.prefix) duration = 0.2 frames = [AnimationFrame(x, duration) for x in imgs] flipFrames = [AnimationFrame(x, duration) for x in flipImgs] self.animation = Animation(frames) if flipFrames: self.flipAnimation = Animation(flipFrames) pyglet.sprite.Sprite.__init__(self, self.animation) self.done = False
def __init__(self, prefix, numFrames, doOutroFrames=True): self.prefix = prefix self.facing = Facing.right imgs, flipImgs = self.loadImgsAndFlipImgs(doOutroFrames, numFrames, self.prefix) duration = 0.1 frames = [AnimationFrame(x, duration) for x in imgs] flipFrames = [AnimationFrame(x, duration) for x in flipImgs] self.animation = Animation(frames) if flipFrames: self.flipAnimation = Animation(flipFrames) pyglet.sprite.Sprite.__init__(self, self.animation) self.done = False
def explode(self): # 停止前行 self.stop_move() # 精灵图片 animation = Animation.from_image_sequence( map( lambda x: pyglet.resource.image('imgs/enemy/enemy_small%d.png' % x), [x for x in range(2, 5)]), 0.05, False) self.image = animation # 播放音效 audio.pygame.mixer.init() sound = audio.pygame.mixer.Sound('sounds/enemy_die.ogg') sound.play(0, 0) # 消失 def disppear(dt): self.position = -10, -10 self.cshape.center = collision.eu.Vector2(-10, -10) # 发送重用敌机的事件 fj_event_dispatcher.dispatch_event('on_small_enemy_reuseable', self) self.unschedule(disppear) self.schedule_interval(disppear, 0.15)
def create_animation(self, prefix, key, framedefs): frames = [ AnimationFrame(self['%s%s' % (prefix, frame['name'])], frame['duration']) for frame in framedefs ] anim_key = '%s%s' % (prefix, key) self[anim_key] = Animation(frames)
def decode_animation(self, file, filename): # If file is not an animated GIF, it will be loaded as a single-frame animation. file_bytes = file.read() data = c_void_p(cf.CFDataCreate(None, file_bytes, len(file_bytes))) sourceRef = c_void_p(quartz.CGImageSourceCreateWithData(data, None)) # Get number of frames in the animation. count = quartz.CGImageSourceGetCount(sourceRef) frames = [] for index in range(count): # Try to determine frame duration from GIF properties dictionary. duration = 0.1 # default duration if none found props = c_void_p(quartz.CGImageSourceCopyPropertiesAtIndex(sourceRef, index, None)) if cf.CFDictionaryContainsKey(props, kCGImagePropertyGIFDictionary): gif_props = c_void_p(cf.CFDictionaryGetValue(props, kCGImagePropertyGIFDictionary)) if cf.CFDictionaryContainsKey(gif_props, kCGImagePropertyGIFDelayTime): duration = cfnumber_to_number(c_void_p(cf.CFDictionaryGetValue(gif_props, kCGImagePropertyGIFDelayTime))) cf.CFRelease(props) image = self._get_pyglet_ImageData_from_source_at_index(sourceRef, index) frames.append( AnimationFrame(image, duration) ) cf.CFRelease(data) cf.CFRelease(sourceRef) return Animation(frames)
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 load(self, fname): try: return self.loaded[fname] except KeyError: pass from pyglet.image import Animation, AnimationFrame self.doc = json.load(resource_stream('wildwest', fname)) animations = {} default = None for name, a in list(self.doc.items()): if name == 'default': if isinstance(a, str): default = a continue else: default = 'default' frames = [] for f in a['frames']: im = pyglet.resource.image(f['file']) im.anchor_x, im.anchor_y = a.get('anchor', (0, 0)) frames.append( [im, a.get('frametime', 0.1)] ) if not a.get('loop', False): if len(frames) == 1: frames.append(frames[0]) frames[-1][1] = 0 animations[name] = Animation([AnimationFrame(*f) for f in frames]) self.loaded[fname] = default, animations return default, animations
def decode_animation(self, file, filename): header, frames, layers, pitch = self._parse_file(file, filename) animation_frames = [] for frame in frames: pixel_data = frame.get_pixel_array(layers=layers) image = ImageData(header.width, header.height, 'RGBA', pixel_data, -pitch) animation_frames.append(AnimationFrame(image, frame.duration/1000.0)) return Animation(animation_frames)
def create_effect(image_frames, duration=1.0, loop=False): frames = [] for img in image_frames: image = loader.image(img) frames.append(AnimationFrame(image, duration)) if loop is False: frames[len(image_frames) - 1].duration = None return Animation(frames=frames)
def make_sprite(self): img = self.game.load_image('smoke.png') grid = list(pyglet.image.ImageGrid(img, 1, 8)) [(pixelate(g), center_image(g)) for g in grid] ani = Animation.from_image_sequence(grid, 0.1, loop=False) sprite = pyglet.sprite.Sprite(ani, batch=self.game.effect_batch) sprite.position = map(int, self.position) sprite.scale = 2 return sprite
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 make_sprite(self): img = self.game.load_image('firebolt.png') grid = list(pyglet.image.ImageGrid(img, 1, 5)) [(pixelate(g), center_image(g)) for g in grid] ani = Animation.from_image_sequence(grid, 0.05) sprite = pyglet.sprite.Sprite(ani, batch=self.game.object_batch) sprite.position = map(int, self.position) sprite.rotation = self.rotation sprite.scale = 2 return sprite
def load_sprite_animation(name, action, frames=8, duration=0.1): " Creates an animation from files in the assets folder " images = [ resource.image("assets/%s/%s%d.png" % (name, action, i)) for i in range(1, frames + 1) ] for image in images: image.anchor_x = image.width / 2 frames = [AnimationFrame(i, duration) for i in images] return Animation(frames)
def explode(self): self.unschedule(self.run_enemy) frames = [] for x in range(2, 5): texure = pyglet.resource.image('img/enemy/enemy_small%d.png' % x) frames.append(texure) anim = Animation.from_image_sequence(frames, 0.05, False) self.image = anim self.schedule_interval(self._prepare_to_use, 0.15)
def create_effect_animation(image_name, duration, brow, rows, column, columns): effect_seq = pyglet.image.ImageGrid(loader.image(image_name), rows, columns) effect_frames = [] end = brow * columns start = end - (columns - 1) for effect_frame in effect_seq[start:end:1]: effect_frames.append(AnimationFrame(effect_frame, duration)) # effect_frames[((rows-brow) * (columns -column) ) -1].duration = None return Animation(effect_frames)
def create_animation_by_grids_inverse(self, image_name, duration, rotation, rows, columns): effect_seq = pyglet.image.ImageGrid(self.image(image_name, rotation), rows, columns) effect_frames = [] for row in range(rows, 0, -1): end = row * columns start = end - (columns - 1) - 1 for effect_frame in effect_seq[start:end:1]: effect_frames.append(AnimationFrame(effect_frame, duration)) effect_frames[(rows * columns) - 1].duration = None return Animation(effect_frames)
def __init__(self, p_level, *args, **kws): self.anim_default = Animation.from_image_sequence(ImageGrid(load(fp( self.image_file)), 1, 1), 5, True) applyAnchor(self.anim_default, 25, 0) self.anim_default_left = self.anim_default.get_transform(True) super(Character, self).__init__(self.anim_default, *args, **kws) self.p_level = p_level self.movement = None self.keys = None self.velocity_y = 0 self.touch_ground = True self.orientation_right = True
def create_effect_animation(self, image_name, columns, rows): effect_seq = pyglet.image.ImageGrid(pyglet.image.load(image_name), rows, columns) effect_frames = [] for row in range(rows, 0, -1): end = row * columns start = end - (columns - 1) - 1 for effect_frame in effect_seq[start:end:1]: effect_frames.append(AnimationFrame(effect_frame, 0.1)) effect_frames[(rows * columns) - 1].duration = None return Animation(effect_frames)
def explode(self): frames = [] for x in range(3, 6): texure = pyglet.resource.image('img/hero/hero%d.png' % x) frames.append(texure) anim = Animation.from_image_sequence(frames, 0.05, False) self.image = anim sound = pygame.mixer.Sound('sounds/hero_die.ogg') sound.play() self.schedule_interval(self._game_over, 1)
def init_image(self): frames = [] for x in range(1, 3): texure = pyglet.resource.image('img/hero/hero%d.png' % x) frames.append(texure) anim = Animation.from_image_sequence(frames, 0.05) super(Hero, self).__init__(anim) self.scale = 0.5 self.position = config.WINDOS_WIDTH // 2, 200 self.cshape = collision.AARectShape( collision.eu.Vector2(*self.position), self.width // 4, self.height // 4)
def __init__(self): self.prefix = 'beerthrow' numFrames = 3 imgs, flipImgs = self.loadImgsAndFlipImgs(False, numFrames, self.prefix) duration = 0.1 frames = [AnimationFrame(x, duration) for x in imgs] self.animation = Animation(frames) pyglet.sprite.Sprite.__init__(self, self.animation) self.done = False
def __init__(self, descfile): str = self.readStrFromFile(descfile + '.desc') desc = json.loads(str) texture = image.load(desc["name"] + '.png') list = [] for w in desc["frames"] : frame = texture.get_region(w["x"], w["y"], w["width"], 64) # TODO: 64 修改为 desc 的坐标有些问题, TODO list.append(frame) period = 0.2 # TODO: 参数 self.animation = Animation.from_image_sequence(list, period, False)
def createAnimation(image=None, columns=0, rows=0, anchor_x=0, anchor_y=0): #effect_seq = pyglet.image.ImageGrid(pyglet.image.load(image_name), rows, columns) effect_seq = pyglet.image.ImageGrid(image, rows, columns) effect_frames = [] for row in range(rows, 0, -1): end = row * columns start = end - (columns - 1) - 1 for effect_frame in effect_seq[start:end:1]: effect_frame.anchor_x = anchor_x effect_frame.anchor_y = anchor_y effect_frames.append(AnimationFrame(effect_frame, 0.3)) #effect_frames[(rows * columns) -1].duration = None return Animation(effect_frames)
def animationByList(image=None, aniList=[]): effect_frames=[] tmpImageY = image.height print(tmpImageY) for f in aniList: tmpFrame = image.get_region(f["x"], f["y"], f["w"], f["h"]) tmpFrame.anchor_x = f["anchor_x"] tmpFrame.anchor_y = f["anchor_y"] effect_frames.append(AnimationFrame(tmpFrame, f["duration"])) return Animation(effect_frames)
def __init__(self, pos): from pyglet.image import Animation, AnimationFrame im1 = pyglet.resource.image('wheels.png') im2 = pyglet.resource.image('wheels2.png') im3 = pyglet.resource.image('wheels3.png') t = 0.05 anim = Animation([ AnimationFrame(im1, t), AnimationFrame(im2, t), AnimationFrame(im3, t), ]) self.sprite1 = pyglet.sprite.Sprite(anim) self.sprite2 = pyglet.sprite.Sprite(anim) self.sprite2.color = (64, 64, 64) self.pos = pos
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 __init__(self, p_level, *args, **kws): super(Player, self).__init__(p_level, *args, **kws) ig_step = ImageGrid(load(fp('panda_bounce_test.png')), 1, 7) self.animation = self.anim_default self.anim_step_right = Animation.from_image_sequence( ig_step, 0.1, True) applyAnchor(self.anim_step_right, 25, 0) self.anim_step_left = self.anim_step_right.get_transform(True) # Convenience class for key handling, pushed to window self.keys = key.KeyStateHandler() self.default_movement = DefaultMove(self) self.movement = self.default_movement self.collision_box = property(self.get_collision_box, None) self.attack_box = property(self.get_attack_box, None) self.init()
def die_action(self): # 改变被撞的精灵图片 image = Animation.from_image_sequence( map(lambda x: pyglet.resource.image('imgs/hero/hero%d.png' % x), [x for x in range(3, 6)]), 0.05, False) self.image = image # 停止发射 self.stop_fire() # 播放爆炸的声音 audio.pygame.mixer.init() sound = audio.pygame.mixer.Sound('sounds/hero_die.ogg') sound.play(0, 0) # 闪几下后消失 self.do(actions.Blink(2, 1) + actions.Hide())
def create_animation_by_frames(self, image_frames, duration=1.0, rotation=0, looped=False, anchor_x=0, anchor_y=0): frames = [] for img in image_frames: image = self.image(img, rotation) self._anchor_image(image, anchor_x, anchor_y) # self._center_image(image) frames.append(AnimationFrame(image, duration)) if looped is False: frames[len(image_frames) - 1].duration = None return Animation(frames=frames)
def load_textures(self): img = self.game.load_image('player.png') grid = pyglet.image.ImageGrid(img, 4, 4) for img in grid: pixelate(img) img.width *= 2 img.height *= 2 center_image(img, 0.5, 0.3) self.ani_running = {} self.ani_standing = {} for row, name in enumerate(('up','right','left','down')): ani_run = [grid[row*4+col] for col in (1,2,3,2)] img_stand = grid[row*4+0] self.ani_running[name] = Animation.from_image_sequence(ani_run, 0.15) self.ani_standing[name] = img_stand self.sprite = pyglet.sprite.Sprite(self.ani_standing['down'], batch=self.game.object_batch) self.sprite.position = self.position self.moves = False
def load_animation(image): seq = ImageGrid(load(image), 2, 1) return Animation.from_image_sequence(seq, 0.5)
import math import cocos.sprite import cocos.audio import cocos.actions as ac import cocos.euclid as eu import cocos.collision_model as cm import pyglet.image from pyglet.image import Animation raw = pyglet.image.load('assets/explosion.png') seq = pyglet.image.ImageGrid(raw, 1, 8) explosion_img = Animation.from_image_sequence(seq, 0.07, False) class Explosion(cocos.sprite.Sprite): def __init__(self, pos): super(Explosion, self).__init__(explosion_img, pos) self.do(ac.Delay(1) + ac.CallFunc(self.kill)) class Shoot(cocos.sprite.Sprite): def __init__(self, pos, offset, target): super(Shoot, self).__init__('shoot.png', position=pos) self.do(ac.MoveBy(offset, 0.1) + ac.CallFunc(self.kill) + ac.CallFunc(target.hit)) class Hit(ac.IntervalAction):
def __init__(self, seq, row, *args, **kwargs): super(Enemy, self).__init__(Sprite(Animation.from_image_sequence(seq, ENEMY_ANIM_SPEED), *args, **kwargs)) self.direction = 'right' self.row = row self.game.objects.append(self)