ComplexNPC

class pygamelib.board_items.ComplexNPC(**kwargs)

Bases: pygamelib.board_items.NPC, pygamelib.board_items.BoardComplexItem

New in version 1.2.0.

A complex NPC is nothing more than a NPC mashed with a BoardComplexItem.

It supports all parameters of both with inheritance going first to NPC and second to BoardComplexItem.

The main interest is of course the multiple cell representation and the Sprites support.

Example:

player = ComplexNPC(
        name='Idiot McComplexStupid',
        sprite=npc_sprite_collection['troll_licking_stones']
    )
__init__(**kwargs)

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

Methods

__init__(**kwargs) Like the object class, this class constructor takes no parameter.
can_move() Movable implements can_move().
collides_with(other) Tells if this item collides with another item.
debug_info() Return a string with the list of the attributes and their current value.
display() Print the model WITHOUT carriage return.
distance_to(other) Calculates the distance with an item.
has_inventory() Define if the NPC has an inventory.
inventory_space A property to get and set the size that the BoardItem takes in the Inventory.
item(row, column) Return the item component at the row, column position if it is within the complex item’s boundaries.
load(data) Load data and create a new ComplexNPC out of it.
overlappable() Returns True if the item is overlappable, False otherwise.
pickable() Define if the NPC is pickable.
position_as_vector() Returns the current item position as a Vector2D
render_to_buffer(buffer, row, column, …) Render the complex board item into a display buffer (not a screen buffer).
serialize() Serialize the NPC object.
store_position(row, column[, layer]) Store the BoardItem position for self access.
update_sprite() Update the complex item with the current sprite.

Attributes

column Convenience method to get the current stored column of the item.
dtmove
height Convenience method to get the height of the item.
model
row Convenience method to get the current stored row of the item.
width Convenience method to get the width of the item.
attach(observer)

Attach an observer to this instance. It means that until it is detached, it will be notified everytime 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)
be_notified(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 paramters 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. This can be None.
  • value (Any) – The new value of the attribute. This can be None.
can_move() → bool

Movable implements can_move().

Returns:True
Return type:Boolean
collides_with(other)

Tells if this item collides with another item.

Important

collides_with() does not take the layer into account! It is not desirable for the pygamelib to assume that 2 items on different layers wont collide. For example, if a player is over a door, they are on different layers, but logically speaking they are colliding. The player is overlapping the door. Therefor, it is the responsibility of the developper to check for layers in collision, if it is important to the game logic.

Parameters:other (BoardItem) – The item you want to check for collision.
Return type:bool

Example:

if projectile.collides_with(game.player):
    game.player.hp -= 5
column

Convenience method to get the current stored column of the item.

This is absolutely equivalent to access to item.pos[1].

Returns:The column coordinate
Return type:int

Example:

if item.column != item.pos[1]:
    print('Something extremely unlikely just happened...')
debug_info()

Return a string with the list of the attributes and their current value.

Return type:str
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)
display()

Print the model WITHOUT carriage return.

distance_to(other)

Calculates the distance with an item.

Parameters:other (BoardItem) – The item you want to calculate the distance to.
Returns:The distance between this item and the other.
Return type:float

Example:

if npc.distance_to(game.player) <= 2.0:
    npc.seek_and_destroy = True
dtmove
has_inventory()

Define if the NPC has an inventory.

This method returns false because the game engine doesn’t manage NPC inventory yet but it could be in the future. It’s a good habit to check the value returned by this function.

Returns:False
Return type:Boolean

Example:

if mynpc.has_inventory():
    print("Cool: we can pickpocket that NPC!")
else:
    print("No pickpocketing XP for us today :(")
height

Convenience method to get the height of the item.

This is absolutely equivalent to access to item.size[1].

Returns:The height
Return type:int

Example:

if item.height > board.height:
    print('The item is too big for the board.')
inventory_space

A property to get and set the size that the BoardItem takes in the Inventory.

Returns:The size of the item.
Return type:int
item(row, column)

Return the item component at the row, column position if it is within the complex item’s boundaries.

Return type:~pygamelib.board_items.BoardItem
Raises:PglOutOfBoardBoundException – if row or column are out of bound.
layer

Convenience method to get the current stored layer number of the item.

This is absolutely equivalent to access to item.pos[2].

Returns:The layer number
Return type:int

Example:

if item.layer != item.pos[2]:
    print('Something extremely unlikely just happened...')
classmethod load(data)

Load data and create a new ComplexNPC out of it.

Parameters:data (dict) – Data to create a new complex npc (usually generated by serialize())
Returns:A new complex npc.
Return type:~pygamelib.board_items.ComplexNPC
model
notify(modifier=None, attribute: str = None, value: Any = None) → None

Notify all the observers that a change occurred. Two important points:

  1. The “change” that occurred is not specified (but the notifying object is passed as parameter)
  2. No parameters are passed to the be_notified() method except the notifying object.
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()
overlappable()

Returns True if the item is overlappable, False otherwise.

Example:

if board.item(4,5).overlappable():
    print('The item is overlappable')
pickable()

Define if the NPC is pickable.

Obviously this method always return False.

Returns:False
Return type:Boolean

Example:

if mynpc.pickable():
    Utils.warn("Something is fishy, that NPC is pickable"
        "but is not a Pokemon...")
position_as_vector()

Returns the current item position as a Vector2D

Returns:The position as a 2D vector
Return type:Vector2D

Example:

gravity = Vector2D(9.81, 0)
next_position = item.position_as_vector() + gravity.unit()
render_to_buffer(buffer, row, column, height, width)

Render the complex board item 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.
restorable()

Returns True if the item is restorable, False otherwise.

Example:

if board.item(4,5).restorable():
    print('The item is restorable')
row

Convenience method to get the current stored row of the item.

This is absolutely equivalent to access to item.pos[0].

Returns:The row coordinate
Return type:int

Example:

if item.row != item.pos[0]:
    print('Something extremely unlikely just happened...')
serialize() → dict

Serialize the NPC object.

This returns a dictionnary that contains all the key/value pairs that makes up the object.

set_can_move(value)

Set the value of the can_move property to value.

Parameters:value (bool) – The value to set.

Example:

item.set_can_move(False)
set_overlappable(value)

Set the value of the overlappable property to value.

Parameters:value (bool) – The value to set.

Example:

item.set_overlappable(False)
set_pickable(value)

Set the value of the pickable property to value.

Parameters:value (bool) – The value to set.

Example:

item.set_pickable(False)
set_restorable(value)

Set the value of the restorable property to value.

Parameters:value (bool) – The value to set.

Example:

item.set_restorable(False)
size

A read-only property that gives the size of the item as a 2 dimensions list. The first element is the width and the second the height.

Returns:The size.
Return type:list

Example:

# This is a silly example because the Board object does not allow
# that use case.
if item.column + item.size[0] >= board.width:
    Game.instance().screen.display_line(
        f"{item.name} cannot be placed at {item.pos}."
    )
sprite

A property to easily access and update a complex item’s sprite.

Parameters:new_sprite (Sprite) – The sprite to set

Example:

npc1 = board_items.ComplexNpc(
                                sprite=npc_sprite_collection['npc1_idle']
                            )
# to access the sprite:
if npc1.sprite.width * npc1.sprite.height > CONSTANT_BIG_GUY:
    game.screen.place(
        base.Text(
            'Big boi detected!!!',
            core.Color(255,0,0),
            style=constants.BOLD,
        ),
        notifications.row,
        notifications.column,
    )
# And to set it:
if game.player in game.neighbors(3, npc1):
    npc1.sprite = npc_sprite_collection['npc1_fight']
store_position(row, column, layer=0)

Store the BoardItem position for self access.

The stored position is used for consistency and quick access to the self postion. It is a redundant information and might not be synchronized.

Parameters:
  • row (int) – the row of the item in the Board.
  • column (int) – the column of the item in the Board.
  • layer – the layer of the item in the Board. By default layer is set to 0.

Example:

item.store_position(3,4)
update_sprite()

Update the complex item with the current sprite.

Note

This method use to need to be called everytime the sprite was changed. Starting with version 1.3.0, it is no longer a requirement as BoardComplexItem.sprite was turned into a property that takes care of calling update_sprite().

Example:

item = BoardComplexItem(sprite=position_idle)
for s in [walk_1, walk_2, walk_3, walk_4]:
    # This is not only no longer required but also wasteful as
    # update_sprite() is called twice here.
    item.sprite = s
    item.update_sprite()
    board.move(item, constants.RIGHT, 1)
    time.sleep(0.2)
width

Convenience method to get the width of the item.

This is absolutely equivalent to access to item.size[0].

Returns:The width
Return type:int

Example:

if item.width > board.width:
    print('The item is too big for the board.')