API#
An object-oriented package for helping using cards in pygame.
Every class has an object class and a graphics class. The graphics are handled by a manager.
Game Objects and Graphic Objects#
pygame_cards is object oriented in the sense that all the game elements are implemented as python objects.
pygame_cards also aims in the future at being able to run on a server and on clients, splitting the graphic part of the game and the logic part.
For that reason, each game element has its own object and a corresponding graphic object. For example, a Card object will have a corresponding CardGraphic object.
The documentation sections will contain for each type of game element all the possible graphics implemented.
Abstract Graphics#
The abstract graphic class is the parent for all graphics classes in pygame_cards it contains the main elements required for compatibility with pygame_cards.
- class pygame_cards.abstract.AbstractGraphic#
An abstract class for all the graphics used in the game.
The graphic is showed using the surface property, which is a pygame.Surface object. The size of the suface is also determined by the size property. The suface should always be rendered for the desired size. This helps showing cards well on screen with different sizes.
In case one need graphics of different sizes for the same object the best is to create two instances of graphics for the same object for performance reasons (not having to recreate the surface every time).
- Parameters:
surface – The
pygame.Surfacecorresponding to the current graphic. This attribute must be implemented as a cached property. Whe the size of the graphic is changed, the cached surface is deleted and a new one is created.size – The size of the graphic. If you change that attribute, the surface will be recreated.
logger – The logger for this class. Useful for debugging.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
Cards#
- class pygame_cards.abstract.AbstractCard(name: str)#
The minimum required for a class.
When inheriting from this class, use the decorator: @dataclass(eq=False) such that you can inherit from the hash method, which is safely handled by the u_id attribute.
- Parameters:
name – The name of the card
u_id – A unique identifier for each card. Cards can be in two similar exemplar, but will have different u_ids.
graphics_type – The type of graphics we want to use.
logger – A
logging.Loggerobject. Useful for debugging purposes.
- property graphics: AbstractCardGraphics#
The graphics for the card.
Graphics#
- class pygame_cards.abstract.AbstractCardGraphics(card: AbstractCard, size: tuple[int, int] = (110, 180))#
A base representation for what a card should look like.
- property surface: Surface#
The surface of the card.
- class pygame_cards.back.CardBackGraphics(card: AbstractCard, size: tuple[int, int] = (110, 180))#
A simple graphics for a card back.
You can assign that graphics to any card you want.
- property surface: Surface#
The surface of the card.
Cards Set#
- class pygame_cards.set.CardsSet(*args: AbstractCard)#
A list of cards.
This class inherit diretly from the python list. This implies that any method from lists can be used. It represent the card set at the code or API level. If is meant to be used together with
AbstractCardGraphicsfor the graphics.- append(object, /)#
Append object to the end of the list.
- check_cards() bool#
Check whether only cards are given in this.
- clear()#
Remove all items from list.
- copy()#
Return a shallow copy of the list.
- count(value, /)#
Return number of occurrences of value.
- distribute(n_sets: int, n_cards: int | None = None, *, shuffle: bool = True, equally: bool = True) list[pygame_cards.set.CardsSet]#
Distribute the set in n sets.
The cards are removed from this CardsSet.
- Parameters:
n_sets – The number of set that should be done
n_cards – The number of cards that should be given to each set. If not specified, will distribute all the possible cards.
shuffle – Whether to shuffle the cards before distributing.
equally – Whether each set should contain the exact same number of cards. This is useful only if n_cards is not specified and if the cards cannot be all distrubuted equally. If True, the extra cards will be dropped. If False, the m extra cards are distrubted to the m first sets.
- distribute_to(other_sets: list[pygame_cards.set.CardsSet], n_cards: int | None = None, *, equally: bool = True, shuffle: bool = False, n_cards_at_a_time: int = 1) None#
Distribute n_cards from this set to the other sets.
Similar to
CardsSet.distribute(), but with additional feature that this can act as a cards packet where cards are distributed from the top, s.t. the order is preserved.Assume the first element of the list is the card at the top of the packet, so the first to be distributed.
- Parameters:
other_sets – The number of set that should be done
n_cards – see
CardsSet.distribute()equally – see
CardsSet.distribute()shuffle – Whether to shuffle the cards before distributing. Note that the default in this function is False instead of True, as for
CardsSet.distribute()n_cards_at_a_time – The number of cards that should be distributed at one time.
- draw(n_cards: int) CardsSet#
Draw the n first cards from the set.
To draw the first card of the set you can use the
pop(0)().- Parameters:
n_cards – The number of cards to draw. If -1, will draw all the cards
- extend(iterable, /)#
Extend list by appending elements from the iterable.
- filter_for_n_players(n_players: int) CardsSet#
Keep only the cards for the requested number of players.
Remove the cards that are not supposed to be used by the number of players. :return: A new card set that contain only the specifed cards.
- find_by_name(name: str) AbstractCard | None#
Find the first card matchin the name in the set.
- Returns:
The card requested or None if no card was found.
- classmethod generate() CardsSet#
Generate a cards set.
This will create the cards set from different parameters. You can override this method in daughter classes.
- index(value, start=0, stop=9223372036854775807, /)#
Return first index of value.
Raises ValueError if the value is not present.
- insert(index, object, /)#
Insert object before index.
- pop(index=-1, /)#
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
- remove(value, /)#
Remove first occurrence of value.
Raises ValueError if the value is not present.
- reverse()#
Reverse IN PLACE.
- shuffle()#
Shuffle the cards in the set in a random order.
- sort(*, key=None, reverse=False)#
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
- to_json(file: Path) None#
Save the cards set as a json file.
Graphics#
Hands and Piles are similiar but they have the main difference that in a hand cards will always try to fill the space available. Piles will try to arrange the cards nicely based on the offset, but might not fill the space. Piles will contract the cards if the space they try to fill is too small.
- class pygame_cards.set.CardsetGraphic(cardset: CardsSet, size: tuple[int, int] = (900, 240), card_size: tuple[int, int] = (110, 180), card_border_radius_ratio: float = 0.05, graphics_type: type | None = None, max_cards: int = 0)#
A base graphic for any card holder.
This will show a card set on the screen. You should implement the
surface().- Parameters:
cardset – The set of card that is shown.
size – A tuple with the size of the requested card in this graphic.
card_size – A tuple with the size of the cards in this graphic.
card_border_radius – The radius of the cards in this card set.
max_cards – The max number of card that can be contained in this graphic. If 0, this is unlimited.
- append_card(card: AbstractCard) None#
Append a card to the cardset.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- abstract get_card_at(pos: tuple[int, int]) AbstractCard | None#
Return the card at the given pixel position
- Parameters:
pos – The position inside the CardsetGraphic surface.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
- abstract get_cards_at(pos: tuple[int, int]) CardsSet | None#
Return a cardset at the given pixel position.
This can be implemented for allowing moving multiple cards. You will still have to implement
get_card_at(). You will also need to setdrag_multiple_cardsto True. inCarsetRights. TheCardsManagerwill then use this method for selection.- Parameters:
pos – The position inside the CardsetGraphic surface.
- pop_card(card_index: int) AbstractCard#
Remove a card from the cardset.
- Parameters:
card_index – The index at which the card we want to pop is.
- Return card_at_index:
The card at the desired index.
- remove_all_cards() CardsSet#
Remove all cards from the cardset.
- Return cards:
A cardset with all the cards remaining.
- remove_card(card: AbstractCard) None#
Remove a card from the cardset.
- with_hovered(card: AbstractCard | None) Surface#
Show the hand with the card hovered.
- class pygame_cards.deck.CardBackOwner(*args, card_back: Path | str | Surface = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/pygame-cards/envs/latest/lib/python3.10/site-packages/pygame_cards/images/DEFAULT_CARDBACK.png'), **kwargs)#
Graphic that can be used for any cardset that will show some card backs.
Support setting card backs using the path to files or using directly a pygame surface.
This is intended to be inherited from if you need to have card backs in a custom CardsetGraphic.
- property card_back: Surface#
The card back that should be shown.
- class pygame_cards.deck.Deck(*args, visible: bool = False, **kwargs)#
Graphics for a deck.
A deck simply shows its back.
- get_card_at(pos: tuple[int, int]) AbstractCard | None#
Return the card at the given pixel position
- Parameters:
pos – The position inside the CardsetGraphic surface.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
- property surface: Surface#
Should make a pile of cards.
- class pygame_cards.hands.BaseHand(*args, overlap_hide: CardOverlap = CardOverlap.right, **kwargs)#
A base class for a hand.
Usually in a hand the cards are shown on next to the other.
- Parameters:
overlap_hide – The card to hide if to cards are one over each other. By default the card overlap on the right, which is the standard in card games. This also implies that the cards are located at the opposite side of their overlap.
- class pygame_cards.hands.AlignedHand(*args, card_spacing: float = 0.15, **kwargs)#
A hand of card with all the cards aligned.
- Parameters:
card_spacing –
The offset proportion of the position between the cards.
0, means the cards are directly next to each other.
- Positive offset, means the card will be further
away from each other.
- Negative, means cards will be closer
to each other.
- calculate_x_positions() tuple[list[float], float]#
Calculate the x position of the cards.
- Return (x_positions, offset_value):
The x_positions is the positions of each card. The offset_value is the value used to make the spacing between the cards.
- get_card_at(pos: tuple[int, int]) AbstractCard | None#
Return the card at the given pixel position
- Parameters:
pos – The position inside the CardsetGraphic surface.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
- remove_card(card: AbstractCard) None#
Remove a card from the cardset.
- property surface: Surface#
The surface of the hand.
- with_hovered(card: AbstractCard | None, radius: float = 20, **kwargs) Surface#
Show the hand with the card hovered.
- class pygame_cards.hands.RoundedHand(*args, angle: float = 90, **kwargs)#
A hand of card with all the cards aligned on an arc of a circle.
This will produced an hand of card where cards are clipped insided the size of the hand.
- Parameters:
angle – The angle in which the cards are constrained (Unit: Degrees) If 0, the cards are all aligned. If not zero, the cards will be placed on an arc of a circle with the given angle.
- get_card_at(pos: tuple[int, int]) AbstractCard | None#
Return the card at the given pixel position
- Parameters:
pos – The position inside the CardsetGraphic surface.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
- property surface: Surface#
The surface of the hand.
- class pygame_cards.hands.Pile(*args, rel_offset: float = 0.2, **kwargs)#
A pile has only its last/s card/s that can be selected.
- Parameters:
rel_offset – The offset between cards. Relative to the card size.
- get_card_at(pos: tuple[int, int]) AbstractCard | None#
Return the card at the given pixel position
- Parameters:
pos – The position inside the CardsetGraphic surface.
- class pygame_cards.hands.VerticalPileGraphic(*args, **kwargs)#
Show a column in cards aligned.
Cards are shown from first one to the last one on the bottom.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
- class pygame_cards.hands.HorizontalPileGraphic(*args, **kwargs)#
Show a cards horizontally aligned.
Cards are shown from first one to the last one on the bottom.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- get_card_positions() dict[pygame_cards.abstract.AbstractCard, tuple[int, int]]#
Return the position of each card from the cardset.
Boards#
Some game require players to interact with different pile/sets of cards. For that reason pygame_cards implements a boards on which card sets can be placed.
- class pygame_cards.board.GameBoard(cardsets: list[pygame_cards.set.CardsSet] = [])#
Base class for game boards.
Graphics#
- class pygame_cards.board.GameBoardGraphic(cardsets_rel_pos: dict[pygame_cards.set.CardsSet, tuple[float, float]] = {}, cardsets_rel_size: dict[pygame_cards.set.CardsSet, tuple[float, float]] | tuple[int, int] = (0.2, 0.8), size: tuple[int, int] = (720, 560))#
Represent the graphics of the game board.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- property surface: Surface#
Show the game board with the gards.
- class pygame_cards.board.ColumnsBoardGraphic(game_board: GameBoard, size: tuple[int, int] = (720, 560), space_ratio: float = 0.15, horizontal_margins_ratio: float = 0.15, vertical_margins_ratio: float = 0.15, card_size_ratio: tuple[int | float, int | float] = (110, 180))#
A game board organized in columns.
- property card_size: tuple[int, int]#
Define the card size based on the layout of the board.
- clear_cache() None#
Clear the cache.
- property margins: tuple[int, int]#
Margins for the sides of the board.
Other Objects#
In many card games players also use tokens.
pygame_cards also include suport for tokens.
Token graphics for displaying a token
ValuedToken is a token with a Value
Token container which display piles of tokens
- class pygame_cards.tokens.Dice(edge: int = 100, radius: int = 20, value: int = 1, dot_radius: int = 10, border_width: int = 0, background_color: _ColorValue = 'white', drawings_color: _ColorValue = 'black')#
A dice from 2D top view.
- Parameters:
value – The value of the dice (from 1 to 6)
dot_radius – The size of the radius of the circles on the dice.
border_width – The width of the line defining the border of the dice.
background_color – The color of the background of the dice.
drawings_color – The color of the drawings on the dice (the dots and the border).
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- set_value(value: int)#
Set the value of the dice.
- class pygame_cards.tokens.PokerChipGraphics(radius: int = 200, color: _ColorValue = 'blue', drawings_color: _ColorValue = 'white', border_radius: int = 20, inner_line_width: int = 10)#
A poker chip
- Parameters:
color – The color of the token.
drawings_color – The color of the drawings on the token.
border_radius – The radius of the border
inner_line_width – The width of the line inside
- class pygame_cards.tokens.RoundTokenGraphics(radius: int = 200)#
A graphic for a round token.
- Parameters:
radius – The radius of the round token.
- class pygame_cards.tokens.SquaredTokenGraphics(edge: int = 100, radius: int = 20)#
A graphic for a square token.
- Parameters:
edge – The edge size of the square token.
radius – The radius of the corner of the square token. Allows to round the corners of the Token.
Game Managers#
- class pygame_cards.abstract.Manager#
Abstract class for cards manager.
- class pygame_cards.manager.CardsManager(click_time: int = 150)#
A card manager handling cardset graphics.
This is meant to be used similarily as the ui_manager from
pygame_gui.Capabilities :
Tracking which cardset and card are under the player mouse.
Moving cards from on cardset to another
Add related events in the game loop
The cards manager can be inherited from if you need to add special graphic mechanics.
- add_set(card_set: ~pygame_cards.set.CardsetGraphic, position: tuple[int, int], card_set_rights: ~pygame_cards.manager.CardSetRights = CardSetRights(clickable=False, draggable_out=<function CardSetRights.__post_init__.<locals>.<lambda>>, draggable_in=<function CardSetRights.__post_init__.<locals>.<lambda>>, highlight_hovered_card=True, drag_multiple_cards=False))#
Add a card set graphics to be managed.
- Parameters:
card_set – The cardset graphics to add.
position – The position where to show it on screen.
- draw(window: Surface, rotate_moving_card: bool = True)#
Draw the cards on the screen.
- process_events(event: Event)#
Process a pygame event.
- start_crazy(screen: Surface)#
Start the crazy mode.
Good way to end a game.
- update(time: int) bool#
Update the manager with the new time.
Has to be called after process events.
- Parameters:
time – The time since the last update. in ms.
- Returns:
whether the surface was updated or not.
- class pygame_cards.manager.CardSetRights(clickable: bool = False, draggable_out: bool | Callable[[AbstractCard], bool] = True, draggable_in: bool | Callable[[AbstractCard], bool] = True, highlight_hovered_card: bool = True, drag_multiple_cards: bool = False)#
Rigths for what the manager can do with a card set.
- Parameters:
clickable – Whether clicking on the set will generate CARDSSET_CLICKED events.
draggable_out – Whether we can drag the card out of the card set to another one.
draggable_in – Whether we can drag a card from another card set into this one.
highlight_hovered_card – Whether to highlight the hoverd_card from the cardset when the card set is hovered
Classic cards#
Classic playing cards module.
Many games use classic game cards. For that reason pygame_cards implements them using a simple api.
The current implementation is based on emojis and graphics are created at runtime.
- class pygame_cards.classics.CardSets#
Default card sets that can be used.
- Parameters:
n52 – A 52 game cards.
n36 – A 36 game cards.
- class pygame_cards.classics.Colors(value)#
Colors of the cards.
- class pygame_cards.classics.EmojisFrenchSuits(card: NumberCard, size: tuple[int, int] = (110, 180))#
A graphics showing the cards with emojis.
- clear_cache() None#
Clear the cache of this graphics.
Usually you don’t want to draw the same thing every time you will render a surface, so you will cache the surfaces. But sometimes the graphic will change and you will need to clear the cache of it.
- property surface: Surface#
The surface of the card.
- property top_label: Surface#
The label at top of the cards.
- class pygame_cards.classics.Level(value)#
Levels of special cards.
- class pygame_cards.classics.NumberCard(name: 'str', number: 'int | Level', color: 'Colors')#
- graphics_type#
alias of
EmojisFrenchSuits
- is_one_level_less_than(other_card: NumberCard, as_equals_1: bool = False) bool#
Return whether this card is one level less than the other_card.
- Parameters:
as_equals_1 – Whether the As should be considered as 1 (worst of all) or if it should be considered as the Best card
Drawing Functions#
pygame_cards also comes with some functions to draw cards related objects.
Some effects for cards.
- class pygame_cards.effects.Decay(value)#
Different decays for halos.
- pygame_cards.effects.outer_border(surface: Surface, width: int = 3, radius: int = 20, color: Color = (105, 105, 105, 255), inplace: bool = False) Surface#
Generate a border for the surface.
- Parameters:
surface – The surface that will have the border.
radius – The radius of the angles.
width – The width of the border.
color – The color of the border.
inplace – Whether to operate directly on the given surface or returning a new surface containing only the border.
- pygame_cards.effects.outer_halo(inner_surface: Surface, radius: int = 20, inner_color: Color = (255, 255, 255, 255), outer_color: Color = (255, 255, 255, 0), decay: Decay = Decay.QUADRATIC, fill_inside: bool = True) Surface#
Create a halo around the card.
- Parameters:
radius – The radius of the halo in pixels.
fill_inside – If false, it is transparent where the card is. Else, fill with the inner_color.
- Returns:
The halo surface.
Events#
pygame_cards custom events.
If you want to use them, don’t use the int values, but instead import the event from this module. They are supposed to be used the same way as pygame events and are dumped to the event loop.
from pygame_cards.events import CARD_CUSTOM_EVENT_YOU_WANT
Events have function corresponding to them that genereate the event based on the card/cardsets concerned with the event.
Most of the events are fully handled by the CardsManager .
- pygame_cards.events.CARDSSET_CLICKED = 32873#
A cardset was clicked
- pygame_cards.events.CARD_DRAG_MOVED = 32868#
The card being dragged was moved
- pygame_cards.events.CARD_DRAG_STARTED = 32867#
A card drag was started
- pygame_cards.events.CARD_DRAG_STOPPED = 32869#
The card being dragged was released
- pygame_cards.events.CARD_HOVERED = 32872#
Card hovered (for some time)
- pygame_cards.events.CARD_MOVED = 32871#
Card moved from a set to another (the attempt was allowed by the manager)
- pygame_cards.events.CARD_MOVE_ATTEMPT = 32870#
The players drags a card from a set to another
- pygame_cards.events.card_moved(card: AbstractCard, from_set: CardsetGraphic, to_set: CardsetGraphic) Event#
When a card has been moved from one set to another.
- pygame_cards.events.cardsset_clicked(set: CardsSet, card: AbstractCard | None = None) Event#
When a cardset has been clicked by a user.
The card clicked is also given. None if no card was under the click.
Networking#
Warning
This is currently not implemented
- class pygame_cards.defaults.DefaultCardsSet(*args: AbstractCard)#
- pygame_cards.defaults.get_default_card_set(name: str) DefaultCardsSet#
This is a card set that the user already has installed in the package.
This is useful for networking to specify the card set exists.
Currently not used.
Utilities#
- class pygame_cards.utils.AutoName(value)#
An enumeration.
- class pygame_cards.utils.AutoUpperName(value)#
Same as autoname, but enforcing upper case.
- pygame_cards.utils.position_for_centering(surface_on: Surface, surface_under: Surface) tuple[int, int]#
Calculate the position for surface on to be on the center of surface_under.
Then you could just blit the surface using:
center_pos = position_for_centering(surface_on, surface_under) surface_under.blit(surface_on, center_pos)