Sprite

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

Bases: PglBaseObject

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=None, parent=None, size=[2, 2], name=None)

Like the object class, this class constructor takes no parameter.

Methods

__init__([sprixels, default_sprixel, ...])

Like the object class, this class constructor takes no parameter.

attach(observer)

Attach an observer to this instance.

calculate_size()

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

copy()

Returns a (deep) copy of the sprite.

detach(observer)

Detach an observer from this instance.

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.

handle_notification(subject[, attribute, value])

A virtual method that needs to be implemented by the observer.

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.

notify([modifier, attribute, value])

Notify all the observers that a change occurred.

render_to_buffer(buffer, row, column, ...)

Render the sprite from the display buffer to the frame buffer.

scale([ratio])

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

serialize()

Serialize a Sprite into a dictionary.

set_sprixel(row, column, value)

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.

store_screen_position(row, column)

Store the screen position of the object.

tint(color[, ratio])

Tint a copy of the sprite with the color.

Attributes

height

Property that returns the height of the Sprite.

screen_column

A property to get/set the screen column.

screen_row

A property to get/set the screen row.

width

Property that returns the width of the Sprite.

attach(observer)

Attach an observer to this instance. It means that until it is detached, it will be notified every time that a notification is issued (usually on changes).

An object cannot add itself to the list of observers (to avoid infinite recursions).

Parameters:

observer (PglBaseObject) – An observer to attach to this object.

Returns:

True or False depending on the success of the operation.

Return type:

bool

Example:

myboard = Board()
screen = Game.instance().screen
# screen will be notified of all changes in myboard
myboard.attach(screen)
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!'
            )
copy()

Returns a (deep) copy of the sprite.

New in version 1.3.0.

detach(observer)

Detach an observer from this instance. If observer is not in the list this returns False.

Parameters:

observer (PglBaseObject) – An observer to detach from this object.

Returns:

True or False depending on the success of the operation.

Return type:

bool

Example:

# screen will no longer be notified of the changes in myboard.
myboard.detach(screen)
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}' )
handle_notification(subject, attribute=None, value=None)

A virtual method that needs to be implemented by the observer. By default it does nothing but each observer needs to implement it if something needs to be done when notified.

This method always receive the notifying object as first parameter. The 2 other parameters are optional and can be None.

You can use the attribute and value as you see fit. You are free to consider attribute as an event and value as the event’s value.

Parameters:
  • subject (PglBaseObject) – The object that has changed.

  • attribute (str) – The attribute that has changed, it is usually a “FQDN style” string. This can be None.

  • value (Any) – The new value of the attribute. This can be None.

property height

Property that returns the height of the Sprite.

New in version 1.3.0.

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.

New in version 1.3.0.

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: Color, ratio: float = 0.5)

Modulate the sprite colors with the color in parameters.

New in version 1.3.0.

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

When this method is called, the observers are notified of the change with the pygamelib.core.Sprite.color:modulated event. No arguments are passed along this event.

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)
notify(modifier=None, attribute: str = None, value: Any = None) None

Notify all the observers that a change occurred.

Parameters:
  • modifier (PglBaseObject) – An optional parameter that identify the modifier object to exclude it from the notified objects.

  • attribute (str) – An optional parameter that identify the attribute that has changed.

  • value (Any) – An optional parameter that identify the new value of the attribute.

Example:

# This example is silly, you would usually notify other objects from inside
# an object that changes a value that's important for the observers.
color = Color(255,200,125)
color.attach(some_text_object)
color.notify()
render_to_buffer(buffer, row, column, buffer_height, buffer_width)

Render the sprite from the display buffer to the frame buffer.

New in version 1.3.0.

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)

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

New in version 1.3.0.

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)
property screen_column: int

A property to get/set the screen column.

Parameters:

value (int) – the screen column

Return type:

int

property screen_row: int

A property to get/set the screen row.

Parameters:

value (int) – the screen row

Return type:

int

serialize()

Serialize a Sprite into a dictionary.

New in version 1.3.0.

Returns:

The class as a dictionary

Return type:

dict

Example:

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

Set a specific sprixel in the sprite to the given value.

Parameters:
  • row (int) – The row of the sprite (WARNING: internal sprite coordinates)

  • column (int) – The column of the sprite (same warning)

  • value (Sprixel) – The sprixel to set at [row, column]

When a sprixel is changed, the observers are notified of the change with the pygamelib.gfx.core.Sprite.sprixel:changed event. A structure is passed as the value parameter. This structure has 3 members: row, column and sprixel.

Example:

my_sprite.set_sprixel(1, 2, Sprixel("#",fg_color=green))
set_transparency(state)

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

New in version 1.3.0.

Parameters:

state – a boolean to enable or disable background transparency

When the transparency is changed, the observers are notified of the change with the pygamelib.gfx.core.Sprite.transparency:changed event. The new transparency state is passed as the value parameter.

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!

store_screen_position(row: int, column: int) bool

Store the screen position of the object.

This method is automatically called by Screen.place().

Parameters:
  • row (int) – The row (or y) coordinate.

  • column (int) – The column (or x) coordinate.

Example:

an_object.store_screen_coordinate(3,8)
tint(color: Color, ratio: float = 0.5)

Tint a copy of the sprite with the color.

New in version 1.3.0.

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
                        )
property width

Property that returns the width of the Sprite.

New in version 1.3.0.

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