SpriteAnimation

Animates a sequence of images. Can scale, flip, and recolor itself.

Source code in robingame/image/sprite_animation.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class SpriteAnimation:
    """
    Animates a sequence of images.
    Can scale, flip, and recolor itself.
    """

    images: list[Surface] | None

    def __init__(
        self,
        images: list[Surface] = None,
        scale: float = None,
        flip_x: bool = False,
        flip_y: bool = False,
        colormap: dict[Color:Color] = None,
    ):
        """
        Args:
            images: a list of Surfaces to use as frames
            scale: factor by which to scale images
            flip_x: flip all images horizontally if True
            flip_y: flip all images vertically if True
            colormap: used to recolor a sprite. It is a mapping of old colours to new colours
        """
        self.images = images
        if scale:
            self.scale(scale)
        if flip_x or flip_y:
            self.flip(flip_x, flip_y)
        if colormap:
            self.recolor(colormap)

    @classmethod
    def from_image(
        cls,
        filename: Path | str,
        colorkey=None,
        scale: float = None,
        flip_x: bool = False,
        flip_y: bool = False,
        colormap: dict = None,
    ) -> "SpriteAnimation":
        """
        Load the SpriteAnimation from a single image.
        Alias for `from_spritesheet`.
        """
        return cls.from_spritesheet(
            filename=filename,
            image_size=None,
            colorkey=colorkey,
            flip_x=flip_x,
            flip_y=flip_y,
            colormap=colormap,
            scale=scale,
        )

    @classmethod
    def from_spritesheet(
        cls,
        filename: Path | str,
        image_size: (int, int),
        colorkey=None,
        num_images: int = 0,
        scale: float = None,
        flip_x: bool = False,
        flip_y: bool = False,
        colormap: dict = None,
    ) -> "SpriteAnimation":
        """
        Load a SpriteAnimation from a spritesheet.
        """
        images = load_spritesheet(
            filename=filename, image_size=image_size, colorkey=colorkey, num_images=num_images
        )
        return cls(images=images, scale=scale, flip_x=flip_x, flip_y=flip_y, colormap=colormap)

    @classmethod
    def from_image_sequence(
        cls,
        pattern: Path | str,
        colorkey=None,
        num_images: int = 0,
        scale: float = None,
        flip_x: bool = False,
        flip_y: bool = False,
        colormap: dict = None,
    ) -> "SpriteAnimation":
        """
        Load a SpriteAnimation from a sequence of images in a folder.

        Args:
            pattern: glob pattern used by `load_image_sequence`
        """
        images = load_image_sequence(pattern=pattern, colorkey=colorkey, num_images=num_images)
        return cls(images=images, scale=scale, flip_x=flip_x, flip_y=flip_y, colormap=colormap)

    ############## playback ###############
    def play(self, n: int) -> Surface | bool:
        """
        Fetch frame with index `n`.
        This is used in the game loop (where `n` is the iteration counter) to animate the sprite.
        Return False when we've run out of frames.

        Args:
            n:

        Returns:
            the frame to display
        """
        try:
            return self.images[n]
        except IndexError:
            return False

    def loop(self, n: int) -> Surface:
        """
        Like `play()` but if `n` is greater than the number of frames, start again at the beginning.

        Args:
            n:

        Returns:
            the frame to display
        """
        return self.play(n % len(self.images))

    def play_once(self, n: int, repeat_frame: int = -1) -> Surface:
        """
        Run the animation once and then continue returning the specified frame
        (default=last frame).

        Args:
            n:
            repeat_frame: the frame to repeat after the animation has finished (default = last
                frame)

        Returns:
            the frame to display
        """
        try:
            return self.images[n]
        except IndexError:
            return self.images[repeat_frame]

    ############## edit in place ###############
    def flip(self, flip_x: bool, flip_y: bool):
        """
        Flip in place.

        Args:
            flip_x: flip horizontally
            flip_y: flip vertically
        """
        self.images = flip_images(self.images, flip_x, flip_y)

    def recolor(self, colormap: dict):
        """
        Recolor in place.

        Args:
            colormap: mapping of old colours to new colours
        """
        self.images = recolor_images(self.images, colormap)

    def scale(self, scale: float):
        """
        Scale in place.

        Args:
            scale: factor by which to scale images
        """
        self.images = scale_images(self.images, scale)

    ############## edit and copy ###############
    def flipped_copy(self, flip_x=False, flip_y=False) -> "SpriteAnimation":
        """
        Like `flip()` but returns a new instance.

        Returns:
            a new instance
        """
        return self.__class__(images=flip_images(self.images, flip_x, flip_y))

    def recolored_copy(self, colormap: dict) -> "SpriteAnimation":
        """
        Like `recolor()` but returns a new instance.

        Returns:
            a new instance
        """
        return self.__class__(images=recolor_images(self.images, colormap))

    def scaled_copy(self, scale: float) -> "SpriteAnimation":
        """
        Like `scale()` but returns a new instance.

        Returns:
            a new instance
        """
        return self.__class__(images=scale_images(self.images, scale))

    def __len__(self):
        return len(self.images)

__init__(images=None, scale=None, flip_x=False, flip_y=False, colormap=None)

Parameters:
  • images (list[Surface]) –

    a list of Surfaces to use as frames

  • scale (float) –

    factor by which to scale images

  • flip_x (bool) –

    flip all images horizontally if True

  • flip_y (bool) –

    flip all images vertically if True

  • colormap (dict[Color:Color]) –

    used to recolor a sprite. It is a mapping of old colours to new colours

robingame/image/sprite_animation.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def __init__(
    self,
    images: list[Surface] = None,
    scale: float = None,
    flip_x: bool = False,
    flip_y: bool = False,
    colormap: dict[Color:Color] = None,
):
    """
    Args:
        images: a list of Surfaces to use as frames
        scale: factor by which to scale images
        flip_x: flip all images horizontally if True
        flip_y: flip all images vertically if True
        colormap: used to recolor a sprite. It is a mapping of old colours to new colours
    """
    self.images = images
    if scale:
        self.scale(scale)
    if flip_x or flip_y:
        self.flip(flip_x, flip_y)
    if colormap:
        self.recolor(colormap)

flip(flip_x, flip_y)

Flip in place.

Parameters:
  • flip_x (bool) –

    flip horizontally

  • flip_y (bool) –

    flip vertically

robingame/image/sprite_animation.py
159
160
161
162
163
164
165
166
167
def flip(self, flip_x: bool, flip_y: bool):
    """
    Flip in place.

    Args:
        flip_x: flip horizontally
        flip_y: flip vertically
    """
    self.images = flip_images(self.images, flip_x, flip_y)

flipped_copy(flip_x=False, flip_y=False)

Like flip() but returns a new instance.

Returns:
robingame/image/sprite_animation.py
188
189
190
191
192
193
194
195
def flipped_copy(self, flip_x=False, flip_y=False) -> "SpriteAnimation":
    """
    Like `flip()` but returns a new instance.

    Returns:
        a new instance
    """
    return self.__class__(images=flip_images(self.images, flip_x, flip_y))

from_image(filename, colorkey=None, scale=None, flip_x=False, flip_y=False, colormap=None) classmethod

Load the SpriteAnimation from a single image. Alias for from_spritesheet.

robingame/image/sprite_animation.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@classmethod
def from_image(
    cls,
    filename: Path | str,
    colorkey=None,
    scale: float = None,
    flip_x: bool = False,
    flip_y: bool = False,
    colormap: dict = None,
) -> "SpriteAnimation":
    """
    Load the SpriteAnimation from a single image.
    Alias for `from_spritesheet`.
    """
    return cls.from_spritesheet(
        filename=filename,
        image_size=None,
        colorkey=colorkey,
        flip_x=flip_x,
        flip_y=flip_y,
        colormap=colormap,
        scale=scale,
    )

from_image_sequence(pattern, colorkey=None, num_images=0, scale=None, flip_x=False, flip_y=False, colormap=None) classmethod

Load a SpriteAnimation from a sequence of images in a folder.

Parameters:
  • pattern (Path | str) –

    glob pattern used by load_image_sequence

robingame/image/sprite_animation.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
@classmethod
def from_image_sequence(
    cls,
    pattern: Path | str,
    colorkey=None,
    num_images: int = 0,
    scale: float = None,
    flip_x: bool = False,
    flip_y: bool = False,
    colormap: dict = None,
) -> "SpriteAnimation":
    """
    Load a SpriteAnimation from a sequence of images in a folder.

    Args:
        pattern: glob pattern used by `load_image_sequence`
    """
    images = load_image_sequence(pattern=pattern, colorkey=colorkey, num_images=num_images)
    return cls(images=images, scale=scale, flip_x=flip_x, flip_y=flip_y, colormap=colormap)

from_spritesheet(filename, image_size, colorkey=None, num_images=0, scale=None, flip_x=False, flip_y=False, colormap=None) classmethod

Load a SpriteAnimation from a spritesheet.

robingame/image/sprite_animation.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@classmethod
def from_spritesheet(
    cls,
    filename: Path | str,
    image_size: (int, int),
    colorkey=None,
    num_images: int = 0,
    scale: float = None,
    flip_x: bool = False,
    flip_y: bool = False,
    colormap: dict = None,
) -> "SpriteAnimation":
    """
    Load a SpriteAnimation from a spritesheet.
    """
    images = load_spritesheet(
        filename=filename, image_size=image_size, colorkey=colorkey, num_images=num_images
    )
    return cls(images=images, scale=scale, flip_x=flip_x, flip_y=flip_y, colormap=colormap)

loop(n)

Like play() but if n is greater than the number of frames, start again at the beginning.

Parameters:
  • n (int) –
Returns:
  • Surface

    the frame to display

robingame/image/sprite_animation.py
128
129
130
131
132
133
134
135
136
137
138
def loop(self, n: int) -> Surface:
    """
    Like `play()` but if `n` is greater than the number of frames, start again at the beginning.

    Args:
        n:

    Returns:
        the frame to display
    """
    return self.play(n % len(self.images))

play(n)

Fetch frame with index n. This is used in the game loop (where n is the iteration counter) to animate the sprite. Return False when we've run out of frames.

Parameters:
  • n (int) –
Returns:
  • Surface | bool

    the frame to display

robingame/image/sprite_animation.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def play(self, n: int) -> Surface | bool:
    """
    Fetch frame with index `n`.
    This is used in the game loop (where `n` is the iteration counter) to animate the sprite.
    Return False when we've run out of frames.

    Args:
        n:

    Returns:
        the frame to display
    """
    try:
        return self.images[n]
    except IndexError:
        return False

play_once(n, repeat_frame=-1)

Run the animation once and then continue returning the specified frame (default=last frame).

Parameters:
  • n (int) –
  • repeat_frame (int) –

    the frame to repeat after the animation has finished (default = last frame)

Returns:
  • Surface

    the frame to display

robingame/image/sprite_animation.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def play_once(self, n: int, repeat_frame: int = -1) -> Surface:
    """
    Run the animation once and then continue returning the specified frame
    (default=last frame).

    Args:
        n:
        repeat_frame: the frame to repeat after the animation has finished (default = last
            frame)

    Returns:
        the frame to display
    """
    try:
        return self.images[n]
    except IndexError:
        return self.images[repeat_frame]

recolor(colormap)

Recolor in place.

Parameters:
  • colormap (dict) –

    mapping of old colours to new colours

robingame/image/sprite_animation.py
169
170
171
172
173
174
175
176
def recolor(self, colormap: dict):
    """
    Recolor in place.

    Args:
        colormap: mapping of old colours to new colours
    """
    self.images = recolor_images(self.images, colormap)

recolored_copy(colormap)

Like recolor() but returns a new instance.

Returns:
robingame/image/sprite_animation.py
197
198
199
200
201
202
203
204
def recolored_copy(self, colormap: dict) -> "SpriteAnimation":
    """
    Like `recolor()` but returns a new instance.

    Returns:
        a new instance
    """
    return self.__class__(images=recolor_images(self.images, colormap))

scale(scale)

Scale in place.

Parameters:
  • scale (float) –

    factor by which to scale images

robingame/image/sprite_animation.py
178
179
180
181
182
183
184
185
def scale(self, scale: float):
    """
    Scale in place.

    Args:
        scale: factor by which to scale images
    """
    self.images = scale_images(self.images, scale)

scaled_copy(scale)

Like scale() but returns a new instance.

Returns:
robingame/image/sprite_animation.py
206
207
208
209
210
211
212
213
def scaled_copy(self, scale: float) -> "SpriteAnimation":
    """
    Like `scale()` but returns a new instance.

    Returns:
        a new instance
    """
    return self.__class__(images=scale_images(self.images, scale))