bgameb package

base

Base constructs for build package objects

log_enable(log_path: str = './logs/game.log', log_level: str = 'DEBUG') None[source]

Enable logging

Parameters
  • log_path (str, optional) – path to log file. Defaults to ‘./logs/game.log’.

  • log_level (str, optional) – logging level. Defaults to ‘DEBUG’.

pydantic model PropertyBaseModel[source]

Bases: BaseModel

Serializing properties with pydantic https://github.com/samuelcolvin/pydantic/issues/935 https://github.com/pydantic/pydantic/issues/935#issuecomment-554378904 https://github.com/pydantic/pydantic/issues/935#issuecomment-1152457432

Show JSON schema
{
   "title": "PropertyBaseModel",
   "description": "Serializing properties with pydantic\nhttps://github.com/samuelcolvin/pydantic/issues/935\nhttps://github.com/pydantic/pydantic/issues/935#issuecomment-554378904\nhttps://github.com/pydantic/pydantic/issues/935#issuecomment-1152457432",
   "type": "object",
   "properties": {}
}

dict(*, include: Optional[Union[AbstractSet[Union[int, str]], Mapping[Union[int, str], Any]]] = None, exclude: Optional[Union[AbstractSet[Union[int, str]], Mapping[Union[int, str], Any]]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) dict[str, Any][source]

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

classmethod get_properties()[source]
pydantic model Base[source]

Bases: PropertyBaseModel

Base class for game, players, tools and items

Show JSON schema
{
   "title": "Base",
   "description": "Base class for game, players, tools and items\n\n..\n    Attr:\n\n        id (str): id of stuff\n\n        _counter (Counter): Counter object.\n                            Isn't represented in final json or dict.\n                            Is initialized automaticaly by __init__.\n                            Counter is a collection.Counter.\n\n        _logger (Logger): loguru logger\n\n    Counter is a `collection.Counter\n    <https://docs.python.org/3/library/collections.html#collections.Counter>`_",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field id: str [Required]
_counter: Counter[Any]
model Config[source]

Bases: object

underscore_attrs_are_private = True
pydantic model BaseGame[source]

Bases: Base

Base class for games

Show JSON schema
{
   "title": "BaseGame",
   "description": "Base class for games\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields

pydantic model BasePlayer[source]

Bases: Base

Base class for players

Show JSON schema
{
   "title": "BasePlayer",
   "description": "Base class for players\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields

pydantic model BaseItem[source]

Bases: Base

Base class for items (like dices or cards)

Show JSON schema
{
   "title": "BaseItem",
   "description": "Base class for items (like dices or cards)\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields

pydantic model Components[source]

Bases: GenericModel, Generic[V], Mapping[str, V]

Components mapping represents a collection of objects, used for create instance of game items, like dices or decks

Show JSON schema
{
   "title": "Components",
   "description": "Components mapping represents a collection of objects,\nused for create instance of game items, like dices or decks",
   "type": "object",
   "properties": {}
}

by_id(id: str) Optional[V][source]

Get item object by its id

Parameters

id (str) – item id

Returns

item object

Return type

V, optional

items() a set-like object providing a view on D's items[source]
keys() a set-like object providing a view on D's keys[source]
to_json() str[source]
update(stuff: V, name: Optional[str] = None) None[source]

Update Component dict with safe name

Parameters
  • stuff (BaseItem) – item added to Components

  • name (Optional[str]) –

values() an object providing a view on D's values[source]
property ids: list[str]

Get ids of all items in Components

Returns

list of stuff ids

Return type

list[str]

pydantic model BaseTool[source]

Bases: Base, GenericModel, Generic[V]

Base class for game tools

Show JSON schema
{
   "title": "BaseTool",
   "description": "Base class for game tools\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "current": {
         "title": "Current",
         "default": [],
         "type": "array",
         "items": {
            "$ref": "#/definitions/BaseItem"
         }
      },
      "last": {
         "$ref": "#/definitions/BaseItem"
      }
   },
   "required": [
      "id"
   ],
   "definitions": {
      "BaseItem": {
         "title": "BaseItem",
         "description": "Base class for items (like dices or cards)\n    ",
         "type": "object",
         "properties": {
            "id": {
               "title": "Id",
               "type": "string"
            }
         },
         "required": [
            "id"
         ]
      }
   }
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field current: list[V] = []
field last: Optional[V] = None
by_id(id: str) list[V][source]

Get item from current by its id

Parameters

id (str) – item id

Returns

items

Return type

list[BaseItem]

clear() None[source]

Clear the current and last

count(item_id: str) int[source]

Count the number of current items with given id.

Parameters

item_id (str) – an item id

Returns

count of items

Return type

int

pop() V[source]

Remove and return an item from the current. If no items are present, raises an IndexError.

Returns

an item object

Return type

BaseItem

property current_ids: list[str]

Get ids of current items

Returns

list ids of current

Return type

list[str]

property last_id: Optional[str]

Get id of last

Returns

id

Return type

Optional[str]

pydantic model BaseToolExtended[source]

Bases: BaseTool, Generic[V]

Extends BaseTool class by list-like methods

Show JSON schema
{
   "title": "BaseToolExtended",
   "description": "Extends BaseTool class by list-like methods\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "current": {
         "title": "Current",
         "default": [],
         "type": "array",
         "items": {
            "$ref": "#/definitions/BaseItem"
         }
      },
      "last": {
         "$ref": "#/definitions/BaseItem"
      }
   },
   "required": [
      "id"
   ],
   "definitions": {
      "BaseItem": {
         "title": "BaseItem",
         "description": "Base class for items (like dices or cards)\n    ",
         "type": "object",
         "properties": {
            "id": {
               "title": "Id",
               "type": "string"
            }
         },
         "required": [
            "id"
         ]
      }
   }
}

Config
  • underscore_attrs_are_private: bool = True

Fields

append(item: V) None[source]

Append item to current

Parameters

item (BaseItem) – appended items

extend(items: Iterable[V]) None[source]

Extend the current by appending items started from the left side of iterable.

Parameters

items (Iterable[BaseItem]) – iterable with items

index(item_id: str, start: int = 0, end: Optional[int] = None) int[source]

Return the position of item in the current (after index start and before index stop). Returns the first match or raises ValueError if not found.

Parameters
  • item_id (str) – an item id

  • start (int) – start index. Default to 0.

  • end (int, optional) – stop index. Default to None.

Returns

index of the the first match

Return type

int

insert(item: V, pos: int) None[source]

Insert item into the current at given position.

Parameters
  • item (BaseItem) – an item object

  • pos (int) – position

remove(item_id: str) None[source]

Remove the first occurrence of item from current. If not found, raises a ValueError.

Parameters

item_id (str) – an item id

reverse() None[source]

Reverse the items in the current.

game

Main engine to create game

pydantic model Game[source]

Bases: BaseGame

The main game object

Show JSON schema
{
   "title": "Game",
   "description": "The main game object\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields

players

Game players classes

pydantic model Player[source]

Bases: BasePlayer

Player or bot

Show JSON schema
{
   "title": "Player",
   "description": "Player or bot\n    ",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields

items

Game dices, coins, cards and other items

pydantic model Step[source]

Bases: BaseItem

Game steps or turns

Show JSON schema
{
   "title": "Step",
   "description": "Game steps or turns\n\n..\n    Attr:\n\n        priority (NonNegativeInt): priority queue number. Default to 0.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "priority": {
         "title": "Priority",
         "default": 0,
         "minimum": 0,
         "type": "integer"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field priority: NonNegativeInt = 0
Constraints
  • minimum = 0

class Sides[source]

Bases: ConstrainedInt

Int subtipe to define sides of dices

gt = 1
pydantic model Dice[source]

Bases: BaseItem

Rolling or tossed objects, like dices or coins.

Example:
    dice = Dice(id='coin', sides=2, mapping={1: 'this', 2: 'that'})

Show JSON schema
{
   "title": "Dice",
   "description": "Rolling or tossed objects, like dices or coins.\n\n.. code-block::\n    :caption: Example:\n\n        dice = Dice(id='coin', sides=2, mapping={1: 'this', 2: 'that'})\n\n..\n    Attr:\n\n        count (PositiveInt): count of dices. Default to 1.\n\n        sides (Sides): sides of dice or coin. Default to 2.\n\n        mapping (dict[PositiveInt, Any]):\n            optional mapping of roll result. Mapping must define\n            values for each side.\n\n        last roll (list[PositiveInt]), optional:\n            last roll values.\n\n        last roll mapped (list[Any]), optional:\n            last mapped roll values.\n\n        _range (list[PositiveInt]): range of roll, started from 1.\n\n    Raises:\n\n        StuffDefineError: mapping keys is not equal of roll range.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "count": {
         "title": "Count",
         "default": 1,
         "exclusiveMinimum": 0,
         "type": "integer"
      },
      "sides": {
         "title": "Sides",
         "default": 2,
         "exclusiveMinimum": 1,
         "type": "integer"
      },
      "mapping": {
         "title": "Mapping",
         "default": {},
         "type": "object"
      },
      "last_roll": {
         "title": "Last Roll",
         "default": [],
         "type": "array",
         "items": {
            "type": "integer",
            "exclusiveMinimum": 0
         }
      },
      "last_roll_mapped": {
         "title": "Last Roll Mapped",
         "default": [],
         "type": "array",
         "items": {}
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field count: PositiveInt = 1
Constraints
  • exclusiveMinimum = 0

field last_roll: list[pydantic.types.PositiveInt] = []
field last_roll_mapped: list[Any] = []
field mapping: dict[pydantic.types.PositiveInt, Any] = {}
field sides: Sides = 2
Constraints
  • exclusiveMinimum = 1

roll() list[pydantic.types.PositiveInt][source]

Roll and return result

Returns

result of roll

Return type

list[PositiveInt]

roll_mapped() list[Any][source]

Roll and return mapped result

Returns

result of roll

Return type

list[Any]

pydantic model Card[source]

Bases: BaseItem

Card objects

Example:
    card = Card(id='unique_card')
    card.tap(side='left')

Show JSON schema
{
   "title": "Card",
   "description": "Card objects\n\n..\n    Attr:\n\n        count (PositiveInt): count of cards. Default to 1.\n\n        is_revealed (bool): is card oppened. Default to False.\n\n        is_active (bool): is card tapped. Default to False.\n\n        side (str, optional): the side of tap. Default to None.\n\n.. code-block::\n    :caption: Example:\n\n        card = Card(id='unique_card')\n        card.tap(side='left')",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "count": {
         "title": "Count",
         "default": 1,
         "exclusiveMinimum": 0,
         "type": "integer"
      },
      "is_revealed": {
         "title": "Is Revealed",
         "default": false,
         "type": "boolean"
      },
      "is_active": {
         "title": "Is Active",
         "default": true,
         "type": "boolean"
      },
      "side": {
         "title": "Side",
         "type": "string"
      }
   },
   "required": [
      "id"
   ]
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field count: PositiveInt = 1
Constraints
  • exclusiveMinimum = 0

field is_active: bool = True
field is_revealed: bool = False
field side: Optional[str] = None
alter() NoReturn[source]

Many cards have alter views. For example card can have main view, that apply most time of the game and second view, that apply only if card played as that alternative. For ease of understanding, consider that different views of the same card are not related directly to each other.

flip() Card[source]

Face up or face down the card regardles of it condition

Returns

Card

hide() Card[source]

Face down the card

Returns

Card

open() Card[source]

Face up the card

Returns

Card

tap(side='right') Card[source]

Tap the card to the given side

Parameters

side (str, optional) – side to tap. Defaults to ‘right’.

Returns

Card

untap() Card[source]

Untap the card

Returns

Card

tools

Game tools classes

pydantic model Shaker[source]

Bases: BaseToolExtended[Dice]

Shaker object

Show JSON schema
{
   "title": "Shaker",
   "description": "Shaker object\n\n..\n    Attr:\n\n        current (list[Dice]): Current dices representation of shaker.\n                              This making from Components items.\n\n        last (Dice), optional: last dice removed from current.\n\n        last_roll (dict[str, list[PositiveInt]), optional:\n            last roll result.\n\n        last_roll_mapped (dict[str, list[Any]]), optional:\n            last mapped roll result.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "current": {
         "title": "Current",
         "default": [],
         "type": "array",
         "items": {
            "$ref": "#/definitions/Dice"
         }
      },
      "last": {
         "$ref": "#/definitions/Dice"
      },
      "last_roll": {
         "title": "Last Roll",
         "default": {},
         "type": "object",
         "additionalProperties": {
            "type": "array",
            "items": {
               "type": "integer",
               "exclusiveMinimum": 0
            }
         }
      },
      "last_roll_mapped": {
         "title": "Last Roll Mapped",
         "default": {},
         "type": "object",
         "additionalProperties": {
            "type": "array",
            "items": {}
         }
      }
   },
   "required": [
      "id"
   ],
   "definitions": {
      "Dice": {
         "title": "Dice",
         "description": "Rolling or tossed objects, like dices or coins.\n\n.. code-block::\n    :caption: Example:\n\n        dice = Dice(id='coin', sides=2, mapping={1: 'this', 2: 'that'})\n\n..\n    Attr:\n\n        count (PositiveInt): count of dices. Default to 1.\n\n        sides (Sides): sides of dice or coin. Default to 2.\n\n        mapping (dict[PositiveInt, Any]):\n            optional mapping of roll result. Mapping must define\n            values for each side.\n\n        last roll (list[PositiveInt]), optional:\n            last roll values.\n\n        last roll mapped (list[Any]), optional:\n            last mapped roll values.\n\n        _range (list[PositiveInt]): range of roll, started from 1.\n\n    Raises:\n\n        StuffDefineError: mapping keys is not equal of roll range.",
         "type": "object",
         "properties": {
            "id": {
               "title": "Id",
               "type": "string"
            },
            "count": {
               "title": "Count",
               "default": 1,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "sides": {
               "title": "Sides",
               "default": 2,
               "exclusiveMinimum": 1,
               "type": "integer"
            },
            "mapping": {
               "title": "Mapping",
               "default": {},
               "type": "object"
            },
            "last_roll": {
               "title": "Last Roll",
               "default": [],
               "type": "array",
               "items": {
                  "type": "integer",
                  "exclusiveMinimum": 0
               }
            },
            "last_roll_mapped": {
               "title": "Last Roll Mapped",
               "default": [],
               "type": "array",
               "items": {}
            }
         },
         "required": [
            "id"
         ]
      }
   }
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field last_roll: dict[str, list[pydantic.types.PositiveInt]] = {}
field last_roll_mapped: dict[str, list[Any]] = {}
deal(components: Components[Dice], items: Optional[list[str]] = None) Shaker[source]

Deal new shaker current. The current is cleared before deal.

Parameters
  • components (Components) – game components

  • items (Optional[list[str]]) – item ids

Returns

Shaker

roll() dict[str, list[int]][source]

Roll all stuff in shaker and return results

Returns

result of roll

Return type

dict[str, list[int]]

Example:
    {
        "six_dice": [5, 3, 2, 5],
        "twenty_dice": [2, 12, 4],
    }
roll_mapped() dict[str, list[Any]][source]

Roll all stuff in shaker and return mapped results. If any stuff unmaped - empty list returned for this item.

Returns

result of roll

Return type

dict[str, list[Any]]

pydantic model Deck[source]

Bases: BaseToolExtended[Card]

Deck object

Show JSON schema
{
   "title": "Deck",
   "description": "Deck object\n\n..\n    You can add cards, define it counts and deal a deck.\n    Result is saved in current attr as deque object. This object\n    has all methods of\n    `python deque\n    <https://docs.python.org/3/library/collections.html#deque-objects>`_\n\n    Attr:\n\n        current (Deque[Card]): Current cards representation of deck.\n                               This making from Component items.\n\n        last (Card), optional: last card, removed from current.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "current": {
         "title": "Current",
         "type": "array",
         "items": {
            "$ref": "#/definitions/Card"
         }
      },
      "last": {
         "$ref": "#/definitions/Card"
      }
   },
   "required": [
      "id"
   ],
   "definitions": {
      "Card": {
         "title": "Card",
         "description": "Card objects\n\n..\n    Attr:\n\n        count (PositiveInt): count of cards. Default to 1.\n\n        is_revealed (bool): is card oppened. Default to False.\n\n        is_active (bool): is card tapped. Default to False.\n\n        side (str, optional): the side of tap. Default to None.\n\n.. code-block::\n    :caption: Example:\n\n        card = Card(id='unique_card')\n        card.tap(side='left')",
         "type": "object",
         "properties": {
            "id": {
               "title": "Id",
               "type": "string"
            },
            "count": {
               "title": "Count",
               "default": 1,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "is_revealed": {
               "title": "Is Revealed",
               "default": false,
               "type": "boolean"
            },
            "is_active": {
               "title": "Is Active",
               "default": true,
               "type": "boolean"
            },
            "side": {
               "title": "Side",
               "type": "string"
            }
         },
         "required": [
            "id"
         ]
      }
   }
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field current: deque[Card] [Optional]
_check_is_to_arrange_valid(order: list[str], to_arrange: Union[list[str], KeysView[str]]) None[source]

Chek is order and deque contains same elements

Parameters
  • order (list[str]) – ordered list of cards ids

  • to_arrange (list[str]) – list of deque ids

Raises

ArrangeIndexError – Given card ids and deque ids not match

_check_order_len(len_: int) None[source]

Check is order len valid

Parameters

l (int) – len of order of cards

Raises
_item_replace(item: Card) Card[source]

Get replaced copy of card

Parameters

item (Card) – a card object

Returns

Card

appendleft(item: Card) None[source]

Add card to the left side of the current deck.

Parameters

item (Card) – a card object

deal(components: Components[Card], items: Optional[list[str]] = None) Deck[source]

Deal new deck current. Curent is cleared before deal.

Parameters
  • components (Components) – game components

  • items (Optional[list[str]]) – list of cards ids

Returns

Deck

extendleft(items: Iterable[Card]) None[source]

Extend the left side of the current deck by appending cards started from the right side of iterable. The series of left appends results in reversing the order of cards in the iterable argument.

Parameters

items (Iterable[Card]) – iterable with cards

get_random(count: int = 1, remove: bool = True) list[bgameb.items.Card][source]

Get random cards from current deck

Parameters
  • count (int, optional) – count of random cards. Defaults to 1.

  • remove (bool, optional) – if True - remove random cards from current deck. Default to True.

Returns

list of random cards

Return type

list[Card]

popleft() Card[source]

Remove and return a card from the left side of the current deck. If no cards are present, raises an IndexError.

Returns

Card

reorder(order: list[str]) Deck[source]

Reorder current deque from right side.

Parameters
  • order (list[str]) – ordered list of cards ids

  • right (ordered from left side to) –

Returns

Deck

reorderfrom(order: list[str], start: int) Deck[source]

Reorder current deque from right side started with given position.

Parameters
  • start (int) – start of reordering

  • order (list[str]) – ordered list of cards ids

  • left (ordered from right side to) –

Returns

Deck

reorderleft(order: list[str]) Deck[source]

Reorder current deque from left side.

Parameters
  • order (list[str]) – ordered list of cards ids

  • right (ordered from left side to) –

Returns

Deck

rotate(n: int) None[source]

Rotate the current deck n steps to the right. If n is negative, rotate to the left.

Parameters

n (int) – steps to rotation

search(query: dict[str, int], remove: bool = True) list[bgameb.items.Card][source]

Search for cards in current by its id.

Parameters
  • query (dict[str, int]) – dict with id of searched cards and count of searching

  • remove (bool) – if True - remove searched cards from current deck. Default to True.

Returns

list of find cards, equal searching count

Return type

List[Card]

Example:
    game.deck1.search(
        {'card1': 2,
         'card2': 1 },
        remove=False
        )
shuffle() Deck[source]

Random shuffle current deck.

Returns

Deck

pydantic model Steps[source]

Bases: BaseTool[Step]

Game steps order object

Show JSON schema
{
   "title": "Steps",
   "description": "Game steps order object\n\n..\n    Attr:\n\n        current (list[Step]]):\n            Current representation of order in steps.\n            This making from Component items.\n\n        last (Step), optional: last poped from current step.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "string"
      },
      "current": {
         "title": "Current",
         "default": [],
         "type": "array",
         "items": {
            "$ref": "#/definitions/Step"
         }
      },
      "last": {
         "$ref": "#/definitions/Step"
      }
   },
   "required": [
      "id"
   ],
   "definitions": {
      "Step": {
         "title": "Step",
         "description": "Game steps or turns\n\n..\n    Attr:\n\n        priority (NonNegativeInt): priority queue number. Default to 0.",
         "type": "object",
         "properties": {
            "id": {
               "title": "Id",
               "type": "string"
            },
            "priority": {
               "title": "Priority",
               "default": 0,
               "minimum": 0,
               "type": "integer"
            }
         },
         "required": [
            "id"
         ]
      }
   }
}

Config
  • underscore_attrs_are_private: bool = True

Fields
field current: list[bgameb.items.Step] = []
field last: Optional[Step] = None
deal(components: Components[Step], items: Optional[list[str]] = None) Steps[source]

Clear current order and create new current order

Parameters
  • components (Components) – game components

  • items (Optional[list[str]]) – list of stuff ids

Returns

Steps

pops() Step[source]

Pop Step object from current with smallest priority

Returns

Step

push(item: Step) None[source]

Push Step object to current

Parameters

item (Step) – Step class instance

errors

Custom error classes

exception CustomRuntimeError[source]

Bases: RuntimeError

Base class for other runtime exceptions

exception ComponentNameError(name: str)[source]

Bases: CustomRuntimeError

Given name of component is wrong or name isn’t unique.

exception ComponentClassError(obj_)[source]

Bases: CustomRuntimeError

Given class can’t be a part of components.

exception StuffDefineError(message: str, logger: Logger)[source]

Bases: AttributeError

Bad definition of item.

exception ArrangeIndexError(message: str, logger: Logger)[source]

Bases: IndexError

Index error for arrange tool.