Sprite

class pygamelib.gfx.core.Sprite(sprixels=None, default_sprixel=, parent=None, size=[2, 2], name=None)

Bases: object

The Sprite object represent a 2D “image” that can be used to represent any complex item. Obviously, a sprite in the pygamelib is not really an image, it is a series of glyphs (or characters) with colors (foreground and background) information.

A Sprite object is a 2D array of Sprixel.

If you use the climage python module, you can load the generated result into a Sprite through Sprite.load_from_ansi_file().

Parameters:
  • sprixels (list) – A 2D array of Sprixel.
  • default_sprixel (Sprixel) – A default Sprixel to complete lines that are not long enough. By default, it’s an empty Sprixel.
  • parent (BoardComplexItem (suggested)) – The parent object of this Sprite. If it’s left to None, the BoardComplexItem constructor takes ownership of the sprite.
  • size (list) – A 2 elements list that represent the width and height ([width, height]) of the Sprite. It is only needed if you create an empty Sprite. If you load from a file or provide an array of sprixels it’s obviously calculated automatically. Default value: [2, 2].
  • name (str) – The name of sprite. If none is given, an UUID will be automatically generated.

Example:

void = Sprixel()
# This represent a panda
panda_sprite = Sprite(
    sprixels=[
        [void, void, void, void, void, void, void, void],
        [
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            void,
            void,
            void,
            void,
            Sprixel.black_rect(),
            Sprixel.black_rect(),
        ],
        [
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
        ],
        [
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.black_rect(),
            Sprixel.black_rect(),
        ],
        [
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.red_rect(),
            Sprixel.red_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
        ],
        [
            void,
            void,
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            void,
            void,
        ],
        [
            void,
            void,
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.white_rect(),
            Sprixel.black_rect(),
            Sprixel.black_rect(),
        ],
        [
            void,
            void,
            Sprixel.black_rect(),
            Sprixel.black_rect(),
            void,
            void,
            void,
            void,
        ],
    ],
)
__init__(sprixels=None, default_sprixel=, parent=None, size=[2, 2], name=None)

Initialize self. See help(type(self)) for accurate signature.

Methods

__init__([sprixels, default_sprixel, …]) Initialize self.
calculate_size() Calculate the size of the sprite and update the size variable.
empty() Empty the sprite and fill it with default sprixels.
flip_horizontally() Flip the sprite horizontally.
flip_vertically() Flip the sprite vertically (i.e upside/down).
from_text(text_object) Create a Sprite from a Text object.
load(data) Create a new Sprite object based on serialized data.
load_from_ansi_file(filename[, default_sprixel]) Load an ANSI encoded file into a Sprite object.
modulate(color, ratio) Modulate the sprite colors with the color in parameters.
render_to_buffer(buffer, row, column, …) Render the sprite into a display buffer (not a screen buffer).
scale([ratio])

New in version 1.3.0.

serialize() Serialize a Sprite into a dictionary.
set_sprixel(row, column, val) Set a specific sprixel in the sprite to the given value.
set_transparency(state) This method enable transparent background to all the sprite’s sprixels.
sprixel([row, column]) Return a sprixel at a specific position within the sprite.
tint(color, ratio) Tint a copy of the sprite with the color.

Attributes

height Property that returns the height of the Sprite.
width Property that returns the width of the Sprite.
calculate_size()

Calculate the size of the sprite and update the size variable.

The size is immediately returned.

It is done separately for concerns about performances of doing that everytime the size is requested.

Return type:list

Example:

spr_size = spr.calculate_size()
if spr_size != spr.size:
    raise PglException(
                'perturbation_in_the_Force',
                'Something is very wrong with the sprite!'
            )
empty()

Empty the sprite and fill it with default sprixels.

Example:

player_sprite.empty()
flip_horizontally()

Flip the sprite horizontally.

This method performs a symmetry versus the vertical axis.

At the moment, glyph are not inverted. Only the position of the sprixels.

The flipped sprite is returned (original sprite is not modified).

Return type:Sprite

Example:

reflection_sprite = player_sprite.flip_horizontally()
flip_vertically()

Flip the sprite vertically (i.e upside/down).

At the moment, glyph are not inverted. Only the position of the sprixels. There is one exception however, as climage uses the ‘▄’ utf8 glyph as a marker, that specific glyph is inverted to ‘▀’ and vice versa.

The flipped sprite is returned (original sprite is not modified).

Return type:Sprite

Example:

reflection_sprite = player_sprite.flip_vertically()
classmethod from_text(text_object)

Create a Sprite from a Text object.

Parameters:text_object (Text) – A text object to transform into Sprite.

Example:

# The Text object allow for easy manipulation of text
village_name = base.Text('Khukdale',fg_red, bg_green)
# It can be converted into a Sprite to be displayed on the Board
village_sign = board_items.Tile(sprite=Sprite.from_text(village_name))
# And can be used as formatted text
notifications.push( f'You enter the dreaded village of {village_name}' )
height

Property that returns the height of the Sprite.

Contrary to Sprite.size[1], this property always calls Sprite.calculate_size() before returning the height.

classmethod load(data)

Create a new Sprite object based on serialized data.

Parameters:data (dict) – Data loaded from a JSON sprite file (deserialized).
Return type:Sprite

Example:

new_sprite = Sprite.load(json_parsed_data)
classmethod load_from_ansi_file(filename, default_sprixel=None)

Load an ANSI encoded file into a Sprite object.

This class method can load a file produced by the climage python module and load it into a Sprite class. Each character is properly decoded into a Sprixel with model, background and foreground colors.

A Sprite is rectangular (at least for the moment), so in case the file is not shaped as a rectangle, this method automatically fills the void with a default sprixel (to make sure all lines in the sprite have the same length). By default, it fills the table with None “values” but you can specify a default sprixel.

The reasons the default sprixel is set to None is because None values in a sprite are not translated into a component in BoardComplexItem (i.e no sub item is generated).

Parameters:
  • filename (str) – The path to a file to load.
  • default_sprixel (None | Sprixel) – The default Sprixel to fill a non rectangular shaped sprite.

Example:

player_sprite = gfx_core.Sprite.load_from_ansi_file('gfx/models/player.ans')
modulate(color: pygamelib.gfx.core.Color, ratio: float = 0.5)

Modulate the sprite colors with the color in parameters.

This method tint all the sprixels of the sprite with the color at the specified ratio. The original sprite IS modified.

If you want to keep the original sprite intact consider using tint().

Parameters:
  • color (Color) – The modulation color.
  • ratio (float) – The modulation ratio between 0.0 and 1.0 (default: 0.5)
Returns:

None

Example:

player_sprites = core.SpriteCollection.load_json_file("gfx/player.spr")
# After that, the sprite is quite not "normal" anymore...
player_sprites["normal"].modulate(core.Color(0, 255, 0), 0.3)
render_to_buffer(buffer, row, column, buffer_height, buffer_width)

Render the sprite into a display buffer (not a screen buffer).

This method is automatically called by pygamelib.engine.Screen.render().

Parameters:
  • buffer (numpy.array) – A screen buffer to render the item into.
  • row (int) – The row to render in.
  • column (int) – The column to render in.
  • height (int) – The total height of the display buffer.
  • width (int) – The total width of the display buffer.
scale(ratio=1.0)

New in version 1.3.0.

Scale a sprite up and down using the nearest neighbor algorithm.

Parameters:ratio (float) – The scaling ration.
Returns:An upscaled/downscaled sprite.
Return type:Sprite

Note

The sprites generated with pgl-converter.py don’t scale well yet if the –unicode flag is active

Example:

bigger_sprite = original_sprite.scale(2)
serialize()

Serialize a Sprite into a dictionary.

Returns:The class as a dictionary
Return type:dict

Example:

json.dump( sprite.serialize() )
set_sprixel(row, column, val)

Set a specific sprixel in the sprite to the given value. :param name: some param :type name: str

Example:

method()
set_transparency(state)

This method enable transparent background to all the sprite’s sprixels.

Parameters:state – a boolean to enable or disable background transparency

Example:

player_sprite.set_transparency(True)

Warning

This set background transparency on all sprixels, make sure you are not using background colors as part of your sprite before doing that. It can also be used as a game/rendering mechanic. Just make sure you know what you do. As a reminder, by default, sprixels with no background have transparent background enable.

sprixel(row=0, column=None)

Return a sprixel at a specific position within the sprite.

If the column is set to None, the whole row is returned.

Parameters:
  • row (int) – The row to access within the sprite.
  • column (int) – The column to access within the sprite.
Returns:

Sprixel

Example:

# Return the entire line at row index 2
scanline = house_sprite.sprixel(2)
# Return the specific sprixel at sprite internal coordinate 2,3
house_sprixel = house_sprite.sprixel(2, 3)

Warning

For performance consideration sprixel() does not check the size of its matrix. This method is called many times during rendering and 2 calls to len() in a row are adding up pretty quickly. It checks the boundary of the sprite using the cached size. Make sure it is up to date!

tint(color: pygamelib.gfx.core.Color, ratio: float = 0.5)

Tint a copy of the sprite with the color.

This method creates a copy of the sprite and tint all its sprixels with the color at the specified ratio. It then returns the new sprite. The original sprite is NOT modified.

Parameters:
  • color (Color) – The tint color.
  • ratio (float) – The tint ration between 0.0 and 1.0 (default: 0.5)
Returns:

Sprite

Example:

player_sprites = core.SpriteCollection.load_json_file("gfx/player.spr")
player_sprites["sick"] = player_sprites["normal"].tint(
                            core.Color(0, 255, 0), 0.3
                        )
width

Property that returns the width of the Sprite.

Contrary to Sprite.size[0], this property always calls Sprite.calculate_size() before returning the width.