engine

The game module contains the core classes for a game:

  • The Game object itself.
  • The Board object.
  • The Inventory object.

The Game object is what could be called the game engine. It holds a lot of methods that helps taking care of some complex mechanics behind the curtain.

The Board class is the base class for all levels.

Board(**kwargs) A class that represent a game board.
Game([name, boards, menu, current_level, …]) A class that serve as a game engine.
Inventory([max_size, parent]) A class that represent the Player (or NPC) inventory.
Screen([terminal]) The screen object is pretty straightforward: it is an object that allow manipulation of the screen.
class pygamelib.engine.Board(**kwargs)

Bases: object

A class that represent a game board.

The board is being represented by a square matrix. For the moment a board only support one player.

The Board object is the base object to build a level :
you create a Board and then you add BoardItems (or objects derived from BoardItem).
Parameters:
  • name (str) – the name of the Board
  • size (list) – array [width,height] with width and height being int. The size of the board.
  • player_starting_position (list) – array [row,column] with row and column being int. The coordinates at which Game will place the player on change_level().
  • ui_borders (str) – To set all the borders to the same value
  • ui_border_left (str) – A string that represents the left border.
  • ui_border_right (str) – A string that represents the right border.
  • ui_border_top (str) – A string that represents the top border.
  • ui_border_bottom (str) – A string that represents the bottom border.
  • ui_board_void_cell (str) – A string that represents an empty cell. This option is going to be the model of the BoardItemVoid (see pygamelib.board_items.BoardItemVoid)
  • parent (Game) – The parent object (usually the Game object).
  • DISPLAY_SIZE_WARNINGS (bool) – A boolean to show or hide the warning about boards bigger than 80 rows and columns.
check_sanity()

Check the board sanity.

This is essentially an internal method called by the constructor.

clear_cell(row, column)

Clear cell (row, column)

This method clears a cell, meaning it position a void_cell BoardItemVoid at these coordinates.

Parameters:
  • row (int) – The row of the item to remove
  • column (int) – The column of the item to remove

Example:

myboard.clear_cell(3,4)

Warning

This method does not check the content before, it will overwrite the content.

Important

This method test if something is left on the overlapped layer. If so, it restore what was overlapped instead of creating a new void item. It also removes the items from the the list of movables and immovables. In the case of a BoardComplexItem derivative (Tile, ComplexPlayer, ComplexNPC , etc.) clearing one cell of the entire item is enough to remove the entire item from the list of movables or immovables.

display()

Display the entire board.

This method display the Board (as in print()), taking care of displaying the borders, and everything inside.

It uses the __str__ method of the item, which by default uses (in order) BoardItem.sprixel and (if no sprixel is defined) BoardItem.model. If you want to override this behavior you have to subclass BoardItem.

display_around(item, row_radius, column_radius)

Display only a part of the board.

This method behaves like display() but only display a part of the board around an object (usually the player). Example:

# This will display only a total of 30 cells vertically and
# 60 cells horizontally.
board.display_around(player, 15, 30)
Parameters:
  • object (BoardItem) – an item to center the view on (it has to be a subclass of BoardItem)
  • row_radius (int) – The radius of display in number of rows showed. Remember that it is a radius not a diameter…
  • column_radius (int) – The radius of display in number of columns showed. Remember that… Well, same thing.

It uses the same display algorithm than the regular display() method.

generate_void_cell()

This method return a void cell.

If ui_board_void_cell_sprixel is defined it uses it, otherwise use ui_board_void_cell to generate the void item.

Returns:A void board item
Return type:BoardItemVoid

Example:

board.generate_void_cell()
get_immovables(**kwargs)

Return a list of all the Immovable objects in the Board.

See pygamelib.board_items.Immovable for more on
an Immovable object.
Parameters:**kwargs – an optional dictionnary with keys matching Immovables class members and value being something contained in that member.
Returns:A list of Immovable items

Example:

for m in myboard.get_immovables():
    print(m.name)

# Get all the Immovable objects that type contains "wall"
    AND name contains fire
walls = myboard.get_immovables(type="wall",name="fire")
get_movables(**kwargs)

Return a list of all the Movable objects in the Board.

See pygamelib.board_items.Movable for more on a Movable object.

Parameters:**kwargs – an optional dictionnary with keys matching Movables class members and value being something contained in that member.
Returns:A list of Movable items

Example:

for m in myboard.get_movables():
    print(m.name)

# Get all the Movable objects that has a type that contains "foe"
foes = myboard.get_movables(type="foe")
height

A convenience read only property to get the height of the Board.

It is absolutely equivalent to access to board.size[1].

Returns:The height of the board.
Return type:int

Example:

if board.size[1] != board.height:
    print('Houston, we have a problem...')
init_board()

Initialize the board with BoardItemVoid that uses ui_board_void_cell as model.

Example:

myboard.init_board()
init_cell(row, column)

Initialize a specific cell of the board with BoardItemVoid that uses ui_board_void_cell as model.

Parameters:
  • row (int) – the row coordinate.
  • column (int) – the column coordinate.

Example:

myboard.init_cell(2,3)
item(row, column)

Return the item at the row, column position if within board’s boundaries.

Return type:pygamelib.board_items.BoardItem
Raises:PglOutOfBoardBoundException – if row or column are out of bound.
move(item, direction, step=1)

Board.move() is a routing function. It does 2 things:

1 - If the direction is a Vector2D, round the
values to the nearest integer (as move works with entire board cells, i.e integers).
2 - route toward the right moving function depending if the item is complex or
not.

Move an item in the specified direction for a number of steps.

Parameters:

If the number of steps is greater than the Board, the item will be move to the maximum possible position.

If the item is not a subclass of Movable, an PglObjectIsNotMovableException exception (see pygamelib.base.PglObjectIsNotMovableException).

Example:

board.move(player,constants.UP,1)

Important

if the move is successfull, an empty BoardItemVoid (see pygamelib.boards_item.BoardItemVoid) will be put at the departure position (unless the movable item is over an overlappable item). If the movable item is over an overlappable item, the overlapped item is restored.

Important

Also important: If the direction is a Vector2D, the values will be rounded to the nearest integer (as move works with entire board cells). It allows for movement accumulation before actually moving. The step parameter is not used in that case.

place_item(item, row, column)

Place an item at coordinates row and column.

If row or column are our of the board boundaries, an PglOutOfBoardBoundException is raised.

If the item is not a subclass of BoardItem, an PglInvalidTypeException

Warning

Nothing prevents you from placing an object on top of another. Be sure to check that. This method will check for items that are both overlappable and restorable to save them, but that’s the extend of it.

remove_item(item)

Remove an item from the board.

If the item is a single BoardItem, this method is absolutely equivalent to calling clear_cell(). If item is a derivative of BoardComplexItem, it is not as clear_cell() only clears a specific cell (that can be part of a complex item). This method actually remove the entire item and clears all its cells.

Parameters:item (BoardItem) – The item to remove.

Example:

game.current_board().remove_item(game.player)
width

A convenience read only property to get the width of the Board.

It is absolutely equivalent to access to board.size[0].

Returns:The width of the board.
Return type:int

Example:

if board.size[0] != board.width:
    print('Houston, we have a problem...')
class pygamelib.engine.Game(name='Game', boards={}, menu={}, current_level=None, enable_partial_display=False, partial_display_viewport=None, mode=90000003, user_update=None, input_lag=0.01, enable_physic=False)

Bases: object

A class that serve as a game engine.

This object is the central system that allow the management of a game. It holds boards (see pygamelib.engine.Board), associate it to level, takes care of level changing, etc.

Parameters:
  • name (str) – The Game name.
  • boards (dict) – A dictionnary of boards with the level number as key and a board reference as value.
  • menu (dict) – A dictionnary of menus with a category (str) as key and another dictionnary (key: a shortcut, value: a description) as value.
  • current_level (int) – The current level.
  • enable_partial_display (bool) – A boolean to tell the Game object to enable or not partial display of boards. Default: False.
  • partial_display_viewport (list) – A 2 int elements array that gives the radius of the partial display in number of row and column. Please see display_around().
  • mode (int) – The mode parameter configures the way the run() method is going to behave. The default value is constants.MODE_TBT. TBT is short for “Turn By Turn”. In that mode, the Game object wait for an user input before looping. Exactly like when you wait for user input with get_key(). The other possible value is constants.MODE_RT. RT stands for “Real Time”. In that mode, the Game object waits for a minimal amount of time (0.01 i.e 100 FPS, configurable through the input_lag parameter) in order to get the input from the user and call the update function right away. This parameter is only useful if you use Game.run().
  • user_update (function) – A reference to the main program update function. The update function is called for each new frame. It is called with 3 parameters: the game object, the user input (can be None) and the elapsed time since last frame.
  • input_lag (float|int) – The amount of time the run() function is going to wait for a user input before returning None and calling the update function. Default is 0.01.

Note

The game object has an object_library member that is always an empty array except just after loading a board. In this case, if the board have a “library” field, it is going to be used to populate object_library. This library is accessible through the Game object mainly so people have access to it across different Boards during level design in the editor. That architecture decision is debatable.

Note

The constructor of Game takes care of initializing the terminal to properly render the colors on Windows.

Important

The Game object automatically assumes ownership over the Player.

actuate_npcs(level_number, elapsed_time=0.0)

Actuate all NPCs on a given level

This method actuate all NPCs on a board associated with a level. At the moment it means moving the NPCs but as the Actuators become more capable this method will evolve to allow more choice (like attack use objects, etc.)

Parameters:
  • level_number (int) – The number of the level to actuate NPCs in.
  • elapsed_time (float) – The amount of time that passed since last call. This parameter is not mandatory.

Example:

mygame.actuate_npcs(1)

Note

This method only move NPCs when their actuator state is RUNNING. If it is PAUSED or STOPPED, the NPC is not moved.

Note

Since version 1.2.0 it’s possible for a Movable item to have different vertical and horizontal movement steps, so actuate_npc respect that by integrating the steps with a unit direction vector. It should be completely transparent and you should not expect any change. Just more movement freedom. If you do experience issues, please report a bug.

Note

Since version 1.2.0 and the appearance of the realtime mode, we have to account for movement speed. This method does it.

actuate_projectiles(level_number, elapsed_time=0.0)

Actuate all Projectiles on a given level

This method actuate all Projectiles on a board associated with a level. This method differs from actuate_npcs() as some logic is involved with projectiles that NPC do not have. This method decrease the available range by projectile.step each time it’s called. It also detects potential collisions. If the available range falls to 0 or a collision is detected the projectile hit_callback is called.

Parameters:
  • level_number (int) – The number of the level to actuate Projectiles in.
  • elapsed_time (float) – The amount of time that passed since last call. This parameter is not mandatory.

Example:

mygame.actuate_projectiles(1)

Note

This method only move Projectiles when their actuator state is RUNNING. If it is PAUSED or STOPPED, the Projectile is not moved.

Important

Please have a look at the pygamelib.board_items.Projectile.hit() method for more information on the projectile hit mechanic.

add_board(level_number, board)

Add a board for the level number.

This method associate a Board (pygamelib.engine.Board) to a level number.

Example:

game.add_board(1,myboard)
Parameters:
  • level_number (int) – the level number to associate the board to.
  • board (pygamelib.engine.Board) – a Board object corresponding to the level number.
Raises:

PglInvalidTypeException – If either of these parameters are not of the correct type.

add_menu_entry(category, shortcut, message, data=None)

Add a new entry to the menu.

Add another shortcut and message to the specified category.

Categories help organize the different sections of a menu or dialogues.

Parameters:
  • category (str) – The category to which the entry should be added.
  • shortcut (str) – A shortcut (usually one key) to display.
  • message (various) – a message that explains what the shortcut does.
  • data – a data that you can get from the menu object.

The shortcut and data is optional.

Example:

game.add_menu_entry('main_menu','d','Go right',constants.RIGHT)
game.add_menu_entry('main_menu',None,'-----------------')
game.add_menu_entry('main_menu','v','Change game speed')
add_npc(level_number, npc, row=None, column=None)

Add a NPC to the game. It will be placed on the board corresponding to the level_number. If row and column are not None, the NPC is placed at these coordinates. Else, it’s randomly placed in an empty cell.

Example:

game.add_npc(1,my_evil_npc,5,2)
Parameters:
  • level_number (int) – the level number of the board.
  • npc (pygamelib.board_items.NPC) – the NPC to place.
  • row (int) – the row coordinate to place the NPC at.
  • column (int) – the column coordinate to place the NPC at.

If either of these parameters are not of the correct type, a PglInvalidTypeException exception is raised.

Important

If the NPC does not have an actuator, this method is going to affect a pygamelib.actuators.RandomActuator() to npc.actuator. And if npc.step == None, this method sets it to 1

add_projectile(level_number, projectile, row=None, column=None)

Add a Projectile to the game. It will be placed on the board corresponding to level_number. Neither row nor column can be None.

Example:

game.add_projectile(1, fireball, 5, 2)
Parameters:
  • level_number (int) – the level number of the board.
  • projectile (Projectile) – the Projectile to place.
  • row (int) – the row coordinate to place the Projectile at.
  • column (int) – the column coordinate to place the Projectile at.

If either of these parameters are not of the correct type, a PglInvalidTypeException exception is raised.

Important

If the Projectile does not have an actuator, this method is going to affect pygamelib.actuators.RandomActuator(moveset=[RIGHT]) to projectile.actuator. And if projectile.step == None, this method sets it to 1.

animate_items(level_number, elapsed_time=0.0)

That method goes through all the BoardItems of a given map and call Animation.next_frame().

Parameters:
  • level_number (int) – The number of the level to animate items in.
  • elapsed_time (float) – The amount of time that passed since last call. This parameter is not mandatory.
Raise:

PglInvalidLevelException PglInvalidTypeException

Example:

mygame.animate_items(1)
change_level(level_number)

Change the current level, load the board and place the player to the right place.

Example:

game.change_level(1)
Parameters:level_number (int) – the level number to change to.
Raises:base.PglInvalidTypeException – If parameter is not an int.
clear_screen()

Clear the whole screen (i.e: remove everything written in terminal)

Deprecated since version 1.2.0: Starting 1.2.0 we are using the pygamelib.engine.Screen object to manage the screen. That function is a simple forward and is kept for backward compatibility only. You should use Game.screen.clear()

config(section='main')

Get the content of a previously loaded configuration section.

Parameters:section (str) – The name of the section.

Example:

if mygame.config('main')['pgl-version-required'] < 10200:
    print('The pygamelib version 1.2.0 or greater is required.')
    exit()
create_config(section)

Initialize a new config section.

The new section is a dictionary.

Parameters:section (str) – The name of the new section.

Example:

if mygame.config('high_scores') is None:
    mygame.create_config('high_scores')
mygame.config('high_scores')['first_place'] = mygame.player.name
current_board()

This method return the board object corresponding to the current_level.

Example:

game.current_board().display()

If current_level is set to a value with no corresponding board a PglException exception is raised with an invalid_level error.

delete_menu_category(category=None)

Delete an entire category from the menu.

That function removes the entire list of messages that are attached to the category.

Parameters:category (str) – The category to delete.
Raises:PglInvalidTypeException – If the category is not a string

Important

If the entry have no shortcut it’s advised not to try to update unless you have only one NoneType as a shortcut.

Example:

game.add_menu_entry('main_menu','d','Go right')
game.update_menu_entry('main_menu','d','Go LEFT',constants.LEFT)
display_board()

Display the current board.

The behavior of that function is dependant on how you configured this object. If you set enable_partial_display to True AND partial_display_viewport is set to a correct value, it will call Game.current_board().display_around() with the correct parameters. The partial display will be centered on the player (Game.player). Otherwise it will just call Game.current_board().display().

If the player is not set or is set to constants.NO_PLAYER partial display won’t activate automatically.

Example:

mygame.enable_partial_display = True
# Number of rows, number of column (on each side, total viewport
# will be 20x20 in that case).
mygame.partial_display_viewport = [10, 10]
# This will call Game.current_board().display_around()
mygame.display()
mygame.enable_partial_display = False
# This will call Game.current_board().display()
mygame.display()
display_menu(category, orientation=30000100, paginate=10)

Display the menu.

This method display the whole menu for a given category.

Parameters:
  • category (str) – The category to display. Mandatory parameter.
  • orientation (pygamelib.constants) – The shortcut of the entry you want to get.
  • paginate (int) – pagination parameter (how many items to display before changing line or page).

Example:

game.display_menu('main_menu')
game.display_menu('main_menu', constants.ORIENTATION_HORIZONTAL, 5)
display_player_stats(life_model='\x1b[41m \x1b[0m', void_model='\x1b[40m \x1b[0m')

Display the player name and health.

This method print the Player name, a health bar (20 blocks of life_model). When life is missing the complement (20-life missing) is printed using void_model. It also display the inventory value as “Score”.

Parameters:
  • life_model (str) – The character(s) that should be used to represent the remaining life.
  • void_model (str) – The character(s) that should be used to represent the lost life.

Note

This method might change in the future. Particularly it could take a template of what to display.

get_board(level_number)

This method returns the board associated with a level number. :param level_number: The number of the level. :type level_number: int

Raises:PglInvalidTypeException – if the level_number is not an int.

Example:

level1_board = mygame.get_board(1)
static get_key()

Reads the next key-stroke returning it as a string.

Example:

key = Utils.get_key()
if key == Utils.key.UP:
    print("Up")
elif key == "q"
    exit()

Note

See readkey documentation in readchar package.

get_menu_entry(category, shortcut)

Get an entry of the menu.

This method return a dictionnary with 3 entries :
  • shortcut
  • message
  • data
Parameters:
  • category (str) – The category in which the entry is located.
  • shortcut (str) – The shortcut of the entry you want to get.
Returns:

The menu entry or None if none was found

Return type:

dict

Example:

ent = game.get_menu_entry('main_menu','d')
game.move_player(int(ent['data']),1)
load_board(filename, lvl_number=0)

Load a saved board

Load a Board saved on the disk as a JSON file. This method creates a new Board object, populate it with all the elements (except a Player) and then return it.

If the filename argument is not an existing file, the open function is going to raise an exception.

This method, load the board from the JSON file, populate it with all BoardItem included, check for sanity, init the board with BoardItemVoid and then associate the freshly created board to a lvl_number. It then create the NPCs and add them to the board.

Parameters:
  • filename (str) – The file to load
  • lvl_number (int) – The level number to associate the board to. Default is 0.
Returns:

a newly created board (see pygamelib.engine.Board)

Example:

mynewboard = game.load_board( 'awesome_level.json', 1 )
game.change_level( 1 )
load_config(filename, section='main')

Load a configuration file from the disk. The configuration file must respect the INI syntax. The goal of these methods is to simplify configuration files management.

Parameters:
  • filename (str) – The filename to load. does not check for existence.
  • section (str) – The section to put the read config file into. This allow for multiple files for multiple purpose. Section is a human readable unique identifier.
Raises:
  • FileNotFoundError – If filename is not found on the disk.
  • json.decoder.JSONDecodeError – If filename could not be decoded as JSON.
Returns:

The parsed data.

Return type:

dict

Warning

breaking changes: before v1.1.0 that method use to load file using the configparser module. This have been dumped in favor of json files. Since that methods was apparently not used, there is no backward compatibility.

Example:

mygame.load_config('game_controls.json','game_control')
move_player(direction, step=1)

Easy wrapper for Board.move().

Example:

mygame.move_player(constants.RIGHT,1)
neighbors(radius=1, obj=None)

Get a list of neighbors (non void item) around an object.

This method returns a list of objects that are all around an object between the position of an object and all the cells at radius.

Parameters:
  • radius (int) – The radius in which non void item should be included
  • object (pygamelib.board_items.BoardItem) – The central object. The neighbors are calculated for that object. If None, the player is the object.
Returns:

A list of BoardItem. No BoardItemVoid is included.

Raises:

PglInvalidTypeException – If radius is not an int.

Example:

for item in game.neighbors(2):
    print(f'{item.name} is around player at coordinates '
        '({item.pos[0]},{item.pos[1]})')
pause()

Set the game engine state to PAUSE.

Example:

mygame.pause()
remove_npc(level_number, npc)

This methods remove the NPC from the level in parameter.

Parameters:
  • level (int) – The number of the level from where the NPC is to be removed.
  • npc (NPC) – The NPC object to remove.

Example:

mygame.remove_npc(1, dead_npc)
run()

New in version 1.2.0.

The run() method act as the main game loop and does a number of things for you:

  1. It grabs the user input. If the Game object is configured with MODE_TBT (the default), nothing happen until the user hit a key. If the mode is set to MODE_RT, it will wait for input_lag secondes for a user input before going to step 3.
  2. It calculate the elapsed time between 2 frames.
  3. Accumulates the elapsed time in the player dtmove variable (if there is a player object configured)
  4. It sets the cursor position to 0,0 (meaning that your user_update function will draw on top of the previously drawn window). The Board.display() and Board.display_around() method clean the end of their line.
  5. It calls the user_update function with 3 parameters: the game object, the key hit by the user (it can be None) and the elapsed time between to calls.
  6. Clears the end of the screen.
  7. Actuates NPCs.
  8. Actuates projectiles.
  9. Animates items.
  10. Actuates particles (WIP).
Raises:PglInvalidTypeException, PglInvalidTypeException

Example:

mygame.run()
save_board(lvl_number, filename)

Save a board to a JSON file

This method saves a Board and everything in it but the BoardItemVoid.

Not check are done on the filename, if anything happen you get the exceptions from open().

Parameters:
  • lvl_number (int) – The level number to get the board from.
  • filename (str) – The path to the file to save the data to.
Raises:

Example:

game.save_board( 1, 'hac-maps/level1.json')

If Game.object_library is not an empty array, it will be saved also.

save_config(section=None, filename=None, append=False)

Save a configuration section.

Parameters:
  • section (str) – The name of the section to save on disk.
  • filename (str) – The file to write in. If not provided it will write in the file that was used to load the given section. If section was not loaded from a file, save will raise an exception.
  • append (bool) – Do we need to append to the file or replace the content (True = append, False = replace)

Example:

mygame.save_config('game_controls', 'data/game_controls.json')
start()

Set the game engine state to RUNNING.

The game has to be RUNNING for actuate_npcs() and move_player() to do anything.

Example:

mygame.start()
stop()

Set the game engine state to STOPPED.

Example:

mygame.stop()
update_menu_entry(category, shortcut, message, data=None)

Update an entry of the menu.

Update the message associated to a category and a shortcut.

Parameters:
  • category (str) – The category in which the entry is located.
  • shortcut (str) – The shortcut of the entry you want to update.
  • message (various) – a message that explains what the shortcut does.
  • data – a data that you can get from the menu object.

Important

If the entry have no shortcut it’s advised not to try to update unless you have only one NoneType as a shortcut.

Example:

game.add_menu_entry('main_menu','d','Go right')
game.update_menu_entry('main_menu','d','Go LEFT',constants.LEFT)
class pygamelib.engine.Inventory(max_size=10, parent=None)

Bases: object

A class that represent the Player (or NPC) inventory.

This class is pretty straightforward: it is an object container, you can add, get and remove items and you can get a value from the objects in the inventory.

The constructor takes only one parameter: the maximum size of the inventory. Each BoardItem that is going to be put in the inventory has a size (default is 1), the total addition of all these size cannot exceed max_size.

Parameters:
  • max_size (int) – The maximum size of the inventory. Deafult value: 10.
  • parent – The parent object (usually a BoardItem).

Note

You can print() the inventory. This is mostly useful for debug as you want to have a better display in your game.

Warning

The Game engine and Player takes care to initiate an inventory for the player, you don’t need to do it.

add_item(item)

Add an item to the inventory.

This method will add an item to the inventory unless:

  • it is not an instance of BoardItem,
  • you try to add an item that is not pickable,
  • there is no more space left in the inventory (i.e: the cumulated size of the inventory + your item.size is greater than the inventory max_size)
Parameters:item (BoardItem) – the item you want to add
Raises:PglInventoryException, PglInvalidTypeException

Example:

item = Treasure(model=Sprites.MONEY_BAG,size=2,name='Money bag')
try:
    mygame.player.inventory.add_item(item)
expect PglInventoryException as e:
    if e.error == 'not_enough_space':
        print(f"Impossible to add {item.name} to the inventory, there is no"
        "space left in it!")
        print(e.message)
    elif e.error == 'not_pickable':
        print(e.message)

Warning

if you try to add more than one item with the same name (or if the name is empty), this function will automatically change the name of the item by adding a UUID to it.

delete_item(name)

Delete the item corresponding to the name given in argument.

Parameters:name (str) – the name of the item you want to delete.

Note

in case an execpetion is raised, the error will be ‘no_item_by_that_name’ and the message is giving the specifics.

Example:

life_container = mygame.player.inventory.get_item('heart_1')
if isinstance(life_container,GenericActionableStructure):
    life_container.action(life_container.action_parameters)
    mygame.player.inventory.delete_item('heart_1')
empty()

Empty the inventory Example:

if inventory.size() > 0:
    inventory.empty()
get_item(name)

Return the item corresponding to the name given in argument.

Parameters:name (str) – the name of the item you want to get.
Returns:An item.
Return type:BoardItem
Raises:PglInventoryException

Note

in case an execpetion is raised, the error will be ‘no_item_by_that_name’ and the message is giving the specifics.

Example:

life_container = mygame.player.inventory.get_item('heart_1')
if isinstance(life_container,GenericActionableStructure):
    life_container.action(life_container.action_parameters)

Note

Please note that the item object reference is returned but nothing is changed in the inventory. The item hasn’t been removed.

items_name()

Return the list of all items names in the inventory.

Returns:a list of string representing the items names.
Return type:list
search(query)

Search for objects in the inventory.

All objects that matches the query are going to be returned. :param query: the query that items in the inventory have to match to be returned :type name: str :returns: a table of BoardItems. :rtype: list

Example:

for item in game.player.inventory.search('mighty'):
    print(f"This is a mighty item: {item.name}")
size()

Return the cumulated size of the inventory. It can be used in the UI to display the size compared to max_size for example.

Returns:size of inventory
Return type:int

Example:

print(f"Inventory: {mygame.player.inventory.size()}/"
"{mygame.player.inventory.max_size}")
value()

Return the cumulated value of the inventory. It can be used for scoring for example.

Returns:value of inventory
Return type:int

Example:

if inventory.value() >= 10:
    print('Victory!')
    break
class pygamelib.engine.Screen(terminal=None)

Bases: object

The screen object is pretty straightforward: it is an object that allow manipulation of the screen. At the moment it relies heavily on the blessed module, but it wraps a lot of its methods and provide easy calls to actions.

Parameters:terminal (Terminal) – A Terminal reference.

Example:

screen = Screen(terminal=Terminal())
screen.display_at('This is centered', int(screen.height/2), int(screen.width/2))
clear()

This methods clear the screen

display_at(text, row=0, column=0, clear_eol=False, end='\n', file=<colorama.ansitowin32.StreamWrapper object>, flush=False)

Displays text at a given position. If clear_eol is True, also clear the end of line. Additionally you can specify all the parameters of a regular print() if you need to.

Parameters:
  • text (str) – The text to display. Please note that in that case text is a single string.
  • row (int) – The row position in the terminal window.
  • column (int) – The column position in the terminal window.
  • clear_eol (bool) – If True this clears the end of the line (everything after the last character displayed by that method).
  • end (str) – end sub string added to the printed text. Usually a carriage return.
  • file (stream) –
  • flush (bool) –

Important

The cursor is only moved for printing the text. It is returned to its previous position after.

Note

The position respect the row/column convention accross the library. It is reversed compared to the blessed module.

Example:

screen.display_at('This is centered',
                  int(screen.height/2),
                  int(screen.width/2),
                  clear_eol=True,
                  end=''
                )
display_line(*text, end='\n', file=<colorama.ansitowin32.StreamWrapper object>, flush=False)

New in version 1.2.0.

A wrapper to Python’s print() builtin function except it will always add an ANSI sequence to clear the end of the line. Making it more suitable to use in a user_update callback.

The reason is that with line with variating length, if you use run() but not clear(), some characters will remain on screen because run(), for performances concerns does not clear the entire screen. It just bring the cursor back to the top left corner of the screen. So if you want to benefit from the increase performances you should use display_line().

Parameters:
  • *text (str|objects) – objects that can serialize to str. The ANSI sequence to clear the end of the line is always appended to the the text.
  • end (str) – end sub string added to the printed text. Usually a carriage return.
  • file (stream) –
  • flush (bool) –

Example:

game.display_line(f'This line will display correctly: {elapsed_time}')
# That line will have trailing characters that are not cleared after redraw
# if you don't use clear().
print(f'That one won't: {elapsed_time}')
height

This method wraps Terminal.height and return the height of the terminal window in number of characters.

width

This method wraps Terminal.width and return the width of the terminal window in number of characters.