Last active
January 12, 2024 08:53
-
-
Save joereynolds/1c20645bfa54bd2df62133a8fb9de7cb to your computer and use it in GitHub Desktop.
Pygame animation class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame | |
from src.countdown_timer import CountdownTimer | |
import src.config.events as e | |
class Animates: | |
def __init__( | |
self, | |
parent: pygame.sprite.Sprite, | |
frames, | |
named_frames: dict = {}, | |
speed: float = 0.125, | |
play = True, | |
play_frames: str = '', | |
loop = True, | |
callback_frames: str = '' | |
): | |
""" | |
frames: The frames from Tiled that we'll be animating | |
named_frames: Those same frames broken into a dictionary in the format "animation" : [frames...] | |
e.g. "walking": [5,6,7,8] | |
speed: At what speed should we animate them | |
play: Whether to animate or not | |
play_frames: Which frames from the named frames we should animate e.g. "walking", "dying" etc... | |
loop: Whether to loop the animation or not | |
callback_frames: The frames to animate once play_frames have finished animating (optional obviously) | |
""" | |
self.frames = frames | |
self.timer = CountdownTimer(speed) | |
self.parent = parent | |
self.play_frames = play_frames | |
self.named_frames = named_frames | |
self.play = play | |
self.loop = loop | |
self.frame_index = self.named_frames[self.play_frames][0] | |
self.parent.image = self.frames[self.frame_index] | |
self.frames_to_play = self.named_frames[self.play_frames] | |
self.callback_frames = callback_frames | |
def change_frames(self, frames: str): | |
self.frame_index = self.named_frames[frames][0] | |
self.frames_to_play = self.named_frames[frames] | |
def update(self, dt: float, level, player, events): | |
""" | |
dt: Delta time | |
Ignore the other args, these are specific to a game in progress | |
""" | |
if not self.play: | |
return | |
self.timer.update(dt) | |
if self.timer.has_ended(): | |
if self.frame_index >= max(self.frames_to_play): | |
if not self.loop: | |
self.frame_index = self.frames_to_play[-1] | |
if self.loop: | |
self.frame_index = self.frames_to_play[0] | |
if self.callback_frames: | |
self.change_frames(self.callback_frames) | |
pygame.event.post( | |
pygame.event.Event( | |
e.events['animation-finished-event'], | |
{'entity_id': self.parent.id} | |
) | |
) | |
else: | |
self.frame_index += 1 | |
self.parent.image = self.frames[self.frame_index] | |
self.timer.reset() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment