Board

class pygamelib.engine.Board(name: str = 'Board', size: list = [10, 10], ui_borders: str = None, ui_border_bottom: str = '-', ui_border_top: str = '-', ui_border_left: str = '|', ui_border_right: str = '|', ui_board_void_cell=' ', ui_board_void_cell_sprixel: pygamelib.gfx.core.Sprixel = None, player_starting_position=[0, 0, 0], DISPLAY_SIZE_WARNINGS=True, parent=None, partial_display_viewport=None, partial_display_focus=None, enable_partial_display=False)

Bases: pygamelib.base.PglBaseObject

A class that represent a game board.

The board object is a 2D matrix of board items. This means that you can visualize it as a chessboard for example. All board items are positionned on this chessboard-like object and can be moved around.

The Board object is the base object to build a level. Once created to your liking you can add items from the board_items module. You can also derived BoardItem to create your own board items, specific to your game.

If you want a detailled introduction to the Board object, go the the pygamelib wiki and read the “Getting started: the Board” article.

Note

In version 1.3.0 a new screen rendering stack was introduced. With this came the need for some object to hold more information about their state. This is the case for Board. To use partial display with the Screen buffer system the board itself needs to hold the information about were to draw and on what to focus on. The existing code will still work as the Game object takes care of forwarding the information to the Board. However, it is now possible to exploit the Camera object to create cutscenes and more interesting movements.

Important

Partial display related parameters are information used by the display_around() method and the Screen object to either display directly the board (display_around) or render the Board in the screen buffer. You have to make sure that the focus element’s position is updated. If you use the player, you have nothing to do but the Camera object needs to be manually updated for example.

Warning

in 1.3.0 the notion of layers was added to the Board object. Layers are used to better manage items overlapping. For the moment, layers are automatically managed to expand and shrink on demand (or on a need basis). You can use the layer system to add some depth to your game but you should be warned that you may experience some issues. If it is the case please report them on the Github issues page. For existing code, the entire Board object behaves exactly like in version 1.2.x.

__init__(name: str = 'Board', size: list = [10, 10], ui_borders: str = None, ui_border_bottom: str = '-', ui_border_top: str = '-', ui_border_left: str = '|', ui_border_right: str = '|', ui_board_void_cell=' ', ui_board_void_cell_sprixel: pygamelib.gfx.core.Sprixel = None, player_starting_position=[0, 0, 0], DISPLAY_SIZE_WARNINGS=True, parent=None, partial_display_viewport=None, partial_display_focus=None, enable_partial_display=False)
Parameters:
  • name (str) – the name of the Board
  • size (list) – array [width,height] with width and height being int. The size of the board. If layers is not specified it is set to 5.
  • 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/or columns.
  • enable_partial_display (bool) – A boolean to tell the Board 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().
  • partial_display_focus (BoardItem or Vector2D) – An item to focus (i.e center) the view on. When partial display is enabled the rendered view will be centered on this focus point/item. It can be an item or a vector.

Methods

__init__(name, size, 10], ui_borders, …[, …])
param name:the name of the Board
check_sanity() Check the board sanity.
clear_cell(row, column[, layer]) Clear cell (row, column, layer)
display() Display the entire board.
display_around(item, row_radius, column_radius) Display only a part of the board.
generate_void_cell() This method return a void cell.
get_immovables(**kwargs) Return a list of all the Immovable objects in the Board.
get_movables(**kwargs) Return a list of all the Movable objects in the Board.
init_board() Initialize the board with BoardItemVoid that uses ui_board_void_cell_sprixel or ui_board_void_cell (in that order of preference) as model.
init_cell(row, column[, layer]) Initialize a specific cell of the board with BoardItemVoid that uses ui_board_void_cell as model.
item(row, column[, layer]) Return the item at the row, column, layer position if within board’s boundaries.
move(item, direction[, step]) Board.move() is a routing function.
place_item(item, row, column, layer, auto_layer) Place an item at coordinates row, column and layer.
remove_item(item) Remove an item from the board.
render_cell(row, column)

New in version 1.3.0.

render_to_buffer(buffer, row, column, …) Render the board into a display buffer (not a screen buffer).

Attributes

height A convenience read only property to get the height of the Board.
width A convenience read only property to get the width of the Board.
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.
check_sanity() → None

Check the board sanity.

This is essentially an internal method called by the constructor.

clear_cell(row, column, layer=0)

Clear cell (row, column, layer)

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

It also removes the items from the the list of movables and immovables.

Parameters:
  • row (int) – The row of the item to remove
  • column (int) – The column of the item to remove
  • layer (int) – The layer of the item to remove. The default value is 0 to remain coherent with previous version of the library.

Example:

myboard.clear_cell(3,4,0)

Warning

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

Important

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.

Note

Starting in 1.3.0 and the addition of board’s layers, there is no more overlapping matrix. With no more moving items around this method should be a little faster. It also means that the layer parameter is really important (a wrong layer means that you’ll clear the wrong cell). Be ready to catch an IndexError exception

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() → None

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) → None

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_sprixel or ui_board_void_cell (in that order of preference) as model.

This method is automatically called by the Board’s constructor.

Example:

myboard.init_board()
init_cell(row, column, layer=0) → None

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,0)
static instantiate_item(data: dict)

Instantiate a BoardItem from its serialized data.

Parameters:data (dict) – The data to use to build the item.
Returns:an instance of a BoardItem.

Important

The actual object depends on the serialized data. It can be any derivative of BoardItem (even custom objects as long as they inherit from BoardItem) as long as they are importable by this class.

Example:

# First get some board item serialization data. For example:
data = super_duper_npc.serialize()
# Then instantiate a new one:
another_super_duper_npc = Board.instantiate_item(data)
item(row, column, layer=-1)

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

Parameters:
  • row (int) – The row to probe.
  • column (int) – The column to probe.
  • layer (int) – The layer to probe (default: -1 i.e the top item).
Return type:

pygamelib.board_items.BoardItem

Raises:

PglOutOfBoardBoundException – if row, column or layer are out of bound.

layers(row, column) → int

A method to get the number of layers at the Board’s given coordinates.

Returns:The number of layers of the board.
Return type:int

Example:

if board.layers(game.player.row, game.player.column) > 1:
    print('The player is stomping on something!')
classmethod load(data: dict = None)

Create a new Board object based on serialized data.

If data is None, None is returned.

If a color component is missing from data, it is set to 0 (see examples).

Raises an exception if the color components are not integer.

Parameters:data (dict) – Data loaded from JSON data (serialized).
Returns:Either a Board object or None if data where empty.
Return type:Board | NoneType
Raise:PglInvalidTypeException

Example:

# Loading from parsed JSON data
new_board = Board.load(json.load("board_lvl_01.json"))
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.

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()
place_item(item, row: int, column: int, layer: int = 0, auto_layer: bool = True)

Place an item at coordinates row, column and layer.

If row, column or layer are out of the board boundaries, a PglOutOfBoardBoundException is raised.

If the item is not a subclass of BoardItem, a 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)
render_cell(row, column)

New in version 1.3.0.

Render the cell at given position.

This method always return a Sprixel (it could be an empty one though). It automatically render the highest item (if items are overlapping for example). If the rendered Sprixel is configured to have transparent background, this method is going to go through the layers to make sure that it is rendering the sprixels correctly (i.e: with the right background color).

For basic usage of the library it is unlikely that you will use it. It is part of the screen rendering stack introduced in version 1.3.0. Actually unless you need to write a different rendering system you won’t use that method.

Parameters:
  • row (int) – The row to render.
  • column (int) – The column to render.
Return type:

Sprixel

Raises:

PglOutOfBoardBoundException – if row or column are out of bound.

Example:

# This renders the board from the top left corner of the screen.
for row in range(0, myboard.height):
    for column in range(0, myboard.height):
        myscreen.place(
            myboard.render_cell(row, column)
        ),
        row,
        column,
render_to_buffer(buffer, row, column, buffer_height, buffer_width) → None

Render the board 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.
serialize()

Return a serialized version of the board.

Returns:A dictionary containing the board’s attributes.

Example:

serialized_board_data = myboard.serialize()
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...')