Complete API Reference

The following is complete documentation on all public functions and classes within Spyral. If you need further information on how the internals of a class work, please consider checking the source code attached.

Actors

class spyral.Actor

Actors are a powerful mechanism for quickly adding multiprocessing behavior to your game through Greenlets . Any object that subclasses the Actor mixin can implement a main method that will run concurrently. You can put a non-terminating loop into it, and it will work like magic, allowing other actors and the main game itself to keep processing:

class MyActor(spyral.Actor):
    def main(self, delta):
        while True:
            print "Acting!"

When an instance of the above class is created in a scene, it will continuously print “Acting!” until the scene ends. Like a Sprite, An Actor belongs to the Scene that was currently active when it was created.

main(delta)

The main function is executed continuously until either the program ends or the main function ends. While the Actor’s scene is not on the top of the stack, the Actor is paused; it will continue when the Scene is back on the top of the Directory’s stack.

Parameters:delta (float) – The amount of time that has passed since this method was last invoked.
run_animation(animation)

Run this animation, without blocking other Actors, until the animation completes.

wait(delta=0)

Switches execution from this Actor for delta frames to the other Actors. Returns the amount of time that this actor was left waiting.

Parameters:delta (number) – the number of frames(?) to wait.
Return type:float

Animations

class spyral.Animation(property, easing, duration=1.0, absolute=True, shift=None, loop=False)

Creates an animation on property, with the specified easing, to last duration in seconds.

The following example shows a Sprite with an animation that will linearly change its ‘x’ property from 0 to 100 over 2 seconds.:

from spyral import Sprite, Animation, easing
...
my_sprite = Sprite(my_scene)
my_animation = Animation('x', easing.Linear(0, 100), 2.0)
my_sprite.animate(my_animation)

Animations can be appended one after another with the + operator, and can be run in parallel with the & operator.

>>> from spyral import Animation, easing
>>> first  = Animation('x', easing.Linear(0, 100), 2.0)
>>> second = Animation('y', easing.Linear(0, 100), 2.0)
# Sequential animations
>>> right_angle = first + second
# Parallel animations
>>> diagonal = first & second
Parameters:
  • property (string) – The property of the sprite to change (e.g., ‘x’)
  • easing (Easing) – The easing (rate of change) of the property.
  • duration (float) – How many seconds to play the animation
  • absolute (boolean) – (Unimplemented?) Whether to position this relative to the sprite’s offset, or to absolutely position it on the screen.
  • shift (None, a Vec2D, or a number) – How much to offset the animation (a number if the property is scalar, a Vec2D if the property is “pos”, and None if there is no offset.
  • loop (boolean) – Whether to loop indefinitely
evaluate(sprite, progress)

For a given sprite, complete progress‘s worth of this animation. Basically, complete a step of the animation. Returns a dictionary representing the changed property and its new value, e.g.: {"x": 100}. Typically, you will use the sprite’s animate function instead of calling this directly.

Parameters:
  • sprite (Sprite) – The Sprite that will be manipulated.
  • progress (float) – The amount of progress to make on this animation.
Return type:

dict

Director

The director handles initializing and running your game. It is also responsible for keeping track of the game’s scenes. If you are not using the Example.Activity, then you will need to call init at the very start of your game, before you try to run run your first scene.

spyral.director.init((640, 480))
# Scene and sprite creation
spyral.director.run(scene=MyScene())

Note that the director provides three ways to change the current scene:

  • Pushing new Scenes on top of old ones.
  • Popping the current Scene, revealing the one underneath (or ending the game if this is the only scene on the stack)
  • Replacing the current Scene with a new one.
spyral.director.get_scene()[source]

Returns the currently running scene; this will be the Scene on the top of the director’s stack.

Return type:Scene
Returns:The currently running Scene, or None.
spyral.director.get_tick()[source]

Returns the current tick number, where ticks happen on each update, not on each frame. A tick is a “tick of the clock”, and will happen many (usually 30) times per second.

Return type:int
Returns:The current number of ticks since the start of the game.
spyral.director.init(size=(0, 0), max_ups=30, max_fps=30, fullscreen=False, caption='My Spyral Game')[source]

Initializes the director. This should be called at the very beginning of your game.

Parameters:
  • size (Vec2D) – The resolution of the display window. (0,0) uses the screen resolution
  • max_fps (int) – The number of times that the director.update event will occur per frame. This will remain the same, even if fps drops.
  • max_ups (int) – The number of frames per second that should occur when your game is run.
  • fullscreen (bool) – Whether your game should start in fullscreen mode.
  • caption (str) – The caption that will be displayed in the window. Typically the name of your game.
spyral.director.pop()[source]

Pop the top scene off the stack, returning control to the next scene on the stack. If the stack is empty, the program will quit. This does return control, so remember to return immediately after calling it.

spyral.director.push(scene)[source]

Place scene on the top of the stack, and move control to it. This does return control, so remember to return immediately after calling it.

Parameters:scene (Scene) – The new scene.
spyral.director.quit()[source]

Cleanly quits out of spyral by emptying the stack.

spyral.director.replace(scene)[source]

Replace the currently running scene on the stack with scene. Execution will continue after this is called, so make sure you return; otherwise you may find unexpected behavior:

spyral.director.replace(Scene())
print "This will be printed!"
return
Parameters:scene (Scene) – The new scene.
spyral.director.run(sugar=False, profiling=False, scene=None)[source]

Begins running the game, starting with the scene on top of the stack. You can also pass in a scene to push that scene on top of the stack. This function will run until your game ends, at which point execution will end too.

Parameters:
  • sugar (bool) – Whether to run the game for Sugar. This is only to the special XO Launcher; it is safe to ignore.
  • profiling (bool) – Whether to enable profiling mode, where this function will return on every scene change so that scenes can be profiled independently.
  • scene (Scene) – The first scene.

Easings

This module provides a set of built-in easings which can be used by any game. Additionally, custom easings can be built. An easing should be a function (or callable) which takes in a sprite, and a time delta which is normalized to [0,1], and returns the state of easing at that time. See the source code of this module for some example implementations. Built-in easings are stateless, so the same animation can be used many times or on many different objects. Custom easings do not have to be stateless.

Visualizations of these easings are available at http://easings.net .

spyral.easing.Arc(center=(0, 0), radius=1, theta_start=0, theta_end=6.283185307179586)[source]

Increasing according to a circular curve for two properties.

spyral.easing.CubicIn(start=0.0, finish=1.0)[source]

Cubically increasing, starts very slow : f(x) = x^3

spyral.easing.CubicInOut(start=0.1, finish=1.0)[source]

Cubically increasing, starts and ends very slowly but very fast in the middle.

spyral.easing.CubicOut(start=0.0, finish=1.0)[source]

Cubically increasing, starts very fast : f(x) = 1 + (x-1)^3

spyral.easing.Iterate(items, times=1)[source]

Iterate over a list of items. This particular easing is very useful for creating image animations, e.g.:

walk_images = [spyral.Image('f1.png'), spyral.Image('f2.png'), spyral.Image('f3.png')]
walking_animation = Animation('image', easing.Iterate(walk_images), 2.0, loop=True)
my_sprite.animate(walking_animation)
Parameters:
  • items (list) – A list of items (e.g., a list of Images).
  • times (int) – The number of times to iterate through the list.
spyral.easing.Linear(start=0.0, finish=1.0)[source]

Linearly increasing: f(x) = x

spyral.easing.LinearTuple(start=(0, 0), finish=(0, 0))[source]

Linearly increasing, but with two properites instead of one.

spyral.easing.Polar(center=(0, 0), radius=<function <lambda> at 0x7f3804c9b7d0>, theta_start=0, theta_end=6.283185307179586)[source]

Similar to an Arc, except the radius should be a function of time.

spyral.easing.QuadraticIn(start=0.0, finish=1.0)[source]

Quadratically increasing, starts slower : f(x) = x ^ 2

spyral.easing.QuadraticInOut(start=0.0, finish=1.0)[source]

Quadratically increasing, starts and ends slowly but fast in the middle.

spyral.easing.QuadraticOut(start=0.0, finish=1.0)[source]

Quadratically increasing, starts faster : f(x) = 2x - x^2

spyral.easing.Sine(amplitude=1.0, phase=0, end_phase=6.283185307179586)[source]

Depending on the arguments, moves at a different pace according to the sine function.

Events

This module contains functions and classes for creating and issuing events. For a list of the events that are built into Spyral, check the Event List.

spyral.event.keys

A special attribute for accessing the constants associated with a given key. For instance, spyral.keys.down and spyral.keys.f. This is useful for testing for keyboard events. A complete list of all the key constants can be found in the Keyboard Keys appendix.

spyral.event.mods

A special attribute for accessing the constants associated with a given mod key. For instance, spyral.mods.lshift (left shift) and spyral.mods.ralt (Right alt). This is useful for testing for keyboard events. A complete list of all the key constants can be found in the Keyboard Modifiers appendix.

class spyral.event.Event(**kwargs)[source]

A class for building for attaching data to an event. Keyword arguments will be named attributes of the Event when it is passed into queue:

collision_event = Event(ball=ball, paddle=paddle)
spyral.event.queue("ball.collides.paddle", collision_event)
spyral.event.clear_namespace(namespace, scene=None)[source]

Clears all handlers from namespaces that are at least as specific as the provided namespace.

Parameters:
  • namespace (str) – The complete namespace.
  • scene (Scene or None) – The scene to clear the namespace of; if it is None, then it will be attached to the currently running scene.
spyral.event.handle(event_name, event=None, scene=None)[source]

Instructs spyral to execute the handlers for this event right now. When you have a custom event, this is the function you call to have the event occur.

Parameters:
  • event_name (str) – The type of event (e.g., "system.quit", "input.mouse.up", or "pong.score".
  • event (Event) – An Event object that holds properties for the event.
  • scene (Scene or None.) – The scene to queue this event on; if None is given, the currently executing scene will be used.
spyral.event.queue(event_name, event=None, scene=None)[source]

Queues a new event in the system, meaning that it will be run at the next available opportunity.

Parameters:
  • event_name (str) – The type of event (e.g., "system.quit", "input.mouse.up", or "pong.score".
  • event (Event) – An Event object that holds properties for the event.
  • scene (Scene or None.) – The scene to queue this event on; if None is given, the currently executing scene will be used.
spyral.event.register(event_namespace, handler, args=None, kwargs=None, priority=0, scene=None)[source]

Registers an event handler to a namespace. Whenever an event in that event_namespace is fired, the event handler will execute with that event.

Parameters:
  • event_namespace (str) – the namespace of the event, e.g. "input.mouse.left.click" or "pong.score".
  • handler (function) – A function that will handle the event. The first argument to the function will be the event.
  • args (sequence) – any additional arguments that need to be passed in to the handler.
  • kwargs (dict) – any additional keyword arguments that need to be passed into the handler.
  • priority (int) – the higher the priority, the sooner this handler will be called in reaction to the event, relative to the other event handlers registered.
  • scene (Scene or None) – The scene to register this event on; if it is None, then it will be attached to the currently running scene.
spyral.event.register_dynamic(event_namespace, handler_string, args=None, kwargs=None, priority=0, scene=None)[source]

Similar to spyral.event.register() function, except that instead of passing in a function, you pass in the name of a property of this scene that holds a function.

Example:

class MyScene(Scene):
    def __init__(self):
        ...
        self.register_dynamic("orc.dies", "future_function")
        ...
Parameters:
  • event_namespace (str) – The namespace of the event, e.g. "input.mouse.left.click" or "pong.score".
  • handler (str) – The name of an attribute on this scene that will hold a function. The first argument to the function will be the event.
  • args (sequence) – any additional arguments that need to be passed in to the handler.
  • kwargs (dict) – any additional keyword arguments that need to be passed into the handler.
  • priority (int) – the higher the priority, the sooner this handler will be called in reaction to the event, relative to the other event handlers registered.
  • scene (Scene or None) – The scene to register this event on; if it is None, then it will be attached to the currently running scene.
spyral.event.register_multiple(event_namespace, handlers, args=None, kwargs=None, priority=0, scene=None)[source]

Similar to spyral.event.register() function, except a sequence of handlers are be given instead of just one.

Parameters:
  • event_namespace (string) – the namespace of the event, e.g. "input.mouse.left.click" or "pong.score".
  • handler (list of functions) – A list of functions that will be run on this event.
  • args (sequence) – any additional arguments that need to be passed in to the handler.
  • kwargs (dict) – any additional keyword arguments that need to be passed into the handler.
  • priority (int) – the higher the priority, the sooner this handler will be called in reaction to the event, relative to the other event handlers registered.
  • scene (Scene or None) – The scene to register this event on; if it is None, then it will be attached to the currently running scene.
spyral.event.register_multiple_dynamic(event_namespace, handler_strings, args=None, kwargs=None, priority=0, scene=None)[source]

Similar to spyral.Scene.register() function, except a sequence of strings representing handlers can be given instead of just one.

Parameters:
  • event_namespace (string) – the namespace of the event, e.g. "input.mouse.left.click" or "pong.score".
  • handler (list of strings) – A list of names of an attribute on this scene that will hold a function. The first argument to the function will be the event.
  • args (sequence) – any additional arguments that need to be passed in to the handler.
  • kwargs (dict) – any additional keyword arguments that need to be passed into the handler.
  • priority (int) – the higher the priority, the sooner this handler will be called in reaction to the event, relative to the other event handlers registered.
  • scene (Scene or None) – The scene to register this event on; if it is None, then it will be attached to the currently running scene.
spyral.event.unregister(event_namespace, handler, scene=None)[source]

Unregisters a registered handler for that namespace. Dynamic handler strings are supported as well.

Parameters:
  • event_namespace (str) – An event namespace
  • handler (a function or string.) – The handler to unregister.
  • scene (Scene or None) – The scene to unregister the event; if it is None, then it will be attached to the currently running scene.

Event Handlers

Event Handlers are used to process events from the system and pass them into Spyral. In addition to the default EventHandler, there are other event handlers for recording and restoring events to a file; using these events, you could generate demos or functional tests of your game. EventHandlers are an advanced feature that can be set through a private attribute of scenes: spyral.Scene._event_source

Note

Eventually, these event handlers will be set through the dev launcher.

class spyral.event.EventHandler[source]

Base event handler class.

get(types=[])[source]

Gets events from the event handler. Types is an optional iterable which has types which you would like to get.

tick()[source]

Should be called at the beginning of update cycle. For the event handler which is part of a scene, this function will be called automatically. For any additional event handlers, you must call this function manually.

class spyral.event.LiveEventHandler(output_file=None)[source]

An event handler which pulls events from the operating system.

The optional output_file argument specifies the path to a file where the event handler will save a custom json file that can be used with the ReplayEventHandler to show replays of a game in action, or be used for other clever purposes.

Note

If you use the output_file parameter, this function will reseed the random number generator, save the seed used. It will then be restored by the ReplayEventHandler.

class spyral.event.ReplayEventHandler(input_file)[source]

An event handler which replays the events from a custom json file saved by the LiveEventHandler.

pause()[source]

Pauses the replay of the events, making tick() a noop until resume is called.

resume()[source]

Resumes the replay of events.

Fonts

class spyral.Font(font_path, size, default_color=(0, 0, 0))

Font objects are how you get text onto the screen. They are loaded from TrueType Font files (*.ttf); system fonts are not supported for asthetic reasons. If you need direction on what the different size-related properties of a Font object, check out the Font example.

Parameters:
  • font_path (str) – The location of the *.ttf file.
  • size (int) – The size of the font; font sizes refer to the height of the font in pixels.
  • color (A three-tuple.) – A three-tuple of RGB values ranging from 0-255. Defaults to black (0, 0, 0).
ascent

The height in pixels from the font baseline to the top of the font. Read-only.

descent

The height in pixels from the font baseline to the bottom of the font. Read-only.

get_metrics(text)

Returns a list containing the font metrics for each character in the text. The metrics is a tuple containing the minimum x offset, maximum x offset, minimum y offset, maximum y offset, and the advance offset of the character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny, maxy, advance), ...]

Parameters:text (str) – The text to gather metrics on.
Return type:list of tuples.
get_size(text)

Returns the size needed to render the text without actually rendering the text. Useful for word-wrapping. Remember to keep in mind font kerning may be used.

Parameters:text (str) – The text to get the size of.
Returns:The size (width and height) of the text as it would be rendered.
Return type:Vec2D
height

The average height in pixels for each glyph in the font. Read-only.

linesize

The height in pixels for a line of text rendered with the font. Read-only.

render(text, color=None, underline=False, italic=False, bold=False)

Renders the given text. Italicizing and bolding are artificially added, and may not look good for many fonts. It is preferable to load a bold or italic font where possible instead of using these options.

Parameters:
  • text (str) – The text to render. Some characters might not be able to be rendered (e.g., “\n”).
  • color (A three-tuple.) – A three-tuple of RGB values ranging from 0-255. Defaults to the default Font color.
  • underline (bool) – Whether to underline this text. Note that the line will always be 1 pixel wide, no matter the font size.
  • italic (bool) – Whether to artificially italicize this font by angling it.
  • bold (bool) – Whether to artificially embolden this font by stretching it.
Return type:

Image

Forms

class spyral.Form(scene)

Bases: spyral.view.View

Forms are a subclass of Views that hold a set of Widgets. Forms will manage focus and event delegation between the widgets, ensuring that only one widget is active at a given time. Forms are defined using a special class-based syntax:

class MyForm(spyral.Form):
    name = spyral.widgets.TextInput(100, "Current Name")
    remember_me = spyral.widgets.Checkbox()
    save = spyral.widgets.ToggleButton("Save")

my_form = MyForm()

When referencing widgets in this way, the “Widget” part of the widget’s name is dropped: spyral.widgets.ButtonWidget becomes spyral.widgets.Button. Every widget in a form is accessible as an attribute of the form:

>>> print my_form.remember_me.value
"up"
Parameters:scene (Scene or View.) – The Scene or View that this Form belongs to.
add_widget(name, widget, tab_order=None)

Adds a new widget to this form. When this method is used to add a Widget to a Form, you create the Widget as you would create a normal Sprite. It is preferred to use the class-based method instead of this; consider carefully whether you can achieve dynamicity through visibility and disabling.

>>> my_widget = spyral.widgets.ButtonWidget(my_form, "save")
>>> my_form.add_widget("save", my_widget)
Parameters:
  • name (str) – A unique name for this widget.
  • widget (Widget) – The new Widget.
  • tab_order (int) – Sets the tab order for this widget explicitly. If tab-order is None, it is set to one higher than the highest tab order.
blur()

Defocuses the entire form.

focus(widget=None)

Sets the focus to be on a specific widget. Focus by default goes to the first widget added to the form.

Parameters:widget (Widget) – The widget that is gaining focus; if None, then the first widget gains focus.
next(wrap=True)

Focuses on the next widget in tab order.

Parameters:wrap (bool) – Whether to continue to the first widget when the end of the tab order is reached.
previous(wrap=True)

Focuses the previous widget in tab order.

Parameters:wrap (bool) – Whether to continue to the last widget when the first of the tab order is reached.
values

A dictionary of the values for all the fields, mapping the name of each widget with the value associated with that widget. Read-only.

Images

A module for manipulating Images, which are specially wrapped Pygame surfaces.

class spyral.image.Image(filename=None, size=None)[source]

The image is the basic drawable item in spyral. They can be created either by loading from common file formats, or by creating a new image and using some of the draw methods. Images are not drawn on their own, they are placed as the image attribute on Sprites to be drawn.

Almost all of the methods of an Image instance return the Image itself, enabling commands to be chained in a fluent interface.

Parameters:
  • size (Vec2D) – If size is passed, creates a new blank image of that size to draw on. If you do not specify a size, you must pass in a filename.
  • filename (str) – If filename is set, the file with that name is loaded. The appendix has a list of the valid image formats. If you do not specify a filename, you must pass in a size.
copy()[source]

Returns a copy of this image that can be changed while preserving the original.

Returns:A new image.
crop(position, size=None)[source]

Removes the edges of an image, keeping the internal rectangle specified by position and size.

Parameters:
  • position (a Vec2D or a Rect.) – The upperleft corner of the internal rectangle that will be preserved.
  • size (Vec2D or None.) – The size of the internal rectangle to preserve. If a Rect was passed in for position, this should be None.
Returns:

This image.

draw_arc(color, start_angle, end_angle, position, size=None, border_width=0, anchor='topleft')[source]

Draws an elliptical arc on this image.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • start_angle (float) – The starting angle, in radians, of the arc.
  • end_angle (float) – The ending angle, in radians, of the arc.
  • position (Vec2D or Rect) – The starting position of the ellipse (top-left corner). If position is a Rect, then size should be None.
  • size (Vec2D) – The size of the ellipse; should not be given if position is a rect.
  • border_width (int) – The width of the ellipse. If it is 0, the ellipse is filled with the color specified.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

draw_circle(color, position, radius, width=0, anchor='topleft')[source]

Draws a circle on this image.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • position (Vec2D) – The center of this circle
  • radius (int) – The radius of this circle
  • width (int) – The width of the circle. If it is 0, the circle is filled with the color specified.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

draw_ellipse(color, position, size=None, border_width=0, anchor='topleft')[source]

Draws an ellipse on this image.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • position (Vec2D or Rect) – The starting position of the ellipse (top-left corner). If position is a Rect, then size should be None.
  • size (Vec2D) – The size of the ellipse; should not be given if position is a rect.
  • border_width (int) – The width of the ellipse. If it is 0, the ellipse is filled with the color specified.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

draw_image(image, position=(0, 0), anchor='topleft')[source]

Draws another image over this one.

Parameters:
  • image (Image) – The image to overlay on top of this one.
  • position (Vec2D) – The position of this image.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

draw_lines(color, points, width=1, closed=False)[source]

Draws a series of connected lines on a image, with the vertices specified by points. This does not draw any sort of end caps on lines.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • points (A list of Vec2D s.) – A list of points that will be connected, one to another.
  • width (int) – The width of the lines.
  • closed (bool) – If closed is True, the first and last point will be connected. If closed is True and width is 0, the shape will be filled.
Returns:

This image.

draw_point(color, position, anchor='topleft')[source]

Draws a point on this image.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • position (Vec2D) – The position of this point.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

draw_rect(color, position, size=None, border_width=0, anchor='topleft')[source]

Draws a rectangle on this image.

Parameters:
  • color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
  • position (Vec2D or Rect) – The starting position of the rect (top-left corner). If position is a Rect, then size should be None.
  • size (Vec2D) – The size of the rectangle; should not be given if position is a rect.
  • border_width (int) – The width of the border to draw. If it is 0, the rectangle is filled with the color specified.
  • anchor (str) – The anchor parameter is an anchor position.
Returns:

This image.

fill(color)[source]

Fills the entire image with the specified color.

Parameters:color (a three-tuple of ints.) – a three-tuple of RGB values ranging from 0-255. Example: (255, 128, 0) is orange.
Returns:This image.
flip(flip_x=True, flip_y=True)[source]

Flips the image horizontally, vertically, or both.

Parameters:
  • flip_x (bool) – whether to flip horizontally.
  • flip_y (bool) – whether to flip vertically.
Returns:

This image.

height

The height of this image in pixels (int). Read-only.

rotate(angle)[source]

Rotates the image by angle degrees clockwise. This may change the image dimensions if the angle is not a multiple of 90.

Successive rotations degrate image quality. Save a copy of the original if you plan to do many rotations.

Parameters:angle (float) – The number of degrees to rotate.
Returns:This image.
scale(size)[source]

Scales the image to the destination size.

Parameters:size (Vec2D) – The new size of the image.
Returns:This image.
size

The (width, height) of the image (Vec2D <spyral.Vec2D). Read-only.

width

The width of this image in pixels (int). Read-only.

spyral.image.from_conglomerate(sequence)[source]

A function that generates a new image from a sequence of (image, position) pairs. These images will be placed onto a singe image large enough to hold all of them. More explicit and less convenient than from_seqeuence.

Parameters:sequence (List of image, position pairs.) – A list of (image, position) pairs, where the positions are Vec2D s.
Returns:A new Image
spyral.image.from_sequence(images, orientation='right', padding=0)[source]

A function that returns a new Image from a list of images by placing them next to each other.

Parameters:
  • images (List of Image) – A list of images to lay out.
  • orientation (str) – Either ‘left’, ‘right’, ‘above’, ‘below’, or ‘square’ (square images will be placed in a grid shape, like a chess board).
  • padding (int or a list of ints.) – The padding between each image. Can be specified as a scalar number (for constant padding between all images) or a list (for different paddings between each image).
Returns:

A new Image

spyral.image.render_nine_slice(image, size)[source]

Creates a new image by dividing the given image into a 3x3 grid, and stretching the sides and center while leaving the corners the same size. This is ideal for buttons and other rectangular shapes.

Parameters:
  • image (Image) – The image to stretch.
  • size (Vec2D) – The new (width, height) of this image.
Returns:

A new Image similar to the old one.

Keyboard

The keyboard modules provides an interface to adjust the keyboard’s repeat rate.

spyral.keyboard.repeat

When the keyboard repeat is enabled, keys that are held down will keep generating new events over time. Defaults to False.

spyral.keyboard.delay

int to control how many milliseconds before the repeats start.

spyral.keyboard.interval

int to control how many milliseconds to wait between repeated events.

Mouse

The mouse modules provides an interface to adjust the mouse cursor.

spyral.mouse.visible

Bool that adjust whether the mouse cursor should be shown. This is useful if you want to, for example, use a Sprite instead of the regular mouse cursor.

spyral.mouse.cursor

str value that lets you choose from among the built-in options for cursors. The options are:

  • "arrow" : the regular arrow-shaped cursor
  • "diamond" : a diamond shaped cursor
  • "x" : a broken X, useful for indicating disabled states.
  • "left": a triangle pointing to the left
  • "right": a triangle pointing to the right

Warning

Custom non-Sprite mouse cursors are currently not supported.

Rects

class spyral.Rect(*args)

Rect represents a rectangle and provides some useful features. Rects can be specified 3 ways in the constructor:

  1. Four numbers, x, y, width, height
  2. Two tuples, (x, y) and (width, height)
  3. Another rect, which is copied
>>> rect1 = spyral.Rect(10, 10, 64, 64)               # Method 1
>>> rect2 = spyral.Rect((10, 10), (64, 64))           # Method 2
>>> rect3 = spyral.Rect(rect1.topleft, rect1.size)    # Method 2
>>> rect4 = spyral.Rect(rect3)                        # Method 3

Rects support all the usual anchor points as attributes, so you can both get rect.center and assign to it. Rects also support attributes of right, left, top, bottom, x, and y.

>>> rect1.x
10
>>> rect1.centerx
42.0
>>> rect1.width
64
>>> rect1.topleft
Vec2D(10, 10)
>>> rect1.bottomright
Vec2D(74, 74)
>>> rect1.center
Vec2D(42.0, 42.0)
>>> rect1.size
Vec2D(64, 64)
clip(other)

Returns a Rect which is cropped to be completely inside of other. If the other does not overlap with this rect, a rect of size 0 is returned.

Parameters:other (Rect) – The other Rect.
Returns:A new Rect
clip_ip(other)

Modifies this rect to be cropped completely inside of other. If the other does not overlap with this rect, this rect will have a size of 0.

Parameters:other (Rect) – The other Rect.
collide_point(point)
Parameters:point (Vec2D) – The point.
Returns:A bool indicating whether the point is contained within this rect.
collide_rect(other)

Returns True if this rect collides with the other rect.

Parameters:other (Rect) – The other Rect.
Returns:A bool indicating whether this rect is contained within another.
contains(other)

Returns True if the other rect is contained inside this rect.

Parameters:other (Rect) – The other Rect.
Returns:A bool indicating whether this rect is contained within another.
copy()

Returns a copy of this rect

Returns:A new Rect
inflate(width, height)

Returns a copy of this rect inflated by width and height.

Parameters:
  • width (float) – The amount to add horizontally.
  • height (float) – The amount to add vertically.
Returns:

A new Rect

inflate_ip(width, height)

Inflates this rect by width, height.

Parameters:
  • width (float) – The amount to add horizontally.
  • height (float) – The amount to add vertically.
move(x, y)

Returns a copy of this rect offset by x and y.

Parameters:
  • x (float) – The horizontal offset.
  • y (float) – The vertical offset.
Returns:

A new Rect

move_ip(x, y)

Moves this rect by x and y.

Parameters:
  • x (float) – The horizontal offset.
  • y (float) – The vertical offset.
union(other)

Returns a new rect which represents the union of this rect with other – in other words, a new rect is created that can fit both original rects.

Parameters:other (Rect) – The other Rect.
Returns:A new Rect
union_ip(other)

Modifies this rect to be the union of it and the other – in other words, this rect will expand to include the other rect.

Parameters:other (Rect) – The other Rect.

Scenes

class spyral.Scene(size=None, max_ups=None, max_fps=None)

Creates a new Scene. When a scene is not active, no events will be processed for it. Scenes are the basic units that are executed by spyral for your game, and should be subclassed and filled in with code which is relevant to your game. The Director, is a manager for Scenes, which maintains a stacks and actually executes the code.

Parameters:
  • size (width, height) – The size of the scene internally (or “virtually”). This is the coordinate space that you place Sprites in, but it does not have to match up 1:1 to the window (which could be scaled).
  • max_ups (int) – Maximum updates to process per second. By default, max_ups is pulled from the director.
  • max_fps (int) – Maximum frames to draw per second. By default, max_fps is pulled from the director.
add_style_function(name, function)

Adds a new function that will then be available to be used in a stylesheet file.

Example:

import random
class MyScene(spyral.Scene):
    def __init__(self):
        ...
        self.load_style("my_style.spys")
        self.add_style_function("randint", random.randint)
        # inside of style file you can now use the randint function!
        ...
Parameters:
  • name (string) – The name the function will go by in the style file.
  • function (function) – The actual function to add to the style file.
background

The background of this scene. The given Image must be the same size as the Scene. A background will be handled intelligently by Spyral; it knows to only redraw portions of it rather than the whole thing, unlike a Sprite.

collide_point(sprite, point)

Returns whether the sprite is colliding with the point.

Parameters:
  • sprite (Sprite) – A sprite
  • point (Vec2D) – A point
Returns:

A bool

collide_rect(sprite, rect)

Returns whether the sprite is colliding with the rect.

Parameters:
  • sprite (Sprite) – A sprite
  • rect (Rect) – A rect
Returns:

A bool

collide_sprites(first, second)

Returns whether the first sprite is colliding with the second.

Parameters:
  • first (Sprite or a View) – A sprite or view
  • second (Sprite or a View) – Another sprite or view
Returns:

A bool

height

The height of this scene. Read-only number.

layers

A list of strings representing the layers that are available for this scene. The first layer is at the bottom, and the last is at the top.

Note that the layers can only be set once.

load_style(path)

Loads the style file in path and applies it to this Scene and any Sprites and Views that it contains. Most properties are stylable.

Parameters:path (str) – The location of the style file to load. Should have the extension ”.spys”.
parent

Returns this scene. Read-only.

rect

Returns a Rect representing the position (0, 0) and size of this Scene.

redraw()

Force the entire visible window to be completely redrawn.

This is particularly useful for Sugar, which loves to put artifacts over our window.

scene

Returns this scene. Read-only.

size

Read-only property that returns a Vec2D of the width and height of the Scene’s size. This is the coordinate space that you place Sprites in, but it does not have to match up 1:1 to the window (which could be scaled). This property can only be set once.

width

The width of this scene. Read-only number.

Sprites

class spyral.Sprite(parent)

Sprites are how images are positioned and drawn onto the screen. They aggregate together information such as where to be drawn, layering information, and more.

Parameters:parent (View or Scene) – The parent that this Sprite will belong to.
anchor

Defines an anchor point where coordinates are relative to on the image. String.

angle

An angle to rotate the image by. Rotation is computed after scaling and flipping, and keeps the center of the original image aligned with the center of the rotated image.

animate(animation)

Animates this sprite given an animation. Read more about animation.

Parameters:animation (Animation) – The animation to run.
collide_point(point)

Returns whether this sprite is currently colliding with the position. This uses the appropriate offsetting for the sprite within its views.

Parameters:point (Vec2D) – The point (relative to the window dimensions).
Returns:bool indicating whether this sprite is colliding with the position.
collide_rect(rect)

Returns whether this sprite is currently colliding with the rect. This uses the appropriate offsetting for the sprite within its views.

Parameters:rect (Rect) – The rect (relative to the window dimensions).
Returns:bool indicating whether this sprite is colliding with the rect.
collide_sprite(other)

Returns whether this sprite is currently colliding with the other sprite. This collision will be computed correctly regarding the sprites offsetting and scaling within their views.

Parameters:other (Sprite) – The other sprite
Returns:bool indicating whether this sprite is colliding with the other sprite.
flip_x

A boolean that determines whether the image should be flipped horizontally.

flip_y

A boolean that determines whether the image should be flipped vertically.

height

The height of the image after all transforms. Number.

image

The Image for this sprite.

kill()

When you no longer need a Sprite, you can call this method to have it removed from the Scene. This will not remove the sprite entirely from memory if there are other references to it; if you need to do that, remember to del the reference to it.

layer

String. The name of the layer this sprite belongs to. See layering for more.

mask

A Rect to use instead of the current image’s rect for computing collisions. None if the image’s rect should be used.

parent

The parent of this sprite, either a View or a Scene. Read-only.

pos

The position of a sprite in 2D coordinates, represented as a Vec2D

rect

Returns a Rect representing the position and size of this Sprite’s image. Note that if you change a property of this rect that it will not actually update this sprite’s properties:

>>> my_sprite.rect.top = 10

Does not adjust the y coordinate of my_sprite. Changing the rect will adjust the sprite however

>>> my_sprite.rect = spyral.Rect(10, 10, 64, 64)
scale

A scale factor for resizing the image. When read, it will always contain a spyral.Vec2D with an x factor and a y factor, but it can be set to a numeric value which wil ensure identical scaling along both axes.

scale_x

The x factor of the scaling that’s kept in sync with scale. Number.

scale_y

The y factor of the scaling that’s kept in sync with scale. Number.

scene

The top-level scene that this sprite belongs to. Read-only.

size

The size of the image after all transforms (Vec2D).

stop_all_animations()

Stops all animations currently running on this sprite.

stop_animation(animation)

Stops a given animation currently running on this sprite.

Parameters:animation (Animation) – The animation to stop.
visible

A boolean indicating whether this sprite should be drawn.

width

The width of the image after all transforms. Number.

x

The x coordinate of the sprite, which will remain synced with the position. Number.

y

The y coordinate of the sprite, which will remain synced with the position. Number

Vec2Ds

class spyral.Vec2D(*args)

Vec2D is a class that behaves like a 2-tuple, but with a number of convenient methods for vector calculation and manipulation. It can be created with two arguments for x,y, or by passing a 2-tuple.

In addition to the methods documented below, Vec2D supports the following:

>>> from spyral import Vec2D
>>> v1 = Vec2D(1,0)
>>> v2 = Vec2D((0,1))    # Note 2-tuple argument!

Tuple access, or x,y attribute access

>>> v1.x
1
>>> v1.y
0
>>> v1[0]
1
>>> v1[1]
0

Addition, subtraction, and multiplication

>>> v1 + v2
Vec2D(1, 1)
>>> v1 - v2
Vec2D(1, -1)
>>> 3 * v1
Vec2D(3, 0)
>>> (3, 4) * (v1+v2)
Vec2D(3, 4)

Compatibility with standard tuples

>>> v1 + (1,1)
Vec2D(2, 1)
>>> (1,1) + v1
Vec2D(2, 1)
angle(other)

Returns the angle between this point and another point.

Parameters:other (2-tuple or Vec2D) – the other point
Return type:float
distance(other)

Returns the distance from this Vec2D to the other point.

Parameters:other (2-tuple or Vec2D) – the other point
Return type:float
dot(other)

Returns the dot product of this point with another.

Parameters:other (2-tuple or Vec2D) – the other point
Return type:int
floor()

Converts the components of this vector into ints, discarding anything past the decimal place.

Returns:this Vec2D
static from_polar(*args)

Takes in radius, theta or (radius, theta) and returns rectangular Vec2D.

Return type:Vec2D
get_angle()

Return the angle this vector makes with the positive x axis.

Return type:float
get_length()

Return the length of this vector.

Return type:float
get_length_squared()

Return the squared length of this vector.

Return type:int
normalized()

Returns a new vector based on this one, normalized to length 1. That is, it keeps the same angle, but its length is now 1.

Return type:Vec2D
perpendicular()

Returns a new Vec2D perpendicular to this one.

Return type:Vec2D
projection(other)

Returns the projection of this Vec2D onto another point.

Parameters:other (2-tuple or Vec2D) – the other point
Return type:float
rotated(angle, center=(0, 0))

Returns a new vector from the old point rotated by angle radians about the optional center.

Parameters:
  • angle (float) – angle in radians.
  • center (2-tuple or Vec2D) – an optional center
Return type:

Vec2D

to_polar()

Returns Vec2D(radius, theta) for this vector, where radius is the length and theta is the angle.

Return type:Vec2D

Views

class spyral.View(parent)

Creates a new view with a scene or view as a parent. A view is a collection of Sprites and Views that can be collectively transformed - e.g., flipped, cropped, scaled, offset, hidden, etc. A View can also have a mask, in order to treat it as a single collidable object. Like a Sprite, a View cannot be moved between Scenes.

Parameters:parent (View or Scene) – The view or scene that this View belongs in.
anchor

Defines an anchor point where coordinates are relative to on the view. String.

collide_point(pos)

Returns whether this view is colliding with the point.

Parameters:point (Vec2D) – A point
Returns:A bool
collide_rect(rect)

Returns whether this view is colliding with the rect.

Parameters:rect (Rect) – A rect
Returns:A bool
collide_sprite(other)

Returns whether this view is colliding with the sprite or view.

Parameters:other (Sprite or a View) – A sprite or a view
Returns:A bool
crop

A bool that determines whether the view should crop anything outside of it’s size (default: True).

crop_height

The height of the cropped area. Number.

crop_size

The (width, height) of the area that will be cropped; anything outside of this region will be removed when the crop is active.

crop_width

The width of the cropped area. Number.

height

The height of the view. Number.

kill()

Completely remove any parent’s links to this view. When you want to remove a View, you should call this function.

layer

The layer (a str) that this View is on, within its parent.

layers

A list of strings representing the layers that are available for this view. The first layer is at the bottom, and the last is at the top. For more information on layers, check out the layers appendix.

mask

Return this View’s mask, a spyral.Rect representing the collidable area.

Return type:Rect if this value has been set, otherwise it will be None.
output_height

The height of this view when drawn on the parent. Number.

output_size

The (width, height) of this view when drawn on the parent (Vec2D). Defaults to size of the parent.

output_width

The width of this view when drawn on the parent. Number.

parent

The first parent View or Scene that this View belongs to. Read-only.

pos

Returns the position (Vec2D) of this View within its parent.

rect

A Rect representing the position and size of this View. Can be set through a Rect, a 2-tuple of position and size, or a 4-tuple.

scale

A scale factor from the size to the output_size for the view. It will always contain a Vec2D with an x factor and a y factor, but it can be set to a numeric value which will be set for both coordinates.

scale_x

The x factor of the scaling. Kept in sync with scale. Number.

scale_y

The y factor of the scaling. Kept in sync with scale. Number.

scene

The top-most parent Scene that this View belongs to. Read-only.

size

The (width, height) of this view’s coordinate space (Vec2D). Defaults to size of the parent.

visible

Whether or not this View and its children will be drawn (bool). Defaults to False.

width

The width of the view. Number.

x

The x coordinate of the view, which will remain synced with the position. Number.

y

The y coordinate of the view, which will remain synced with the position. Number.

Widgets

class spyral.widgets.ButtonWidget(form, name, text='Okay')[source]

A ButtonWidget is a simple button that can be pressed. It can have some text. If you don’t specify an explicit width, then it will be sized according to it’s text.

Parameters:
  • form (Form) – The parent form that this Widget belongs to.
  • name (str) – The name of this widget.
  • text (str) – The text that will be rendered on this button.
text

The text rendered on this button (str).

value

Whether or not this widget is currently "up" or "down".

class spyral.widgets.CheckboxWidget(form, name)[source]

A CheckboxWidget is identical to a ToggleButtonWidget, only it doesn’t have any text.

class spyral.widgets.ToggleButtonWidget(form, name, text='Okay')[source]

A ToggleButtonWidget is similar to a Button, except that it will stay down after it’s been clicked, until it is clicked again.

Parameters:
  • form (Form) – The parent form that this Widget belongs to.
  • name (str) – The name of this widget.
  • text (str) – The text that will be rendered on this button.
class spyral.widgets.TextInputWidget(form, name, width, value='', default_value=True, text_length=None, validator=None)[source]

The TextInputWidget is used to get text data from the user, through an editable textbox.

Parameters:
  • form (Form) – The parent form that this Widget belongs to.
  • name (str) – The name of this widget.
  • width (int) – The rendered width in pixels of this widget.
  • value (str) – The initial value of this widget.
  • default_value (bool) – Whether to clear the text of this widget the first time it gains focus.
  • text_length (int) – The maximum number of characters that can be entered into this box. If None, then there is no maximum.
  • validator (set) – A set of characters that are allowed to be printed. Defaults to all regularly printable characters (which does not include tab and newlines).
anchor

Defines an anchor point <anchors> where coordinates are relative to on the view. String.

cursor_pos

The current index of the text cursor within this widget. A int.

nine_slice

The Image used to build the internal nine-slice image.

padding

A single int representing both the vertical and horizontal padding within this widget.

value

The current value of this widget, i.e, the text the user has input. When this value is changed, it triggers a form.<name>.<widget>.changed event. A str.