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 __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 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 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 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 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 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 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 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__(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 __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 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 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 __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 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 __init__(self): image = Animation.from_image_sequence( map(lambda x: pyglet.resource.image('imgs/hero/hero%d.png' % x), [x for x in range(1, 3)]), 0.05, True) super(Hero, self).__init__(image) self.scale = 0.5 self.position = config.WIN_WIDTH // 2, 70 self._alive = True # 精灵batch self.batch_bullets = batch.BatchNode() self.all_bullets = set() self.active_bullets = set() self.reuse_bullets = set() # cshape self.cshape = collision.AARectShape( collision.eu.Vector2(*self.position), self.width // 2, self.height // 2) # 事件调度 self.schedule_interval(self.fire, 0.2)
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()
class Wyvern(cocos.layer.Layer): gravity = -9.8 secondsPerFrame = 0.075 # Create a texture atlas from the individual frames of the wyvern animations wyvernBin = pyglet.image.atlas.TextureBin() wyvernTextures = [] for i in range(0, 24): name = "images/wyvernNE{}.png".format(i) wyvernTextures.append(wyvernBin.add(pyglet.image.load(name))) wyvernsTextures = [] for i in range(0, 24): names = "images/wyvernsNE{}.png".format(i) wyvernsTextures.append(wyvernBin.add(pyglet.image.load(names))) ############################################################################# animation = { 'hover': Anim.from_image_sequence(wyvernTextures[0:8], secondsPerFrame, loop=True), 'fly': Anim.from_image_sequence(wyvernTextures[8:16], secondsPerFrame, loop=True), 'die': Anim.from_image_sequence(wyvernTextures[16:24], secondsPerFrame, loop=False), } animations = { 'hover': Anim.from_image_sequence(wyvernsTextures[0:8], secondsPerFrame, loop=True), 'fly': Anim.from_image_sequence(wyvernsTextures[8:16], secondsPerFrame, loop=True), 'die': Anim.from_image_sequence(wyvernsTextures[16:24], secondsPerFrame, loop=False), } ############################################################################# def __init__(self): """ Constructor """ super(Wyvern, self).__init__() self.altitude = 0 self.verticalVelocity = 0 self.horizontalVelocity = 0 self.lateralVelocity = 0 self.sprite = cocos.sprite.Sprite(Wyvern.animation['hover']) self.sprite.position = 200, 80 + self.altitude self.sprites = cocos.sprite.Sprite(Wyvern.animations['hover']) self.sprites.position = 200, 100 self.mapPosition = (4, 0, 0) self.animationName = 'hover' self.sprite.image = Wyvern.animation[self.animationName] self.sprites.image = Wyvern.animations[self.animationName] self.isDead = False ############################################################################# def moveLeft(self): if not self.isDead: self.lateralVelocity -= 0.1 ############################################################################# def moveRight(self): if not self.isDead: self.lateralVelocity += 0.1 ############################################################################# def flap(self): if not self.isDead: self.verticalVelocity += 3 self.horizontalVelocity = min(0.3, self.horizontalVelocity + 0.02) ############################################################################# def respawn(self): self.isDead = False ############################################################################# def update(self, dt): self.verticalVelocity = self.verticalVelocity + Wyvern.gravity * dt self.altitude += self.verticalVelocity if self.altitude <= 0: self.altitude = 0 self.verticalVelocity = 0 self.horizontalVelocity = max(0, self.horizontalVelocity - 0.1) elif self.altitude > 500: self.altitude = 500 self.verticalVelocity = 0 x, y, z = self.mapPosition x = min(max(-1.0, x + self.lateralVelocity), 6.0) self.lateralVelocity *= 0.9 # make lateralVelocity decay y = self.altitude / 96 z += self.horizontalVelocity self.mapPosition = (x, y, z) self.sprite.position = Map.Map.positionForMapPosition(x, y, z) self.sprites.position = Map.Map.positionForMapPosition(x, 0, z) if self.isDead: if self.animationName != 'die': self.animationName = 'die' self.sprite.image = Wyvern.animation[self.animationName] self.sprites.image = Wyvern.animations[self.animationName] elif self.horizontalVelocity < 0.05: if self.animationName != 'hover': self.animationName = 'hover' self.sprite.image = Wyvern.animation[self.animationName] self.sprites.image = Wyvern.animations[self.animationName] elif self.animationName != 'fly': self.animationName = 'fly' self.sprite.image = Wyvern.animation[self.animationName] self.sprites.image = Wyvern.animations[self.animationName]
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 __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)
def load_animation(imgage): """ Animation for each image """ seq = ImageGrid(load(imgage), 2, 1) return Animation.from_image_sequence(seq, 0.5)
def set_animation(self, score): '''设置动画''' image = silver_coin_img if score <= 20 else gold_coin_img coin_seq = pyglet.image.ImageGrid(image, 10, 1) self.coin_img = Animation.from_image_sequence(coin_seq, 0.02) self.set_image_center(self.coin_img)
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 load_animation(img, x, y, loop): raw = pyglet.image.load(img) seq = pyglet.image.ImageGrid(raw, x, y) return Animation.from_image_sequence(seq, 0.25, loop)
def __init__(self, res_img_path_seq: List[ResourceImage], duration: float=1/20, loop: bool=True): self.path_seq = [res.path for res in res_img_path_seq] self.duration = duration self.loop = loop self.animation = Animation.from_image_sequence(sequence=[res.img for res in res_img_path_seq], duration=self.duration, loop=self.loop)
image_paths = glob.glob(pathname="resources/*R.png") image_paths.sort() # Create pigboy animation pigboy_imgs = [] for path in image_paths: path = os.path.basename(path) img = pyglet.resource.image(path) img.anchor_x = img.width // 2 img.anchor_y = img.height // 2 pigboy_imgs.append(pyglet.resource.image(path)) pigboy_imgsL = [] for img in pigboy_imgs: pigboy_imgsL.append(img.get_transform(flip_x=True)) pigboy_animationR = Animation.from_image_sequence(pigboy_imgs, 1/20.0) pigboy_animationL = Animation.from_image_sequence(pigboy_imgsL, 1/20.0) # Pig lives image pig_heart = pyglet.resource.image("extras/pig_heart.png") ### Platform Resources ### pltfm_short_grass = pyglet.resource.image("platform_grass.png") pltfm_short_grass.anchor_x = pltfm_short_grass.width // 2 pltfm_short_grass.anchor_y = pltfm_short_grass.height // 2 ### Enemy Class ### enemy_ghostL = pyglet.resource.image("enemies/enemyL0.png") enemy_ghostL.anchor_x = enemy_ghostL.width // 2 enemy_ghostL.anchor_y = enemy_ghostL.height // 2 enemy_ghostR = enemy_ghostL.get_transform(flip_x=True)
def load_animation(image): seq = ImageGrid(load(image), 2, 1) return Animation.from_image_sequence(seq, 0.5)
import pyglet from pyglet_utils.tutorial import resources from pyglet.window import Window from pyglet.image import Animation from pyglet.sprite import Sprite # Create and open a window window = Window(width=500, height=500, caption='Bird Atlas') bird_anim = Animation.from_image_sequence(sequence=resources.bird_seq, duration=1 / 20, loop=True) bird_sprite = Sprite(img=bird_anim, x=50, y=150) bird_sprite.scale = 2 @window.event def on_draw(): window.clear() bird_sprite.draw() if __name__ == '__main__': pyglet.app.run()
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)
def load_animation(imgage): #載入動畫 seq = ImageGrid(load(imgage), 2, 1) #載入一個圖片網格 return Animation.from_image_sequence(seq, 0.5) #每0.5秒變換一次圖片
class Hit(ac.IntervalAction): # runs for 0.5 seconds def init(self, duration=0.5): self.duration = duration # called several times with t in the (0, 1) range # t is the percent of the duration that has elapsed def update(self, t): # Red overlay gradually fades as t gets closer to 1 self.target.color = (255, 255 * t, 255 * t) # load this outside a class/function so it only happens once raw = pyglet.image.load('assets/explosion.png') seq = pyglet.image.ImageGrid(raw, 1, 8) explosion_img = Animation.from_image_sequence(seq, 0.07, False) # just a sprite, not an actor 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 Enemy(Actor): # initial position and actions come from Scenario def __init__(self, x, y, actions): super(Enemy, self).__init__('tank.png', x, y) self.health = 100 self.points = 20
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)
class Resources(ABC): pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent') audioPath = "res/audio/" pyglet.font.add_file("res/font.ttf") # gameOverMusic = pyglet.media.load(audioPath + "", streaming=False) owMusic = pyglet.media.load(audioPath + "ow.wav", streaming=False) owMusicFast = pyglet.media.load(audioPath + "ow_fast.wav", streaming=False) ugMusic = pyglet.media.load(audioPath + "ug.wav", streaming=False) ugMusicFast = pyglet.media.load(audioPath + "ug_fast.wav", streaming=False) jumpSmall = pyglet.media.load(audioPath + "jump_small.wav", streaming=False) jumpSuper = pyglet.media.load(audioPath + "jump_super.wav", streaming=False) breakblock = pyglet.media.load(audioPath + "breakblock.wav", streaming=False) stomp = pyglet.media.load(audioPath + "stomp.wav", streaming=False) kick = pyglet.media.load(audioPath + "kick.wav", streaming=False) bump = pyglet.media.load(audioPath + "bump.wav", streaming=False) coin = pyglet.media.load(audioPath + "coin.wav", streaming=False) fireball = pyglet.media.load(audioPath + "fireball.wav", streaming=False) powerupAppears = pyglet.media.load(audioPath + "powerup_appears.wav", streaming=False) powerup = pyglet.media.load(audioPath + "powerup.wav", streaming=False) powerdown = pyglet.media.load(audioPath + "powerdown.wav", streaming=False) flagpole = pyglet.media.load(audioPath + "flagpole.wav", streaming=False) mariodie = pyglet.media.load(audioPath + "mariodie.wav", streaming=False) hurryUp = pyglet.media.load(audioPath + "hurry_up.wav", streaming=False) oneup = pyglet.media.load(audioPath + "1_up.wav", streaming=False) star = pyglet.media.load(audioPath + "starlong.wav", streaming=False) bgMusic = None ### spritesPath = "res/sprites/" playerSmallSize = Vector2(16, 16) playerBigSize = Vector2(16, 32) enemySmallSize = Vector2(16, 16) enemyBigSize = Vector2(16, 24) fireBallSize = Vector2(8, 8) fireBallExplosionSize = Vector2(16, 16) powerUpSize = Vector2(16, 16) bg = image.load(spritesPath + "bgLevel1-1.png") player = image.load(spritesPath + "player.png") tileset = image.load(spritesPath + "tileset.png") items = image.load(spritesPath + "items.png") misc = image.load(spritesPath + "misc.png") castle = image.load(spritesPath + "castle.png") enemies = image.load(spritesPath + "enemies.png") platform = image.load(spritesPath + "platform.png") theme = { "ow": { "ground": getRegion(tileset, 0, 0, tileSize), "brick": getRegion(tileset, 0 + tileSizeNum, 0, tileSize), "brickPieces": [ getRegion(misc, 304, 112 + 8, Vector2(8, 8)), getRegion(misc, 304 + 8, 112 + 8, Vector2(8, 8)), getRegion(misc, 304, 112, Vector2(8, 8)), getRegion(misc, 304 + 8, 112, Vector2(8, 8)), ], "hardBlock": getRegion(tileset, 0, 16, tileSize), "questionBlock": Animation.from_image_sequence([ getRegion(tileset, 384, 0, tileSize), getRegion(tileset, 384 + tileSizeNum, 0, tileSize), getRegion(tileset, 384 + 2 * tileSizeNum, 0, tileSize), getRegion(tileset, 384 + tileSizeNum, 0, tileSize), getRegion(tileset, 384, 0, tileSize), getRegion(tileset, 384, 0, tileSize) ], 0.125), "questionBlockHit": getRegion(tileset, 432, 0, tileSize), "coin": Animation.from_image_sequence([ getRegion(items, 0, 96, powerUpSize), getRegion(items, 16, 96, powerUpSize), getRegion(items, 32, 96, powerUpSize), getRegion(items, 16, 96, powerUpSize), getRegion(items, 0, 96, powerUpSize), getRegion(items, 0, 96, powerUpSize) ], 0.125), "pillar": getRegion(tileset, 80, 16, tileSize), "grassLeft": getRegion(tileset, 80, 128, tileSize), "grassMiddle": getRegion(tileset, 96, 128, tileSize), "grassRight": getRegion(tileset, 112, 128, tileSize), ### "goombaWalking": Animation.from_image_sequence([ getRegion(enemies, 0, 16, enemySmallSize), getRegion(enemies, 16, 16, enemySmallSize) ], 0.20), "goombaSmashed": getRegion(enemies, 32, 16, enemySmallSize), "goombaFlipped": getRegion(enemies, 0, 16, enemySmallSize), "green": { "koopaTroopaWalking": Animation.from_image_sequence([ getRegion(enemies, 96, 8, enemyBigSize), getRegion(enemies, 112, 8, enemyBigSize) ], 0.25), "koopaTroopaStomped": getRegion(enemies, 160, 16, enemySmallSize), "koopaTroopaRecovering": Animation.from_image_sequence([ getRegion(enemies, 160, 16, enemySmallSize), getRegion(enemies, 176, 16, enemySmallSize) ], 0.25), }, "red": { "koopaTroopaWalking": Animation.from_image_sequence([ getRegion(enemies, 96, 8 + 64, enemyBigSize), getRegion(enemies, 112, 8 + 64, enemyBigSize) ], 0.25), "koopaTroopaStomped": getRegion(enemies, 160, 16 + 64, enemySmallSize), "koopaTroopaRecovering": Animation.from_image_sequence([ getRegion(enemies, 160, 16 + 64, enemySmallSize), getRegion(enemies, 176, 16 + 64, enemySmallSize) ], 0.25), }, "piranhaPlant": Animation.from_image_sequence([ getRegion(enemies, 192, 8, enemyBigSize), getRegion(enemies, 192 + 16, 8, enemyBigSize), ], 0.25), ### "vPipeHead": getRegion(tileset, 0, 128, Vector2(32, 16)), "vPipeBody": getRegion(tileset, 2, 144, Vector2(28, 16)), "hPipeHead": getRegion(tileset, 32, 128, Vector2(16, 32)), "hPipeBody": getRegion(tileset, 48, 129, Vector2(16, 30)), "hPipeConnection": getRegion(tileset, 64, 128, Vector2(16, 32)), ### "flagPoleBody": getRegion(tileset, 256, 144, tileSize), "flagPoleHead": getRegion(tileset, 256, 128, tileSize), "flag": getRegion(items, 128, 32, tileSize), ### "superMushroom": getRegion(items, 0, 0, powerUpSize), "oneUp": getRegion(items, 16, 0, powerUpSize), "fireFlower": Animation.from_image_sequence([ getRegion(items, 0, 32, powerUpSize), getRegion(items, 16, 32, powerUpSize), getRegion(items, 32, 32, powerUpSize), getRegion(items, 48, 32, powerUpSize) ], 0.02), "superStar": Animation.from_image_sequence([ getRegion(items, 0, 48, powerUpSize), getRegion(items, 16, 48, powerUpSize), getRegion(items, 32, 48, powerUpSize), getRegion(items, 48, 48, powerUpSize) ], 0.02) }, "ug": { "ground": getRegion(tileset, 0, 0+32, tileSize), "brick": getRegion(tileset, 16 + tileSizeNum, 0+32, tileSize), "brickPieces": [ getRegion(misc, 304, 112 + 16 + 8, Vector2(8, 8)), getRegion(misc, 304 + 8, 112 + 16 + 8, Vector2(8, 8)), getRegion(misc, 304, 112 + 16, Vector2(8, 8)), getRegion(misc, 304 + 8, 112 + 16, Vector2(8, 8)), ], "hardBlock": getRegion(tileset, 0, 16+32, tileSize), "questionBlock": Animation.from_image_sequence([ getRegion(tileset, 384, 0+32, tileSize), getRegion(tileset, 384 + tileSizeNum, 0+32, tileSize), getRegion(tileset, 384 + 2 * tileSizeNum, 0+32, tileSize), getRegion(tileset, 384 + tileSizeNum, 0+32, tileSize), getRegion(tileset, 384, 0+32, tileSize), getRegion(tileset, 384, 0+32, tileSize) ], 0.125), "questionBlockHit": getRegion(tileset, 432, 0+32, tileSize), "coin": Animation.from_image_sequence([ getRegion(items, 144, 96, powerUpSize), getRegion(items, 160, 96, powerUpSize), getRegion(items, 176, 96, powerUpSize), getRegion(items, 160, 96, powerUpSize), getRegion(items, 144, 96, powerUpSize), getRegion(items, 144, 96, powerUpSize) ], 0.125), ### "goombaWalking": Animation.from_image_sequence([ getRegion(enemies, 0, 16 + 32, enemySmallSize), getRegion(enemies, 16, 16 + 32, enemySmallSize) ], 0.20), "goombaSmashed": getRegion(enemies, 32, 16 + 32, enemySmallSize), "goombaFlipped": getRegion(enemies, 0, 16 + 32, enemySmallSize), "green": { "koopaTroopaWalking": Animation.from_image_sequence([ getRegion(enemies, 96, 8 + 32, enemyBigSize), getRegion(enemies, 112, 8 + 32, enemyBigSize) ], 0.25), "koopaTroopaStomped": getRegion(enemies, 160, 16 + 32, enemySmallSize), "koopaTroopaRecovering": Animation.from_image_sequence([ getRegion(enemies, 160, 16 + 32, enemySmallSize), getRegion(enemies, 176, 16 + 32, enemySmallSize) ], 0.25), }, "red": { "koopaTroopaWalking": Animation.from_image_sequence([ getRegion(enemies, 96, 8 + 64, enemyBigSize), getRegion(enemies, 112, 8 + 64, enemyBigSize) ], 0.25), "koopaTroopaStomped": getRegion(enemies, 160, 16 + 64, enemySmallSize), "koopaTroopaRecovering": Animation.from_image_sequence([ getRegion(enemies, 160, 16 + 64, enemySmallSize), getRegion(enemies, 176, 16 + 64, enemySmallSize) ], 0.25), }, "piranhaPlant": Animation.from_image_sequence([ getRegion(enemies, 192, 8 + 32, enemyBigSize), getRegion(enemies, 192 + 16, 8 + 32, enemyBigSize), ], 0.25), ### "vPipeHead": getRegion(tileset, 0, 128+32, Vector2(32, 16)), "vPipeBody": getRegion(tileset, 2, 144+32, Vector2(28, 16)), "hPipeHead": getRegion(tileset, 32, 128+32, Vector2(16, 32)), "hPipeBody": getRegion(tileset, 48, 129+32, Vector2(16, 30)), "hPipeConnection": getRegion(tileset, 64, 128+32, Vector2(16, 32)), ### "flagPoleBody": getRegion(tileset, 256, 144+32, tileSize), "flagPoleHead": getRegion(tileset, 256, 128+32, tileSize), "flag": getRegion(items, 272, 32, tileSize), }, "castle": { "ground": getRegion(tileset, 32, 80, tileSize), "wave": getRegion(tileset, 48, 384, tileSize), "liquid": getRegion(tileset, 48, 384+tileSizeNum, tileSize) } } redKoopaTroopaWalking = Animation.from_image_sequence([ getRegion(enemies, 96, 8 + 32, enemyBigSize), getRegion(enemies, 112, 8 + 32, enemyBigSize) ], 0.25) redKoopaTroopaStomped = getRegion(enemies, 160, 16 + 32, enemySmallSize) redKoopaTroopaRecovering = Animation.from_image_sequence([ getRegion(enemies, 160, 16 + 32, enemySmallSize), getRegion(enemies, 176, 16 + 32, enemySmallSize) ], 0.25) fireBall = Animation.from_image_sequence([ getRegion(items, 96, 144, fireBallSize), getRegion(items, 104, 144, fireBallSize), getRegion(items, 96, 152, fireBallSize), getRegion(items, 104, 152, fireBallSize), ], 0.05) fireBallExplosion = Animation.from_image_sequence([ getRegion(items, 112, 144, fireBallExplosionSize), getRegion(items, 112, 160, fireBallExplosionSize), getRegion(items, 112, 176, fireBallExplosionSize), ], 0.02, False) rotatingCoin = Animation.from_image_sequence([ getRegion(items, 0, 112, tileSize), getRegion(items, 0 + tileSizeNum, 112, tileSize), getRegion(items, 0 + 2 * tileSizeNum, 112, tileSize), getRegion(items, 0 + 3 * tileSizeNum, 112, tileSize), ], 0.05) playerSprites = { "mario": { "small": { "stand": getRegion(player, 80, 34, playerSmallSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 34, playerSmallSize), getRegion(player, 114, 34, playerSmallSize), getRegion(player, 131, 34, playerSmallSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 34, playerSmallSize), getRegion(player, 114, 34, playerSmallSize), getRegion(player, 131, 34, playerSmallSize), ], 0.05), "break": getRegion(player, 148, 34, playerSmallSize), "jump": getRegion(player, 165, 34, playerSmallSize), "crouch": getRegion(player, 80, 34, playerSmallSize), "die": getRegion(player, 182, 34, playerSmallSize) }, "big": { "stand": getRegion(player, 80, 1, playerBigSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 1, playerBigSize), getRegion(player, 114, 1, playerBigSize), getRegion(player, 131, 1, playerBigSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 1, playerBigSize), getRegion(player, 114, 1, playerBigSize), getRegion(player, 131, 1, playerBigSize), ], 0.05), "break": getRegion(player, 148, 1, playerBigSize), "jump": getRegion(player, 165, 1, playerBigSize), "crouch": getRegion(player, 182, 1, playerBigSize) } }, "luigi": { "small": { "stand": getRegion(player, 80, 99, playerSmallSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 99, playerSmallSize), getRegion(player, 114, 99, playerSmallSize), getRegion(player, 131, 99, playerSmallSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 99, playerSmallSize), getRegion(player, 114, 99, playerSmallSize), getRegion(player, 131, 99, playerSmallSize), ], 0.05), "break": getRegion(player, 148, 99, playerSmallSize), "jump": getRegion(player, 165, 99, playerSmallSize), "crouch": getRegion(player, 80, 99, playerSmallSize), "die": getRegion(player, 182, 99, playerSmallSize) }, "big": { "stand": getRegion(player, 80, 66, playerBigSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 66, playerBigSize), getRegion(player, 114, 66, playerBigSize), getRegion(player, 131, 66, playerBigSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 66, playerBigSize), getRegion(player, 114, 66, playerBigSize), getRegion(player, 131, 66, playerBigSize), ], 0.05), "break": getRegion(player, 148, 66, playerBigSize), "jump": getRegion(player, 165, 66, playerBigSize), "crouch": getRegion(player, 182, 66, playerBigSize) } }, "fire": { "stand": getRegion(player, 80, 129, playerBigSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 129, playerBigSize), getRegion(player, 114, 129, playerBigSize), getRegion(player, 131, 129, playerBigSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 129, playerBigSize), getRegion(player, 114, 129, playerBigSize), getRegion(player, 131, 129, playerBigSize), ], 0.05), "break": getRegion(player, 148, 129, playerBigSize), "jump": getRegion(player, 165, 129, playerBigSize), "crouch": getRegion(player, 182, 129, playerBigSize) }, "invincible": { "small": { "stand": getRegion(player, 80, 225, playerSmallSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 225, playerSmallSize), getRegion(player, 114, 225, playerSmallSize), getRegion(player, 131, 225, playerSmallSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 225, playerSmallSize), getRegion(player, 114, 225, playerSmallSize), getRegion(player, 131, 225, playerSmallSize), ], 0.05), "break": getRegion(player, 148, 225, playerSmallSize), "jump": getRegion(player, 165, 225, playerSmallSize), "crouch": getRegion(player, 80, 225, playerSmallSize), }, "big": { "stand": getRegion(player, 80, 192, playerBigSize), "walk": Animation.from_image_sequence([ getRegion(player, 97, 192, playerBigSize), getRegion(player, 114, 192, playerBigSize), getRegion(player, 131, 192, playerBigSize), ], 0.1), "run": Animation.from_image_sequence([ getRegion(player, 97, 192, playerBigSize), getRegion(player, 114, 192, playerBigSize), getRegion(player, 131, 192, playerBigSize), ], 0.05), "break": getRegion(player, 148, 192, playerBigSize), "jump": getRegion(player, 165, 192, playerBigSize), "crouch": getRegion(player, 182, 192, playerBigSize) } } } castle1 = getRegion(castle, 0, 0, Vector2(47, 80)) castle2 = getRegion(castle, 48, 0, Vector2(32, 80))
import math import cocos import cocos.actions as ac import cocos.collision_model as cm import cocos.euclid as eu import cocos.sprite import pyglet.image from pyglet.image import Animation EXPLOSION_IMG = Animation.from_image_sequence( pyglet.image.ImageGrid(pyglet.image.load("assets\explosion.png"), 1, 8), 0.07, False) class Actor(cocos.sprite.Sprite): def __init__(self, img, x, y): super(Actor, self).__init__(img, position=(x, y)) self._cshape = cm.CircleShape(self.position, self.width * 0.5) @property def cshape(self): """ Actions like MoveBy only update the sprite position, not the cshape.center With this construct, when the cshape is read, we also update the cshape.center """ self._cshape.center = eu.Vector2(self.x, self.y) return self._cshape class Turret(Actor):