Full API Documentation#
This page describes all user-accessible API components to the rubato project.
- init(res=(500, 500), window_size=None, window_pos=None, fullscreen=False, name='Untitled Rubato App', icon='', maximize=False, target_fps=0, physics_fps=50, hidden=False)[source]#
Initializes rubato.
- Parameters:
name (
str
) -- The title that appears at the top of the window. Defaults to "Untitled Rubato App".res (
UnionType
[Vector
,tuple
[float
,float
]]) -- The pixel resolution of the game, cast to int Vector. Defaults to (500, 500).window_size (
Union
[Vector
,tuple
[float
,float
],None
]) -- The size of the window, cast to int Vector. When not set, defaults to half the resolution. This is usually the sweet spot between performance and image quality.window_pos (
Union
[Vector
,tuple
[float
,float
],None
]) -- The position of the window, cast to int Vector. Set to None to let the computer decide. Defaults to None.icon (
str
) -- The path to the icon that will appear in the window. Defaults to "" (the rubato logo).fullscreen (
bool
) -- Whether the game should be fullscreen. Defaults to False.maximize (
bool
) -- Whether the game should be maximized. If fullscreen is set to True, that will take priority. Defaults to False.target_fps (
int
) -- The target frames per second. If set to 0, the target fps will be uncapped. Defaults to 0.physics_fps (
int
) -- The physics simulation's frames per second. Defaults to 50.hidden (
bool
) -- Whether the window should be hidden. Defaults to False.
- begin()[source]#
Starts the main game loop.
- Raises:
RuntimeError -- rubato has not been initialized before calling.
Game#
An abstraction surrounding the main game loop in rubato.
- class Game[source]#
A static class controlling rubato game flow.
- classmethod current()[source]#
The current scene of the game.
- Return type:
- Returns:
The current Scene.
- classmethod set_scene(scene_id)[source]#
Changes the current scene. Takes effect on the next frame.
- Parameters:
scene_id (
str
) -- The id of the new scene.
Scenes and Their Management#
Scenes
manages a set of GameObjects
and a
Camera
. Scenes are used to compartmentalize code. For example,
you could have each level of your game on a different scene. Then to switch levels you would switch scenes.
Scene#
An abstraction for a "level", or scene, in rubato.
- class Scene(name=None, background_color=Color.white, border_color=Color.black)[source]#
A scene divides different, potentially unrelated, sections of a game into groups. For instance, there may be a scene for the main menu, a scene for each level, and a scene for the win screen.
- Parameters:
name (
Optional
[str
]) -- The name of the scene. This is used to reference the scene. Automatically set if not assigned. Once this is set, it cannot be changed.background_color (
Color
) -- The color of the background of the window. Defaults to Color(255, 255, 255).border_color (
Color
) -- The color of the border of the window. Defaults to Color(0, 0, 0).
- camera#
The camera of this scene.
- border_color#
The color of the border of the window.
- background_color#
The color of the background of the window.
- property name#
The name of this scene. Read-only.
- add(*gos)[source]#
Adds gameobject(s) to the scene.
- Parameters:
*gos -- The gameobjects to add to the scene.
- remove(*gos)[source]#
Removes gameobject(s) from the scene. This will return false if any of the gameobjects are not in the scene, but it will guarantee that all the gameobjects are removed.
- Parameters:
*gos -- The gameobjects to remove.
- Return type:
- Returns:
True if all gameobjects were present in the scene, False otherwise.
- setup()[source]#
The start loop for this scene. It is run before the first frame. Is empty be default and can be overriden.
- update()[source]#
The update loop for this scene. It is run once every frame, before
draw()
. Is empty by default and can be overridden.
- fixed_update()[source]#
The fixed update loop for this scene. It is run (potentially) many times a frame. Is empty by default and can be overridden.
Note
You should define fixed_update only for high priority calculations that need to match the physics fps.
- paused_update()[source]#
The paused update loop for this scene. It is run once a frame when the game is paused. Is empty by default and can be overridden.
- draw()[source]#
The draw loop for this scene. It is run once every frame. Is empty by default and can be overridden.
- clone()[source]#
Clones this scene.
Warning
This is a relatively expensive operation as it clones every gameobject in the scene.
- Return type:
- contains(go)[source]#
Checks if the scene contains a gameobject.
- Parameters:
go (
GameObject
) -- The gameobject to check for.- Return type:
Camera#
The Camera module handles where things are drawn. A camera can zoom, pan, and travel along the z-index. GameObjects only render if their z-index is not more than that of the camera's.
The current scene's camera can be accessed through Game.current().camera
.
Game Object and Components#
Game Objects
are the main item in a game. They hold Components, have a position, and
have a z-index. By themselves, they have very little functionality.
Components
are how Game Objects get their functionality. Each component adds or
changes something about the Game Object. For example, an Image component draws an image from your filesystem to the game at the
Game Object's position.
Game Object#
A game object is a basic element describing a "thing" in rubato. Its functionality is defined by the components it holds.
- class GameObject(pos=(0, 0), rotation=0, z_index=0, ignore_cam=False, parent=None, name='', debug=False, active=True, hidden=False)[source]#
An element describing a set of functionality grouped as a "thing", such as a player or a wall.
- Parameters:
pos (
UnionType
[Vector
,tuple
[float
,float
]]) -- The position of the game object. Defaults to (0, 0).rotation (
float
) -- The rotation of the game object. Defaults to 0.z_index (
int
) -- The z-index of the game object. Defaults to 0.ignore_cam (
bool
) -- Whether the game object ignores the scene's camera when drawing or not. If set, all children will ignore the scene's camera. Defaults to False.parent (
Optional
[GameObject
]) -- The parent of the game object. Defaults to None.name (
str
) -- The name of the game object. Defaults to "".debug (
bool
) -- Whether to draw the center of the game object. Defaults to False.active (
bool
) -- Whether the game object is active or not. Defaults to True.hidden (
bool
) -- Whether the game object is hidden or not. Defaults to False.
Whether the game object is hidden (not drawn).
- property parent: rubato.structure.gameobject.game_object.GameObject | None#
The parent of the game object.
- Return type:
- true_z()[source]#
The true z-index of the game object.
- Returns:
The true z-index of the game object.
- Return type:
- true_pos()[source]#
The position of the game object relative to the scene.
- Returns:
The true position of the game object.
- Return type:
- true_rotation()[source]#
The rotation of the game object relative to the scene.
- Returns:
The true rotation of the game object.
- Return type:
- children()[source]#
The children of the game object. Note that this is an immutable tuple.
- Return type:
- Returns:
The children of the game object.
- add(*components)[source]#
Add a component to the game object.
- Parameters:
components (Component) -- The component(s) to add.
- Raises:
DuplicateComponentError -- Raised when there is already a component of the same type in the game object. Note that this error is only raised if the component type's 'singular' attribute is True.
- Returns:
This GameObject.
- Return type:
- remove(comp_type)[source]#
Removes the first instance of a type of component from the game object.
- Parameters:
comp_type (
Type
[Component
]) -- The type of the component to remove.- Raises:
IndexError -- The component was not in the game object and nothing was removed.
- remove_all(comp_type)[source]#
Removes all components of a type from the game object.
- Parameters:
comp_type (
Type
[Component
]) -- The type of the component to remove.- Raises:
IndexError -- The components were not in the game object and nothing was removed.
Components#
The default Component class.
The component abstraction that represents a template for all component types.
Attention
Each component can only be attached to one game object. To add one component to multiple game objects, use the
clone()
method.
- class Component(offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
A component adds functionality to the game object it is attached to. Note that this is a template class and should not be used directly. Instead, create another class and extend from this one.
- Parameters:
offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the component from the game object. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the component from the game object. Defaults to 0.z_index (
int
) -- The vertical offset of where to draw the component. Defaults to 0.hidden (
bool
) -- Whether the component is hidden or not. Defaults to False.
Whether the component is hidden (not drawn).
- gameobj: GameObject#
The game object this component is attached to.
- true_z()[source]#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- true_rotation()[source]#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
Raster#
- class Raster(width=32, height=32, af=False, scale=(1, 1), offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
A raster is a component that contains a surface.
- Parameters:
width (
int
) -- The width of the Raster. Defaults to 32.height (
int
) -- The height of the Raster. Defaults to 32.af (
bool
) -- Whether to use anisotropic filtering. Defaults to False.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the Raster. Defaults to (1, 1).offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the Raster. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the Raster. Defaults to 0.z_index (
int
) -- The z-index of the Raster. Defaults to 0.hidden (
bool
) -- Whether to hide the Raster. Defaults to False.
- get_rect()[source]#
Generates the rectangular bounding box of the raster.
- Return type:
- Returns:
The Rectangle hitbox that bounds the raster.
- blit(other, src_rect=None, dst=(0, 0))[source]#
Blits (merges / copies) another Surface onto this one.
- Parameters:
other (
Raster
) -- The Surface to blit onto this one.src_rect (
Optional
[tuple
[int
,int
,int
,int
]]) -- The area (center_x, center_y, width, height) to crop from the source surface (other). Defaults to the whole surface.dst (
UnionType
[Vector
,tuple
[int
,int
]]) -- The position to place the other surface. Defaults to (0, 0).
Note
Will not stretch the other surface to fit the destination rectangle.
- draw(camera)[source]#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- fill(color)[source]#
Fill the surface with a color.
- Parameters:
color (
Color
) -- The color to fill with.
- draw_line(start, end, color=Color.black, aa=False, thickness=1, blending=True)[source]#
Draws a line on the surface.
- Parameters:
start (
UnionType
[Vector
,tuple
[float
,float
]]) -- The start of the line.end (
UnionType
[Vector
,tuple
[float
,float
]]) -- The end of the line.color (
Color
) -- The color of the line. Defaults to black.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.thickness (
int
) -- The thickness of the line. Defaults to 1.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_rect(center, dims, border=Color.black, border_thickness=1, fill=None, blending=True)[source]#
Draws a rectangle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The top left corner of the rectangle.dims (
UnionType
[Vector
,tuple
[float
,float
]]) -- The dimensions of the rectangle.border (
Color
) -- The border color of the rectangle. Defaults to black.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the rectangle. Set to None for no fill. Defaults to None.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_circle(center, radius, border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a circle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the circle.radius (
int
) -- The radius of the circle.border (
Optional
[Color
]) -- The border color of the circle. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the circle. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_poly(points, center=(0, 0), border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a polygon on the surface.
- Parameters:
points (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The points of the polygon.center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the polygon.border (
Optional
[Color
]) -- The border color of the polygon. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the polygon. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- get_size()[source]#
Gets the current size of the surface.
- Return type:
- Returns:
The size of the surface
- set_colorkey(color)[source]#
Sets the colorkey of the surface. :type color:
Color
:param color: Color to set as the colorkey.
- set_alpha(new)[source]#
Sets surface wide alpha.
- Parameters:
new (
int
) -- The new alpha. (value between 0-255)
- save_as(filename, path='./', extension='png', save_to_temp_path=False, quality=100)[source]#
Save the raster to a file.
- Parameters:
filename (
str
) -- The name of the file to save to.path (
str
) -- Path to output folder.extension (
str
) -- The extension to save the file as. (png, jpg, bmp supported)save_to_temp_path (
bool
) -- Whether to save the file to a temporary path (i.e. MEIPASS used in exe).quality (
int
) -- The quality of the jpg 0-100 (only used for jpgs).
- Return type:
- Returns:
If save was successful.
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Image#
- class Image(path, af=False, scale=(1, 1), offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
An image is a raster subclass that generates the surface from an image file.
- Parameters:
path (
str
) -- The path to the file.af (
bool
) -- Whether to use anisotropic filtering. Defaults to False.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the Raster. Defaults to (1, 1).offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the Raster. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the Raster. Defaults to 0.z_index (
int
) -- The z-index of the Raster. Defaults to 0.hidden (
bool
) -- Whether to hide the Raster. Defaults to False.
- blit(other, src_rect=None, dst=(0, 0))#
Blits (merges / copies) another Surface onto this one.
- Parameters:
other (
Raster
) -- The Surface to blit onto this one.src_rect (
Optional
[tuple
[int
,int
,int
,int
]]) -- The area (center_x, center_y, width, height) to crop from the source surface (other). Defaults to the whole surface.dst (
UnionType
[Vector
,tuple
[int
,int
]]) -- The position to place the other surface. Defaults to (0, 0).
Note
Will not stretch the other surface to fit the destination rectangle.
- clear()#
Clears the surface.
- draw(camera)#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- draw_circle(center, radius, border=None, border_thickness=1, fill=None, aa=False, blending=True)#
Draws a circle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the circle.radius (
int
) -- The radius of the circle.border (
Optional
[Color
]) -- The border color of the circle. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the circle. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_line(start, end, color=Color.black, aa=False, thickness=1, blending=True)#
Draws a line on the surface.
- Parameters:
start (
UnionType
[Vector
,tuple
[float
,float
]]) -- The start of the line.end (
UnionType
[Vector
,tuple
[float
,float
]]) -- The end of the line.color (
Color
) -- The color of the line. Defaults to black.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.thickness (
int
) -- The thickness of the line. Defaults to 1.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_poly(points, center=(0, 0), border=None, border_thickness=1, fill=None, aa=False, blending=True)#
Draws a polygon on the surface.
- Parameters:
points (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The points of the polygon.center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the polygon.border (
Optional
[Color
]) -- The border color of the polygon. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the polygon. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_rect(center, dims, border=Color.black, border_thickness=1, fill=None, blending=True)#
Draws a rectangle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The top left corner of the rectangle.dims (
UnionType
[Vector
,tuple
[float
,float
]]) -- The dimensions of the rectangle.border (
Color
) -- The border color of the rectangle. Defaults to black.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the rectangle. Set to None for no fill. Defaults to None.blending (
bool
) -- Whether to use blending. Defaults to False.
- fixed_update()#
The physics function for a component.
- flip_anti_diagonal()#
Flips the surface along the anti-diagonal.
- flip_x()#
Flips the raster along the x-axis.
- flip_y()#
Flips the raster along the y-axis.
- get_pixel(pos)#
Gets the color of a pixel on the surface.
- get_rect()#
Generates the rectangular bounding box of the raster.
- Return type:
- Returns:
The Rectangle hitbox that bounds the raster.
- get_size()#
Gets the current size of the surface.
- Return type:
- Returns:
The size of the surface
- save_as(filename, path='./', extension='png', save_to_temp_path=False, quality=100)#
Save the raster to a file.
- Parameters:
filename (
str
) -- The name of the file to save to.path (
str
) -- Path to output folder.extension (
str
) -- The extension to save the file as. (png, jpg, bmp supported)save_to_temp_path (
bool
) -- Whether to save the file to a temporary path (i.e. MEIPASS used in exe).quality (
int
) -- The quality of the jpg 0-100 (only used for jpgs).
- Return type:
- Returns:
If save was successful.
- set_alpha(new)#
Sets surface wide alpha.
- Parameters:
new (
int
) -- The new alpha. (value between 0-255)
- set_colorkey(color)#
Sets the colorkey of the surface. :type color:
Color
:param color: Color to set as the colorkey.
- set_pixel(pos, color=Color.black, blending=True)#
Draws a point on the surface.
- setup()#
The setup function for a component.
- switch_color(color, new_color)#
Switches a color in the surface.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Text#
A text component.
- class Text(text='', font=Font(), justify='left', anchor=(0, 0), width=0, af=True, offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
A text component. Add this to game objects or UI elements to give them text. Takes a font object to render the text.
- Parameters:
text (
str
) -- The text to display. Defaults to "".font (
Font
) -- The font to use. Defaults to Font().justify (
Literal
['left', 'center', 'right']) -- The justification of the text. Defaults to "left".anchor (
UnionType
[Vector
,tuple
[float
,float
]]) -- The anchor of the text. The zero vector means it is centered. x component is whether to shift left, none, or right (-1, 0, 1). y component is whether to shift top, none, or bottom (-1, 0, 1). Defaults to Vector(0, 0).width (
int
) -- The width of the text. Defaults to 0.af (
bool
) -- Whether to use anisotropic filtering. Defaults to True.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the text from the game object. Defaults to Vector(0, 0).rot_offset (
float
) -- The rotation offset of the text from the game object. Defaults to 0.z_index (
int
) -- The z index of the text. Defaults to 0.hidden (
bool
) -- Whether the text is hidden. Defaults to False.
- anchor: Vector#
The anchor vector of the text.
This controls the position of the text relative to the game object. Is a vector where the x value controls the x anchor and the y value controls the y anchor. The values for each can be either -1, 0 or 1. This offset the text around the game object center.
Example
An anchor of
Vector(0, 0)
will center the text on the game object. An anchor ofVector(1, 1)
will move the text so that it's top left corner is at the game object's center.
- property justify: Literal['left', 'center', 'right']#
The justification of the text.
Can be one of:
"left"
,"center"
,"right"
.- Return type:
Literal
['left', 'center', 'right']
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- property width: int#
The maximum width of the text. Will automatically wrap the text. Use -1 to disable wrapping.
- Return type:
Animation#
This is the animation component module for game objects.
- class Animation(scale=(1, 1), fps=24, af=False, flipx=False, flipy=False, alpha=255, offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
Animations are a series of images that update automatically in accordance with parameters.
- Parameters:
scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the animation. Defaults to (1, 1).fps (
int
) -- The frames per second of the animation. Defaults to 24.af (
bool
) -- Whether to use anisotropic filtering on the animation. Defaults to False.flipx (
bool
) -- Whether to flip the animation horizontally. Defaults to False.flipy (
bool
) -- Whether to flip the animation vertically. Defaults to False.alpha (
int
) -- The alpha of the animation. Defaults to 255.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the animation from the game object. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the animation from the game object. Defaults to 0.z_index (
int
) -- The z-index of the animation. Defaults to 0.hidden (
bool
) -- Whether the animation is hidden. Defaults to False.
- fixed_update()#
The physics function for a component.
- property fps#
The fps of the animation.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- set_state(new_state, loop=False, freeze=-1)[source]#
Set the current animation state.
- Parameters:
- Raises:
KeyError -- The new_state key is not in the initialized states.
- add_folder(state_name, path, recursive=True)[source]#
Adds a state from a folder of images. Directory must be solely comprised of images.
- add_spritesheet(state_name, spritesheet, from_coord=(0, 0), to_coord=(0, 0))[source]#
Adds a state from a spritesheet. Will include all sprites from the from_coord to the to_coord.
- Parameters:
state_name (
str
) -- The key used to reference this state.spritesheet (
Spritesheet
) -- The spritesheet to use.from_coord (
UnionType
[Vector
,tuple
[float
,float
]]) -- The grid coordinate of the first frame. Defaults to (0, 0).to_coord (
UnionType
[Vector
,tuple
[float
,float
]]) -- The grid coordinate of the last coord. Defaults to (0, 0).
Example
animation.add_spritesheet("idle", spritesheet, Vector(0, 0), Vector(1, 3)) # This will add the frames (0, 0) to (0, size) and (1, 0) to (1, 3) inclusive to the animation # with the state name "idle". animation.add_spritesheet("idle", spritesheet, to_coord=spritesheet.end) # This will just load from the start to the end of the spritesheet.
Spritesheet#
Utility class for loading spritesheets.
- class Spritesheet(path, sprite_size=(32, 32), grid_size=None)[source]#
A spritesheet from the filesystem.
- Parameters:
path (
str
) -- The relative path to the spritesheet.sprite_size (
UnionType
[Vector
,tuple
[float
,float
]]) -- The size of each sprite in the spritesheet. Defaults to (32, 32).grid_size (
Union
[Vector
,tuple
[float
,float
],None
]) -- The size of the grid of sprites in the spritesheet. Set to None to automatically determine the grid size. Defaults to None.
- Raises:
IndexError -- If user does not load the entire sheet.
- property sprites: list[list[rubato.utils.rendering.surface.Surface]]#
The list of all the sprites as sprites (readonly).
- property end#
The end indexes of the Spritesheet as a vector.
Example
You can use
spritesheet.get(*spritesheet.end)
to get the final Sprite
- get(x, y)[source]#
Gets the Sprite at the corresponding grid coordinate of the spritesheet.
- Parameters:
- Raises:
IndexError -- One or both of the coordinates are out of range of the spritesheet's size.
- Return type:
- Returns:
The Sprite at the corresponding coordinate.
- static from_folder(path, sprite_size, default_state=None, recursive=True)[source]#
Creates an Animation from a folder of spritesheets. Directory must be comprised solely of spritesheets. Added alphabetically. Default is the first sheet loaded.
- Parameters:
path (
str
) -- The relative path to the folder you wish to importsprite_size (
UnionType
[Vector
,tuple
[float
,float
]]) -- The size of a single sprite in your spritesheet, should be the same in all imported sheets.default_state (
Optional
[str
]) -- Sets the default state of the animation.recursive (
bool
) -- Whether it will import an animation shallowly or recursively. Defaults to True.
- Returns:
the animation loaded from the folder of spritesheets
- Return type:
Particle Sytem#
A simple particle system.
- enum ParticleSystemMode(value)[source]#
The mode of the particle system.
- Member Type:
Valid values are as follows:
- RANDOM = <ParticleSystemMode.RANDOM: 0>#
The particles are generated randomly.
- LOOP = <ParticleSystemMode.LOOP: 1>#
Animate the generation around the shape.
- PINGPONG = <ParticleSystemMode.PINGPONG: 2>#
Animate the generation in a pingpong fashion.
- BURST = <ParticleSystemMode.BURST: 3>#
Generate the particles in a burst.
- class ParticleSystem(new_particle=None, duration=5, loop=False, max_particles=Math.INF, mode=ParticleSystemMode.RANDOM, spread=5, density=1, local_space=False, running=False, offset=(0, 0), rot_offset=0, z_index=0)[source]#
A simple particle system.
- Parameters:
new_particle (
Optional
[Callable
[[float
],Particle
]]) -- The method to generate a new particle. Takes in an angle and should return a particle object. Defaults to ParticleSystem.default_particle.duration (
float
) -- The duration of the system in seconds (when to stop generating particles). Defaults to 5.loop (
bool
) -- Whether the system should loop (start again at the end of its duration). Defaults to False.max_particles (
int
) -- The maximum number of particles in the system. Defaults to Math.INF.mode (
ParticleSystemMode
) -- The particle generation mode of the system. Defaults to ParticleSystemMode.RANDOM.spread (
float
) -- The gap between particles (in degrees). Defaults to 45.density (
int
) -- The density of the system. This is the number of particles generated per fixed update. Defaults to 1.local_space (
bool
) -- Whether the particles should be in local space.running (
bool
) -- Whether the system should start as soon as it becomes active.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the system. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the system. Defaults to 0.z_index (
int
) -- The z-index of the system. Defaults to 0.
- new_particle#
The user-defined function that generates a particle.
- mode: ParticleSystemMode#
The particle generation mode of the system.
- density: int#
The density of the system. This is the number of particles generated per fixed update.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- draw(camera)[source]#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- static default_particle(angle)[source]#
The default particle generation function. This can be passed into the Particle System constructor.
- Return type:
- static particle_gen(surface, movement=None, pos_func=None, dir_func=Particle.circle_direction(), start_speed=1, acceleration=(0, 0), rotation=0, rot_velocity=0, rot_acceleration=0, scale=(1, 1), lifespan=1, z_index=0, age=0)[source]#
Generates a particle generation function for the Particle System constructor.
- Parameters:
surface (
Surface
) -- The surface to use for the particle.movement (
Optional
[Callable
[[Particle
,float
],None
]]) -- The movement function. Defaults to Particle.default_movement.pos_func (
Optional
[Callable
[[float
],Vector
]]) -- The function used to determine each starting position. Must take in an angle relative to the system. Defaults to lambda _: Vector(0, 0).dir_func (
Callable
[[float
],Vector
]) -- The function used to determine each starting direction. Must take in an angle relative to the system. Defaults to Particle.circle_direction().start_speed (
float
) -- The starting speed. Defaults to 1.acceleration (
UnionType
[Vector
,tuple
[float
,float
]]) -- The starting acceleration. Defaults to (0, 0).rotation (
float
) -- The starting rotation. Defaults to 0.rot_velocity (
float
) -- The starting rotational velocity. Defaults to 0.rot_acceleration (
float
) -- The starting rotational acceleration. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The starting scale. Defaults to (1, 1).lifespan (
float
) -- The lifespan of each particle. Defaults to 1.z_index (
int
) -- The z-index of each particle. Defaults to 0.age (
float
) -- The starting age of each particle. Defaults to 0.
- Return type:
- Returns:
A particle generation function.
Particle#
A simple particle.
- class Particle(surface, movement=None, pos=(0, 0), velocity=(0, 0), acceleration=(0, 0), rotation=0, rot_velocity=0, rot_acceleration=0, scale=(1, 1), lifespan=1, z_index=0, age=0)[source]#
A simple particle.
- Parameters:
surface (
Surface
) -- The surface of the particle.movement (
Optional
[Callable
[[Particle
,float
],None
]]) -- The movement function of a particle. Takes in a Particle and a delta time. Defaults to Particle.default_movement.pos (
UnionType
[Vector
,tuple
[float
,float
]]) -- The position of the particle. Defaults to (0, 0).velocity (
UnionType
[Vector
,tuple
[float
,float
]]) -- The velocity of the particle. Defaults to (0, 0).acceleration (
UnionType
[Vector
,tuple
[float
,float
]]) -- The acceleration of the particle. Defaults to (0, 0).rotation (
float
) -- The rotation of the particle. Defaults to 0.rot_velocity (
float
) -- The rotational velocity of the particle. Defaults to 0.rot_acceleration (
float
) -- The rotational acceleration of the particle. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the particle. Defaults to (1, 1).lifespan (
float
) -- The lifespan of the particle (in seconds). Defaults to 1.z_index (
int
) -- The z-index of the particle. Defaults to 0.age (
float
) -- The starting age of the particle (in seconds). Defaults to 0.
- static circle_shape(radius)[source]#
A shape function that returns a circle. The output of this generator can be used as a position value for Particles.
- static circle_direction()[source]#
A direction function that returns a circle. The output of this generator can be used to control the initial direction of Particles.
Tilemap#
A Tiled tilemap.
- class Tilemap(map_path, scale=(1, 1), collider_tag='', z_index=0, hidden=False)[source]#
A tilemap that is loaded from a Tiled map file. Once a tilemap component is created, it won't stay updated with the map file. To automatically add hitboxes to the gameobject, use Tiled Objects. We support Rectangles and Polygons in layers or on the individual tiles.
We do not support all of Tiled's features, but we do support the most common ones. Here is a list of major features that we DO NOT support:
Infinite maps
Non-orthogonal maps
Non-rectangular tiles
Animated tiles
Multiple tilesets per map
Image layers
Tile and layer opacity
Parallax scrolling
Worlds
Terrain
- Parameters:
map_path (
str
) -- The path to the map file.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the tilemap. Defaults to (1, 1).collider_tag (
str
) -- The tag of the colliders. Defaults to "".z_index (
int
) -- The z index of the tilemap. Defaults to 0.hidden (
bool
) -- Whether the tilemap is hidden. Defaults to False.
- draw(camera)[source]#
The draw function for a component.
- Parameters:
camera -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Simple Tilemap#
A simple tilemap doesn't need to use the Tiled editor. It uses an array of numbers to keep track of tile types.
- class SimpleTilemap(tilemap, tiles, tile_size=(32, 32), collision=None, collider_tag=None, scale=(1, 1), offset=(0, 0), rot_offset=0, z_index=0, hidden=False)[source]#
A simple tilemap doesn't need to use the Tiled editor. It uses an array of numbers to keep track of tile types.
- Parameters:
tilemap (
list
[list
[int
]]) -- A 2D array of integers representing the tilemap.tiles (
list
[Surface
]) -- A list of surfaces representing the tiles. The index of the surface in the list is the number used in the tilemap array.tile_size (
UnionType
[Vector
,tuple
[int
,int
]]) -- The size of each tile in the tilemap. Defaults to (32, 32).collision (
Optional
[list
[int
]]) -- A list of integers representing the tiles that should have collision. Defaults to [].collider_tag (
Optional
[list
[str
]]) -- A list of strings representing the tags of the colliders. The index of the tag in the list is the number used in the tilemap array. Defaults to [].scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the tilemap. Defaults to (1, 1).offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the tilemap. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the tilemap. Defaults to 0.z_index (
int
) -- The z-index of the tilemap. Defaults to 0.hidden (
bool
) -- Whether the tilemap is hidden. Defaults to False.
- scale#
The scale of the tilemap.
- uptodate#
Whether the tilemap is up to date.
- draw(camera)[source]#
The draw function for a component.
- Parameters:
camera -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Hitbox#
Various hitbox components that enable collisions
- class Hitbox(color=None, tag='', trigger=False, should_collide=None, on_collide=None, on_enter=None, on_exit=None, offset=(0, 0), rot_offset=0, z_index=0, scale=(1, 1), debug=False, hidden=False)[source]#
A hitbox superclass. Do not use this class to attach hitboxes to your game objects. Instead, use Polygon or Circle, which inherit Hitbox properties.
- Parameters:
color (
Optional
[Color
]) -- The color of the hitbox. Set to None to not show the hitbox. Defaults to None.tag (
str
) -- A string to tag the hitbox. Defaults to "".trigger (
bool
) -- Whether the hitbox is a trigger. Defaults to False.should_collide (
Optional
[Callable
[[Hitbox
,Hitbox
],bool
]]) -- A function to call to determine whether the hitbox should collide with another hitbox. Defaults to lambda self, other: True.on_collide (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_enter (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox enters another hitbox. Defaults to lambda manifold: None.on_exit (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the hitbox from the gameobject. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the hitbox. Defaults to 0.z_index (
int
) -- The z-index of the hitbox. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the hitbox. Defaults to (1, 1).debug (
bool
) -- Whether to draw the hitbox. Defaults to False.hidden (
bool
) -- Whether the hitbox is hidden. Defaults to False.
- should_collide: Callable[[Hitbox, Hitbox], bool]#
The should_collide function to call to determine whether two hitboxes should collide.
- on_collide: Callable[[Manifold], None]#
The on_collide function to call when a collision happens with this hitbox.
- on_enter: Callable[[Manifold], None]#
The on_enter function to call when collision begins with this hitbox.
- on_exit: Callable[[Manifold], None]#
The on_exit function to call when a collision ends with this hitbox.
- get_aabb()[source]#
Gets bottom left and top right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- draw(camera)[source]#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Rectangle#
- class Rectangle(width=0, height=0, color=None, tag='', trigger=False, should_collide=None, on_collide=None, on_enter=None, on_exit=None, offset=(0, 0), rot_offset=0, z_index=0, scale=(1, 1), debug=False, hidden=False)[source]#
A Rectangular Hitbox component.
- Parameters:
width (
UnionType
[int
,float
]) -- The width of the rectangle. Defaults to 0.height (
UnionType
[int
,float
]) -- The height of the rectangle. Defaults to 0.color (
Optional
[Color
]) -- The color of the hitbox. Set to None to not show the hitbox. Defaults to None.tag (
str
) -- A string to tag the hitbox. Defaults to "".trigger (
bool
) -- Whether the hitbox is a trigger. Defaults to False.should_collide (
Optional
[Callable
[[Hitbox
,Hitbox
],bool
]]) -- A function to call to determine whether the hitbox should collide with another hitbox. Defaults to lambda self, other: True.on_collide (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_enter (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox enters another hitbox. Defaults to lambda manifold: None.on_exit (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the hitbox from the gameobject. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the hitbox. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the hitbox. Defaults to (1, 1).debug (
bool
) -- Whether to draw the hitbox. Defaults to False.z_index (
int
) -- The z-index of the hitbox. Defaults to 0.hidden (
bool
) -- Whether the hitbox is hidden. Defaults to False.
- property verts: list[rubato.utils.computation.vector.Vector]#
The list of Rectangle vertices. (get-only)
- property top_left#
The top left corner of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property bottom_left#
The bottom left corner of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property top_right#
The top right corner of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property bottom_right#
The bottom right corner of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property top#
The y value of the top side of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- draw(camera)#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- should_collide: Callable[[Hitbox, Hitbox], bool]#
The should_collide function to call to determine whether two hitboxes should collide.
- on_collide: Callable[[Manifold], None]#
The on_collide function to call when a collision happens with this hitbox.
- on_enter: Callable[[Manifold], None]#
The on_enter function to call when collision begins with this hitbox.
- on_exit: Callable[[Manifold], None]#
The on_exit function to call when a collision ends with this hitbox.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- property left#
The x value of the left side of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property bottom#
The y value of the bottom side of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- property right#
The x value of the right side of the AABB surrounding the rectangle. Setting to this value changes the gameobject's position, not the hitbox offset.
- get_aabb()[source]#
Gets bottom left and top right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- true_verts()[source]#
Returns a list of the Rectangle's vertices in world coordinates. Accounts for gameobject position and rotation.
Polygon#
- class Polygon(verts=[], color=None, tag='', trigger=False, should_collide=None, on_collide=None, on_enter=None, on_exit=None, offset=(0, 0), rot_offset=0, z_index=0, scale=(1, 1), debug=False, hidden=False)[source]#
A Polygonal Hitbox component.
Danger
If creating vertices by hand, make sure you generate them in a CLOCKWISE direction. Otherwise, polygons may not behave or draw properly. We recommend using Vector.poly() to generate the vertex list for regular polygons.
Warning
rubato does not currently support concave polygons. Creating concave polygons will result in undesired behavior.
- Parameters:
verts (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The vertices of the polygon. Defaults to [].color (
Optional
[Color
]) -- The color of the hitbox. Set to None to not show the hitbox. Defaults to None.tag (
str
) -- A string to tag the hitbox. Defaults to "".trigger (
bool
) -- Whether the hitbox is a trigger. Defaults to False.should_collide (
Optional
[Callable
[[Hitbox
,Hitbox
],bool
]]) -- A function to call to determine whether the hitbox should collide with another hitbox. Defaults to lambda self, other: True.on_collide (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_enter (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox enters another hitbox. Defaults to lambda manifold: None.on_exit (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the hitbox from the gameobject. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the hitbox. Defaults to 0.z_index (
int
) -- The z-index of the hitbox. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the hitbox. Defaults to (1, 1).debug (
bool
) -- Whether to draw the hitbox. Defaults to False.hidden (
bool
) -- Whether the hitbox is hidden. Defaults to False.
- property verts: list[rubato.utils.computation.vector.Vector]#
A list of the vertices in the Polygon.
- get_aabb()[source]#
Gets bottom left and top right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- true_verts()[source]#
Returns a list of the Polygon's vertices in world coordinates. Accounts for gameobject position and rotation.
- draw(camera)#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- should_collide: Callable[[Hitbox, Hitbox], bool]#
The should_collide function to call to determine whether two hitboxes should collide.
- on_collide: Callable[[Manifold], None]#
The on_collide function to call when a collision happens with this hitbox.
- on_enter: Callable[[Manifold], None]#
The on_enter function to call when collision begins with this hitbox.
- on_exit: Callable[[Manifold], None]#
The on_exit function to call when a collision ends with this hitbox.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
Circle#
- class Circle(radius=0, color=None, tag='', trigger=False, should_collide=None, on_collide=None, on_enter=None, on_exit=None, offset=(0, 0), rot_offset=0, z_index=0, scale=(1, 1), debug=False, hidden=False)[source]#
A Circular Hitbox component.
- Parameters:
radius (
UnionType
[int
,float
]) -- The radius of the circle. Defaults to 0.color (
Optional
[Color
]) -- The color of the hitbox. Set to None to not show the hitbox. Defaults to None.tag (
str
) -- A string to tag the hitbox. Defaults to "".trigger (
bool
) -- Whether the hitbox is a trigger. Defaults to False.should_collide (
Optional
[Callable
[[Hitbox
,Hitbox
],bool
]]) -- A function to call to determine whether the hitbox should collide with another hitbox. Defaults to lambda self, other: True.on_collide (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_enter (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox enters another hitbox. Defaults to lambda manifold: None.on_exit (
Optional
[Callable
[[Manifold
],None
]]) -- A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the hitbox from the gameobject. Defaults to (0, 0).rot_offset (
float
) -- The rotation offset of the hitbox. Defaults to 0.z_index (
int
) -- The z-index of the hitbox. Defaults to 0.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the hitbox. Note that only the largest value will determine the scale. Defaults to (1, 1).debug (
bool
) -- Whether to draw the hitbox. Defaults to False.hidden (
bool
) -- Whether the hitbox is hidden. Defaults to False.
- draw(camera)#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- fixed_update()#
The physics function for a component.
- regen()#
Regenerates internal hitbox information.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- should_collide: Callable[[Hitbox, Hitbox], bool]#
The should_collide function to call to determine whether two hitboxes should collide.
- on_collide: Callable[[Manifold], None]#
The on_collide function to call when a collision happens with this hitbox.
- on_enter: Callable[[Manifold], None]#
The on_enter function to call when collision begins with this hitbox.
- on_exit: Callable[[Manifold], None]#
The on_exit function to call when a collision ends with this hitbox.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- property center: Vector#
The center of the circle. Equivalent to true_pos. Setting to this will change the Gameobject position.
- Return type:
- get_aabb()[source]#
Gets bottom left and top right corners of the axis-aligned bounding box of the hitbox in world coordinates.
Manifold#
RigidBody#
The Rigidbody component describes how the physics engine handles a game object.
- class RigidBody(mass=1, gravity=(0, 0), friction=0, static=False, bounciness=0, max_speed=(Math.INF, Math.INF), velocity=(0, 0), ang_vel=0, pos_correction=0.25, offset=(0, 0), rot_offset=0, z_index=0)[source]#
A RigidBody implementation with built in physics and collisions. Rigidbodies require hitboxes.
- Parameters:
mass (
float
) -- The mass of the rigidbody. Defaults to -1.gravity (
UnionType
[Vector
,tuple
[float
,float
]]) -- The gravity of the rigidbody. Defaults to (0, 0).friction (
float
) -- The friction of the rigidbody. Defaults to 0.static (
bool
) -- Whether the rigidbody is static. Defaults to False.bounciness (
float
) -- The bounciness of the rigidbody. Defaults to 0.max_speed (
UnionType
[Vector
,tuple
[float
,float
]]) -- The maximum speed of the rigidbody. Defaults to (INF, INF).velocity (
UnionType
[Vector
,tuple
[float
,float
]]) -- The velocity of the rigidbody. Defaults to (0, 0).ang_vel (
float
) -- The angular velocity of the rigidbody. Defaults to 0.pos_correction (
float
) -- The positional correction of the rigidbody. Defaults to 0.25.offset (
UnionType
[Vector
,tuple
[float
,float
]]) -- The offset of the rigidbody from the gameobject. Defaults to (0, 0).rot_offset (
float
) -- The offset of the rigidbody's rotation from the gameobject. Defaults to 0.z_index (
int
) -- The z-index of the rigidbody. Defaults to 0.
- draw(camera)#
The draw function for a component.
- Parameters:
camera (
Camera
) -- The camera to draw the component with.
- setup()#
The setup function for a component.
- true_rotation()#
Returns the rotation of the component offset by its parent gameobject rotation.
- Return type:
- true_z()#
Returns the z_index of the component offset by its parent gameobject z_index.
- Return type:
- update()#
The update function for a component.
- gameobj: GameObject#
The game object this component is attached to.
Whether the component is hidden (not drawn).
- add_cont_force(force, time)[source]#
Add a continuous force to the Rigidbody. A continuous force is a force that is continuously applied over a time period. (the force is added every frame for a specific duration).
Hardware Interaction#
All of these static classes let you interact with the hardware. Either by checking for user input, drawing to the screen or playing a sound.
Display#
Static class that allows for intuitive window management.
- class Display[source]#
A static class that houses all of the display information
- window#
The pysdl2 window element.
- Type:
sdl2.Window
- renderer#
The pysdl2 renderer element.
- Type:
sdl2.Renderer
- format#
The pysdl2 pixel format element.
- Type:
sdl2.PixelFormat
- window_size#
The pixel size of the physical window.
Warning
Using this value to determine the placement of your game objects may lead to unexpected results. You should instead use
Display.res
- Type:
- res#
The pixel resolution of the game. This is the number of virtual pixels on the window.
Example
The window (
Display.window_size
) could be rendered at 500x500 while the resolution is at 1000x1000. This would mean that you can place game objects at 900, 900 and still see them despite the window not being 900 pixels tall.Warning
While this value can be changed, it is recommended that you do not alter it after initialization as it will scale your entire project in unexpected ways. If you wish to achieve scaling across an entire scene, simply utilize the
camera zoom
property in your scene's camera.- Type:
Whether the window is currently hidden.
- Type:
- class property display_ratio: Vector#
The ratio of the renderer resolution to the window size. This is a read-only property.
- Returns:
The ratio of the renderer resolution to the window size seperated by x and y.
- Return type:
- class property border_size: int#
The size of the black border on either side of the drawing area when the aspect ratios don't match.
- Return type:
- classmethod has_x_border()[source]#
Whether the window has a black border on the left or right side.
- Return type:
- classmethod has_y_border()[source]#
Whether the window has a black border on the top or bottom.
- Return type:
- classmethod set_window_icon(path)[source]#
Set the icon of the window.
- Parameters:
path (
str
) -- The path to the icon.
- classmethod set_fullscreen(on=True)[source]#
Set the window to fullscreen.
- Parameters:
on (
bool
) -- Whether to set the window to fullscreen.
- classmethod get_window_border_size()[source]#
Get the size of the window border. pixels on the top sides and bottom of the window.
- Returns:
The size of the window border.
- classmethod save_screenshot(filename, path='./', extension='png', save_to_temp_path=False, quality=100)[source]#
Save the current screen to a file.
- Parameters:
filename (
str
) -- The name of the file to save to.path (
str
) -- Path to output folder.extension (
str
) -- The extension to save the file as. (png, jpg, bmp supported)save_to_temp_path (
bool
) -- Whether to save the file to a temporary path (i.e. MEIPASS used in exe).quality (
int
) -- The quality of the jpg 0-100 (only used for jpgs).
- Return type:
- Returns:
If save was successful.
Input#
An abstraction for checking for hardware input from a user.
- class Input[source]#
The input class, handling keyboard, mouse, and controller functionality.
Go here for a list of all the available keys.
- classmethod controllers()[source]#
A list of the controllers currently registered.
If non-zero, the controllers are registered from 0 to n-1 where n is the number of controllers. This number index is passed to events that are propagated when controllers are inputted to.
- classmethod controller_name(controller)[source]#
Get the name of the controller at the given index.
- Parameters:
index -- The index of the controller to get the name of.
- Raises:
IndexError -- The controller for the given index is not registered.
- Return type:
- Returns:
The name of the controller.
- classmethod controller_axis(controller, axis)[source]#
Get the value of a given joystick axis on a controller.
- Parameters:
- Raises:
IndexError -- The controller for the given index is not registered.
- Return type:
- Returns:
The value of the axis.
- classmethod axis_centered(val)[source]#
Check whether a given axis value is within the +/-10% bounds of deadzone considered the "center".
- classmethod controller_button(controller, button)[source]#
Check whether a given button on a controller is pressed.
- Parameters:
- Raises:
IndexError -- The controller for the given index is not registered.
- Return type:
- Returns:
Whether the button is pressed.
- classmethod controller_hat(controller, hat)[source]#
Get the value of a given hat on a controller.
- Parameters:
- Raises:
IndexError -- The controller for the given index is not registered.
- Returns:
The value of the hat, which you can translate with translate_hat().
- Return type:
- classmethod key_pressed(*keys)[source]#
Checks if keys are pressed. Case insensitive.
- Parameters:
*keys -- The names of the keys to check.
- Returns:
Whether the keys are pressed.
- Return type:
Example
if rb.Input.key_pressed("a"): # handle the "a" keypress if rb.Input.key_pressed("shift", "w"): # handle the "shift+w" keypress
- classmethod window_focused()[source]#
Checks if the display has keyboard focus.
- Returns:
True if the window is focused, false otherwise.
- Return type:
- classmethod mouse_pressed()[source]#
Checks if any mouse button is pressed.
- Return type:
- Returns:
True if any button is pressed, false otherwise.
- classmethod get_mouse_pos()[source]#
The current position of the mouse, in screen-coordinates.
- Return type:
- Returns:
A Vector representing position.
- static get_mouse_abs_pos()[source]#
The current absolute position of the mouse, in display coordinates.
- Return type:
- Returns:
A Vector representing position.
- classmethod mouse_is_visible()[source]#
Checks if the mouse is currently visible.
- Returns:
True for visible, false otherwise.
- Return type:
- classmethod set_mouse_visibility(toggle)[source]#
Sets the mouse visibility.
- Parameters:
toggle (
bool
) -- True to show the mouse and false to hide the mouse.
Sound#
A multi-channel sound system for rubato.
- class Sound(path, sound_name='')[source]#
- Used to play sounds in rubato. The following file formats are supported:
MP3
WAV
OGG
FLAC
MOD
MIDI (not always available on linux)
OPUS
AIFF
VOC
- Parameters:
- loaded_sounds: dict[str, rubato.utils.hardware.sound.Sound] = {}#
A dictionary housing all the loaded sounds, stored by their name.
- active_channels: dict[int, rubato.utils.hardware.sound.Sound] = {}#
A dictionary housing all the active sounds, stored by their name.
- property state: int#
The current state of the sound.
The possible states are:
Sound.STOPPED Sound.PLAYING Sound.PAUSED
- Returns:
The current state of the sound.
- Return type:
- set_volume(volume)[source]#
Sets the volume of the sound.
- Parameters:
volume (
int
) -- The volume of the sound. range(0, MIX_MAX_VOLUME=>128)
- get_volume()[source]#
Gets the volume of the sound.
- Return type:
- Returns:
The volume of the sound. range(0, MIX_MAX_VOLUME=>128)
- classmethod import_sound_folder(path, duplicate_names=False, recursive=True)[source]#
Imports a folder of sounds, saving each one in the loaded_sounds dictionary by filename.
- Parameters:
path (
str
) -- The relative path to the folder you wish to import.duplicate_names -- if you wish to have duplicate names to your sounds,
name (it will use the relative and the sound path for the sounds) --
recursive (
bool
) -- Whether it will import an animation shallowly or recursively. Defaults to True.
Utilities#
These classes are utility classes that are used to make certain tasks easier.
Surface#
An abstraction for a grid of pixels that can be drawn onto.
- class Surface(width=32, height=32, scale=(1, 1), rotation=0, af=False)[source]#
A grid of pixels that can be modified without being attached to a game object.
- Parameters:
width (
int
) -- The width of the surface in pixels. Once set this cannot be changed. Defaults to 32.height (
int
) -- The height of the surface in pixels. Once set this cannot be changed. Defaults to 32.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the surface. Defaults to (1, 1).rotation (
float
) -- The clockwise rotation of the sprite.af (
bool
) -- Whether to use anisotropic filtering. Defaults to False.
- uptodate: bool#
Whether the texture is up to date with the surface. Can be set to False to trigger a texture regeneration at the next draw cycle.
- property af#
Whether to use anisotropic filtering.
- size_scaled()[source]#
Gets the current size of the Surface. (Scaled)
- Return type:
- Returns:
The size of the Surface
- size()[source]#
Gets the current size of the Surface. (Unscaled)
- Return type:
- Returns:
The size of the Surface
- blit(other, src_rect=None, dst=(0, 0))[source]#
Blits (merges / copies) another Surface onto this one.
- Parameters:
other (
Surface
) -- The Surface to blit onto this one.src_rect (
Optional
[tuple
[int
,int
,int
,int
]]) -- The area (center_x, center_y, width, height) to crop from the source surface (other). Defaults to the whole surface.dst (
UnionType
[Vector
,tuple
[int
,int
]]) -- The position to place the other surface. Defaults to (0, 0).
Note
Will not stretch the other surface to fit the destination rectangle.
- fill(color)[source]#
Fill the surface with a color.
- Parameters:
color (
Color
) -- The color to fill with.
- draw_line(start, end, color=Color.black, aa=False, thickness=1, blending=True)[source]#
Draws a line on the surface.
- Parameters:
start (
UnionType
[Vector
,tuple
[float
,float
]]) -- The start of the line.end (
UnionType
[Vector
,tuple
[float
,float
]]) -- The end of the line.color (
Color
) -- The color of the line. Defaults to black.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.thickness (
int
) -- The thickness of the line. Defaults to 1.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_rect(center, dims, border=None, border_thickness=1, fill=None, blending=True)[source]#
Draws a rectangle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The top left corner of the rectangle.dims (
UnionType
[Vector
,tuple
[float
,float
]]) -- The dimensions of the rectangle.border (
Optional
[Color
]) -- The border color of the rectangle. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the rectangle. Set to None for no fill. Defaults to None.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_circle(center, radius, border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a circle on the surface.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the circle.radius (
int
) -- The radius of the circle.border (
Optional
[Color
]) -- The border color of the circle. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the circle. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- draw_poly(points, center=(0, 0), border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a polygon on the surface.
- Parameters:
points (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The points of the polygon.center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the polygon.border (
Optional
[Color
]) -- The border color of the polygon. Defaults to None.border_thickness (
int
) -- The thickness of the border. Defaults to 1.fill (
Optional
[Color
]) -- The fill color of the polygon. Set to None for no fill. Defaults to None.aa (
bool
) -- Whether to use anti-aliasing. Defaults to False.blending (
bool
) -- Whether to use blending. Defaults to False.
- set_colorkey(color)[source]#
Sets the colorkey of the surface.
- Parameters:
color (
Color
) -- Color to set as the colorkey.
- set_alpha(new)[source]#
Sets surface wide alpha.
- Parameters:
new (
int
) -- The new alpha. (value between 0-255)
- save_as(filename, path='./', extension='png', save_to_temp_path=False, quality=100)[source]#
Save the surface to a file.
- Parameters:
filename (
str
) -- The name of the file to save to.path (
str
) -- Path to output folder.extension (
str
) -- The extension to save the file as. (png, jpg, bmp supported)save_to_temp_path (
bool
) -- Whether to save the file to a temporary path (i.e. MEIPASS used in exe).quality (
int
) -- The quality of the jpg 0-100 (only used for jpgs).
- Return type:
- Returns:
If save was successful.
Draw#
A static class for drawing things directly to the window.
- class Draw[source]#
A static class allowing drawing items to the window.
- classmethod clear(background_color=Color.white, border_color=Color.black)[source]#
Clears the screen and draws a background.
- classmethod queue_pixel(pos, color=Color.cyan, z_index=0, camera=None)[source]#
Draw a point onto the renderer at the end of the frame.
- classmethod pixel(pos, color=Color.cyan, camera=None)[source]#
Draw a point onto the renderer immediately.
- classmethod queue_line(p1, p2, color=Color.cyan, width=1, z_index=0, camera=None)[source]#
Draw a line onto the renderer at the end of the frame.
- Parameters:
p1 (
UnionType
[Vector
,tuple
[float
,float
]]) -- The first point of the line.p2 (
UnionType
[Vector
,tuple
[float
,float
]]) -- The second point of the line.color (
Color
) -- The color to use for the line. Defaults to Color.cyan.width (
UnionType
[int
,float
]) -- The width of the line. Defaults to 1.z_index (
int
) -- Where to draw it in the drawing order. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- static line(p1, p2, color=Color.cyan, width=1, camera=None)[source]#
Draw a line onto the renderer immediately.
- Parameters:
p1 (
UnionType
[Vector
,tuple
[float
,float
]]) -- The first point of the line.p2 (
UnionType
[Vector
,tuple
[float
,float
]]) -- The second point of the line.color (
Color
) -- The color to use for the line. Defaults to Color.cyan.width (
UnionType
[int
,float
]) -- The width of the line. Defaults to 1.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod queue_rect(center, width, height, border=Color.cyan, border_thickness=1, fill=None, angle=0, z_index=0, camera=None)[source]#
Draws a rectangle onto the renderer at the end of the frame.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the rectangle.width (
UnionType
[int
,float
]) -- The width of the rectangle.height (
UnionType
[int
,float
]) -- The height of the rectangle.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.angle (
float
) -- The angle in degrees. Defaults to 0.z_index (
int
) -- Where to draw it in the drawing order. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod rect(center, width, height, border=Color.cyan, border_thickness=1, fill=None, angle=0, camera=None)[source]#
Draws a rectangle onto the renderer immediately.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the rectangle.width (
UnionType
[int
,float
]) -- The width of the rectangle.height (
UnionType
[int
,float
]) -- The height of the rectangle.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.angle (
float
) -- The angle in degrees. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- Raises:
ValueError -- If the width and height are not positive.
- classmethod queue_circle(center, radius=4, border=Color.cyan, border_thickness=1, fill=None, z_index=0, camera=None)[source]#
Draws a circle onto the renderer at the end of the frame.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center.radius (
int
) -- The radius. Defaults to 4.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.z_index (
int
) -- Where to draw it in the drawing order. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod circle(center, radius=4, border=Color.cyan, border_thickness=1, fill=None, camera=None)[source]#
Draws a circle onto the renderer immediately.
- Parameters:
center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center.radius (
UnionType
[int
,float
]) -- The radius. Defaults to 4.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- Raises:
ValueError -- If the radius is not positive.
- classmethod queue_poly(points, center, border=Color.cyan, border_thickness=1, fill=None, z_index=0, camera=None)[source]#
Draws a polygon onto the renderer at the end of the frame.
- Parameters:
points (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The list of points to draw relative to the center.center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the polygon.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.z_index (
int
) -- Where to draw it in the drawing order. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod poly(points, center, border=Color.cyan, border_thickness=1, fill=None, camera=None)[source]#
Draws a polygon onto the renderer immediately.
- Parameters:
points (
UnionType
[list
[Vector
],list
[tuple
[float
,float
]]]) -- The list of points to draw relative to the center.center (
UnionType
[Vector
,tuple
[float
,float
]]) -- The center of the polygon.border (
Optional
[Color
]) -- The border color. Defaults to Color.cyan.border_thickness (
UnionType
[int
,float
]) -- The border thickness. Defaults to 1.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod queue_text(text, font, pos=(0, 0), justify='left', align=(0, 0), width=0, scale=(1, 1), shadow=False, shadow_pad=(0, 0), af=True, z_index=0, camera=None)[source]#
Draws some text onto the renderer at the end of the frame.
- Parameters:
text (
str
) -- The text to draw.font (
Font
) -- The Font object to use.pos (
UnionType
[Vector
,tuple
[float
,float
]]) -- The top left corner of the text. Defaults to (0, 0).justify (
str
) -- The justification of the text. (left, center, right). Defaults to "left".align (
UnionType
[Vector
,tuple
[float
,float
]]) -- The alignment of the text. Defaults to (0, 0).width (
UnionType
[int
,float
]) -- The maximum width of the text. Will automatically wrap the text. Defaults to -1.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the text. Defaults to (1, 1).shadow (
bool
) -- Whether to draw a basic shadow box behind the text. Defaults to False.shadow_pad (
UnionType
[Vector
,tuple
[float
,float
]]) -- What padding to use for the shadow. Defaults to (0, 0).af (
bool
) -- Whether to use anisotropic filtering. Defaults to True.z_index (
int
) -- Where to draw it in the drawing order. Defaults to 0.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod text(text, font, pos=(0, 0), justify='left', align=(0, 0), width=0, scale=(1, 1), shadow=False, shadow_pad=(0, 0), af=True, camera=None)[source]#
Draws some text onto the renderer immediately.
- Parameters:
text (
str
) -- The text to draw.font (
Font
) -- The Font object to use.pos (
UnionType
[Vector
,tuple
[float
,float
]]) -- The top left corner of the text. Defaults to (0, 0).justify (
str
) -- The justification of the text. (left, center, right). Defaults to "left".align (
UnionType
[Vector
,tuple
[float
,float
]]) -- The alignment of the text. Defaults to (0, 0).width (
UnionType
[int
,float
]) -- The maximum width of the text. Will automatically wrap the text. Defaults to -1.scale (
UnionType
[Vector
,tuple
[float
,float
]]) -- The scale of the text. Defaults to (1, 1).shadow (
bool
) -- Whether to draw a basic shadow box behind the text. Defaults to False.shadow_pad (
UnionType
[Vector
,tuple
[float
,float
]]) -- What padding to use for the shadow. Defaults to (0, 0).af (
bool
) -- Whether to use anisotropic filtering. Defaults to True.camera (
Optional
[Camera
]) -- The camera to use. Defaults to None.
- classmethod queue_surface(surface, pos=(0, 0), z_index=0, camera=None)[source]#
Draws an surface onto the renderer at the end of the frame.
- classmethod surface(surface, pos=(0, 0), camera=None)[source]#
Draws an surface onto the renderer immediately.
- classmethod clear_cache()[source]#
Clears the draw cache.
Generally, you shouldn't need to call this method, but it can help free up memory if you're running low; the true best way to avoid this though is to rely on surfaces for shapes that change/recolor often, and call the draw surface method directly instead of the draw shape methods.
Vector#
An abstraction for a container of x and y values.
- class Vector(x=0, y=0)[source]#
A Vector object that defines a 2D point in space
- Parameters:
- property rationalized_mag: str#
Returns a string representation of a rationalized vector magnitude as you would use in math class.
Example
>>> Vector(8, 8).rationalized_mag 4√8
Warning
Should only be used on vectors with integer components.
- Return type:
- property rationalized_mag_vector: Vector#
Returns a vector with the rationalized magnitude.
Example
>>> Vector(8, 8).rationalized_mag rubato.Vector(4, 8)
Warning
Should only be used on vectors with integer components.
- Return type:
- property rationalized_unit: str#
Returns a string representation of a rationalized unit vector as you would use in math class.
Warning
Should only be used on vectors with integer components.
- Return type:
- perpendicular(scalar=1, out=None)[source]#
Computes a scaled 90 degree clockwise rotation on a given vector.
- Parameters:
- Return type:
- Returns:
The resultant vector when transformed.
- clamp(lower, upper, absolute=False, out=None)[source]#
Clamps x and y between the two values given.
- Parameters:
lower (
UnionType
[Vector
,float
,int
]) -- The lower bound. If a vector is specified, its x coord is used to clamp the x coordinate and same for y.upper (
UnionType
[Vector
,float
,int
]) -- The upper bound. If a vector is specified, its x coord is used to clamp the x coordinate and same for y.absolute (
bool
) -- Whether to clamp the absolute value of the vector instead of the actual value. Defaults to False.out (
Optional
[Vector
]) -- The output vector to set to. Defaults to a new vector. If you want the function to act on itself, set this value to the reference of the vector.
- rotate(angle, out=None)[source]#
Rotates the vector by a given number of degrees.
- Parameters:
- Return type:
- Returns:
The resultant Vector.
- lerp(target, t, out=None)[source]#
Lerps the current vector to target by a factor of t.
- Parameters:
- Return type:
- Returns:
The resulting vector.
- round(decimal_places=0, out=None)[source]#
Returns a new vector with the coordinates rounded.
- Parameters:
- Returns:
The resultant Vector.
- Return type:
- within(other, distance)[source]#
Checks if the vector is within a certain distance of another vector (or tuple of floats).
- static from_radial(magnitude, angle)[source]#
Generates a Vector from the given angle and magnitude.
- static clamp_magnitude(vector, max_magnitude, min_magnitude=0)[source]#
Clamps the magnitude of the vector to the given range.
- Parameters:
- Return type:
- Returns:
A new vector with the magnitude clamped to the given range.
- classmethod rand_unit_vector()[source]#
Returns a random unit vector inside the unit circle.
- Return type:
- Returns:
Random vector inside the unit circle.
- classmethod poly(num_sides, radius=1)[source]#
Returns a list of vectors representing a polygon with the given number of sides and radius.
Math#
The math module includes some helper functions for commonly used equations.
- class Math[source]#
Adds additonal functionality to the math module that is commonly used in game development.
- classmethod map(variable, variable_lower, variable_upper, map_lower, map_upper)[source]#
Maps the variable from its range defined by lower and upper to a new range defined by map_lower and map_upper.
- Parameters:
variable -- The variable to map.
variable_lower -- The lower bound of the variable.
variable_upper -- The upper bound of the variable.
map_lower -- The lower bound of the new range.
map_upper -- The upper bound of the new range.
- Returns:
The mapped value.
- Return type:
- static is_int(x, error=0)[source]#
Checks if a float can be rounded to an integer without dropping decimal places (within a certain error).
- static simplify_sqrt(square_rooted)[source]#
Simplifies a square root.
- Parameters:
square_rooted (
int
) -- The sqrt to simplify (inside the sqrt).- Return type:
- Returns:
The simplified square root, (multiple, square rooted).
Example
Will try to simplify radicals.
>>> Math.simplify_sqrt(16) # √16 = 4√1 (4, 1) >>> Math.simplify_sqrt(26) # √26 = 1√26 (1, 26) >>> Math.simplify_sqrt(20) # √20 = 2√5
- static gen_primes()[source]#
Generate an infinite sequence of prime numbers. A python generator ie. must use next().
Notes
Sieve of Eratosthenes Code by David Eppstein, UC Irvine, 28 Feb 2002 http://code.activestate.com/recipes/117119/
- Returns:
A generator of prime numbers.
- Return type:
generator
Example
>>> generator = Math.gen_primes() >>> next(generator) 2
Noise#
A utility for generating simple smooth noise in your projects.
- class Noise[source]#
A utility for generating simple smooth noise, based on OpenSimplex2.
- seed: int = 0#
The seed for the random noise. Setting to a fixed value will result in the same noise every time.
Time#
A static class to monitor time and to call functions at delay/interval.
- class DelayedTask(task, delay)[source]#
A task that is run after a specified number of seconds.
- Parameters:
- class FramesTask(task, delay)[source]#
A task that is run after a specified number of frames.
- Parameters:
- class RecurrentTask(task, interval, delay=0)[source]#
A task that is run every specified number of seconds.
- Parameters:
- class Time[source]#
Implements time-related functions in rubato.
- fps = 60#
The fps estimate using the last frame.
- target_fps = 0#
The fps that the game should try to run at. 0 means that the game's fps will not be capped. Defaults to 0.
- class property delta_time: float#
The number of seconds between the last frame and the current frame (get-only).
- Return type:
- classmethod frame_start()[source]#
Time from the start of the game to the start of the current frame, in seconds.
- Return type:
- classmethod delayed_frames(task, delay)[source]#
Calls the function func to be called at a later frame.
- classmethod delayed_call(task, delay)[source]#
Calls the function func to be called at a later time.
- classmethod recurrent_call(task, interval, delay=0)[source]#
Schedules the function func to be repeatedly called every interval.
- Parameters:
task (
Union
[Callable
[[],None
],Callable
[[RecurrentTask
],None
]]) -- The function to call. This method may take a RecurrentTask as an argument, which will be passed to it when it is invoked.interval (
float
) -- The interval (in seconds) to run the function at.delay (
float
) -- The delay (in seconds) to wait before starting the task.
- classmethod schedule(task)[source]#
Schedules a task for execution based on what type of task it is.
- Parameters:
task (
UnionType
[DelayedTask
,FramesTask
,RecurrentTask
]) -- The task to queue.
Color#
The representation for colors in rubato.
- class Color(r=0, g=0, b=0, a=255)[source]#
An RGBA color. Note that although the constructor accepts both integers and floats of any value, they are clamped to the range 0 to 255 and int-cast.
- Parameters:
- darker(amount=20)[source]#
Returns a darker copy of the color. It subtracts
amount
from the RGB values.
- mix(other, t=0.5, mode='mix')[source]#
Mix two colors together.
- Parameters:
other (
Color
) -- The other color.t (
float
) -- The interpolation amount (0 to 1). Defaults to 0.5.mode (
str
) -- The blending mode ("linear", "mix", "blend"). Linear is the linear interpolation between the two colors. Mix and Blend are 2 different algorithms to mix colors. They tend to look better then linear. Defaults to "mix".
- Returns:
The resultant color.
- Return type:
- to_hex()[source]#
Converts the Color to a hexadecimal string.
- Returns:
The hexadecimal output in lowercase. (i.e. ffffffff)
- Return type:
- class property black: Color[source]#
The default black color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property white: Color[source]#
The default white color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property night: Color[source]#
The default night color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property darkgray: Color[source]#
The default darkgray color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property gray: Color[source]#
The default gray color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property lightgray: Color[source]#
The default lightgray color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property snow: Color[source]#
The default snow color. To see the RGB values, check out the Grayscale defaults.
- Return type:
- class property yellow: Color[source]#
The default yellow color. To see the RGB values, check out the Color defaults.
- Return type:
- class property orange: Color[source]#
The default orange color. To see the RGB values, check out the Color defaults.
- Return type:
- class property red: Color[source]#
The default red color. To see the RGB values, check out the Color defaults.
- Return type:
- class property scarlet: Color[source]#
The default scarlet color. To see the RGB values, check out the Color defaults.
- Return type:
- class property magenta: Color[source]#
The default magenta color. To see the RGB values, check out the Color defaults.
- Return type:
- class property purple: Color[source]#
The default purple color. To see the RGB values, check out the Color defaults.
- Return type:
- class property violet: Color[source]#
The default violet color. To see the RGB values, check out the Color defaults.
- Return type:
- class property blue: Color[source]#
The default blue color. To see the RGB values, check out the Color defaults.
- Return type:
- class property cyan: Color[source]#
The default cyan color. To see the RGB values, check out the Color defaults.
- Return type:
- class property turquoize: Color[source]#
The default turquoize color. To see the RGB values, check out the Color defaults.
- Return type:
- class property green: Color[source]#
The default green color. To see the RGB values, check out the Color defaults.
- Return type:
- class property lime: Color[source]#
The default lime color. To see the RGB values, check out the Color defaults.
- Return type:
Default Colors#
_color_defaults = {
"yellow": (253, 203, 110),
"scarlet": (214, 48, 49),
"violet": (108, 92, 231),
"turquoize": (0, 206, 201),
"orange": (225, 112, 85),
"magenta": (232, 67, 147),
"blue": (9, 132, 227),
"green": (0, 184, 148),
"red": (255, 118, 117),
"purple": (162, 155, 254),
"cyan": (116, 185, 255),
"lime": (85, 239, 196),
# colorwheel used (rgb values are not identical):
# https://upload.wikimedia.org/wikipedia/commons/5/54/RGV_color_wheel_1908.png
}
Default Grayscale Colors#
_grayscale_defaults = {
"black": (0, 0, 0),
"white": (255, 255, 255),
"night": (20, 20, 22),
"darkgray": (45, 52, 54),
"gray": (99, 110, 114),
"lightgray": (178, 190, 195),
"snow": (223, 230, 233),
}
Font#
A font abstraction used to render text.
- class Font(font='Roboto', size=16, styles=0, color=Color(0, 0, 0))[source]#
This is the font object that is used to render text.
- Parameters:
font (
Union
[str
,Literal
['Comfortaa', 'Fredoka', 'Merriweather', 'Roboto', 'SourceCodePro', 'Mozart']]) -- The font to use. Can also be a path to a font file. Defaults to Roboto. Included fonts are "Comfortaa", "Fredoka", "Merriweather", "Roboto", "SourceCodePro", "Mozart"size (
int
) -- The size of the font in pixels. Defaults to 16.styles (
int
) -- The styles to apply to the font. Set multiple styles by | them together. Defaults to 0. These are the values you can use: Font.BOLD, Font.ITALIC, Font.UNDERLINE, Font.STRIKETHROUGH.color (
Color
) -- The color of the font. Defaults to Color(0, 0, 0).
- add_style(*styles)[source]#
Adds a style to the font. Style can be one of the following: Font.BOLD, Font.ITALIC, Font.UNDERLINE, Font.STRIKETHROUGH.
- Parameters:
style -- The style to add.
Radio#
The Radio module is a system used to communicate to all parts of the game. This is similar to event systems in other game engines.
To use this, first you need to listen for a specific key using the
Radio.listen()
function. Then from anywhere else in the code, you can
broadcast that event key using Radio.broadcast()
.
Go here to see all the events that can be broadcast.
- class Radio[source]#
Broadcast system manages all events and inter-class communication. Handles event callbacks during the beginning of each
Game.update()
call.- listeners: dict[str, list[rubato.utils.radio.radio.Listener]] = {}#
A dictionary with all of the active listeners.
- class Listener(event, callback)[source]#
The actual listener object itself. A backend class for the Radio.
- Parameters:
- registered: bint = None#
Describes whether the listener is registered
- remove()[source]#
Removes itself from the radio register.
- Raises:
ValueError -- Raises error when listener is not registered
Events#
These events are broadcast by rubato and can be listened to with
rb.Radio.listen()
. Here is an example of how you can listen for a
key down event:
def listener(data: rb.KeyResponse):
if data.key == "a":
print("You pressed the 'a' key!")
rb.Radio.listen(rb.Events.KEYDOWN, listener)
- enum Events(value)[source]#
Describes all rubato-fired events that can be listened for.
Valid values are as follows:
- KEYUP = <Events.KEYUP: 'KEYUP'>#
Fired when a key is released. Responds with a
KeyResponse
object.
- KEYDOWN = <Events.KEYDOWN: 'KEYDOWN'>#
Fired when a key is pressed. Responds with a
KeyResponse
object.
- KEYHOLD = <Events.KEYHOLD: 'KEYHOLD'>#
Fired when a key is held down (After the initial keydown). Responds with a
KeyResponse
object.
- MOUSEUP = <Events.MOUSEUP: 'MOUSEUP'>#
Fired when a mouse button is released. Responds with a
MouseButtonResponse
object.
- MOUSEDOWN = <Events.MOUSEDOWN: 'MOUSEDOWN'>#
Fired when a mouse button is pressed. Responds with a
MouseButtonResponse
object.
- MOUSEWHEEL = <Events.MOUSEWHEEL: 'MOUSEWHEEL'>#
Fired when the mouse wheel is scrolled. Responds with a
MouseWheelResponse
object.
- MOUSEMOTION = <Events.MOUSEMOTION: 'MOUSEMOTION'>#
Fired when the mouse is moved. Responds with a
MouseMotionResponse
object.
- JOYSTICKCONNECT = <Events.JOYSTICKCONNECT: 'JOYSTICKCONNECT'>#
Fired when a controller joystick is connected. Responds with a
JoystickConnectResponse
object.
- JOYSTICKDISCONNECT = <Events.JOYSTICKDISCONNECT: 'JOYSTICKDISCONNECT'>#
Fired when a controller joystick is disconnected. Responds with a
JoystickDisconnectResponse
object.
- JOYAXISMOTION = <Events.JOYAXISMOTION: 'JOYAXISMOTION'>#
Fired when a controller joystick axis is moved. Responds with a
JoyAxisMotionResponse
object.
- JOYHATMOTION = <Events.JOYHATMOTION: 'JOYHATMOTION'>#
Fired when a controller hat button is changed. Responds with a
JoyHatMotionResponse
object.
- JOYBUTTONDOWN = <Events.JOYBUTTONDOWN: 'JOYBUTTONDOWN'>#
Fired when a controller button is pressed. Responds with a
JoyButtonResponse
object.
- JOYBUTTONUP = <Events.JOYBUTTONUP: 'JOYBUTTONUP'>#
Fired when a controller button is released. Responds with a
JoyButtonResponse
object.
- EXIT = <Events.EXIT: 'EXIT'>#
Fired when the game is exiting. Has no response.
- RESIZE = <Events.RESIZE: 'RESIZE'>#
Fired when the window is resized. Responds with a
ResizeResponse
object.
- class EventResponse(timestamp)[source]#
A response to an event. This class behaves like a dict, but is immutable.
- class KeyResponse(timestamp, key, unicode, code, mods)[source]#
A response to a key event
- class MouseButtonResponse(timestamp, button, x, y, clicks, which)[source]#
A response to a mouse event
- class MouseMotionResponse(timestamp, x, y, dx, dy, which)[source]#
A response to a mouse motion event
- class JoystickDisconnectResponse(timestamp, id)[source]#
A response to a joystick disconnection event
- class JoyAxisMotionResponse(timestamp, controller, axis, value, centered)[source]#
A response to a joystick axis event
- class JoyButtonResponse(timestamp, controller, button)[source]#
A response to a joystick button event
- class JoyHatMotionResponse(timestamp, controller, hat, value, name)[source]#
A response to a joystick hat event
Errors#
Custom errors for rubato.
- exception Error[source]#
A basic rubato Error.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception IdError[source]#
An error that is raised when an invalid ID is used.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception SideError[source]#
An error that is raised when the number of sides is invalid
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception DuplicateComponentError[source]#
An error that is raised when you try to add a component to a game object that already has a component of the same type
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception ComponentNotAllowed[source]#
An error that is raised when you try to add a component on a game object that is not allowed by another component on that game object.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception ImplementationError[source]#
An error that is raised when you incorrectly implement something in rubato.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception PrintError[source]#
An error that is raised when you try to print something, and are checking for it with Debug.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception InitError(classObject)[source]#
An error that is raised when you try to initialize a static class.
- Parameters:
classObject (
object
) -- The static class.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- exception RemovedError[source]#
An error that is raised when you try to use a removed function.
- with_traceback()#
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- deprecated(deprecated_ver, removal_ver='', other_func=None)[source]#
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
- Parameters:
deprecated_ver (
str
) -- The version that the function was deprecated in (without the v, i.e. "1.0.0").removal_ver (
str
) -- The version that the function will be removed in (without the v, i.e. "1.0.0"). Use an empty string if there are no removal plans yet. Defaults to "".other_func (
Optional
[Callable
]) -- The function that replaces the deprecated function. Defaults to None.
Miscellaneous#
Miscellaneous helper functions for rubato developers.
- world_mouse()[source]#
Returns the mouse position in world-coordinates.
- Returns:
The mouse position in world coordinates.
- Return type:
- wrap(comp, pos=(0, 0), rotation=0, z_index=0, ignore_cam=False, parent=None, name='', debug=False, active=True, hidden=False)[source]#
Wraps a component or list of components in a GameObject.
- Parameters:
comp (
Union
[Component
,Sequence
[Component
]]) -- The component or list of components to wrap.pos (
UnionType
[Vector
,tuple
[float
,float
]]) -- The position of the GameObject. Defaults to (0, 0).rotation (
float
) -- The rotation of the GameObject. Defaults to 0.z_index (
int
) -- The z_index of the GameObject. Defaults to 0.ignore_cam (
bool
) -- Whether the GameObject ignores the scene's camera when drawing or not. Defaults to False.parent (
Optional
[GameObject
]) -- The parent GameObject of the GameObject. Defaults to None.name (
str
) -- The name of the GameObject. Defaults to "".debug (
bool
) -- Whether the GameObject is in debug mode. Defaults to False.active (
bool
) -- Whether the GameObject is active. Defaults to True.hidden (
bool
) -- Whether the GameObject is hidden. Defaults to False.
- Raises:
TypeError -- If comp is not a Component or a list of Components.
- Returns:
The wrapped GameObject.