core

This module contains the core classes for the “graphic” system.

Sprixel([model, bg_color, fg_color, …]) A sprixel is the representation of 1 cell of the sprite or one cell on the Board.
Sprite([sprixels, default_sprixel, parent, …]) The Sprite object represent a 2D “image” that can be used to represent any complex item.
SpriteCollection([data]) SpriteCollection is a dictionnary class that derives collections.UserDict.
Animation([display_time, auto_replay, …]) The Animation class is used to give the ability to have more than one model for a BoardItem.
class pygamelib.gfx.core.Animation(display_time=0.05, auto_replay=True, frames=None, animated_object=None, refresh_screen=None, initial_index=None, parent=None)

Bases: object

The Animation class is used to give the ability to have more than one model for a BoardItem. A BoardItem can have an animation and all of them that are available to the Game object can be animated through Game.animate_items(lvl_number). To benefit from that, BoardItem.animation must be set explicitely. An animation is controlled via the same state system than the Actuators.

The frames are all stored in a list called frames, that you can access through Animation.frames.

Parameters:
  • display_time (float) – The time each frame is displayed
  • auto_replay (bool) – controls the auto replay of the animation, if false once the animation is played it stays on the last frame of the animation.
  • frames (array[str|Sprixel|Sprite]) – an array of “frames” (string, sprixel or sprite)
  • animated_object (BoardItem) – The object to animate. This parameter is deprecated. Please use parent instead. It is only kept for backward compatibility. The parent parameter always takes precedence over this one.
  • parent (BoardItem) – The parent object. It is also the object to animate. Important: We cannot animate anything else that BoardItems and subclasses.
  • refresh_screen (function) – The callback function that controls the redrawing of the screen. This function reference should come from the main game.

Example

def redraw_screen(game_object):
    game_object.clear_screen()
    game_object.display_board()

item = BoardItem(model=Sprite.ALIEN, name='Friendly Alien')
# By default BoardItem does not have any animation, we have to
# explicitely create one
item.animation = Animation(display_time=0.1, parent=item,
                           refresh_screen=redraw_screen)
add_frame(frame)

Add a frame to the animation.

The frame has to be a string (that includes sprites from the Sprite module and squares from the Utils module).

Raise an exception if frame is not a string.

Parameters:frame (str) – The frame to add to the animation.
Raise:pygamelib.base.PglInvalidTypeException

Example:

item.animation.add_frame(Sprite.ALIEN)
item.animation.add_frame(Sprite.ALIEN_MONSTER)
current_frame()

Return the current frame.

Example:

item.model = item.animation.current_frame()
dtanimate
next_frame()

Update the parent’s model, sprixel or sprite with the next frame of the animation.

That method takes care of automatically replaying the animation if the last frame is reached if the state is constants.RUNNING.

If the the state is PAUSED it still update the parent.model and returning the current frame. It does NOT actually go to next frame.

If parent is not a sub class of BoardItem an exception is raised.

Raise:PglInvalidTypeException

Example:

item.animation.next_frame()

Warning

If you use Sprites as frames, you need to make sure your Animation is attached to a BoardComplexItem.

pause()

Set the animation state to PAUSED.

Example:

item.animation.pause()
play_all()

Play the entire animation once.

That method plays the entire animation only once, there is no auto replay as it blocks the game (for the moment).

If the the state is PAUSED or STOPPED, the animation does not play and the method return False.

If parent is not a sub class of BoardItem an exception is raised.

If screen_refresh is not defined or is not a function an exception is raised.

Raise:PglInvalidTypeException

Example:

item.animation.play_all()
remove_frame(index)

Remove a frame from the animation.

That method remove the frame at the specified index and return it if it exists.

If the index is out of bound an exception is raised. If the index is not an int an exception is raised.

Parameters:index (int) – The index of the frame to remove.
Return type:str
Raise:IndexError, PglInvalidTypeException

Example:

item.animation.remove_frame( item.animation.search_frame(
    Sprite.ALIEN_MONSTER)
)
reset()

Reset the Animation to the first frame.

Example:

item.animation.reset()
search_frame(frame)

Search a frame in the animation.

That method is returning the index of the first occurrence of “frame”.

Raise an exception if frame is not a string.

Parameters:frame (str) – The frame to find.
Return type:int
Raise:PglInvalidTypeException

Example:

item.animation.remove_frame(
    item.animation.search_frame(Sprite.ALIEN_MONSTER)
)
start()

Set the animation state to constants.RUNNING.

If the animation state is not constants.RUNNING, animation’s next_frame() function return the last frame returned.

Example:

item.animation.start()
stop()

Set the animation state to STOPPED.

Example:

item.animation.stop()
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,
        ],
    ],
)
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}' )
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')
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.

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!

class pygamelib.gfx.core.SpriteCollection(data={})

Bases: collections.UserDict

SpriteCollection is a dictionnary class that derives collections.UserDict.

Its main goal is to provide an easy to use object to load and save sprite files. On top of traditional dict method, it provides the following capabilities:

  • loading and writing from and to JSON files,
  • data serialization,
  • shortcut to add sprites to the dictionnary.

A SpriteCollection is an unordered indexed list of Sprites (i.e a dictionnary).

Sprites are indexed by their names in that collection.

Example:

# Load a sprite file
sprites_village1 = SpriteCollection.load_json_file('gfx/village1.spr')
# display the Sprites with their name
for sprite_name in sprites_village1:
    print(f'{sprite_name}:\n{sprites_village1[sprite_name]}')
# Add an empty sprite with name 'house_placeholder'
sprites_village1.add( Sprite(name='house_placeholder') )
# This is absolutely equivalent to:
sprites_village1['house_placeholder'] = Sprite(name='house_placeholder')
# And now rewrite the sprite file with the new placeholder house
sprites_village1.to_json_file('gfx/village1.spr')
add(sprite)

Add a Sprite to the collection. This method is simply a shortcut to the usual dictionnary affectation. The collection requires the name of the Sprite to be the key. That method does that automatically.

Parameters:sprite (Sprite) – A Sprite object to add to the collection.

Warning

As SpriteCollection index Sprites by their name if you change the Sprite’s name after adding it to the collection you will need to manually update the keys.

Example:

sprites_village1 = SpriteCollection.load_json_file('gfx/village1.spr')
new_village = SpriteCollection()
new_village.add( copy.deepcopy( sprites_village1.get('bakery') ) )
print( new_village['bakery'] )
clear() → None. Remove all items from D.
copy()
classmethod fromkeys(iterable, value=None)
get(k[, d]) → D[k] if k in D, else d. d defaults to None.
items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
classmethod load(data)

Load serialized data and return a new SpriteCollection object.

Parameters:data (str) – Serialized data that need to be expanded into objects.
Returns:A new SpriteCollection object.
Return type:SpriteCollection

Example:

sprites_village1 = SpriteCollection.load(
    sprites_village_template.serialize()
)
static load_json_file(filename)

Load a JSON sprite file into a new SpriteCollection object.

Parameters:filename (str) – The complete path (relative or absolute) to the sprite file.
Returns:A new SpriteCollection object.
Return type:SpriteCollection

Example:

sprites_village1 = SpriteCollection.load_json_file('gfx/village1.spr')
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

serialize()

Return a serialized version of the SpriteCollection. The serialized data can be pass to the JSON module to export.

Returns:The SpriteCollection object serialized as a dictionnary.
Return type:dict

Example:

data = sprites_village1.serialize()
setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
to_json_file(filename)

Export the SpriteCollection object in JSON and writes it on the disk.

Parameters:filename (str) – The complete path (relative or absolute) to the sprite file to write.

Example:

sprites_village1.to_json_file('gfx/village1.spr')
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → an object providing a view on D's values
class pygamelib.gfx.core.Sprixel(model='', bg_color='', fg_color='', is_bg_transparent=None)

Bases: object

A sprixel is the representation of 1 cell of the sprite or one cell on the Board. It is not really a pixel but it is the closest notion we’ll have. A Sprixel has a background color, a foreground color and a model. All regular BoardItems can have use Sprixel instead of model.

If the background color and the is_bg_transparent are None or empty strings, the sprixel will be automatically configured with transparent background. In that case, as we can really achieve transparency in the console, the sprixel will take the background color of whatever it is overlapping.

Parameters:
  • model (str) – The model, it can be any string. Preferrably a single character.
  • bg_color (str) – An ANSI escape sequence to configure the background color.
  • fg_color (str) – An ANSI escape sequence to configure the foreground color.
  • is_bg_transparent

Example:

player = Player(sprixel=Sprixel(
                                '#',
                                screen.terminal.on_color_rgb(128,56,32),
                                screen.terminal.color_rgb(255,255,0),
                                ))
bg_color
classmethod black_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.BLACK_RECT. The difference is that BLACK_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.black_rect()
classmethod black_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.BLACK_SQUARE. The difference is that BLACK_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.black_square()
classmethod blue_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.BLUE_RECT. The difference is that BLUE_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.blue_rect()
classmethod blue_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.BLUE_SQUARE. The difference is that BLUE_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.blue_square()
classmethod cyan_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.CYAN_RECT. The difference is that CYAN_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.cyan_rect()
classmethod cyan_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.CYAN_SQUARE. The difference is that CYAN_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.cyan_square()
fg_color
static from_ansi(string)

Takes an ANSI string, parse it and return a Sprixel.

Parameters:string (str) – The ANSI string to parse.

Example:

new_sprixel = Sprixel.from_ansi(
    "\x1b[48;2;139;22;19m\x1b[38;2;160;26;23m▄\x1b[0m"
)

Warning

This has mainly be tested with ANSI string generated by climage.

classmethod green_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.GREEN_RECT. The difference is that GREEN_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.green_rect()
classmethod green_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.GREEN_SQUARE. The difference is that GREEN_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.green_square()
classmethod load(data)

Create a new Sprixel object based on serialized data.

Parameters:data (dict) – Data loaded from JSON data (deserialized).
Return type:Sprixel

Example:

new_sprite = Sprixel.load(json_parsed_data['default_sprixel'])
classmethod magenta_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.MAGENTA_RECT. The difference is that MAGENTA_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.magenta_rect()
classmethod magenta_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.MAGENTA_SQUARE. The difference is that MAGENTA_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.magenta_square()
model
classmethod red_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.RED_RECT. The difference is that RED_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.red_rect()
classmethod red_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.RED_SQUARE. The difference is that RED_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.red_square()
serialize()

Serialize a Sprixel into a dictionary.

Returns:The class as a dictionary
Return type:dict

Example:

json.dump( sprixel.serialize() )
classmethod white_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.WHITE_RECT. The difference is that WHITE_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.white_rect()
classmethod white_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.WHITE_SQUARE. The difference is that WHITE_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Example:

sprixel = Sprixel.white_square()
classmethod yellow_rect()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.YELLOW_RECT. The difference is that YELLOW_RECT is a string and this one is a Sprixel that can be manipulated more easily.

Note

Yellow is often rendered as brown.

Example:

sprixel = Sprixel.yellow_rect()
classmethod yellow_square()

This classmethod returns a sprixel that is the equivalent of pygamelib.assets.graphics.YELLOW_SQUARE. The difference is that YELLOW_SQUARE is a string and this one is a Sprixel that can be manipulated more easily.

Note

Yellow is often rendered as brown.

Example:

sprixel = Sprixel.yellow_square()