Inventory

class pygamelib.engine.Inventory(max_size=10, parent=None)

Bases: PglBaseObject

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.

On top of that, starting with version 1.3.0, a constraints system has been added. It allows to specify a certain amount of constraints that will be applied to the items when they are added to the inventory.

For the moment, constraints are limited to the number of items with a given type/ name/value (any combination of these three).

When a constraint is violated, the item is not added to the inventory and a notification is broadcasted to the observers of the inventory. A PglInventoryException is also raised with name “constraint_violation” and the constraint details in description.

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.

__init__(max_size=10, parent=None)

The constructor takes two parameters: the maximum size of the inventory. And the Inventory owner/parent.

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. Default value: 10.

  • parent – The parent object (usually a BoardItem).

Methods

__init__([max_size, parent])

The constructor takes two parameters: the maximum size of the inventory.

add_constraint(constraint_name[, item_type, ...])

https://img.shields.io/badge/-Alpha-orange

add_item(item)

Add an item to the inventory.

attach(observer)

Attach an observer to this instance.

available_space()

Return the available space in the inventory.

clear_constraints()

Remove all constraints from the inventory.

delete_item(name)

Delete THE FIRST item matching the name given in argument.

delete_items(name)

Delete ALL items matching the name given in argument.

detach(observer)

Detach an observer from this instance.

empty()

Empty the inventory.

get_item(name)

Return the FIRST item corresponding to the name given in argument.

get_items(name)

Return ALL items matching the name given in argument.

handle_notification(subject[, attribute, value])

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

items_name()

Return the list of all items names in the inventory.

load(data)

Load serialized data into a new Inventory object.

notify([modifier, attribute, value])

Notify all the observers that a change occurred.

remove_constraint(constraint_name)

https://img.shields.io/badge/-Alpha-orange

search(query)

Search for objects in the inventory.

serialize()

Serialize the inventory in a dictionary.

size()

Return the cumulated size of the inventory.

store_screen_position(row, column)

Store the screen position of the object.

value()

Return the cumulated value of the inventory.

Attributes

constraints

https://img.shields.io/badge/-Alpha-orange

items

Return the list of all items in the inventory.

screen_column

A property to get/set the screen column.

screen_row

A property to get/set the screen row.

add_constraint(constraint_name: str, item_type: str = None, item_name: str = None, item_value: int = None, max_number: int = 1)
https://img.shields.io/badge/-Alpha-orange

Add a constraint to the inventory.

Parameters:
  • constraint_name (str) – the name of the constraint.

  • item_type (str) – the type of the item.

  • item_name (int) – the name of the item.

  • item_value – the value of the item.

  • max_number (int) – the maximum number of items that match the item_* parameters that can be in the inventory.

The observers are notified of the addition of the constraint with the pygamelib.engine.Inventory.add_constraint event. The constraint that was added is passed as the value of the event as a dictionnary.

New in version 1.3.0.

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.inventory_space is greater than the inventory max_size)

  • An existing constraint is violated.

Parameters:

item (BoardItem) – the item you want to add

Returns:

The index of the newly added item in the inventory or None if the item could not be added.

Return type:

int|None

Raise:

PglInventoryException, PglInvalidTypeException

When an item is successfully added, the observers are notified of the change with the pygamelib.engine.Inventory.add_item event. The item that was added is passed as the value of the event.

When something goes wrong exceptions are raised. The following exceptions can be raised (PglInventoryException):

  • not_pickable: The item you try to add is not pickable.

  • not_enough_space: There is not enough space left in the inventory.

  • constraint_violation: A constraint is violated.

A PglInvalidTypeException is raised when the item you try to add is not a BoardItem.

Example:

item = Treasure(model=graphics.Models.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)

Note

In versions prior to 1.3.0, the inventory object was changing the name of the item if another item with the same name was already in the inventory. This is (fortunately) not the case anymore. The Inventory class does NOT modify the items that are stored into it anymore.

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)
available_space() int

Return the available space in the inventory.

That is to say, Inventory.max_size - Inventory.size().

The returned number is comprised between 0 and Inventory.max_size.

Returns:

The size as an int.

Return type:

int

Example:

method()
clear_constraints()

Remove all constraints from the inventory.

The observers are notified with the pygamelib.engine.Inventory.clear_constraints event. The value is set to None for this event.

New in version 1.3.0.

property constraints
https://img.shields.io/badge/-Alpha-orange

Return the list of all constraints in the inventory.

Returns:

a list of constraints (dict)

Return type:

list

Example:

for cstr in game.player.inventory.constraints:
    print(f" - {cstr[name]}")
delete_item(name)

Delete THE FIRST item matching the name given in argument.

Parameters:

name (str) – the name of the items you want to delete.

When an item is successfully removed, the observers are notified of the change with the pygamelib.engine.Inventory.delete_item event. The item that was deleted is passed as the value of the event.

Example:

mygame.player.inventory.delete_item('heart_1')

Important

Starting with version 1.3.0 this method does not raise exceptions anymore. It’s behavior also changed from deleting a precise item to deleting the first one that matches the name.

delete_items(name)

Delete ALL items matching the name given in argument.

Parameters:

name (str) – the name of the items you want to delete.

The observers are notified of each deletion with the pygamelib.engine.Inventory.delete_item event. The item that was deleted is passed as the value of the event.

Example:

mygame.player.inventory.delete_items('heart_1')

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 inventory.

The observers are notified that the Inventory has been emptied with the pygamelib.engine.Inventory.empty event. Nothing is passed as the value.

Example:

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

Return the FIRST 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 | None

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.

Important

Starting with version 1.3.0 this method does not raise exceptions anymore. Instead it returns None if no item is found. It’s behavior also changed from returning a precise item to the first one that matches the name.

get_items(name)

Return ALL items matching the name given in argument.

Parameters:

name (str) – the name of the item you want to get.

Returns:

An array of items.

Return type:

list

Example:

for life_container in mygame.player.inventory.get_items('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.

New in version 1.3.0.

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 items

Return the list of all items in the inventory.

Returns:

a list of BoardItem

Return type:

list

Example:

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

Return the list of all items names in the inventory.

Returns:

a list of string representing the items names.

Return type:

list

classmethod load(data: dict)

Load serialized data into a new Inventory object.

Parameters:

data (dict) – The serialized data

Returns:

A new Inventory object.

Return type:

Inventory

New in version 1.3.0.

Example:

my_player.inventory = Inventory.load(data)
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()
remove_constraint(constraint_name: str)
https://img.shields.io/badge/-Alpha-orange

Remove a constraint from the inventory.

Parameters:

constraint_name (str) – the name of the constraint.

The observers are notified of the removal of the constraint with the pygamelib.engine.Inventory.remove_constraint event. The constraint that was removed is passed as the value of the event as a dictionnary.

New in version 1.3.0.

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

search(query)

Search for objects in the inventory.

All objects that matches the query are going to be returned. Search is performed on the name and type of the object.

Parameters:

query – the query that items in the inventory have to match to be returned

Returns:

a list of BoardItems.

Return type:

list

Example:

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

Serialize the inventory in a dictionary.

Returns:

The serialized data.

Return type:

dict

New in version 1.3.0.

Example:

json.dump(my_inventory.serialize(), out_file)
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}")
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)
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