def test_insert_2_animation_2_keys(self): """Test generation of 1 animation in GLTF file""" cube = self.create_cube() anim0 = animation.Animation("test_anim0", 0.0, 1.0, "my_event") anim0.append_action("parent", anim0.ACTION_TRANSLATION, [ { "time":1.0, "value": [0.0, 0.0 ,0.0] }, { "time":2.0, "value": [3.0, 0.0 ,0.0] }, ]) anim0.append_action("parent", anim0.ACTION_ROTATION, [ { "time":1.0, "value": [1.0, 0.0 ,0.0, 0.0] }, { "time":2.0, "value": [0.0, 1.0 ,0.0, 0.0] }, ]) cube.add_animation(anim0) anim1 = animation.Animation("test_anim1", 1.0, 2.0, "my_event2") anim1.append_action("parent", anim1.ACTION_TRANSLATION, [ { "time":0.0, "value": [0.0, 0.0 ,0.0] }, { "time":1.0, "value": [0.0, 0.0 ,3.0] }, ]) anim1.append_action("parent", anim0.ACTION_ROTATION, [ { "time":1.0, "value": [1.0, 0.0 ,0.0, 0.0] }, { "time":2.0, "value": [0.0, 1.0 ,0.0, 0.0] }, ]) cube.add_animation(anim1) path_gen = "/tmp/test_animation/output" pathlib.Path(path_gen).mkdir(parents=True, exist_ok=True) #try: cube.generate_gltf(path_gen) concrete_room.preview(path_gen + "/room.gltf", path_gen + "/room_preview.gltf")
def __init__(self, parentLevel, x, y): super().__init__(pygame.image.load("./player/run1.png"), x, y, shape=SHAPE_FANCY) self.parentLevel = parentLevel self.speed = [0, 0] self.inAir = False self.runAcceleration = 3000 self.running = 0 self.jumping = False self.runAcceleration = 1000 self.runSpeed = 400 self.fallSpeed = 0 self.jumpSpeed = 1000 self.airHAcceleration = 1000 self.hAcceleration = 2000 self.vAcceleration = 3000 self.runFrames = [ pygame.image.load("./player/run" + str(x) + ".png") for x in range(1, 7) ] self.runLeftFrames = [ pygame.transform.flip(img, True, False) for img in self.runFrames ] self.leftAnimation = animation.Animation(self.runLeftFrames, [0.02 for x in range(1, 7)]) self.rightAnimation = animation.Animation(self.runFrames, [0.02 for x in range(1, 7)])
def Launch(self): self.all_sprites = pg.sprite.Group() # Une liste de sprites self.ennemies = ... # Une autre player1_stand = [ani.Frame((614, 1063, 120, 191))] player2_stand = [ani.Frame((581, 1265, 121, 191))] player1_animation = ani.Animation(self.spritesheet, player1_stand) player2_animation = ani.Animation(self.spritesheet, player2_stand) player1_animator = ani.Animator(player1_animation) player2_animator = ani.Animator(player2_animation) self.player1 = Player1(player1_animator) self.player2 = Player2(player2_animator) self.all_sprites.add(self.player1) self.all_sprites.add(self.player2) for i in range(10): ennemi_stand = [ani.Frame((568, 1671, 122, 139))] ennemi_animation = ani.Animation(self.spritesheet, ennemi_stand) ennemi_animator = ani.Animator(ennemi_animation) ennemi = Ennemi(ennemi_animator, 50, 10, 10, self.player1) self.all_sprites.add(ennemi) self.ennemies(ennemi) self.Run()
def parser_basic_info(self, parse): ''' @brief Método que parsea la información basica de un objeto del juego. @param parse Parse a Archivo xml con xml.dom.minidom ''' parent_node = parse.firstChild sprite_name = str(parent_node.getAttribute('sprite_code')) self.original_sprite = resource.get_new_sprite(sprite_name) #Cargamos las distintas animaciones del objeto for element in parse.getElementsByTagName('animation'): animation_name = str(element.getAttribute('name')) animation_frames = str(element.getAttribute('frames')) animation_delay = int(element.getAttribute('delay')) #Vemos que tipo de animación es y lo añadimos al mapa de imagenes if animation_name == 'normal': self.animations[NORMAL] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'noaction': self.animations[NOACTION] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'run': self.animations[RUN] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'forward': self.animations[FORWARD] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'reverse': self.animations[REVERSE] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'damaged': self.animations[DAMAGED] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'erase': self.animations[ERASE] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'yaw': self.animations[YAW] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'fall': self.animations[FALL] = animation.Animation( animation_frames, animation_delay) elif animation_name == 'turbo': self.animations[TURBO] = animation.Animation( animation_frames, animation_delay) #Inicializamos la imagen, el rectangulo y la mascara de pixeles self.image = self.original_sprite.get_frame( self.animations[NORMAL].get_frame()) self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) self.hitmask = pixelperfect.get_alpha_hitmask(self.image, self.rect)
def assign_directions(self, data): for ani in data["animations"]: if ani["direction"] == "north": self.north = animation.Animation(self.parent, data, ani) elif ani["direction"] == "east": self.east = animation.Animation(self.parent, data, ani) elif ani["direction"] == "south": self.south = animation.Animation(self.parent, data, ani) elif ani["direction"] == "west": self.west = animation.Animation(self.parent, data, ani) else: print("Error: Avatar Animations Action not valid option") pass
def _load_frames(self): sheet_walk = animation.Sheet(load("walk.png", True), 4) sheet_stand = animation.Sheet(load("stand.png", True), 1) sheet_wait = animation.Sheet(load("wait.png", True), 3) sheet_boo = animation.Sheet(load("boo.png", True), 1) sheet_ok = animation.Sheet(load("ok.png", True), 1) self.animations = { "walk": animation.Animation(sheet_walk, 5, [0, 1, 2, 3]), "stand": animation.Animation(sheet_stand, 1, [0]), "boo": animation.Animation(sheet_boo, 1, [0]), "ok": animation.Animation(sheet_ok, 1, [0]), "wait": animation.Animation(sheet_wait, 10, [0, 1, 2, 1]), }
def __init__(self) -> None: self.mouse_buttons = [False for i in range(6)] self.reload_animation = animation.Animation(animation.ONE_WAY) self.firing_animation = animation.Animation(animation.ONE_WAY) self.holding_animation = animation.Animation() self.ground_animations = [animation.Animation() for i in range(4)] self.mag_size = 30 self.damage = 80 self.current_mag = 30 self.was_reloading = False self.fire_mode = SEMI_AUTO self.fire_cooldown = 0.5 self.current_fire_countdown = 0 self.old_button_states = []
def setupPlayer(image, main_node): #Se crean los distintos frames para cada animacion, recortando la imagen ship_frames1 = anim.createFrames(image, [128, 128], [0, 0], [2], [0, 0]) #animacion para avanzar ship_frames2 = anim.createFrames(image, [128, 128], [0, 0], [2], [0, 1]) #animacion para retroceder hurt_frames = anim.createFrames(image, [128, 128], [0, 0], [2], [2, 2]) # animacion cuando le llega una bala explode_frames = anim.createFrames(image, [128, 128], [0, 0], [2, 5], [2, 0]) # animacion de explosion #se crea un diccionario con las animaciones ship_animations = {} ship_animations["fast"] = anim.Animation(ship_frames1, 12, True, False) ship_animations["slow"] = anim.Animation(ship_frames2, 12, True, False) ship_animations["hurt"] = anim.Animation(hurt_frames, 12, True, False) ship_animations["explode"] = anim.Animation(explode_frames, 9, False, False) #se crea el controlador de animaciones y se inicializa ship_Anim = anim.Anim_Controller(ship_animations, [PLAYER_SIZE, WIDTH / HEIGHT * PLAYER_SIZE, 1], 0) ship_Anim.Play("slow") #se crea un nodo que contiene la animacion anim_node = sg.SceneGraphNode("anim_player") anim_node.childs += [ship_Anim] # se crea un nodo con una gpuShape que servira para detectar las colisiones y verlas si se quiere collision_node = sg.SceneGraphNode("collision_player") collision_node.childs += [es.toGPUShape(cl.createCircleHitbox(PLAYER_HITBOX_RADIO, 10, 0, 1, 0))] # se crea uno nodo/objeto CollisionShape que tiene informacion y metodos para detectar colisiones con respecto de una gpuShape scaled_collision = cl.CollisionShape("scaled_collision", PLAYER_HITBOX_RADIO, True) # se escala la hitbox para que tenga el mismo tamaño que la textura scaled_collision.transform = tr.scale(1, 1 * WIDTH/HEIGHT, 1) scaled_collision.childs += [collision_node] # se crea el objeto player que contendra como nodos hijos a la animacion y la hitbox player_gameObject = playerObject("player") # se traslada la nave en la pantalla a su posicion inicial player_gameObject.transform = tr.translate(0, -0.5, 0) player_gameObject.position[0] = 0 player_gameObject.position[1] = -0.5 player_gameObject.position[2] = 0 player_gameObject.childs += [anim_node] #se agrega la animacion player_gameObject.childs += [scaled_collision] #se agrega la hitbox player_gameObject.childs[1].parent = player_gameObject # se agrega la referencia de padre al objeto CollisionShape #agrega el objeto player a la escena principal main_node.childs += [player_gameObject] #retorna la referencia al objeto player return go.findNode(main_node, "player")
def __init__(self, screen_rect, bg_color): """ Initialize the display. screen_rect: the bounds of the screen bg_color: the background color """ LayeredUpdates.__init__(self) if GUI.num_instances != 0: raise Exception("GUI: can only have one instance of a simulation") GUI.num_instances = 1 # Set up the screen self.screen = pygame.display.set_mode((screen_rect.w, screen_rect.h)) self.screen_rect = screen_rect # The rect containing the info bar self.bar_rect = pygame.Rect(screen_rect.w - BAR_WIDTH, 0, BAR_WIDTH, screen_rect.h) # The rect containing the map view self.view_rect = pygame.Rect(0, 0, MAP_WIDTH, screen_rect.h) self.bg_color = bg_color self.map = None # Set up team information self.num_teams = None self.current_turn = 0 self.win_team = None # The currently selected unit self.sel_unit = None # Set up GUI self.buttons = [ Button(0, "MOVE", self.move_pressed, self.can_move), Button(1, "ATTACK", self.attack_pressed, self.can_attack), Button(2, "END TURN", self.end_turn_pressed, None), Button(3, "HEAL", self.heal_pressed, self.can_heal)] # We start in select mode self.mode = Modes.Select # Tiles we can move to/attack self._movable_tiles = set() self._attackable_tiles = set() # The targeting reticle self._reticle = animation.Animation("assets/reticle.png", 20, 20, RETICLE_RATE) # This will store effects which are drawn over everything else self._effects = pygame.sprite.Group()
def test_animation_4(): a = animation.Animation(os.path.join(assets_dir, 'animation_4.csv'), config) assert a.id == 'two_drones_test' assert a.state == "OK" assert approx(a.original_frames[11].get_pos()) == [0.21774, 1.4, 1.0] assert a.original_frames[11].get_color() == [0, 0, 0] assert a.original_frames[11].pose_is_valid() assert a.takeoff_index == 11 assert a.route_index == 11 assert a.land_index == 139 assert a.static_end_index == 139 assert a.start_frame_index == 0 assert approx(a.start_time) == 0 assert a.output_frames[a.start_frame_index].action == 'arm' assert a.output_frames_takeoff[a.start_frame_index].action == 'takeoff' assert approx(a.output_frames_min_z) == 1 assert a.get_start_action() == 'takeoff' config.set('ANIMATION', 'ratio', [1, 2, 3]) config.set('ANIMATION', 'common_offset', [4, 5, 6]) a.on_config_update(config) assert approx(a.output_frames[0].get_pos()) == [4.2, 7.8, 9] assert approx(a.output_frames_min_z) == 9 assert approx(a.get_start_frame('fly').get_pos()) == [4.2, 7.8, 9] assert a.get_start_action() == 'takeoff' config.set('ANIMATION', 'ratio', [1, 1, 1]) config.set('ANIMATION', 'common_offset', [0, 0, 0])
def __init__(self, fn): """ Open the tileset image, and set up animations. fn - the path to the tileset image. """ #parse the XML file root = data.getTreeRoot(fn) self.tileSize = data.getAttr(root, "tilesize", data.D_INT2LIST) self.transparency = data.getAttr(root, "transparency", data.D_INT3LIST) #create the tiles tilesetPath = os.path.join(settings.path, "data", data.getAttr(root, "file", data.D_STRING)) self.openImage(tilesetPath) #create animations for the tileset self.autoAnimations = {} self.walkontoAnimations = {} for anim in root.findall("animation"): trigger = data.getAttr(anim, "trigger", data.D_STRING) tile = data.getAttr(anim, "tile", data.D_INT) frames = data.getAttr(anim, "frames", data.D_INTLIST) a = animation.Animation(frames) if trigger == "auto": a.play(True) self.autoAnimations[tile] = a elif trigger == "walkonto": self.walkontoAnimations[tile] = a
def test_done(self): anim = animation.Animation(frames=[self.images[0]], loop=False) avw = animation.AnimationView(anim) self.assertTrue(avw.update()) self.assertTrue(avw.done) self.assertFalse(avw.update()) self.assertTrue(avw.done)
def __init__(self, brushinfo=None): if not brushinfo: brushinfo = brush.BrushInfo() brushinfo.load_defaults() self.layers = [] self.brush = brush.Brush(brushinfo) self.ani = animation.Animation(self) self.brush.brushinfo.observers.append(self.brushsettings_changed_cb) self.stroke = None self.canvas_observers = [] #: See `layer_modified_cb()` self.stroke_observers = [] #: See `split_stroke()` self.doc_observers = [] #: See `call_doc_observers()` self.frame_observers = [] self.command_stack_observers = [] self.symmetry_observers = [] #: See `set_symmetry_axis()` self.__symmetry_axis = None self.default_background = (255, 255, 255) self.clear(True) self._frame = [0, 0, 0, 0] self._frame_enabled = False # Used by move_frame() to accumulate values self._frame_dx = 0.0 self._frame_dy = 0.0
def new_explosion(bot, bullet, game_bullets): game_bullets.remove(bullet) if bot.hit: bot.hit = False e = animation.Animation(boat_game.explosion_imgs, bullet.pos, time_scale / 5) e.start() boat_game.explosions.append(e)
def test_animation_no_file(): a = animation.Animation('zzz.csv', config) assert a.id == None assert a.state != "OK" assert a.original_frames == [] assert a.output_frames == [] assert a.output_frames_min_z is None
def loadAnimation(name, width, delay, loop, colorkey=None): image, imageRect = loadImage(name, colorkey) frames = list() for frameNo in xrange(imageRect.width // width): rect = pygame.rect.Rect(frameNo * width, 0, width, imageRect.height) frames.append(image.subsurface(rect)) return animation.Animation(frames, delay, loop)
def __init__(self, spriteId, x, y): self.spriteId = spriteId super().__init__(sprites["hazards"][spriteId], x, y, shape=SHAPE_FANCY) if hazardAnimations[spriteId] != []: anim = animation.Animation( hazardAnimations[spriteId], [0.2 for x in hazardAnimations[spriteId]]) self.setAnimation(anim)
def loadAnimations(self, spriteName, shouldCreateCopy=True): if spriteName in self.animationsCache: if shouldCreateCopy: return self.copy(spriteName) return self.animationsCache[spriteName] # Search for a file named 'spriteConfig.py' through the path specified # in spriteName. Use the deepest one we find. This lets us share # spriteConfigs for similar sprites. directories = spriteName.split(os.sep) modulePath = None path = constants.spritePath for directory in directories: path += os.sep + directory if os.path.exists( os.path.join(path, constants.spriteFilename + '.py')): modulePath = path if modulePath is None: logger.fatal( "Unable to find a spriteConfig.py file anywhere in the path", spriteName) modulePath = os.path.join(modulePath, constants.spriteFilename) spriteModule = game.dynamicClassManager.loadModuleItems( modulePath, ['sprites']) animations = {} for animationName, data in spriteModule.sprites.iteritems(): # Load the bounding polygon, and all optional flags, with sane # defaults. animPolygon = polygon.Polygon( [Vector2D(point) for point in data['polygon']]) shouldLoop = True if 'loop' in data: shouldLoop = data['loop'] updateRate = 1 if 'updateRate' in data: updateRate = data['updateRate'] updateFunc = None if 'updateFunc' in data: updateFunc = data['updateFunc'] drawOffset = Vector2D(0, 0) if 'drawOffset' in data: drawOffset = Vector2D(data['drawOffset']) moveOffset = Vector2D(0, 0) if 'moveOffset' in data: moveOffset = Vector2D(data['moveOffset']) frameActions = dict() if 'frameActions' in data: frameActions = data['frameActions'] animations[animationName] = animation.Animation( spriteName, animationName, animPolygon, shouldLoop, updateRate, updateFunc, drawOffset, moveOffset, frameActions) self.animationsCache[spriteName] = animations if shouldCreateCopy: return self.copy(spriteName) return self.animationsCache[spriteName]
def test_animation_1_2(): a = animation.Animation(os.path.join(assets_dir, 'animation_1.csv'), config) assert a.id == 'basic' assert a.state == "OK" assert approx(a.original_frames[0].get_pos()) == [0, 0, 0] assert a.original_frames[0].get_color() == [204, 2, 0] assert a.original_frames[0].pose_is_valid() assert a.takeoff_index == 10 assert a.route_index == 20 assert a.land_index == 29 assert a.static_end_index == 39 assert a.start_frame_index == a.takeoff_index assert approx(a.start_time) == 1 assert a.output_frames[a.start_frame_index].action == 'arm' assert a.output_frames_takeoff[a.start_frame_index].action == 'takeoff' assert approx(a.output_frames_min_z) == 0 assert a.get_start_action() == 'fly' config.set('ANIMATION', 'ratio', [1, 2, 3]) config.set('ANIMATION', 'common_offset', [4, 5, 6]) a.on_config_update(config) assert approx(a.output_frames[0].get_pos()) == [4., 5., 6.] assert approx(a.output_frames_min_z) == 6. assert approx(a.get_start_frame('fly').get_pos()) == [4., 5., 6.] assert a.get_start_action() == 'takeoff' config.set('ANIMATION', 'ratio', [1, 1, 1]) config.set('ANIMATION', 'common_offset', [0, 0, 0]) a.on_animation_update(os.path.join(assets_dir, 'animation_2.csv'), config) assert a.id == 'parad' assert a.state == "OK" assert approx( a.original_frames[271].get_pos()) == [-1.00519, 2.65699, 0.24386] assert a.original_frames[271].get_color() == [7, 255, 0] assert a.original_frames[271].pose_is_valid() assert a.takeoff_index == 271 assert a.route_index == 285 assert a.land_index == 1064 assert a.static_end_index == 1064 assert a.start_frame_index == a.takeoff_index assert approx(a.start_time) == 27.1 assert a.output_frames[a.start_frame_index].action == 'arm' assert a.output_frames_takeoff[a.start_frame_index].action == 'takeoff' assert approx(a.output_frames_min_z) == 0.21 assert a.get_start_action() == 'fly' config.set('ANIMATION', 'ratio', [1, 2, 3]) config.set('ANIMATION', 'common_offset', [4, 5, 6]) a.on_config_update(config) assert approx(a.output_frames[0].get_pos()) == [2.99481, 10.31398, 6.63] assert approx(a.output_frames_min_z) == 6.63 assert approx( a.get_start_frame('fly').get_pos()) == [2.99481, 10.31398, 6.63] assert a.get_start_action() == 'takeoff' config.set('ANIMATION', 'ratio', [1, 1, 1]) config.set('ANIMATION', 'common_offset', [0, 0, 0])
def setupfinishAnim(lose_image, win_image): global MAIN_NODE, BACKGROUND_ANIM, LETTERS_ANIM, WIN_ANIM backGround_frames = anim.createFrames(lose_image, [256, 76], [0, 0], [10, 1], [0, 0]) #se recorta la imagen letters_frames = anim.createFrames(lose_image, [256, 76], [0, 0], [10, 1], [1, 0]) #se recorta la imagen bg_animations = {"appear" : anim.Animation(backGround_frames, 9, False, False)} #se crean las animaciones lt_animations = {"appear": anim.Animation(letters_frames, 9, False, False)} #se crean las animaciones #Se crean los controladores de las animaciones y se inicializan BACKGROUND_ANIM = anim.Anim_Controller(bg_animations, [2, WIDTH / HEIGHT * 1, 1], 0) BACKGROUND_ANIM.Play("appear") LETTERS_ANIM = anim.Anim_Controller(lt_animations, [2 * 0.4, WIDTH / HEIGHT * 0.4, 1], 0) LETTERS_ANIM.Play("appear") win_frames = anim.createFrames(win_image, [128, 192], [0, 0], [2, 11], [0, 0]) #se recorta la imagen win_animations = {"appear": anim.Animation(win_frames, 12, False, False)} #se crea la animacion # Se crea el controlador de la animacion y se inicializa WIN_ANIM = anim.Anim_Controller(win_animations, [2, WIDTH / HEIGHT * 2 * 1.5, 1], 0) WIN_ANIM.Play("appear")
def __init__(self, *groups): pg.sprite.Sprite.__init__(self, *groups) self.image = pg.image.load( "data/sprites/SkeletonWarrior/front/1.png").convert_alpha() self.rect = self.image.get_rect() self.rect[0], self.rect[1] = spawnEnemy(screenW, screenH) self.xspeed = 0 self.yspeed = 0 self.speed = 2 self.aniID = 0 self.health = 100 self.newAnimator = animation.Animation()
def setupEnemyBullets(image, main_node): global bullet0_animation, bullet1_animation, bullet2_animation #ENEMY 0 BULLET SETUP bullet0_image = anim.createFrames(image, [64, 64], [0, 0], [1], [0, 2]) #se recorta la imagen bullet0_explote_frames = anim.createFrames(image, [64, 64], [0, 0], [6], [0, 3]) # se crean las animaciones bullet0_anim = anim.Animation(bullet0_image, 1, True, False) bullet0_explote_anim = anim.Animation(bullet0_explote_frames, 12, False, False) # se crea la agrupacion de animaciones bullet0_animation = {"shooted" : bullet0_anim, "explote" : bullet0_explote_anim} # ENEMY 1 BULLET SETUP bullet1_image = anim.createFrames(image, [64, 64], [0, 0], [1], [0, 6]) #se recorta la imagen bullet1_explote_frames = anim.createFrames(image, [64, 64], [0, 0], [6], [0, 7]) # se crean las animaciones bullet1_anim = anim.Animation(bullet1_image, 1, True, False) bullet1_explote_anim = anim.Animation(bullet1_explote_frames, 12, False, False) # se crea la agrupacion de animaciones bullet1_animation = {"shooted": bullet1_anim, "explote": bullet1_explote_anim} # ENEMY 2 BULLET SETUP bullet2_image = anim.createFrames(image, [64, 64], [0, 0], [1], [0, 10]) #se recorta la imagen bullet2_explote_frames = anim.createFrames(image, [64, 64], [0, 0], [6], [0, 11]) # se crean las animaciones bullet2_anim = anim.Animation(bullet2_image, 1, True, False) bullet2_explote_anim = anim.Animation(bullet2_explote_frames, 12, False, False) # se crea la agrupacion de animaciones bullet2_animation = {"shooted": bullet2_anim, "explote": bullet2_explote_anim} # se crea la coleccion de balas y se agrega al nodo principal bullets_collection = sg.SceneGraphNode("enemy_bullets") main_node.childs += [bullets_collection] # retorna una referencia a la coleccion de balas enemigas return go.findNode(main_node, "enemy_bullets")
def _load_entity(loaded_object, is_player = False, game_world = None): initial_x_position = loaded_object['x_position'] initial_y_position = loaded_object['y_position'] front_standing_sprites = animation.Animation() front_standing_sprites.set_frames(__load_animation_frames(loaded_object['frames']['front']['standing']['frames']), loaded_object['frames']['front']['standing']['frame_rate']) rear_standing_sprites = animation.Animation() rear_standing_sprites.set_frames(__load_animation_frames(loaded_object['frames']['rear']['standing']['frames']), loaded_object['frames']['rear']['standing']['frame_rate']) left_standing_sprites = animation.Animation() left_standing_sprites.set_frames(__load_animation_frames(loaded_object['frames']['left']['standing']['frames']), loaded_object['frames']['left']['standing']['frame_rate']) right_standing_sprites = animation.Animation() right_standing_sprites.set_frames(__load_animation_frames(loaded_object['frames']['right']['standing']['frames']), loaded_object['frames']['right']['standing']['frame_rate']) standing_sprites = [front_standing_sprites, rear_standing_sprites, left_standing_sprites, right_standing_sprites] front_walking_sprite_filehandles = loaded_object['frames']['front']['walking']['frames'] rear_walking_sprite_filehandles = loaded_object['frames']['rear']['walking']['frames'] left_walking_sprite_filehandles = loaded_object['frames']['left']['walking']['frames'] right_walking_sprite_filehandles = loaded_object['frames']['right']['walking']['frames'] front_walking_sprites = __load_animation_frames(front_walking_sprite_filehandles) rear_walking_sprites = __load_animation_frames(rear_walking_sprite_filehandles) left_walking_sprites = __load_animation_frames(left_walking_sprite_filehandles) right_walking_sprites = __load_animation_frames(right_walking_sprite_filehandles) front_walking_animation = animation.Animation().set_frames(front_walking_sprites, loaded_object['frames']['front']['walking']['frame_rate']) rear_walking_animation = animation.Animation().set_frames(rear_walking_sprites, loaded_object['frames']['rear']['walking']['frame_rate']) left_walking_animation = animation.Animation().set_frames(left_walking_sprites, loaded_object['frames']['left']['walking']['frame_rate']) right_walking_animation = animation.Animation().set_frames(right_walking_sprites, loaded_object['frames']['left']['walking']['frame_rate']) front_walking_animation.passed_time = 0 rear_walking_animation.passed_time = 0 left_walking_animation.passed_time = 0 right_walking_animation.passed_time = 0 outEntity = entity.Entity(initial_x_position, initial_y_position) if is_player: outEntity = player.Player(game_world, initial_x_position, initial_y_position) outEntity.set_sprites(standing_sprites) outEntity.walking_sprites = [front_walking_animation, rear_walking_animation, left_walking_animation, right_walking_animation] return outEntity
def start_animiation(self, x=0.0, y=0.0, relative=True, duration=250): sprite = self.sprite_group.sprite if self.can_walk_to_pos(sprite, x, y): logger.debug("Dest: {}".format( (sprite.rect.left + x, sprite.rect.top + y))) self.previous_pos = sprite.rect.topleft a = ani.Animation(sprite.rect, x=int(x), y=int(y), duration=duration, relative=relative) a.schedule(self.clear_animations) self.update_walking_sprite(x, y) self.animation_running = True self.animations.add(a)
def __init__(self, speedvector, game): pg.sprite.Sprite.__init__(self) # game objects self.gm = game self.player = game.p self.evm = game.evm self.evm.add_listener(self) # make vector in opposite direction from player self.vector = -1 * speedvector # spritegroups self.gm.allsprites.add(self) self.gm.onscreen.add(self) self.gm.pvedamage.add(self) self.gm.p.allsprites.add(self) self.gm.p.brakeshots.add(self) # get angle to positive x-axis self.angle_d = self.vector.angle_to(pg.math.Vector2((1, 0))) self.angle_r = math.radians(self.angle_d) # load animation self.animation = ani.Animation("brakeblast.png", 64) self.image = self.animation.get_frame_no(0).convert_alpha() # find center for new rect by rotating a pre-defined center # TODO generalize this magic constant to enable scaling center_rightx = self.player.rect.centerx + 50 center_righty = self.player.rect.centery center_right = (center_rightx, center_righty) newcenter = utils.rotate_point(self.player.rect.center, center_right, -1 * self.angle_r) # get rect from image self.rect = pg.transform.rotate( self.image, self.angle_d).get_rect(center=newcenter) print(str(self.vector.length())) print(self.rect) # bool to ensure only dealing damage once self.damage_dealt = False
def _load_frames(self): sheet_walk = animation.Sheet(common.load("player/walk.png", True), 4) sheet_stand = animation.Sheet(common.load("player/stand.png", True), 1) sheet_wait = animation.Sheet(common.load("player/wait.png", True), 2) sheet_working = animation.Sheet(common.load("player/working.png", True), 2) sheet_ok = animation.Sheet(common.load("player/ok.png", True), 1) sheet_stand_moving = animation.Sheet(common.load("player/stand_moving.png", True), 1) sheet_walk_moving = animation.Sheet(common.load("player/walk_moving.png", True), 4) self.animations = { "walk": animation.Animation(sheet_walk, 6, [0, 1, 2, 3]), "stand": animation.Animation(sheet_stand, 1, [0]), "working": animation.Animation(sheet_working, 6, [0, 1]), "ok": animation.Animation(sheet_ok, 1, [0]), "wait": animation.Animation(sheet_wait, 10, [0, 1]), "stand_moving": animation.Animation(sheet_stand_moving, 1, [0]), "walk_moving": animation.Animation(sheet_walk_moving, 6, [0, 1, 2, 3]), }
def addStars(stars_coll): posY = 0 #posicion horizontal del paquete depende de los anteriores if len(stars_coll.childs) == 0: posY = -1 else: posY = stars_coll.childs[-1].position[1] + STAR_POSY #se crea un gameObject que vendria siendo el paquete de estrellas y se posiciona start_node = gameObject("star_node") start_node.transform = tr.translate(0, posY, 0) start_node.position[1] = posY #cantidad random de estrellas que contendra el paquete amountInX = random.randint(STARS_IN_X_MIN, STARS_IN_X_MAX) for x in range(amountInX): #por cada estrella del paquete se crea una animController con una estrella random, tamaño random y se inicializa anim0 = anim.Animation(stars_images[random.randint(0, 15)], random.randint(STAR_MIN_FPS, STAR_MAX_FPS), True, False) scale = STAR_MIN_SIZE + random.random() * (STAR_MAX_SIZE - STAR_MIN_SIZE) anim_Ctl = anim.Anim_Controller({"star": anim0}, [scale, scale * WIDTH / HEIGHT, scale], 0) anim_Ctl.Play("star") #posicion horizontal random startPosX = -1 + (2 / amountInX) * x + random.random() * (2 / amountInX) #posicion vertical variando un poco con respecto a la del paquete startPosY = (-1 + random.random() * 2) * STAR_DELTA_POSY #se crea el gameobject de cada estrella con su animacion star_object = gameObject("star") star_object.transform = tr.translate(startPosX, startPosY, 0) star_object.position = np.array([startPosX, startPosY, 0]) star_object.childs += [anim_Ctl] #se agrega cada estrella al paquete start_node.childs += [star_object] #se agrega el paquete a la coleccion de estrellas stars_coll.childs += [start_node]
def __init__(self, brushinfo=None, painting_only=False): """Initialize :param brushinfo: the lib.brush.BrushInfo instance to use :param painting_only: only use painting layers If painting_only is true, then no tempdir will be created by the document when it is initialized or cleared. """ object.__init__(self) if not brushinfo: brushinfo = brush.BrushInfo() brushinfo.load_defaults() self._layers = layer.RootLayerStack(self) self._layers.layer_content_changed += self._canvas_modified_cb self.brush = brush.Brush(brushinfo) self.ani = animation.Animation(self) self.brush.brushinfo.observers.append(self.brushsettings_changed_cb) self.stroke = None self.doc_observers = [] #: See `call_doc_observers()` self.frame_observers = [] self.symmetry_observers = [] #: See `set_symmetry_axis()` self._symmetry_axis = None self.command_stack = command.CommandStack() self._painting_only = painting_only self._tempdir = None # Optional page area and resolution information self._frame = [0, 0, 0, 0] self._frame_enabled = False self._xres = None self._yres = None # Backgrounds for rendering blank_arr = numpy.zeros((N, N, 4), dtype='uint16') self._blank_bg_surface = tiledsurface.Background(blank_arr) # Compatibility self.layers = _LayerStackMapping(self) self.clear()
def main(): parser = ArgumentParser(prog='gvanim') parser.add_argument( 'animation', nargs='?', type=FileType('r'), default=stdin, help='The file containing animation commands (default: stdin)') parser.add_argument('--delay', '-d', default='100', help='The delay (in ticks per second, default: 100)') parser.add_argument('basename', help='The basename of the generated file') args = parser.parse_args() ga = animation.Animation() ga.parse(args.animation) render.gif(render.render(ga.graphs(), args.basename, 'png'), args.basename, args.delay)
def __init__(self, graphics, position, animations, team=1): self.position = position self.health = 100 self.maxHealth = 100 self.speed = 25 self.targets = [] #walk target self.seekTarget = pygame.sprite.Group( ) #i've kept these here so that the collision avoidance can check self.attackTarget = pygame.sprite.Group( ) #whether this unit is just trying to move or whether it's doing #something useful - maybe there's a better way self.animations = dict() for action, anim in animations.iteritems(): self.animations[action] = animation.Animation(graphics, anim) self.currentanimation = self.animations[ 'default'] #set us to the default animation mapobject.MapObject.__init__( self, self.currentanimation.reset(), position, team) #init the base class with the first frame of the animation self.direction = 100