Full API Documentation#
This page describes all user-accessible API components to the rubato project.
- init(name='Untitled Rubato App', res=Vector(1080, 1080), window_size=None, window_pos=None, icon='', fullscreen='off', target_fps=0, physics_fps=Time.physics_fps, hidden=False)[source]#
Initializes rubato.
- Parameters:
name (
str) – The title that appears at the top of the window. Defaults to “Untitled Rubato App”.res (
Vector) – The pixel resolution of the game, cast to int Vector. Defaults to Vector(1080, 1080).window_size (
Optional[Vector]) – 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 (
Optional[Vector]) – 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 (
Literal[‘off’, ‘desktop’, ‘exclusive’]) – Whether the game should be fullscreen. Can be one of “off”, “desktop”, or “exclusive”. Defaults to “off”.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 60.hidden (
bool) – Whether the window should be hidden. CANNOT BE CHANGED AFTER INIT CALL. Defaults to False.
- begin()[source]#
Starts the main game loop.
- Raises:
RuntimeError – rubato has not been initialized before calling.
Game#
The main game module. It controls everything in the game.
- class Game[source]#
The main game class.
- debug: bool = False#
Whether to use debug-mode.
- show_fps: bool = False#
Whether to show fps.
- state: int = 2#
The state of the game. The game states are:
Game.RUNNING Game.STOPPED Game.PAUSED
- class property current: Scene#
The current scene. (getonly)
- 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.
- class property camera: Camera#
A shortcut getter allowing easy access to the current camera. This is a get-only property.
Note
Returns a pointer to the current camera object. This is so you can access/change the current camera properties faster, but you’d still need to use
Game.current.camerato access the camera directly.- Returns:
The current scene’s camera
- Return type:
- classmethod start()[source]#
Starts the main game loop. Called automatically by
rubato.begin().
Scenes and Their Management#
Scenes holds two Groups. It also manages 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.
Groups hold a collection of Game Objects and/or other Groups. Their main purpose is to
further compartmentalize items. For example, items in 2 different groups won’t collide with each other. In this tutorial,
we won’t be using Groups as we don’t need this functionality here.
Scene#
The Scene class which is a collection of groups. It also houses the current scene camera. Scenes are built with a root group that everything is added to.
- class Scene(name=None, background_color=Color.white, border_color=Color.black)[source]#
A scene is a collection of groups.
- 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).
- ui: Group#
The ui elements of this scene. These are drawn on top of everything else and do not interact with the other game objects.
- 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: str#
The name of this scene. Read-only.
- Return type:
str
- add(*items)[source]#
Adds an item to the root group.
- Parameters:
*items – The items to add to the scene.
- add_ui(*items)[source]#
Adds Game Objects as UI to the scene. When a game object is added as a UI, they draw as they normally would, but they don’t collide with other game objects, they draw on top of everything else, and they are unaffected by the camera.
- Parameters:
*items – The items to add to the scene.
- delete(item)[source]#
Removes an item from the root group.
- Parameters:
item (
UnionType[GameObject,Group]) – The item to remove.
- delete_ui(item)[source]#
Removes an item from the ui group.
- Parameters:
item (
GameObject) – The item to remove.
- clone()[source]#
Clones this scene.
Warning
This is a relatively expensive operation as it clones every group in the scene.
- Return type:
- setup()[source]#
The start loop for this scene. It is run before the first frame. Is empty be default and can be overriden.
- draw()[source]#
The draw loop for this scene. It is run once every frame. Is empty by default an can beoverridden.
- update()[source]#
The update loop for this scene. It is run once every frame, before
draw(). Is empty by default an can be overridden.
Camera#
The Camera module handles where things are drawn. A camera can zoom, pan, and travel along the z-index. Items 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.camera.
- class Camera(pos=None, zoom=1, z_index=Math.INF)[source]#
The camera class.
- Parameters:
pos (
Optional[Vector]) – The position of the camera. Defaults to center of Display.zoom (
float) – The zoom of the camera.z_index (
int) – The z-index of the camera.
- z_index: int#
The current z_index of the camera.
- property zoom: float#
The zoom value of the camera.
- Return type:
float
- transform(point)[source]#
World space coordinates to Screen space coordinates.
- Parameters:
point (
Vector) – The point to transform (world space).- Returns:
The translated coordinates.
- Return type:
Group#
Groups contain game objects or other groups and allow separation between game objects.
- class Group(name='', active=True)[source]#
The group class implementation.
- Parameters:
name (
str) – The name of the group. Defaults to “” and is set to “Group #” when it is added to another Group or Scene.active (
bool) – Whether the group is active or not. Defaults to True.
- name: str#
The name of the group.
- active: bool#
Whether the group is active or not.
- groups: list[rubato.struct.group.Group]#
A list of groups that are children of this group.
- game_objects: list[rubato.struct.gameobject.game_object.GameObject]#
A list of game objects that are children of this group.
- add(*items)[source]#
Adds an item to the group.
- Parameters:
items (
UnionType[GameObject,Group]) – The item(s) you wish to add to the group- Raises:
Error – The item being added is already in the group.
ValueError – The group can only hold game objects or other groups.
- Returns:
This group.
- Return type:
- delete(item)[source]#
Removes an item from the group.
- Parameters:
item (
UnionType[GameObject,Group]) – The item to remove from the group.
Note
The actually game object is not deleted, just removed from the group.
- Raises:
ValueError – The item is not in the group and cannot be deleted.
- fixed_update()[source]#
Runs a physics iteration on the group. Called automatically by rubato as long as the group is added to a scene.
- all_gameobjects(include_self=False)[source]#
Returns a list of all game objects in the group and all of its children.
- Parameters:
include_self (
bool, optional) – Whether to include this group’s direct children. Defaults to False.- Returns:
The resultant list.
- Return type:
list[GameObject]
- count()[source]#
Counts all the GameObjects and subgroups in this group. :returns: The total number of GameObjects and subgroups contained in this group. :rtype: int
- clone()[source]#
Clones the group and all of its children.
Warning
This is a relatively expensive operation as it clones every game object and component in the group.
- Return type:
- contains(other)[source]#
Checks if the group contains the given object.
- Parameters:
other (
UnionType[GameObject,Group]) – The object to check for.- Returns:
Whether the group contains the object or not.
- Return type:
bool
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 that holds components, postion, and z_index.
- class GameObject(name='', pos=Vector(), rotation=0, z_index=0, debug=False)[source]#
The base game object class.
- Parameters:
name (
str) – The name of the game object. Defaults to “”.pos (
Vector) – The position of the game object. Defaults to Vector(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.debug (
bool) – Whether to draw the center of the game object. Defaults to False.
- name: str#
“Game Object {number in group}”
- Type:
The name of the game object. Will default to
- debug: bool#
Whether to draw a debug crosshair for the game object.
- z_index: int#
The z_index of the game object.
- rotation: float#
The rotation of the game object in degrees.
- 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 on the game object.
- Returns:
This GameObject.
- Return type:
- remove(comp_type)[source]#
Removes a component from the game object.
- Parameters:
comp_type (
Type[TypeVar(T)]) – The type of the component to remove.- Raises:
Warning – 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[TypeVar(T)]) – The type of the component to remove.- Raises:
Warning – The components were not in the game object and nothing was removed.
- get(comp_type)[source]#
Gets a component from the game object.
- Parameters:
comp_type (
Type[TypeVar(T)]) – The type of the component to search for.- Return type:
Optional[TypeVar(T)]- Returns:
The component if it was found or None if it wasn’t.
- get_all(comp_type)[source]#
Gets all the components of a type from the game object.
- Parameters:
comp_type (
Type[TypeVar(T)]) – The type of component to search for.- Return type:
list[TypeVar(T)]- Returns:
- A list containing all the components of that type. If no components were found, the
list is empty.
- delete()[source]#
Deletes and frees everything from the game object. This is called when you remove it from a group or scene.
Warning
Calling this will render the gameobject useless in the future.
Components#
The default Component class.
The component module that represents the template for all components.
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=Vector(), rot_offset=0, z_index=0)[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 (
Vector) – The offset of the component from the game object. Defaults to Vector(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.
- gameobj: rubato.struct.gameobject.game_object.GameObject | None#
The game object this component is attached to.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
Image#
- class Image(rel_path='', scale=Vector(1, 1), offset=Vector(0, 0), rot_offset=0, af=False, z_index=0)[source]#
A component that handles Images.
- Parameters:
rel_path (
str) – The relative path to the image. Defaults to “”.scale (
Vector) – The scale of the image. Defaults to Vector(1, 1).offset (
Vector) – The offset of the image from the gameobject. Defaults to Vector(0, 0).rot_offset (
float) – The rotation offset of the image. Defaults to 0.af (
bool) – Whether to use anisotropic filtering. Defaults to False.z_index (
int) – The z-index of the image. Defaults to 0.
- property af: bool#
Whether to use anisotropic filtering.
- Return type:
bool
- delete()#
Deletes the raster component
- draw(camera)#
The draw function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- 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 raster.
- Return type:
- Returns:
The size of the raster
- merge(other)#
Merges the surface of another component into this one.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
Raster#
- class Raster(width=32, height=32, scale=Vector(1, 1), offset=Vector(0, 0), rot_offset=0, af=False, z_index=0)[source]#
A raster is a component that contains a image.
- draw_line(start, end, color=Color.black, aa=False, thickness=1, blending=True)[source]#
Draws a line on the image.
- Parameters:
start (
Vector) – The start of the line.end (
Vector) – 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_circle(center, radius, border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a circle on the image.
- Parameters:
center (
Vector) – 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, border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a polygon on the image.
- Parameters:
points (
list[Vector]) – The points 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 image.
- Return type:
- Returns:
The size of the surface
- get_pixel_tuple(pos)[source]#
Gets the color of a pixel on the image.
- Parameters:
pos (
Vector) – The position of the pixel.- Return type:
tuple[int,int,int,int]- Returns:
The color of the pixel.
- set_colorkey(color)[source]#
Sets the colorkey of the image. :type color:
Color:param color: Color to set as the colorkey.
- property af: bool#
Whether to use anisotropic filtering.
- Return type:
bool
- delete()#
Deletes the raster component
- draw(camera)#
The draw function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- get_rect()#
Generates the rectangular bounding box of the raster.
- Return type:
- Returns:
The Rectangle hitbox that bounds the raster.
- merge(other)#
Merges the surface of another component into this one.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
Text#
A text component.
- class Text(text='', font=Font(), justify='left', anchor=Vector(0, 0), width=0, offset=Vector(), rot_offset=0, z_index=0)[source]#
A text component subclass. Add this to game objects or UI elements to give them 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 (
Vector) – 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.offset (
Vector) – 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.
- property text: str#
The text of the Text.
- Return type:
str
- property justify: str#
The justification of the text.
Can be one of:
"left","center","right".- Return type:
str
- property 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.Warning
Previously was called align.
- Return type:
- property width: int#
The maximum width of the text. Will automatically wrap the text. Use -1 to disable wrapping.
- Return type:
int
- property font_size: int#
The font size.
Warning
Don’t set this too high or font smoothing may misbehave on some systems.
- Return type:
int
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
Slider#
A slider component that can be used in UI.
- class Slider(button_width=10, button_height=10, slider_length=10, slider_direction=Vector(0, -1), onclick=None, onrelease=None, onhover=None, onexit=None, offset=Vector(), rot_offset=0, z_index=0)[source]#
A Slider component. Still needs to be added to a
GameObject.- Parameters:
button_width (
int) – The width of the clickable area. Defaults to 10.button_height (
int) – The height of the clickable area. Defaults to 10.slider_length (
int) – The length of the slider. Defaults to 10.slider_direction (
Vector) – The direction of the slider. Defaults to Vector(0, -1).onclick (
Optional[Callable]) – The function to call when the button is clicked. Defaults to lambda: None.onrelease (
Optional[Callable]) – The function to call when the button is released. Defaults to lambda: None.onhover (
Optional[Callable]) – The function to call when the mouse enters the button. Defaults to lambda: None.onexit (
Optional[Callable]) – The function to call when the mouse exits the button. Defaults to lambda: None.offset (
Vector) – The offset of the component from the game object. Defaults to Vector(0, 0).rot_offset (
float) – The rotation offset of the component from the game object. Defaults to 0.z_index (
int) – The z-index of the component. Defaults to 0.
- pressed: bool#
Whether the button is currently pressed.
- hover: bool#
Whether the mouse is hovering over the button.
- onclick: Callable#
The function to call when the button is clicked.
- onrelease: Callable#
The function to call when the button is released.
- onhover: Callable#
The function to call when the mouse enters the button.
- delete()#
The delete function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- gameobj: GameObject | None#
The game object this component is attached to.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- onexit: Callable#
The function to call when the mouse exits the button.
- slider_length: int#
The length of the slider.
- button#
The button component.
Animation#
This is the animation component module for game objects.
- class Animation(scale=Vector(1, 1), fps=24, af=False, flipx=False, flipy=False, offset=Vector(), rot_offset=0, z_index=0)[source]#
Animations are a series of images that update automatically in accordance with parameters.
- Parameters:
scale (
Vector) – The scale of the animation. Defaults to Vector(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.offset (
Vector) – The offset of the animation from the game object. Defaults to Vector(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.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- default_state: str#
The key of the default state.
- current_state: str#
The key of the current state.
- animation_frames_left: int#
The number of animation frames left.
- loop: bool#
Whether the animation should loop.
- af: bool#
Whether to enable anisotropic filtering.
- flipx: bool#
Whether to flip the animation along the x axis.
- flipy: bool#
Whether to flip the animation along the y axis.
- property fps#
The fps of the animation.
- property current_frame: int#
The current frame that the animation is on.
- Return type:
int
- property image: sdl2.SDL_Surface#
The current SDL Surface holding the image.
- Return type:
SDL_Surface
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- set_current_state(new_state, loop=False, freeze=-1)[source]#
Set the current animation state.
- Parameters:
new_state (
str) – The key of the new current state.loop (
bool) – Whether to loop the state. Defaults to False.freeze (
int) – Freezes the animation once the specified frame is reached (No animation). Use -1 to never freeze. Defaults to -1.
- Raises:
KeyError – The new_state key is not in the initialized states.
- resize(new_size)[source]#
Resize the Animation to a given size in pixels.
- Parameters:
new_size (
Vector) – The new size of the Animation in pixels.
- add(state_name, images)[source]#
Adds a state to the animation.
- Parameters:
state_name (
str) – The key used to reference this state.images (
list[Sprite]) – A list of images to use as the animation.
- add_folder(state_name, rel_path, recursive=True)[source]#
Adds a state from a folder of images. Directory must be solely comprised of images.
- Parameters:
state_name (
str) – The key used to reference this state.rel_path (
str) – The relative path to the folder you wish to importrecursive (
bool) – Whether it will import an animation shallowly or recursively. Defaults to True.
- add_spritesheet(state_name, spritesheet, from_coord=Vector(), to_coord=Vector())[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 (
Vector) – The grid coordinate of the first frame. Defaults to Vector().to_coord (
Vector) – The grid coordinate of the last coord. Defaults to Vector().
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#
A module to load, manage, and interact with spritesheets.
- class Spritesheet(rel_path, sprite_size=Vector(32, 32), grid_size=None)[source]#
A spritesheet from the filesystem.
- Parameters:
rel_path (
str) – The relative path to the spritesheet.sprite_size (
Vector) – The size of each sprite in the spritesheet. Defaults to Vector(32, 32).grid_size (
Optional[Vector]) – 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.struct.sprite.Sprite]]#
The list of all the sprites as sprites (readonly).
- Return type:
list[list[Sprite]]
- 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:
x (
int) – The x grid coordinate.y (
int) – The y grid coordinate.
- 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(rel_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:
rel_path (
str) – The relative path to the folder you wish to importsprite_size (
Vector) – The size of a single sprite in your spritesheet, should be the same in all imported sheets.default_state – 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:
Hitbox#
Various hitbox components that enable collisions
- class Hitbox(color=None, tag='', debug=False, trigger=False, scale=1, on_collide=None, on_exit=None, offset=Vector(0, 0), rot_offset=0, z_index=0)[source]#
A hitbox superclass. Do not use this class to attach hitboxes to your game objects. Instead, use Polygon, Rectangle, 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 “”.debug (
bool) – Whether to draw the hitbox. Defaults to False.trigger (
bool) – Whether the hitbox is a trigger. Defaults to False.scale (
UnionType[int,float]) – The scale of the hitbox. Defaults to 1.on_collide (
Optional[Callable]) – A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_exit (
Optional[Callable]) – A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
Vector) – The offset of the hitbox from the gameobject. Defaults to Vector(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.
- debug: bool#
Whether to draw a green outline around the hitbox or not.
- trigger: bool#
Whether this hitbox is just a trigger or not.
- scale: int | float#
The scale of the hitbox.
- on_collide: Callable#
The on_collide function to call when a collision happens with this hitbox.
- on_exit: Callable#
The on_exit function to call when a collision ends with this hitbox.
- singular: bool#
Whether this hitbox is singular or not.
- tag: str#
The tag of the hitbox (can be used to identify hitboxes in collision callbacks)
- uptodate: bool#
Whether the hitbox image is up to date or not.
- get_aabb()[source]#
Gets top left and bottom right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- get_obb()[source]#
Gets the top left and bottom right corners of the oriented bounding box in world coordinates.
- delete()#
The delete function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
Rectangle#
- class Rectangle(width=10, height=10, color=None, tag='', debug=False, trigger=False, scale=1, on_collide=None, on_exit=None, offset=Vector(0, 0), rot_offset=0, z_index=0)[source]#
A rectangle implementation of the Hitbox subclass.
- Parameters:
width (
UnionType[int,float]) – The width of the rectangle. Defaults to 10.height (
UnionType[int,float]) – The height of the rectangle. Defaults to 10.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 “”.debug (
bool) – Whether to draw the hitbox. Defaults to False.trigger (
bool) – Whether the hitbox is a trigger. Defaults to False.scale (
UnionType[int,float]) – The scale of the hitbox. Defaults to 1.on_collide (
Optional[Callable]) – A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_exit (
Optional[Callable]) – A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
Vector) – The offset of the hitbox from the gameobject. Defaults to Vector(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.
- property width: int#
The width of the rectangle.
- Return type:
int
- property height: int#
The width of the rectangle.
- Return type:
int
- property top_left#
The top left corner of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property bottom_left#
The bottom left corner of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property top_right#
The top right corner of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property bottom_right#
The bottom right corner of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property top#
The top side of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property left#
The bottom side of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property bottom#
The bottom side of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property right#
The right side of the rectangle.
Note
This can only be accessed and set after the Rectangle has been added to a Game Object.
- property radius: float#
The radius of the rectangle.
- Return type:
float
- contains_pt(pt)[source]#
Checks if a point is inside the Rectangle.
- Parameters:
pt (
Vector) – The point to check, in game-world coordinates.- Returns:
Whether the point is inside the Rectangle.
- Return type:
bool
- delete()#
The delete function template for a component subclass.
- draw(camera)#
The draw function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- get_aabb()[source]#
Gets top left and bottom right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- debug: bool#
Whether to draw a green outline around the hitbox or not.
- trigger: bool#
Whether this hitbox is just a trigger or not.
- scale: int | float#
The scale of the hitbox.
- on_collide: Callable#
The on_collide function to call when a collision happens with this hitbox.
- on_exit: Callable#
The on_exit function to call when a collision ends with this hitbox.
- singular: bool#
Whether this hitbox is singular or not.
- tag: str#
The tag of the hitbox (can be used to identify hitboxes in collision callbacks)
- uptodate: bool#
Whether the hitbox image is up to date or not.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- get_obb()[source]#
Gets the top left and bottom right corners of the oriented bounding box in world coordinates.
- vertices()[source]#
Generates a list of the rectangle’s vertices with no transformations applied.
- Returns:
The list of vertices. Top left, top right, bottom right, bottom left.
- Return type:
list[Vector]
- translated_verts()[source]#
Offsets each vertex with the Polygon’s offset. Top left, top right, bottom right, bottom left.
- Returns:
The list of vertices.
- Return type:
list[Vector]
- transformed_verts()[source]#
Generates a list of the rectangle’s vertices, scaled and rotated.
- Returns:
The list of vertices. Top left, top right, bottom right, bottom left.
- Return type:
list[Vector]
Polygon#
- class Polygon(verts=[], color=None, tag='', debug=False, trigger=False, scale=1, on_collide=None, on_exit=None, offset=Vector(0, 0), rot_offset=0, z_index=0)[source]#
A polygon Hitbox implementation. Supports an arbitrary number of custom vertices, as long as the polygon is convex.
Danger
If generating vertices by hand, make sure you generate them in a counter-clockwise direction. Otherwise, polygons will neither behave nor draw properly.
Warning
rubato does not currently support concave polygons explicitly. Creating concave polygons will result in undesired collision behavior. However, you can still use concave polygons in your projects: Simply break them up into multiple convex Polygon hitboxes and add them individually to a gameobject.
- Parameters:
verts (
list[Vector]) – 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 “”.debug (
bool) – Whether to draw the hitbox. Defaults to False.trigger (
bool) – Whether the hitbox is a trigger. Defaults to False.scale (
UnionType[int,float]) – The scale of the hitbox. Defaults to 1.on_collide (
Optional[Callable]) – A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_exit (
Optional[Callable]) – A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
Vector) – The offset of the hitbox from the gameobject. Defaults to Vector(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.
- property verts: list[rubato.utils.vector.Vector]#
A list of the vertices in the Polygon, in anticlockwise direction.
- Return type:
list[Vector]
- property radius: float#
The radius of the Polygon
- Return type:
float
- get_aabb()[source]#
Gets top left and bottom right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- get_obb()[source]#
Gets the top left and bottom right corners of the oriented bounding box in world coordinates.
- transformed_verts()[source]#
Maps each vertex with the Polygon’s scale and rotation
- Return type:
list[Vector]
- contains_pt(pt)[source]#
Checks if a point is inside the Polygon.
- Parameters:
pt (
Vector) – The point to check, in game-world coordinates..- Returns:
Whether the point is inside the Polygon.
- Return type:
bool
- generate_polygon(num_sides, radius=1)[source]#
Generates the vertices of a regular polygon with a specified number of sides and a radius. You can use this as the verts option in the Polygon constructor if you wish to generate a regular polygon.
- delete()#
The delete function template for a component subclass.
- draw(camera)#
The draw function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- debug: bool#
Whether to draw a green outline around the hitbox or not.
- trigger: bool#
Whether this hitbox is just a trigger or not.
- scale: int | float#
The scale of the hitbox.
- on_collide: Callable#
The on_collide function to call when a collision happens with this hitbox.
- on_exit: Callable#
The on_exit function to call when a collision ends with this hitbox.
- singular: bool#
Whether this hitbox is singular or not.
- tag: str#
The tag of the hitbox (can be used to identify hitboxes in collision callbacks)
- uptodate: bool#
Whether the hitbox image is up to date or not.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
Circle#
- class Circle(radius=10, color=None, tag='', debug=False, trigger=False, scale=1, on_collide=None, on_exit=None, offset=Vector(0, 0), rot_offset=0, z_index=0)[source]#
A circle Hitbox subclass defined by a position, radius, and scale.
- Parameters:
radius (
UnionType[int,float]) – The radius of the circle. Defaults to 10.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 “”.debug (
bool) – Whether to draw the hitbox. Defaults to False.trigger (
bool) – Whether the hitbox is a trigger. Defaults to False.scale (
UnionType[int,float]) – The scale of the hitbox. Defaults to 1.on_collide (
Optional[Callable]) – A function to call when the hitbox collides with another hitbox. Defaults to lambda manifold: None.on_exit (
Optional[Callable]) – A function to call when the hitbox exits another hitbox. Defaults to lambda manifold: None.offset (
Vector) – The offset of the hitbox from the gameobject. Defaults to Vector(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.
Note
If color is unassigned, the circle will not be drawn. And will act like a circular hitbox.
- delete()#
The delete function template for a component subclass.
- draw(camera)#
The draw function template for a component subclass.
- fixed_update()#
The physics function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- debug: bool#
Whether to draw a green outline around the hitbox or not.
- trigger: bool#
Whether this hitbox is just a trigger or not.
- scale: int | float#
The scale of the hitbox.
- on_collide: Callable#
The on_collide function to call when a collision happens with this hitbox.
- on_exit: Callable#
The on_exit function to call when a collision ends with this hitbox.
- singular: bool#
Whether this hitbox is singular or not.
- tag: str#
The tag of the hitbox (can be used to identify hitboxes in collision callbacks)
- uptodate: bool#
Whether the hitbox image is up to date or not.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- property radius: int | float#
The radius of the circle.
- Return type:
UnionType[int,float]
- get_aabb()[source]#
Gets top left and bottom right corners of the axis-aligned bounding box of the hitbox in world coordinates.
- get_obb()[source]#
Gets the top left and bottom right corners of the oriented bounding box in world coordinates.
RigidBody#
The Rigidbody component contains an implementation of rigidbody physics. They have hitboxes and can collide and interact with other rigidbodies.
- class RigidBody(mass=1, gravity=Vector(), friction=0, static=False, bounciness=0, max_speed=Vector(Math.INF, Math.INF), velocity=Vector(), ang_vel=0, pos_correction=0.25, offset=Vector(), 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 (
Vector) – The gravity of the rigidbody. Defaults to Vector(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 (
Vector) – The maximum speed of the rigidbody. Defaults to Vector(INF, INF).velocity (
Vector) – The velocity of the rigidbody. Defaults to Vector(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 (
Vector) – The offset of the rigidbody from the gameobject. Defaults to Vector(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.
- static: bool#
Whether the rigidbody is static (as in, it does not move).
- friction: float#
The friction coefficient of the Rigidbody (usually a value between 0 and 1).
- pos_correction: float#
The positional correction of the rigidbody.
- ang_vel: float#
The current angular velocity of the Rigidbody.
- singular: bool#
Whether multiple components of the same type are allowed on a game object.
- bounciness: float#
How bouncy the rigidbody is (usually a value between 0 and 1).
- delete()#
The delete function template for a component subclass.
- draw(camera)#
The draw function template for a component subclass.
- setup()#
The setup function template for a component subclass.
- property true_z#
The z_index of the component offset by its parent gameobject z_index.
- update()#
The update function template for a component subclass.
- gameobj: GameObject | None#
The game object this component is attached to.
- rot_offset: float#
The rotational offset from the game object’s rotation.
- z_index: int#
Where to draw the component in the z direction.
- started#
Whether the component has run its setup method.
Whether the component should not draw.
- property inv_mass: float#
The inverse mass of the Rigidbody.
- Return type:
float
- property mass: float#
The mass of the Rigidbody.
- Return type:
float
- add_force(force)[source]#
Applies a force to the Rigidbody.
- Parameters:
force (
Vector) – The force to add.
- add_impulse(impulse)[source]#
Applies an impulse to the rigidbody.
- Parameters:
impulse (
Vector) – _description_
- 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).
- Parameters:
force (
Vector) – The force to add.time (
int) – The time in seconds that the force should be added.
- add_cont_impulse(impulse, time)[source]#
Add a continuous impulse to the Rigidbody. A continuous impulse is a impulse that is continuously applied over a time period. (the impulse is added every frame for a specific duration).
- Parameters:
impulse (
Vector) – The impulse to add.time (
int) – The time in seconds that the impulse should be added.
Physics#
The Engine and Manifold classes comprise rubato’s collision engine. Collision and overlap tests inside groups are automatically handled by rubato, so these classes are here mainly for reference.
In general, it is recommended that you define callback functions for Hitbox objects instead of calling Engine functions yourself.
Engine#
- class Engine[source]#
rubato’s physics engine. Handles overlap tests for Hitboxes and resolves Rigidbody collisions.
- static resolve(col)[source]#
Resolve the collision between two rigidbodies.
- Parameters:
col (
Manifold) – The collision information.
- static overlap(hitbox_a, hitbox_b)[source]#
Determines if there is overlap between two hitboxes. Returns a Manifold manifold if a collision occurs but does not resolve.
- static collide(hitbox_a, hitbox_b)[source]#
Collides two hitboxes (if they overlap), calling their callbacks if they exist. Resolves the collision using Rigidbody impulse resolution if applicable.
- static circle_circle_test(circle_a, circle_b)[source]#
Checks for overlap between two circles
- Return type:
Optional[Manifold]
- static circle_polygon_test(circle, polygon)[source]#
Checks for overlap between a circle and a polygon
- Return type:
Optional[Manifold]
- static polygon_polygon_test(shape_a, shape_b)[source]#
Checks for overlap between two polygons
- Return type:
Optional[Manifold]
- static axis_least_penetration(a, b)[source]#
Finds the axis of least penetration between two possibly colliding polygons.
- Return type:
float
Manifold#
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#
Global display class that allows for easy screen and 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:
Vector
- 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 zoomproperty in your scene’s camera.- Type:
Vector
- window_pos#
The current position of the window in terms of screen pixels.
- Type:
Vector
- window_name#
The name of the window.
- Type:
str
- 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:
int
- classmethod has_x_border()[source]#
Whether the window has a black border on the left or right side.
- Return type:
bool
- classmethod has_y_border()[source]#
Whether the window has a black border on the top or bottom.
- Return type:
bool
- 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, mode='desktop')[source]#
Set the window to fullscreen.
- Parameters:
on (
bool) – Whether to set the window to fullscreen.mode (
Literal[‘desktop’, ‘exclusive’]) – The type of fullscreen to use. Can be either “desktop” or “exclusive”.
- classmethod update(tx, pos, scale=Vector(1, 1), angle=0, flipx=False, flipy=False)[source]#
Update the current screen.
- Parameters:
tx (
Texture) – The texture to draw on the screen.pos (
Vector) – The position to draw the texture on.scale (
Vector) – The scale of the texture. Defaults to Vector(1, 1).angle (
float) – The clockwise rotation of the texture. Defaults to 0.flipx (
bool) – Whether to flip the texture horizontally. Defaults to False.flipy (
bool) – Whether to flip the texture vertically. Defaults to False.
- classmethod clone_surface(surface)[source]#
Clones an SDL surface.
- Parameters:
surface (
SDL_Surface) – The surface to clone.- Returns:
The cloned surface.
- Return type:
sdl2.SDL_Surface
- 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:
bool- Returns:
If save was successful.
- class property top: float#
The position of the top of the window.
- Return type:
float
- class property right: float#
The position of the right of the window.
- Return type:
float
- class property left: float#
The position of the left of the window.
- Return type:
float
- class property bottom: float#
The position of the bottom of the window.
- Return type:
float
Input#
The Input module is the way you collect input from the user.
- class Input[source]#
The input class, handling keyboard, mouse, and controller functionality.
Go here for a list of all the available keys.
- class property controllers: int#
The number of controllers currently registered. (getonly)
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.
- Returns:
The total number of controllers.
- Return type:
int
- classmethod update_controllers()[source]#
Register or deregister controllers as needed. Called automatically.
- Return type:
None
- classmethod controller_name(controller)[source]#
Get the name of the controller at the given index.
- Parameters:
index (
int) – The index of the controller to get the name of.- Raises:
IndexError – If the index is out of range. Note that no error is thrown if controller is negative.
- Returns:
The name of the controller. If controller is less than 0, returns an empty string.
- Return type:
str
- classmethod controller_axis(controller, axis)[source]#
Get the value of a given joystick axis on a controller.
- Parameters:
controller (
int) – The index of the controller.axis (
int) – The index of the joystick axis.
- Raises:
IndexError – The given controller index is out of range. Note that no error is thrown if controller is negative.
- Returns:
The value of the axis. If controller is less than 0, returns 0.
- Return type:
int
- classmethod axis_centered(val)[source]#
Check whether a given axis value is within the 10% bounds of deadzone considered the “center”.
- Parameters:
val (
int) – The value of the axis.- Returns:
Whether the axis is centered.
- Return type:
bool
- classmethod controller_button(controller, button)[source]#
Get whether a given button on a controller is pressed.
- Parameters:
controller (
int) – The index of the controller.button (
int) – The index of the button.
- Raises:
IndexError – The given controller index is out of range. Note that no error is thrown if controller is negative.
- Returns:
Whether the button is pressed. If controller is less than 0, returns False.
- Return type:
bool
- classmethod controller_hat(controller, hat)[source]#
Get the value of a given hat on a controller.
- Parameters:
controller (
int) – The index of the controller.hat (
int) – The index of the hat.
- Raises:
IndexError – The given controller index is out of range. Note that no error is thrown if controller is negative.
- Returns:
- The value of the hat, which you can translate with translate_hat().
If controller is less than 0, returns 0.
- Return type:
int
- classmethod translate_hat(val)[source]#
Translate a hat value to a string.
- Parameters:
val (
int) – The hat value.- Returns:
The string representation of the hat value.
- Return type:
str
- 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:
bool
Example
if rb.Input.key_pressed("a"): # handle the "a" keypress if rb.Input.key_pressed("shift", "w"): # handle the "shift+w" keypress
- classmethod get_name(code)[source]#
Gets the name of a key from its keycode.
- Parameters:
code (
int) – A keycode.- Returns:
The corresponding key.
- Return type:
str
- classmethod mods_from_code(code)[source]#
Gets the modifier names from a mod code.
- Parameters:
code (
int) – The mod code.- Returns:
A list with the names of the currently pressed modifiers.
- Return type:
list[str]
- classmethod key_from_name(char)[source]#
Gets the keycode of a key from its name.
- Parameters:
char (
str) – The name of the key.- Returns:
The corresponding keycode.
- Return type:
int
- classmethod scancode_from_name(char)[source]#
Gets the scancode of a key from its name.
- Parameters:
char (
str) – The name of the key.- Returns:
The corresponding scancode.
- Return type:
int
- classmethod window_focused()[source]#
Checks if the display has keyboard focus.
- Returns:
True if the window is focused, false otherwise.
- Return type:
bool
- classmethod mouse_state()[source]#
Checks which mouse buttons are pressed.
- Returns:
A tuple with 5 booleans representing the state of each mouse button. (button1, button2, button3, button4, button5)
- Return type:
tuple[bool]
- classmethod mouse_pressed()[source]#
Checks if any mouse button is pressed.
- Return type:
bool- Returns:
True if any button is pressed, false otherwise.
- classmethod mouse_is_pressed(cls)[source]#
Checks which mouse buttons are pressed.
- Returns:
A tuple with 5 booleans representing the state of each mouse button. (button1, button2, button3, button4, button5)
- Return type:
tuple[bool]
- classmethod any_mouse_button_pressed(cls)[source]#
Checks if any mouse button is pressed.
- Return type:
bool- Returns:
True if any button is pressed, false otherwise.
- static get_mouse_pos()[source]#
The current position of the mouse, in screen-coordinates.
- Returns:
A Vector representing position.
- Return type:
- static get_mouse_abs_pos()[source]#
The current absolute position of the mouse. ie. screen coordinates. :rtype:
Vector: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:
bool
- classmethod set_mouse_visibility(toggle)[source]#
Sets the mouse visibility.
- Parameters:
toggle (
bool) – True to show the mouse and false to hide the mouse.
- static pt_in_poly(pt, verts)[source]#
Checks if a point is inside a polygon.
- Parameters:
pt (
Vector) – The point to check.verts (
list[Vector]) – The polygon representation as a list of Vectors (vertices)
- Returns:
Whether the point is inside the polygon.
- Return type:
bool
Sound#
A fully functional, multi-channel sound system.
- class Sound(rel_path, sound_name=None)[source]#
- A sound class that is used to manage the sounds throughout the project. We support the following audio formats:
MP3
WAV
OGG
FLAC
MOD
MIDI (not always available on linux)
OPUS
AIFF
VOC
- Parameters:
rel_path (
str) – The relative path to the sound file you wish to import.sound_name (
Optional[str]) – The name of the sound. Defaults to the name of the file.
- loaded_sounds: dict[str, rubato.utils.sound.Sound] = {}#
A dictionary housing all the loaded sounds, stored by their name.
- active_channels: dict[int, rubato.utils.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:
int
- play(loops=0, init_volume=None)[source]#
Plays a sound.
- Parameters:
loops (
int) – The number of times to loop a sound after the first play through. Use -1 to loop forever. Defaults to 0.’init_volume (
Optional[int]) – The initail volume of the sound. Defaults to the volume of the sound. range(0, MIX_MAX_VOLUME=>128)
- 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:
int- Returns:
The volume of the sound. range(0, MIX_MAX_VOLUME=>128)
- classmethod import_sound_folder(rel_path, duplicate_names=False, recursive=True)[source]#
Imports a folder of sounds, saving each one in the loaded_sounds dictionary by filename.
- Parameters:
rel_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.
Sprite#
A sprite is a class that handles rendering of images.
- class Sprite(rel_path, rotation=0, scale=Vector(1, 1), af=False)[source]#
A sprite is a class that handles rendering of images from your file system independent of Game Objects.
- Parameters:
rel_path (
str) – The relative path to the image.rotation (
float) – The rotation of the image. Defaults to 0.scale (
Vector) – The scale of the image. Defaults to Vector(1, 1).af (
bool) – Whether to use anisotropic filtering. Defaults to False.
- property surf: sdl2.SDL_Surface | None#
The surface that is rendered.
- Return type:
sdl2.SDL_Surface | None
- property af#
Whether to use anisotropic filtering.
- delete()#
Deletes the sprite
- generate_tx()#
Regenerates the texture from the surface.
- get_size()#
Gets the current size of the image. (Scaled)
- Return type:
- Returns:
The size of the image
- get_size_raw()#
Gets the current size of the image. (Unscaled)
- Return type:
- Returns:
The size of the image
- merge(other)#
Merges another surface into this one.
other: The surface to merge into this one.
- rotation#
The clockwise rotation of the sprite.
- scale#
The scale of the sprite.
- tx: sdl2.ext.Texture | None#
(READ ONLY) The generated sprite texture.
- 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.
Surface#
A Surface is a grid of pixels that you can draw shapes onto or edit individual pixels.
- class Surface(width=32, height=32, scale=Vector(1, 1), rotation=0, af=False)[source]#
A surface.
- 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 (
Vector) – The scale of the surface. Defaults to Vector(1, 1).af (
bool) – Whether to use anisotropic filtering. Defaults to False.
- property surf: sdl2.SDL_Surface | None#
The surface that is rendered.
- Return type:
sdl2.SDL_Surface | None
- width: int#
(READ ONLY) The width of the surface in pixels.
- height: int#
(READ ONLY) The height of the surface in pixels.
- draw_line(start, end, color=Color.black, aa=False, thickness=1, blending=True)[source]#
Draws a line on the surface.
- Parameters:
start (
Vector) – The start of the line.end (
Vector) – 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(top_left, dims, border=None, border_thickness=1, fill=None, blending=True)[source]#
Draws a rectangle on the surface.
- Parameters:
top_left (
Vector) – The top left corner of the rectangle.dims (
Vector) – 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 (
Vector) – 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, border=None, border_thickness=1, fill=None, aa=False, blending=True)[source]#
Draws a polygon on the surface.
- Parameters:
points (
list[Vector]) – The points 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_pixel_tuple(pos)[source]#
Gets the color of a pixel on the surface.
- Parameters:
pos (
Vector) – The position of the pixel.- Return type:
tuple[int,int,int,int]- Returns:
The color of the pixel.
- property af#
Whether to use anisotropic filtering.
- delete()#
Deletes the sprite
- generate_tx()#
Regenerates the texture from the surface.
- get_size()#
Gets the current size of the image. (Scaled)
- Return type:
- Returns:
The size of the image
- get_size_raw()#
Gets the current size of the image. (Unscaled)
- Return type:
- Returns:
The size of the image
- merge(other)#
Merges another surface into this one.
other: The surface to merge into this one.
- set_colorkey(color)[source]#
Sets the colorkey of the surface. :type color:
Color:param color: Color to set as the colorkey.
- rotation#
The clockwise rotation of the sprite.
- scale#
The scale of the sprite.
- tx: sdl2.ext.Texture | None#
(READ ONLY) The generated sprite texture.
- 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.
Draw#
A static draw class for drawing things directly to the renderer.
- class Draw[source]#
Draws things to the renderer. Don’t instantiate, instead use it as a static class.
- classmethod clear(background_color=Color.white, border_color=Color.black)[source]#
Clears the renderer and draws the background of the frame.
- Parameters:
background_color (
Color) – The background color. Defaults to white.border_color (
Color) – The border color. Defaults to black. Shown when the aspect ratio of the game does not match the aspect ratio of the window.
- classmethod push(z_index, callback)[source]#
Add a custom draw function to the frame queue.
- Parameters:
z_index (
int) – The z_index to call at (lower z_indexes get called first).callback (
Callable) – The function to call.
- classmethod dump()[source]#
Draws all queued items. Is called automatically at the end of every frame.
- classmethod queue_point(pos, color=Color.cyan, z_index=Math.INF)[source]#
Draw a point onto the renderer at the end of the frame.
- Parameters:
pos (
Vector) – The position of the point.color (
Color) – The color to use for the pixel. Defaults to Color.cyan.z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.
- static point(pos, color=Color.cyan)[source]#
Draw a point onto the renderer immediately.
- Parameters:
pos (
Vector) – The position of the point.color (
Color) – The color to use for the pixel. Defaults to Color.cyan.
- classmethod queue_line(p1, p2, color=Color.cyan, width=1, z_index=Math.INF)[source]#
Draw a line onto the renderer at the end of the frame.
- Parameters:
p1 (
Vector) – The first point of the line.p2 (
Vector) – 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 Math.INF.
- classmethod queue_rect(center, width, height, border=Color.clear, border_thickness=1, fill=None, angle=0, z_index=Math.INF)[source]#
Draws a rectangle onto the renderer at the end of the frame.
- Parameters:
center (
Vector) – The center of the rectangle.width (
UnionType[int,float]) – The width of the rectangle.height (
UnionType[int,float]) – The height of the rectangle.border (
Color) – The border color. Defaults to Color.clear.border_thickness (
UnionType[int,float]) – The border thickness. Defaults to 1.fill (
Optional[Color]) – The fill color. Defaults to None.angle (
float) – The angle in degrees. Defaults to 0.z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.
- static rect(center, width, height, border=Color.clear, border_thickness=1, fill=None, angle=0)[source]#
Draws a rectangle onto the renderer immediately.
- Parameters:
center (
Vector) – The center of the rectangle.width (
UnionType[int,float]) – The width of the rectangle.height (
UnionType[int,float]) – The height of the rectangle.border (
Color) – The border color. Defaults to Color.clear.border_thickness (
UnionType[int,float]) – The border thickness. Defaults to 1.fill (
Optional[Color]) – The fill color. Defaults to None.angle (
float) – The angle in degrees. Defaults to 0.
- classmethod queue_circle(center, radius=4, border=Color.clear, border_thickness=1, fill=None, z_index=Math.INF)[source]#
Draws a circle onto the renderer at the end of the frame.
- Parameters:
center (
Vector) – The center.radius (
int) – The radius. Defaults to 4.border (
Color) – The border color. Defaults to green.border_thickness (
UnionType[int,float]) – The border thickness. Defaults to 1.fill (
Optional[Color]) – The fill color. Defaults to None.z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.
- static circle(center, radius=4, border=Color.clear, border_thickness=1, fill=None)[source]#
Draws a circle onto the renderer immediately.
- classmethod queue_poly(points, border=Color.clear, border_thickness=1, fill=None, z_index=Math.INF)[source]#
Draws a polygon onto the renderer at the end of the frame.
- Parameters:
points (
list[Vector]) – The list of points to draw.border (
Color) – The border color. Defaults to green.border_thickness (
UnionType[int,float]) – The border thickness. Defaults to 1.fill (
Optional[Color]) – The fill color. Defaults to None.z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.
- static poly(points, border=Color.clear, border_thickness=1, fill=None)[source]#
Draws a polygon onto the renderer immediately.
- classmethod queue_text(text, font, pos=Vector(), justify='left', align=Vector(), width=0, z_index=Math.INF)[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 (
Vector) – The position of the text. Defaults to Vector(0, 0).justify (
str) – The justification of the text. (left, center, right). Defaults to “left”.align (
Vector) – The alignment of the text. Defaults to Vector(0, 0).width (
UnionType[int,float]) – The maximum width of the text. Will automatically wrap the text. Defaults to -1.z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.
- static text(text, font, pos=Vector(), justify='left', align=Vector(), width=0)[source]#
Draws some text onto the renderer immediately.
- Parameters:
text (
str) – The text to draw.font (
Font) – The Font object to use.pos (
Vector) – The position of the text. Defaults to Vector(0, 0).justify (
str) – The justification of the text. (left, center, right). Defaults to “left”.align (
Vector) – The alignment of the text. Defaults to Vector(0, 0).width (
UnionType[int,float]) – The maximum width of the text. Will automatically wrap the text. Defaults to -1.
- classmethod queue_texture(texture, pos=Vector(), z_index=Math.INF, scale=Vector(1, 1), angle=0)[source]#
Draws an texture onto the renderer at the end of the frame.
- Parameters:
texture (
Texture) – The texture to draw.pos (
Vector) – The position of the texture. Defaults to Vector(0, 0).z_index (
int) – Where to draw it in the drawing order. Defaults to Math.INF.scale (
Vector) – The scale of the texture. Defaults to Vector(1, 1).angle (
float) – The clockwise rotation of the texture. Defaults to 0.
- static texture(texture, pos=Vector(), scale=Vector(1, 1), angle=0)[source]#
Draws an SDL Texture onto the renderer immediately.
- classmethod queue_surf(surf, pos=Vector(), z_index=Math.INF, camera=None)[source]#
Draws an surf onto the renderer at the end of the frame.
Vector#
A vector implementation.
- class Vector(x=0, y=0)[source]#
A Vector object that defines a 2D point in space
- Parameters:
x (
UnionType[float,int]) – The x coordinate. Defaults to 0.y (
UnionType[float,int]) – The y coordinate. Defaults to 0.
- x: float = None#
The x coordinate.
- y: float = None#
The y coordinate.
- property magnitude: float#
The magnitude of the vector. You can set to this value.
- Return type:
float
- property mag_sq: float#
The squared magnitude of the vector (readonly).
- Return type:
float
- property angle: float#
The angle of the vector degrees (readonly).
- Return type:
float
- 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:
str
- 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:
str
- normalized(out=None)[source]#
Determines the unit vector of this vector.
- Parameters:
out (
Vector, optional) – 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.- Returns:
The vector output of the operation.
- Return type:
- dot(other)[source]#
Takes the dot product of two vectors.
- Parameters:
other (
Vector) – The other vector.- Return type:
UnionType[float,int]- Returns:
The resulting dot product.
- cross(other)[source]#
Takes the cross product of two vectors.
- Parameters:
other (
Vector) – The other vector.- Return type:
UnionType[float,int]- Returns:
The resultant scalar magnitude of the orthogonal vector along an imaginary z-axis.
- perpendicular(scalar=1, out=None)[source]#
Computes a scaled 90 degree clockwise rotation on a given vector.
- Parameters:
scalar (
UnionType[float,int]) – The scalar value.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.
- 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:
angle (
UnionType[float,int]) – The rotation amount in north-degrees you want to rotate by (relative).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.
- Return type:
- Returns:
The resultant Vector.
- to_tuple()[source]#
Returns the x and y coordinates of the vector as a tuple.
- Return type:
tuple[float,float]
- 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:
decimal_places (
int) – The amount of decimal places rounded to. Defaults to 0.out (
Vector, optional) – 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.
- Returns:
The resultant Vector.
- Return type:
- ceil(out=None)[source]#
Returns a new vector with the coordinates ciel-ed.
- Parameters:
out (
Vector, optional) – 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.- Returns:
The resultant Vector.
- Return type:
- floor(out=None)[source]#
Returns a new vector with the coordinates floored.
- Parameters:
out (
Vector, optional) – 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.- Returns:
The resultant Vector.
- Return type:
- abs(out=None)[source]#
Returns a new vector with the absolute value of the original coordinates.
- Parameters:
out (
Vector, optional) – 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.- Returns:
The resultant Vector.
- Return type:
- distance_between(other)[source]#
Finds the pythagorean distance between two vectors.
- Parameters:
other (
Vector) – The other vector.- Returns:
The distance.
- Return type:
float
- static from_radial(magnitude, angle)[source]#
Generates a Vector from the given angle and magnitude.
- Parameters:
magnitude (
UnionType[float,int]) – Length of vector.angle (
UnionType[float,int]) – Direction of vector in North degrees.
- Return type:
- Returns:
Vector from the given direction and distance
- static clamp_magnitude(vector, max_magnitude, min_magnitude=0)[source]#
Clamps the magnitude of the vector to the given range.
- Parameters:
vector (
Vector) – The vector to clamp.max_magnitude (
UnionType[float,int]) – The maximum magnitude of the vector.min_magnitude (
UnionType[float,int]) – The minimum magnitude of the vector. Defaults to 0.
- 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.
Math#
The math module includes some helper functions for commonly used equations.
- class Math[source]#
A more complete math class.s
- INF: int = 2147483647#
The max value of a 32-bit integer.
- PI_HALF: float = 1.5707963267948966#
The value of pi / 2.
- PI_TWO: float = 6.283185307179586#
The value of pi * 2.
- static clamp(a, lower, upper)[source]#
Clamps a value.
- Parameters:
a (
UnionType[float,int]) – The value to clamp.lower (
UnionType[float,int]) – The lower bound of the clamp.upper (
UnionType[float,int]) – The upper bound of the clamp.
- Returns:
The clamped result.
- Return type:
float
- static sign(n)[source]#
Checks the sign of n.
- Parameters:
n (
UnionType[float,int]) – A number to check.- Return type:
int- Returns:
The sign of the number. (1 for positive, 0 for 0, -1 for negative)
- static lerp(a, b, t)[source]#
Linearly interpolates between lower and upper bounds by t
- Parameters:
a (
UnionType[float,int]) – The lower bound.b (
UnionType[float,int]) – The upper bound.t (
float) – Distance between upper and lower (1 gives b, 0 gives a).
- Returns:
The linearly interpolated value.
- Return type:
float
- 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:
float
- static floor(x)[source]#
Quickly rounds down a number.
- Parameters:
x (
float) – The number to round.- Returns:
The rounded number.
- Return type:
int
- static ceil(x)[source]#
Quickly rounds up a number.
- Parameters:
x (
float) – The number to round.- Returns:
The rounded number.
- Return type:
int
- 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).
- Parameters:
x (
float) – The number to check.error (
float) – The error margin from int that we accept, used for float inaccuracy.
- Return type:
bool- Returns:
True if the number is an integer within the error.
- static simplify_sqrt(square_rooted)[source]#
Simplifies a square root.
- Parameters:
square_rooted (
int) – The sqrt to simplify (inside the sqrt).- Return type:
tuple- 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 simplify(a, b)[source]#
Simplifies a fraction.
- Parameters:
a (
int) – numerator.b (
int) – denominator.
- Return type:
tuple- Returns:
The simplified fraction, (numerator, denominator).
- 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 modified implementation of the OpenSimplex2 algorithm.
- seed: int = 0#
The seed for the random noise. Setting to a fixed value will result in the same noise every time.
- classmethod noise(x)[source]#
Creates noise from 1 dimensional input. This is identical to
noise2(x, 0).- Parameters:
x (
float) – the x coordinate of noise.- Returns:
the random noise value.
- Return type:
float
Time#
A static time class to monitor time and to call functions in the future.
- class DelayedTask(delay, task, is_stopped=False)[source]#
A task that is run after a specified number of milliseconds.
- class FramesTask(delay, task, is_stopped=False)[source]#
A task that is run after a specified number of frames.
- class ScheduledTask(interval, task, delay=0, is_stopped=False)[source]#
A task that is run every specified number of milliseconds.
- class Time[source]#
The time class.
- frames: int = 0#
The total number of elapsed frames since the start of the game.
- fixed_delta: float = 0#
The number of seconds since the last fixed update.
- fps = 60#
The current fps of thi 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.
- physics_fps = 30#
The fps that the physics should run at. Defaults to 30.
- class property smooth_fps: int#
The average fps over the past 120 frames. This is a get-only property.
- Return type:
int
- class property frame_start: int#
The time since the start of the game, in milliseconds, taken at the start of the frame. This is a get-only property.
- Return type:
int
- classmethod schedule(task)[source]#
Schedules a task for delayed execution based on what type of task it is.
- Parameters:
task (
DelayedTask | FramesTask | ScheduledTask) – The task to queue.
- classmethod delayed_call(delay, func)[source]#
Calls the function func at a later time.
- Parameters:
delay (
int) – The time from now (in milliseconds) to run the function at.func (
Callable) – The function to call.
- classmethod delayed_frames(delay, func)[source]#
Calls the function func at a later frame.
- Parameters:
delay (
int) – The number of frames to wait.func (
Callable) – The function to call
- classmethod scheduled_call(interval, func)[source]#
Calls the function func at a scheduled interval.
- Parameters:
interval (
int) – The interval (in milliseconds) to run the function at.func (
Callable) – The function to call.
- classmethod milli_to_sec(milli)[source]#
Converts milliseconds to seconds.
- Parameters:
milli (
int) – A number in milliseconds.- Returns:
The converted number in seconds.
- Return type:
float
Color#
This color module contains the Color class, which is used to represent colors in the game.
- class Color(r=0, g=0, b=0, a=255)[source]#
An RGBA color.
- Parameters:
r (
UnionType[int,float]) – The red value. Defaults to 0.g (
UnionType[int,float]) – The green value. Defaults to 0.b (
UnionType[int,float]) – The blue value. Defaults to 0.a (
UnionType[int,float]) – The alpha value. Defaults to 255.
- r: int#
The red value.
- g: int#
The green value.
- b: int#
The blue value.
- a: int#
The alpha value.
- darker(amount=20)[source]#
Returns a darker copy of the color. It subtracts
amountfrom the RGB values.- Parameters:
amount (
int) – How much darker. Defaults to 20.- Returns:
The resultant color.
- Return type:
- lighter(amount=20)[source]#
Returns a lighter copy of the color. It adds
amountto the RGB values.- Parameters:
amount (
int) – How much lighter. Defaults to 20.- Returns:
The resultant color.
- Return type:
- 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_tuple()[source]#
Converts the Color to a tuple.
- Returns:
The tuple representing the color.
- Return type:
tuple(int, int, int, int)
- to_hex()[source]#
Converts the Color to a hexadecimal string.
- Returns:
The hexadecimal output in lowercase. (i.e. ffffffff)
- Return type:
str
- to_hsv()[source]#
Converts the Color to a tuple containing its HSV values.
- Returns:
The Color values as HSV in the form of a tuple.
- Return type:
tuple[int]
- static random_default(grayscale=False)[source]#
Returns a random default Color.
- Parameters:
grayscale (
bool, optional) – Whether to add grayscale colors. Defaults to False.- Returns:
A random default Color.
- Return type:
- classmethod from_rgba32(rgba32)[source]#
Creates a Color object from an RGBA32 representation.
- Parameters:
rgba32 (
int) – The RGBA32 representation as an int.- Return type:
- Returns:
The color object from the RGBA32.
- classmethod from_hex(h)[source]#
Creates a Color object from a hex string.
- Parameters:
h (
str) – The hexadecimal value in the format “RRGGBBAA”.- Returns:
The Color object.
- Return type:
- classmethod from_hsv(h, s, v, a=1)[source]#
Creates a Color object from HSV values.
- Parameters:
h (
float) – The hue degree (0 to 360).s (
float) – The saturation proportion (0 to 1).v (
float) – The value proportion (0 to 1).a (
float) – The alpha proportion (0 to 1).
- Returns:
The Color object.
- 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), # . . . . . . . . . . . . . . . tuple
"scarlet": (214, 48, 49), #. . . . . . . . . . . . . . . . tuple
"violet": (108, 92, 231), #. . . . . . . . . . . . . . . . tuple
"turquoize": (0, 206, 201), #. . . . . . . . . . . . . . . tuple
"orange": (225, 112, 85), #. . . . . . . . . . . . . . . . tuple
"magenta": (232, 67, 147), # . . . . . . . . . . . . . . . tuple
"blue": (9, 132, 227), # . . . . . . . . . . . . . . . . . tuple
"green": (0, 184, 148), #. . . . . . . . . . . . . . . . . tuple
"red": (255, 118, 117), #. . . . . . . . . . . . . . . . . tuple
"purple": (162, 155, 254), # . . . . . . . . . . . . . . . tuple
"cyan": (116, 185, 255), # . . . . . . . . . . . . . . . . tuple
"lime": (85, 239, 196), #. . . . . . . . . . . . . . . . . tuple
# 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), #. . . . . . . . . . . . . . . . . . . tuple
"white": (255, 255, 255), #. . . . . . . . . . . . . . . . tuple
"night": (20, 20, 22), # . . . . . . . . . . . . . . . . . tuple
"darkgray": (45, 52, 54), #. . . . . . . . . . . . . . . . tuple
"gray": (99, 110, 114), #. . . . . . . . . . . . . . . . . tuple
"lightgray": (178, 190, 195), #. . . . . . . . . . . . . . tuple
"snow": (223, 230, 233), # . . . . . . . . . . . . . . . . tuple
}
Debug#
This Debug module provides a set of functions to help with debugging.
Font#
The font module for text rendering
- class Font(font='Roboto', size=16, styles=[], 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’, ‘PressStart’]]) – The font to use. Can also be a path to a font file. Defaults to Roboto.size (
int) – The size of the font. Defaults to 16.styles (
list[str]) – The styles to apply to the font. Defaults to []. Fill with only the following: bold, italic, underline, strikethrough.color (
Color) – The color of the font. Defaults to Color(0, 0, 0).
- property size: int#
The size of the text in points.
- Return type:
int
- generate_surface(text, align=Vector(0, 0), width=0)[source]#
Generate the surface containing the text.
- Parameters:
text (
str) – The text to render.align (
Vector) – The alignment to use. Defaults to Vector(0, 0).width (
UnionType[int,float]) – The maximum width to use. Defaults to -1.rot – The rotation of the text in degrees. Defaults to 0.
- Raises:
ValueError – The width is too small for the text.
ValueError – The size of the text is too large for the font.
- Returns:
The surface containing the text.
- Return type:
sdl2.SDL_Surface
- add_style(style)[source]#
Adds a style to the font.
- Parameters:
style (
str) – The style to add. Can be one of the following: bold, italic, underline, strikethrough.
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 Events[source]#
Describes all rubato-fired events that can be listened for.
- KEYUP = 'KEYUP'#
Fired when a key is released
- KEYDOWN = 'KEYDOWN'#
Fired when a key is pressed
- KEYHOLD = 'KEYHOLD'#
Fired when a key is held down (After the initial keydown)
- MOUSEUP = 'MOUSEUP'#
Fired when a mouse button is released
- MOUSEDOWN = 'MOUSEDOWN'#
Fired when a mouse button is pressed
- JOYAXISMOTION = 'JOYAXISMOTION'#
Fired when a controller joystick axis is moved
- JOYHATMOTION = 'JOYHATMOTION'#
Fired when a controller hat button is changed
- JOYBUTTONDOWN = 'JOYBUTTONDOWN'#
Fired when a controller button is pressed
- JOYBUTTONUP = 'JOYBUTTONUP'#
Fired when a controller button is released
- ZOOM = 'ZOOM'#
Fired when the camera is zoomed
- EXIT = 'EXIT'#
Fired when the game is exiting
- RESIZE = 'RESIZE'#
Fired when the window is resized
- 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.Listener]] = {}#
A dictionary with all of the active listeners.
- classmethod handle()[source]#
Handle the current SDL event queue.
- Returns:
Whether an SDL Quit event was fired.
- Return type:
bool
- classmethod listen(event, func)[source]#
Creates an event listener and registers it.
- Parameters:
event (
str) – The event key to listen for.func (
Callable) – The function to run once the event is broadcast. It may take in a params dictionary argument.
- class Listener(event, callback)[source]#
The actual listener object itself. A backend class for the Radio.
- Parameters:
event (
str) – The event key to listen for.callback (
Callable) – The function to run once the event is broadcast.
- event: str = None#
The event descriptor
- callback: Callable = None#
The function called when the event occurs
- registered: bint = None#
Describes whether the listener is registered
Errors#
Some custom errors
- 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 RemovalWarning[source]#
A warning 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(other_func)[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.
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, name='', pos=Vector(), rotation=0, z_index=0, debug=False)[source]#
Wraps a component or list of components in a GameObject.
- Parameters:
comp (
UnionType[Component,list[Component]]) – The component or list of components to wrap.name (
str) – The name of the GameObject. Defaults to “”.pos (
Vector) – The position of the GameObject. Defaults to Vector().rotation (
float) – The rotation of the GameObject. Defaults to 0.z_index (
int) – The z_index of the GameObject. Defaults to 0.debug (
bool) – Whether the GameObject is in debug mode. Defaults to False.
- Raises:
TypeError – If comp is not a Component or a list of Components.
- Returns:
The wrapped GameObject.