6. Spygame API Reference Documentation¶
6.1. Core API¶
-
class
spygame.
AABBCollision
[source]¶ Bases:
spygame.CollisionAlgorithm
A simple axis-aligned bounding-box collision mechanism which only works on Pygame rects.
-
static
collide
(sprite1, sprite2, collision_objects=None, direction=’x’, direction_veloc=0.0, original_pos=None)[source]¶
-
static
-
class
spygame.
AIBrain
(name=’brain’, commands=None)[source]¶ Bases:
spygame.AnimationLinkedBrain
An AnimationLinkedBrain that can handle simple left/right logic for 2D platformer monsters. The brain will take care of avoiding cliffs, but other than that always just walk from left to right and back. Overwrite this to implement more complex behaviors in the tick method.
-
class
spygame.
AnimatedSprite
(x, y, sprite_sheet, animation_setup, **kwargs)[source]¶ Bases:
spygame.Sprite
Adds an Animation component to each Sprite instance. AnimatedSprites need a SpriteSheet (no static images or no-render allowed).
Parameters: - x (int) – the initial x position of the Sprite
- y (int) – the initial y position of the Sprite
- spritesheet (SpriteSheet) – the SpriteSheet object to use for this Sprite
- animation_setup (dict) – the dictionary with the animation setup data to be sent to Animation.register_settings (the name of the registry record will be kwargs[“anim_settings_name”] OR spritesheet.name)
-
class
spygame.
Animation
(name)[source]¶ Bases:
spygame.Component
A Component that takes care of setting the image property of its owning Sprite object based on so-called “animation settings”. Animation settings are stored in a global registry under the name of the SpriteSheet object that holds the images that belong to the animation setting. The tick method has to be called by the Sprite’s tick method in order for the Sprite’s image to be changed on each tick.
-
animation_flags
= {‘none’: 0, ‘manual’: 1, ‘all’: 65535}¶
-
animation_settings
= {}¶
-
blink_animation
(game_object, rate=3.0, duration=3.0)[source]¶ Blinks the GameObject with the given parameters.
Parameters: - game_object (GameObject) – our GameObject to which blinking is applied
- rate (float) – the rate with which to blink (in 1/s)
- duration (float) – the duration of the blinking (in s); after the duration, the blinking stops
-
static
get_flag
(flags)[source]¶ Returns the bitmap code for an already existing Animation flag or for a new flag (the code will be created then). Flags are usually used to tell a Brain Component or the character directly what effects the animation has.
Parameters: flags (str) – the flag(s) (comma-separated), whose code(s) should be returned Returns: the flag as an int; if many flags are given, returns a bitmask with all those bits set that represent the given flags Return type: int
-
next_flag
= 2¶
-
play_animation
(game_object, name, priority=0)[source]¶ Plays an animation on our GameObject.
Parameters: - game_object (GameObject) – the GameObject on which to play the animation; the animation has to be setup via register_settings with the name of the SpriteSheet of the GameObject
- name (str) – the name of the animation to play
- priority (int) – the priority with which to play this animation (if this method is called multiple times, it will pick the higher one)
-
-
class
spygame.
AnimationLinkedBrain
(name=’brain’, commands=None)[source]¶ Bases:
spygame.Brain
A Brain that is linked to an Animation component and can thus subscribe to events triggered by that Component.
-
class
spygame.
Autobuild
(x, y, w, h, tile_w, tile_h)[source]¶ Bases:
object
Mix-in class to force x, y, width, height structure of ctors. All autobuild objects (objects that are built automatically by a TiledTileLayer with the property autobuild_objects=true) will have to abode to this ctor parameter structure.
-
class
spygame.
Brain
(name=’brain’, commands=None)[source]¶ Bases:
spygame.Component
A generic Brain class that has a command dict for other classes to be able to look up what the brain currently wants. Also has a main-switch to activate/deactivate the Brain. Should implement tick method and set self.commands each tick.
-
class
spygame.
Collision
[source]¶ Bases:
object
A simple feature object that stores collision properties for collisions between two objects or between an object and a TiledTileLayer.
-
class
spygame.
CollisionAlgorithm
[source]¶ Bases:
object
A static class that is used to store a collision algorithm.
-
static
collide
(sprite1, sprite2, collision_objects=None, original_pos=None)[source]¶ solves a simple spatial collision problem for two Sprites (that have a rect property) - defaults to SAT collision between two objects - thanks to doc’s at: http://www.sevenson.com.au/actionscript/sat/ - TODO: handle angles on objects - TODO: handle velocities of sprites prior to collision to calculate correct normals
Parameters: - sprite1 (Sprite) – sprite 1
- sprite2 (Sprite) – sprite 2 (the other sprite)
- collision_objects (Union[None,Tuple[Collision]]) – the two always-recycled returnable Collision instances (aside from None); if None, use our default ones
- original_pos (Union[Tuple[int],None]) – the position of sprite1 before doing the move that lead to this collision-detection call
Returns: a Collision object with all details of the collision between the two Sprites (None if there is no collision)
Return type:
-
default_collision_objects
= (<spygame.Collision object>, <spygame.Collision object>)¶
-
static
-
class
spygame.
Component
(name)[source]¶ Bases:
spygame.GameObject
A Component can be added to and removed from other GameObjects. Use “extend” to make a Component’s method be callable directly from the owning GameObject.
Parameters: name (str) – the name of the component (the name can be used to retrieve any GameObject’s components via the [GameObject].components dict) -
extend
(method)[source]¶ Extends the given method (has to take self as 1st param) onto the GameObject, so that this method can be called directly from the GameObject. The extended method will take two self’s (0=Component, 1=GameObject), thus selfs should be called ‘comp’ and ‘game_object’ OR ‘self’ and ‘game_object’
Parameters: method (callable) – method, which to make callable from within the owning GameObject
-
-
class
spygame.
ControlledPhysicsComponent
(name=’physics’)[source]¶ Bases:
spygame.PhysicsComponent
When added to a GameObject, checks for an existing Brain Component and creates a property (self.game_obj_cmp_brain) for easy access.
-
class
spygame.
Display
(width=600, height=400, title=’Spygame Rocks!’)[source]¶ Bases:
object
A simple wrapper class for a pygame.display/pygame.Surface object representing the pygame display. Also stores offset information for Viewport focusing (if Viewport is smaller that the Level, which is usually the case).
-
change_dims
(width, height)[source]¶ Changes the Display’s size dynamically (during the game).
Parameters:
-
instantiated
= False¶
-
-
class
spygame.
Dockable
(name=’dockable’)[source]¶ Bases:
spygame.Component
A dockable component allows 1) for Sprites to dock to a so-called “mother_ship” and b) for Sprites to become “mother_ships” themselves (other Sprites can dock to this Sprite). Sprites that are docked to our mother_ship (this Component’s Sprite) will be moved along with it when they stand on top.
-
DEFINITELY_DOCKED
= 1¶
-
DEFINITELY_NOT_DOCKED
= 2¶
-
PREVIOUSLY_DOCKED
= 8¶
-
TO_BE_DETERMINED
= 4¶
-
dock_to
(mother_ship)[source]¶ A sprite lands on an elevator -> couple the elevator to the sprite so that when the elevator moves, the sprite moves along with it. Only possible to dock to dockable-type objects.
Parameters: mother_ship (Sprite) – the Sprite to dock to (Sprite needs to have a dockable component)
-
is_docked
()[source]¶ Returns: True if the current state is definitely docked OR (to-be-determined AND previous state was docked) Return type: bool
-
move
(sprite, x, y, absolute=False)[source]¶ This will ‘overwrite’ the normal Sprite’s move method by Component’s extend.
Parameters: - sprite (Sprite) – the GameObject that this Component belongs to (the Sprite to move around)
- x (Union[int,None]) – the amount in pixels to move in x-direction
- y (Union[int,None]) – the amount in pixels to move in y-direction
- absolute (bool) – whether x and y are given as absolute coordinates (default: False): in this case x/y=None means do not move in this dimension
-
state_unsure
()[source]¶ Returns: True if our current docking state is not 100% sure (TO_BE_DETERMINED) Return type: bool
-
-
class
spygame.
Elevator
(x, y, direction=’y’, initial_veloc=50, max_pos=500, min_pos=0)[source]¶ Bases:
spygame.Sprite
A simple elevator/moving platform class. Can either go in x or in y direction, with a configurable speed and in between settable coordinate values. Has a Dockable Component to be able to carry characters standing on top of it. Is of type one_way_platform so one can jump on the Elevator also from below it.
-
class
spygame.
EventObject
[source]¶ Bases:
object
An EventObject introduces event handling and most objects that occur in spygame games will inherit from this class. NOTE: spygame events are not(!) pygame events. EventObject can ‘have’ some events, which are simple strings (the names of the events, e.g. ‘hit’, ‘jump’, ‘collided’, etc..). EventObject can trigger any event by their name. If an EventObject wants to trigger an event, this event must have been registered with the EventObject beforehand (will raise exception otherwise).
-
check_event
(event: str)[source]¶ Checks whether the given event is in this EventObject’s registry (raises exception if not).
Parameters: event (str) – the event to be checked
-
debind_events
()[source]¶ Called to remove any listeners from this object. E.g. when this object is destroyed you’ll want all the event listeners to be removed from this object.
-
off_event
(event, target=None, callback=None, unregister=False)[source]¶ Unbinds an event from a target/callback. Can be called with 1, 2, or 3 parameters, each of which unbinds a more specific listener.
Parameters: - event (str) – the name of the event to unbind from the callback
- target (EventObject) – the target EventObject to unbind this event from (callback would be a member of this target)
- callback (callable) – the callback to unbind the event from
- unregister (bool) – whether we should unregister this event as well
-
on_event
(event, target=None, callback=None, register=False)[source]¶ Binds a callback to an event on this EventObject. If you provide a target object, that object will add this event to it’s list of binds, allowing it to automatically remove it when it is destroyed. From here on, if the event gets triggered, the callback will be called on the target object. Note: Only previously registered events may be triggered (we can register the event here by setting register=True).
Parameters: - event (Union[str,List[str]]) – the name of the event to be bound to the callback (e.g. tick, got_hit, etc..)
- (EventObject) (target) – The target object on which to call the callback (defaults to self if not given)
- callback (callable) – the bound method to call on target if the event gets triggered
- register (bool) – whether we should register this event right now (only registered events are allowed to be triggered later)
-
register_event
(*events)[source]¶ registers a possible event (str) with this object; only registered events are allowed to be triggered later
Parameters: events (str) – the event (or events) that should be registered
-
trigger_event
(event, *params)[source]¶ Triggers an event and specifies the parameters to be passed to the bound event handlers (callbacks) as *params.
Parameters:
-
-
class
spygame.
Game
(screens_and_levels, width=0, height=0, title=’spygame Demo!’, max_fps=60, debug_flags=0)[source]¶ Bases:
object
An object that serves as a container for Screen and Level objects. Manages displaying the screens (start screen, menus, etc..) and playable levels of the game. Also keeps a Display object (and determines its size), which is used for rendering and displaying the game.
-
get_next_level
(level)[source]¶ returns the next level (if exists) as object; None if no next level
Parameters: level (Level) – the Level, whose next Level we would like to get Returns: the next Level after level; None if no next Level exists Return type: Union[Level,None]
-
instantiated
= False¶
-
level_aborted
(level)[source]¶ aborts the level and tries to play the “start” screen
Parameters: level (Level) – the Level object that has been aborted
-
-
class
spygame.
GameLoop
(callback, display, keyboard_inputs=None, max_fps=60)[source]¶ Bases:
object
Class that represents the GameLoop. Has play and pause functions: play starts the tick/callback loop. Has clock for ticking (keeps track of self.dt each tick), handles and abides to max-fps rate setting. Handles keyboard input registrations via its KeyboardInputs object. Needs a callback to know what to do each tick. Tick method does keyboard_inputs.tick, then calls the given callback with self as only argument.
-
active_loop
= None¶
-
play
(max_fps=None)[source]¶ Plays this GameLoop (after pausing the currently running GameLoop, if any).
-
static
play_a_loop
(**kwargs)[source]¶ Factory: plays a given GameLoop object or creates a new one using the given **kwargs options.
Parameters: kwargs (any) – - force_loop (bool): whether to play regardless of whether we still have some active loop running
- callback (callable): the GameLoop’s callback loop function
- keyboard_inputs (KeyboardInputs): the GameLoop’s KeyboardInputs object
- display (Display): the Display object to render everything on
- max_fps (int): the max frames per second to loop through
- screen_obj (Screen): alternatively, a Screen can be given, from which we will extract display, max_fps and keyboard_inputs
- game_loop (Union[str,GameLoop]): the GameLoop to use (instead of creating a new one); “new” or [empty] for new one
- dont_play (bool): whether - after creating the GameLoop - it should be played. Can be used for openAI gym purposes, where we just step, not tick
Returns: the created/played GameLoop object or None Return type: Union[GameLoop,None]
-
-
class
spygame.
GameObject
[source]¶ Bases:
spygame.EventObject
A GameObject adds the capability to add one or more Component objects to the GameObject (e.g. animation, physics, etc..). Component objects are stored by their name in the GameObject.components dict.
-
add_component
(component)[source]¶ Adds a component object to this GameObject -> calls the component’s added method.
Parameters: component (Component) – component to be added to GameObject under game_obj.components[component.name] Returns: the same Component for chaining Return type: Component
-
destroy
()[source]¶ Destroys the GameObject by calling debind and removing the object from it’s parent. Will trigger a destroyed event (callback).
-
id_to_obj
= {0: <Sprite sprite(in 0 groups)>}¶
-
next_id
= 1¶
-
-
class
spygame.
HumanPlayerBrain
(name=’brain’, key_brain_translations=None)[source]¶ Bases:
spygame.AnimationLinkedBrain
An AnimationLinkedBrain that handles agent control (via the GameLoop´s keyboard registry). Supports special keyboard->command translations (e.g. key down -> command A for one tick; key up -> command B for one tick).
-
add_translations
(key_brain_translations)[source]¶ Adds a single or more KeyboardBrainTranslation object to our dict.
Parameters: key_brain_translations (Union[KeyboardBrainTranslation,str,dict,tuple]) – the keyboard-to-command translation to be added to this Brain (can be represented in different ways; see code)
-
-
class
spygame.
KeyboardBrainTranslation
(key, command, flags=0, other_command=None, animation_to_complete=None)[source]¶ Bases:
object
A class to represent a relationship between a pressed key and a command (or two commands) The normal relationship is: [some key]: when pressed -> [command] is True; when not pressed -> [command] is False But other, more complex relationships are supported as well.
-
BLOCK_OTHER_CMD_UNTIL_ANIM_COMPLETE
= 8¶
-
BLOCK_REPEAT_UNTIL_ANIM_COMPLETE
= 4¶
-
DOWN_ONE_TICK
= 1¶
-
NORMAL
= 0¶
-
STATE_CHARGING
= 1¶
-
STATE_CMD_RECEIVED
= 4¶
-
STATE_FULLY_CHARGED
= 2¶
-
STATE_NONE
= 0¶
-
UP_ONE_TICK
= 2¶
-
-
class
spygame.
KeyboardInputs
(key_list=None)[source]¶ Bases:
spygame.EventObject
A class to handle keyboard inputs by the user playing the spygame game. A KeyboardInput object is passed to the GameLoop c’tor, so that the GameLoop can tick the KeyboardInput object each frame. Single keys to watch out for can be registered via the update_keys method (not registered keys will be ignored). The tick method collects all keydown/keyup pygame events and stores the currently registered keys in the keyboard_registry as True (currently pressed) or False (currently not pressed). All keys are described by their pygame names (without the leading K_), e.g. pygame.K_UP=`up`, pygame.K_ESCAPE=`escape`, etc..
-
tick
()[source]¶ Pulls all keyboard events from the event queue and processes them according to our keyboard_registry/descriptions. Triggers events for all registered keys like: ‘key_down.[desc]’ (when pressed) and ‘key_up.[desc]’ (when released), where desc is the lowercase string after pygame.K_… (e.g. ‘down’, ‘up’, etc..).
-
update_keys
(new_key_list=None)[source]¶ Populates our registry and other dicts with the new key-list given (may be an empty list).
Parameters: new_key_list (Union[List,None]) – the new key list, where each item is the lower-case pygame keycode without the leading K_ e.g. up for pygame.K_UP; use None for clearing out the registry (no keys assigned)
-
-
class
spygame.
Ladder
(x, y, w, h, tile_w, tile_h)[source]¶ Bases:
spygame.Sprite
,spygame.Autobuild
A Ladder object that actors can climb on. One-way-platform type: one cannot fall through the top of the ladder but does not collide with the rest (e.g. from below) of the ladder. A Ladder object does not have an image and is thus not(!) being rendered; the image of the ladder has to be integrated into a rendered TiledTileLayer. TiledTileLayers have the possibility to generate Ladder objects automatically from those tiles that are flagged with the type=’ladder’ property. In that case, the TiledTileLayer property ‘build_ladders’ (bool) has to be set to true.
-
class
spygame.
Level
(name: str = ‘test’, **kwargs)[source]¶ Bases:
spygame.Screen
A Level class adds tmx file support to the Screen. TiledTileLayers (background, collision, foreground, etc..) as well as single Sprite objects can be defined in the tmx file.
-
class
spygame.
LiquidBody
(x, y, w, h, tile_w, tile_h, description=’quicksand’)[source]¶ Bases:
spygame.Sprite
,spygame.Autobuild
A LiquidBody object (quicksand, water, etc..) that an actor will sink into and die. The AIBrain of enemies will avoid stepping into such an object.
-
class
spygame.
MovableRock
(x, y, **kwargs)[source]¶ Bases:
spygame.Sprite
-
class
spygame.
PhysicsComponent
(name)[source]¶ Bases:
spygame.Component
Defines an abstract generic physics component that can be added to agents (or enemies) to behave in the world. GameObject’s that own this Comonent may have a Brain component as well in order to steer behavior of the agent in tick. Needs to override tick and collision.
-
collision
(col)[source]¶ This is the resolver for a Collision that happened between two Sprites under this PhysicsComponent.
Parameters: col (Collision) – the Collision object describing the collision that already happened between two sprites
-
tick
(game_loop: spygame.GameLoop)[source]¶ Needs to be called by the GameObject at some point during the GameObject’s tick method.
Parameters: game_loop (GameLoop) – the currently playing GameLoop object
-
static
tile_sprite_handler
(tile_sprite_class, layer)[source]¶ Populates the tile_sprites dict of a TiledTileLayer with tile_sprite_class (e.g. TileSprite or SlopedTileSprite) objects.
Parameters: - layer (TiledTileLayer) – the TiledTileLayer, whose tiles we would like to process and store (each one) in the returned np.ndarray
- tile_sprite_class (type) – the TiledSprite subclass to use for generating TileSprite objects
Returns: a 2D np.ndarray (x,y) with the created TileSprite objects for each x/y coordinate (None if there is no tile at a position)
Return type: np.ndarray (2D)
-
-
class
spygame.
PlatformerPhysics
(name=’physics’)[source]¶ Bases:
spygame.ControlledPhysicsComponent
Defines “The Lost Vikings”-like game physics. Supports: Running over sloped tiles, jumping, ladders, moving platforms and elevators, pushable heavy rocks, one-way-platforms To be addable to any character (player or enemy) or thing (e.g. a pushable rock)
-
collide_in_one_direction
(sprite, direction, direction_veloc, original_pos)[source]¶ Detects and solves all possible collisions between our GameObject and all Stage’s objects (layers and Sprites) in one direction (x or y).
Parameters: - sprite (Sprite) – the GameObject of this Component (the moving/colliding Sprite)
- direction (str) – either “x” or “y”
- direction_veloc (float) – the velocity in the given direction (x/y-component of the velocity vector)
- original_pos (Tuple[int,int]) – the position of the game_object before this collision detection execution
-
collide_with_collision_layer
(sprite, layer, direction, direction_veloc, original_pos)[source]¶ Collides a Sprite with a collision TiledTileLayer (type==default) and solves all detected collisions. Supports slopes of all shapes (given y = mx + b parameterized). Certain restrictions apply for the tiled landscape for this algorithm to work: - no upside-down slopes allowed (slopes on the ceiling) - TODO: what other restrictions?
Parameters: - sprite (Sprite) – the Sprite to test for collisions against a TiledTileLayer
- layer (TiledTileLayer) – the TiledTileLayer object in which to look for collision tiles (full of sloped)
- direction (str) – x or y direction in which the sprite is currently moving before this test
- direction_veloc (float) – the velocity in the given direction (could be negative or positive)
- original_pos (Tuple[int,int]) – the position of the sprite before the move that caused this collision test to be executed
-
collision
(col)[source]¶ Gets called (via event trigger ‘collision’ (setup when this component is added to our GameObject)) when a collision is detected (e.g. by a layer).
Parameters: col (Collision) – the collision object of the detected collision (the first sprite in that Collision object must be our GameObject)
-
static
get_highest_tile
(tiles, direction, start_abs, end_abs)[source]¶ Returns the highest tile in a list (row or column) of sloped, full-collision or empty tiles.
Parameters: Returns: a tuple consisting of a) the highest SlopedTileSprite found in the list and b) the height value measured on a cartesian y-axis (positive=up)
Return type: Tuple[SlopedTileSprite,int]
-
lock_ladder
()[source]¶ Locks the GameObject into a ladder. Makes sure that there is nothing in the x-way (to move to the center of the ladder if standing a little bit aside). Otherwise, will not lock.
-
push_an_object
(pusher, col)[source]¶ Pushes a pushable other GameObject (assuming that this other object also has a PlatformerPhysics Component).
Parameters: - pusher – the Sprite that’s actively pushing against the other GameObject
- col – the Collision object (that caused the push) returned by the collision detector method
-
push_back
(sequence)[source]¶ Pushes the GameObject in x direction for some number of frames (e.g. when being hit by an arrow). The force of the push is given as x-acceleration value being added to the already calculated normal physics acceleration values. E.g. the character’s brain wants to go left: ax is then the running acceleration plus the value of the first item in the sequence. The sequence’s first item is then removed.
Parameters: sequence (list) – a list of additive x-accelerations that will be applied (on top of the regular physics) to the GameObject frame by frame until the list is empty
-
-
class
spygame.
Repeater
(x, y, image_file, **kwargs)[source]¶ Bases:
spygame.Sprite
A background 2D image that scrolls slower than the Viewport (to create a pseudo 3D effect).
-
class
spygame.
SATCollision
[source]¶ Bases:
spygame.CollisionAlgorithm
-
normal
= [0.0, 0.0]¶
-
-
class
spygame.
Screen
(name: str = ‘start’, **kwargs)[source]¶ Bases:
spygame.EventObject
A Screen object has a play and a done method that need to be implemented. The play method stages the Screen on a Stage. The done method can do some cleanup.
-
class
spygame.
SimpleHumanBrain
(name=’brain’, commands=None)[source]¶ Bases:
spygame.Brain
looks for keys that match our stored commands and sets these commands to True if the key is pressed, False otherwise
-
class
spygame.
SimpleScreen
(name, **kwargs)[source]¶ Bases:
spygame.Screen
A simple Screen that has support for labels and sprites (static images) shown on the screen.
-
class
spygame.
SlopedTileSprite
(layer, pytmx_tiled_map, id_, tile_props, rect)[source]¶ Bases:
spygame.TileSprite
a TileSprite that supports storing some temporary calculations about a slope in the tile and its relation to a Sprite that’s currently colliding with the TileSprite - used by the PlatformerPhysics Component when detecting and handling slope collisions
-
get_y
(x)[source]¶ Calculates the y value (in normal cartesian y-direction (positive values on up axis)) for a given x-value.
Parameters: x (int) – the x-value (x=0 for left edge of tile x=tilewidth for right edge of tile) Returns: the calculated y-value Return type: int
-
sloped_xy_pull
(sprite)[source]¶ Applies a so-called xy-pull on a Sprite object moving in x-direction in this sloped tile. An xy-pull is a change in the y-coordinate because of the x-movement (sliding up/down a slope while moving left/right).
Parameters: sprite (Sprite) – the Sprite object that’s moving on the slope
-
-
class
spygame.
Sprite
(x, y, **kwargs)[source]¶ Bases:
spygame.GameObject
,pygame.sprite.Sprite
A Sprite can be added to a Stage; has a type and a collision mask for collision detection with other Sprites or TiledTileLayers also on the Stage. Sprite objects inherit from pygame.sprite.Sprite, so a Sprite has an image and a position/collision rect via rect property (pygame.rect). Each Sprite can have either a static image or hold a SpriteSheet object from which it can pull images for animation purposes; either way, the image property holds the current image. The image rect (property image_rect) can be different from the collision rect (property rect); usually one would want the collision rect to be a little smaller than the actual image.
-
added_to_stage
(stage)[source]¶ adjusts our max positions based on the stage’s level’s dimensions - only if it’s a Level (not a simple Screen)
Parameters: stage (Stage) – the Stage we were added to
-
static
get_type
(types_)[source]¶ Returns the bitmap code for an already existing Sprite type or for a new type (the code will be created then). Types are usually used for collision masks.
Parameters: types (str) – the type(s) (comma-separated), whose code(s) should be returned Returns: the type as an int; if many types are given, returns a bitmask with all those bits set that represent the given types Return type: int
-
move
(x, y, absolute=False)[source]¶ Moves us by x/y pixels (or to x,y if absolute=True).
Parameters:
-
next_type
= 512¶
-
render
(display)[source]¶ Paints the Sprite with its current image onto the given Display object.
Parameters: display (Display) – the Display object to render on (Display has a pygame.Surface, on which we blit our image)
-
types
= {‘none’: 0, ‘dockable’: 1, ‘default’: 2, ‘one_way_platform’: 4, ‘particle’: 8, ‘friendly’: 16, ‘enemy’: 32, ‘all’: 65535}¶
-
-
class
spygame.
SpriteSheet
(file, store_flips=None)[source]¶ Bases:
object
Represents a spritesheet loaded from a tsx file. Stores each single image (as pygame.Surface) in the sheet by its position. Allows for already doing flip transformations (x/y and/or both axes) so we save time during the game. Stores single tile properties in tile_props_by_id dict (only for those tiles that actually have custom properties defined in the tsx file).
-
class
spygame.
Stage
(screen, options=None)[source]¶ Bases:
spygame.GameObject
A Stage is a container class for Sprites sorted by pygame.sprite.Groups and TiledTileLayers. Sprites within a Stage can collide with each other or with the TiledTileLayers in the Stage. Sprites and TiledTileLayers that are to be rendered are stored sorted by their render_order property (lowest renders first).
-
active_stage
= 0¶
-
add_sprite
(sprite, group_name)[source]¶ Adds a new single Sprite to an existing or a new pygame.sprite.Group.
Parameters: Returns: the Sprite that was added
Return type:
-
add_tiled_layer
(pytmx_layer, pytmx_tiled_map)[source]¶ Adds a pytmx.TiledElement to the Stage with all its tiles or objects. The TiledElement could either be converted into a TiledTileLayer or a TiledObjectGroup (these objects are generated in this function based on the pytmx equivalent being passed in).
Parameters: - pytmx_layer (pytmx.pytmx.TiledElement) – the original pytmx object to derive our TiledTileLayer or TileObjectGroup from
- pytmx_tiled_map (pytmx.pytmx.TiledMap) – the original pytmx TiledMap object (the tmx file) to which this layer belongs
-
add_tiled_object_group
(tiled_object_group)[source]¶ Adds a TiledObjectGroup (all it’s objects as single Sprites) to this Stage.
Parameters: tiled_object_group (TiledObjectGroup) –
-
add_tiled_tile_layer
(tiled_tile_layer)[source]¶ Adds a TiledTileLayer to this Stage. Puts it in the ordered to_render list, in the tiled_layers list.
Parameters: tiled_tile_layer (TiledTileLayer) – the TiledTileLayer to add to this Stage
-
static
clear_stage
(idx)[source]¶ Clears one of the Stage objects by index.
Parameters: idx (int) – the index of the Stage to clear (index==slot in static Stage.stages list)
-
detect
(detector, params=None)[source]¶ Returns the first GameObject in this Stage that - when passed to the detector function with params - returns True.
Parameters: - detector (callable) – a function that returns a bool
- params (list) – the list of positional args that are passed to the detector
Returns: the first GameObject in this Stage that - when passed to the detector function with params - returns True
Return type:
-
static
estimate_sprite_direction
(sprite)[source]¶ tries to return an accurate tuple of direction (x/y) and direction_veloc - if sprite directly has vx and vy, use these - if sprite has a physics component: use vx and vy from that Component - else: pretend vx and vy are 0.0 then return the direction whose veloc component is highest plus that highest veloc
Parameters: sprite (Sprite) – the Sprite to estimate Returns: tuple of direction (x/y) and direction_veloc Return type: Tuple[str,float]
-
for_each
(callback, params=None)[source]¶ Calls the given callback function for each sprite, each time passing it the sprite itself and *params.
Parameters:
-
force_remove_sprite
(sprite: spygame.Sprite)[source]¶ Force-removes the given Sprite immediately (without putting it in the remove_list first).
Parameters: sprite (Sprite) – the Sprite to be removed from the Stage
-
static
get_stage
(idx=0)[source]¶ Returns the Stage at the given index (returns None if none found).
Parameters: idx (Union[int,None]) – the index of the Stage to return (0=default Stage) Returns: the Stage object at the given index or None if there is no Stage at that index Return type: Union[Stage,None]
-
invoke
(func_name, params=None)[source]¶ Calls a function on all of the GameObjects on this Stage.
Parameters:
-
locate
(x, y, w=1, h=1, type_=2, collision_mask=2)[source]¶ Returns the first Collision found by colliding the given measurements (Rect) against this Stage’s objects. Starts with all TiledTileLayer objects, then all other Sprites.
Parameters: - x (int) – the x-coordinate of the Rect to check
- y (int) – the y-coordinate of the Rect to check
- w (int) – the width of the Rect to check
- h (int) – the height of the Rect to check
- type (int) – the type of the Rect (has to match collision_mask of Stage’s objects)
- collision_mask (int) – the collision mask of the Rect (only layers and Sprites that match this mask are checked)
Returns: the first Collision encountered
Return type:
-
locate_obj
= <Sprite sprite(in 0 groups)>¶
-
max_stages
= 10¶
-
remove_sprite
(sprite: spygame.Sprite)[source]¶ Removes a Sprite from this Stage by putting it in the remove_list for later removal.
Parameters: sprite (Sprite) – the Sprite to be removed from the Stage
-
render
(display)[source]¶ Gets called each frame by the GameLoop (after ‘tick’ is called on all Stages). Renders all its layers (ordered by ‘render_order’ property of the TiledTileLayer in the tmx file). TODO: renders Sprites that are not part of any layer.
Parameters: display (Display) – the Display object to render on
-
static
render_stages
(display, refresh_after_render=False)[source]¶ Loops through all Stages and renders all of them.
Parameters:
-
solve_collisions
()[source]¶ Look for the objects layer and do each object against the main collision layer. Some objects in the objects layer do their own collision -> skip those here (e.g. ladder climbing objects). After the main collision layer, do each object against each other.
-
static
stage_default_game_loop_callback
(game_loop: spygame.GameLoop)[source]¶ The default game loop callback to use if none is given when staging a Scene. Order: Clamps dt (to avoid extreme values), ticks all stages, renders all stages, updates the pygame.display
Parameters: game_loop (GameLoop) – the currently playing (active) GameLoop
-
static
stage_screen
(screen, screen_func=None, stage_idx=None, options=None)[source]¶ Supported options are (if not given, we take some of them from given Screen object, instead): - stage_idx (int): sets the stage index to use (0-9) - stage_class (class): sets the class (must be a Stage class) to be used when creating the new Stage - force_loop (bool): if set to True and we currently have a GameLoop running, stop the current GameLoop and replace it with a new one, which has to be given via the “game_loop” option (as GameLoop object, or as string “new” for a default GameLoop) - keyboard_inputs (KeyboardInputs): the KeyboardInputs object to use for the new GameLoop - display (Display): the Display to use for the new GameLoop - components (List[Component]): a list of Component objects to add to the new Stage (e.g. a Viewport)
Parameters: Returns: the new Stage object
Return type:
-
stages
= [None, None, None, None, None, None, None, None, None, None]¶
-
tick
(game_loop)[source]¶ Gets called each frame by the GameLoop. Calls the tick method on all its Sprites (but only if the sprite is within the viewport).
Parameters: game_loop (GameLoop) – the GameLoop object that’s currently running (and ticking all Stages)
-
-
class
spygame.
State
[source]¶ Bases:
spygame.EventObject
A simple state class that serves as a dict with settable and gettable key/value pairs. Setting a new value will trigger “changed”+key events.
-
class
spygame.
TileSprite
(layer, pytmx_tiled_map, id_, tile_props, rect)[source]¶ Bases:
spygame.Sprite
Class used by TiledTileLayer objects to have a means of representing single tiles in terms of Sprite objects (used for collision detector function).
-
class
spygame.
TiledObjectGroup
(pytmx_layer: pytmx.pytmx.TiledObjectGroup, pytmx_tiled_map: pytmx.pytmx.TiledMap)[source]¶ Bases:
spygame.TmxLayer
A wrapper class for the pytmx.TiledObjectGroup class, which represents an object layer in a tmx file. Generates all GameObjects specified in the layer (a.g. the agent, enemies, etc..). Implements render by looping through all GameObjects and rendering their Sprites one by one.
-
class
spygame.
TiledTileLayer
(pytmx_layer, pytmx_tiled_map, tile_sprite_handler)[source]¶ Bases:
spygame.TmxLayer
A wrapper class for pytmx.pytmx.TiledTileLayer, which represents a ‘normal’ tile layer in a tmx file. Reads in all tiles’ images into one Surface object so we can render the entire layer at once. Implements render.
-
build_sprite_surface
()[source]¶ Builds the image (pygame.Surface) for this tile layer based on all found tiles in the layer.
-
capture_autobuilds
()[source]¶ Captures all autobuild objects in this layer and returns them in a list of objects. Once an autobuild tile is found: searches neighboring tiles (starting to move right and down) for the same property and thus measures the object’s width and height (in tiles).
Returns: list of generated autobuild objects Return type: List[object]
-
collide_simple_with_sprite
(sprite, collision_detector)[source]¶ Collides a Sprite (that only obeys simple physics rules) with a TiledTileLayer and solves all detected collisions. The Sprite needs to have the properties vx and vy, which are interpreted as the Sprite’s velocity. Ignores slopes.
Parameters:
-
get_overlapping_tiles
(sprite)[source]¶ Returns the tile boundaries (which tiles does the sprite overlap with?).
Parameters: sprite (Sprite) – the sprite to test against Returns: a tuple of (start-x. end-x, start-y, end-y) tile-coordinates to consider as overlapping with the given Sprite Return type: tuple
-
-
class
spygame.
TmxLayer
(tmx_layer_obj, tmx_tiled_map)[source]¶ Bases:
object
A wrapper class for the pytmx TiledObject class that can either represent a TiledTileLayer or a TiledObjectGroup. Needs to implement render and stores some spygame specific properties such as collision, render, etc.
Parameters: - tmx_layer_obj (pytmx.pytmx.TiledElement) – the underlying pytmx TiledTileLayer
- tmx_tiled_map (pytmx.pytmx.TiledMap) – the underlying pytmx TiledMap object (representing the tmx file)
-
class
spygame.
TopDownPhysics
(name=’physics’)[source]¶ Bases:
spygame.ControlledPhysicsComponent
Defines “top-down-2D”-step physics (agent can move in any of the 4 directions using any step-size (smooth walking)). To be addable to any character (player or enemy).
-
collide_in_one_direction
(sprite, direction, direction_veloc, original_pos)[source]¶ Detects and solves all possible collisions between our GameObject and all Stage’s objects (layers and Sprites) in one direction (x or y).
Parameters: - sprite (Sprite) – the GameObject of this Component (the moving/colliding Sprite)
- direction (str) – either “x” or “y”
- direction_veloc (float) – the velocity in the given direction (x/y-component of the velocity vector)
- original_pos (Tuple[int,int]) – the position of the game_object before this collision detection execution
-
collide_with_collision_layer
(sprite, layer, direction, direction_veloc, original_pos)[source]¶ Collides a Sprite with a collision TiledTileLayer (type==default) and solves all detected collisions.
Parameters: - sprite (Sprite) – the Sprite to test for collisions against a TiledTileLayer
- layer (TiledTileLayer) – the TiledTileLayer object in which to look for collision tiles (full of sloped)
- direction (str) – x or y direction in which the sprite is currently moving before this test
- direction_veloc (float) – the velocity in the given direction (could be negative or positive)
- original_pos (Tuple[int,int]) – the position of the sprite before the move that caused this collision test to be executed
-
-
class
spygame.
Viewport
(display)[source]¶ Bases:
spygame.Component
A viewport is a component that can be added to a Stage to help that Stage render the scene depending on scrolling/obj_to_follow certain GameObjects - any GameObject with offset_x/y fields is supported, the Viewport will set these offsets to the Viewports x/y values before each render call
-
center_on
(x=None, y=None)[source]¶ Centers on a given x/y position without(!) respecting the Viewport’s max_speed property (unlike soft_center_on).
Parameters:
-
center_on_xy_with_viewport
(stage, x, y)[source]¶ Centers the Viewport on a given x/y position (so that the x/y position is in the center of the screen afterwards).
Parameters: - stage (GameObject) – our game_object (the Stage) that has self as component
- x (int) – the x position to center on
- y (int) – the y position to center on
-
follow
(game_loop=None, first=False)[source]¶ Helper method to follow our self.obj_to_follow (should not be called by the API user). Called when the Stage triggers Event ‘post_tick’ (passes GameLoop into it which is not used).
Parameters:
-
follow_object_with_viewport
(stage, obj_to_follow, directions=None, bounding_box=None, max_speed=inf)[source]¶ Makes the viewport follow a GameObject (obj_to_follow).
Parameters: - stage (GameObject) – our game_object (the Stage) that has self as component
- obj_to_follow (GameObject) – the GameObject that we should follow
- directions (dict) – dict with ‘x’ and ‘y’ set to either True or False depending on whether we follow only in x direction or y or both
- bounding_box (dict) – should contain min_x, max_x, min_y, max_y so we know the boundaries of the camera
- max_speed (float) – the max speed of the camera
-
move_to
(x=None, y=None)[source]¶ Moves the Viewport to a given x/y position (top-left corner, not centering) without(!) respecting the Viewport’s max_speed property.
Parameters:
-
move_to_xy_with_viewport
(stage, x, y)[source]¶ Moves the Viewport to the given x/y position (top-left corner, not center(!)).
Parameters: - stage (GameObject) – our game_object (the Stage) that has self as Component
- x (int) – the x position to move to
- y (int) – the y position to move to
-
pre_render
(display)[source]¶ Sets the offset property of the given Display so that it matches our (previously) calculated x/y values.
Parameters: display (Display) – the Display, whose offset we will change here
-
shake_viewport
(stage, time=3, frequency=5)[source]¶ Shakes the Viewport object for the given time and with the given frequency.
Parameters: - stage (GameObject) – our game_object (the Stage) that has self as Component
- time (float) – the amount of time (in sec) for which the Viewport should shake
- frequency (floar) – the frequency (in up/down shakes per second) with which we should shake; higher numbers mean more rapid shaking
-
soft_center_on
(x=None, y=None)[source]¶ Soft-centers on a given x/y position respecting the Viewport’s max_speed property (unlike center_on).
Parameters:
-
unfollow_object_with_viewport
(stage)[source]¶ Stops following.
Parameters: stage (GameObject) – our game_object (the Stage) that has self as component
-
-
spygame.
convert_type
(value, force_class=False)[source]¶ Converts the given value from a string (or other) type into the most likely type. E.g. ‘some text’ -> ‘some text’ (str) ‘1’ -> 1 (int) ‘-51’ -> -51 (int) ‘0.1’ -> 0.1 (float) ‘true’ -> True (bool) ‘False’ -> False (bool) [1, 2, 3] -> [1, 2, 3] (list) spygame.Ladder -> <type spygame.Ladder> (a python class object; can be used as a ctor to construct objects of that class)
Parameters: Returns: the converted value
Return type:
-
spygame.
defaults
(dictionary, defaults_dict)[source]¶ Adds all key/value pairs from defaults_dict into dictionary, but only if dictionary doesn’t have the key defined yet.
Parameters:
6.2. Example Classes:¶
6.2.1. The Lost Vikings¶
-
class
spygame.examples.vikings.
Arrow
(shooter)[source]¶ Bases:
spygame.examples.vikings.Shot
arrow class
-
sprite_sheet
= None¶
-
-
class
spygame.examples.vikings.
Baleog
(x, y)[source]¶
-
class
spygame.examples.vikings.
Coconut
(x, y, **kwargs)[source]¶ Bases:
spygame.AnimatedSprite
-
class
spygame.examples.vikings.
Dinosaur
(x, y, color=’blue’)[source]¶ Bases:
spygame.AnimatedSprite
-
hit_particle
(col)[source]¶ Called when hit by a particle type object.
Parameters: col (Collision) – the Collision object describing the collision
-
sprite_sheet
= None¶
-
-
class
spygame.examples.vikings.
DinosaurBrain
[source]¶ Bases:
spygame.AIBrain
-
class
spygame.examples.vikings.
FireSpitter
(x, y, w, h, tile_w, tile_h, **kwargs)[source]¶ Bases:
spygame.Sprite
,spygame.Autobuild
a FireSpitter can spit fireballs that kill the Vikings
-
class
spygame.examples.vikings.
Fireball
(shooter, direction=’right’)[source]¶ Bases:
spygame.examples.vikings.Shot
fireball class
-
sprite_sheet
= None¶
-
-
class
spygame.examples.vikings.
KeyLock
(x, y, color=’yellow’)[source]¶ Bases:
spygame.Sprite
-
class
spygame.examples.vikings.
Scorpion
(x, y)[source]¶ Bases:
spygame.AnimatedSprite
-
sprite_sheet
= None¶
-
-
class
spygame.examples.vikings.
Shot
(offset_x, offset_y, spritesheet, animation_setup, shooter, **kwargs)[source]¶ Bases:
spygame.AnimatedSprite
a shot (like the one a scorpion shoots) - can be extended to do more complicated stuff
-
collision
(col)[source]¶ we hit something -> solves a collision with another object
Parameters: col (spyg.Collision) – the spyg.Collision object to solve
-
-
class
spygame.examples.vikings.
Viking
(x, y, spritesheet, animation_setup)[source]¶ Bases:
spygame.AnimatedSprite
a generic Viking class
-
check_on_ladder
(dt)[source]¶ returns True if we are currently locked into a ladder, False otherwise - if we are locked into a ladder also set the current SpriteSheet frame manually (via animation.frame and animation.animation=None)
Parameters: dt (float) – the time passed since the last tick Returns: whether we are locked into a ladder or not Return type: bool
-