Loads a sound from disk. Supported formats are WAV (.wav) and Ogg Vorbis (.ogg).
Sounds can be played immediately with the play() method; or used as the parameter to a new Voice, if control over the playback is required.
Sounds can be streamed by specifying stream=True; this causes them to load faster but incur a small latency on playback. Background music should always be streamed. Sound effects should not be streamed.
Sounds are kept in memory until explicitly unloaded, see unload().
Parameters: |
|
---|
Release all resources associated with the sound.
Play the sound as a one-shot.
The sound will be played to completion. If the sound is played more than once at a time, it will mix with all previous instances of itself. If you need more control over the playback of sounds, see Voice.
Parameters: |
|
---|
Handle to a single instance of a sound. Voices can be used to:
A voice is created to play back a single sound instance once (besides any looping), and cannot be reused to play another sound, or even to play the same sound once playback of that sound completes.
Do not use a Voice to play simple sound effects that do not require control during playing; see Sound.play().
Create a voice by first loading the sound, then creating a voice to play it:
engine_sound = bacon.Sound('res/Engine.wav')
engine_voice = bacon.Voice(engine_sound)
engine_voice.play()
Specify the loop parameter to play music that loops until stopped:
music_sound = bacon.Sound('res/MyMusic.ogg', stream=True)
music_voice = bacon.Voice(music_sound, loop=True)
music_voice.play()
Voices become invalid when their sound completes (after their callback returns, if one is set). Continuing to use a voice after it has finished will result in an exception; you can check the state of a voice with playing.
Paused voices remain in memory until explicitly destroyed with destroy().
Parameters: |
|
---|
Destroy a voice. Required if a sound is stopped before completing to free associated resources.
Being or resume playing the sound.
Pause playback of the sound.
Get or set the gain (volume) of the sound, between 0.0 and 1.0. Defaults to 1.0
Get or set the pitch (sample rate) of the sound, between 0.4 and 16.0, with 1.0 being normal playback speed.
Get or set the stereo pan of the sound, between -1.0 and 1.0.
True if the sound is currently playing, False if it has finished.
Set the loop points within the sound.
The sound must have been created with loop=True. The default parameters cause the loop points to be set to the entire sound duration.
Note: | There is currently no API for converting sample numbers to times. |
---|---|
Parameters: |
|
Set a callback function to be called when the sound finishes. The function takes no arguments.
Get or set the current sample position within the sound.
Note: | There is currently no API for converting sample numbers to times. |
---|
Base class for all Bacon games. An instance of this class is passed to run(). Override methods on this class to handle game events such as on_tick(). A complete example of a game:
class MyGame(bacon.Game):
def on_tick(self):
# Update and draw game here.
pass
# Start the game
bacon.run(MyGame())
Called once when the game starts. You can use this to do any initialization that requires the graphics device to have been initialized; for example, rendering to a texture.
Called once per frame to update and render the game. You may only call drawing functions within the scope of this method.
Called when a key on the keyboard is pressed or released.
Parameters: |
|
---|
Called when a mouse button is pressed or released.
Parameters: |
|
---|
Called when the mouse scroll wheel is scrolled. Most mice have a scroll wheel that moves in the y axis only; Apple trackpads and mice support scrolling in x as well.
Note: | units are aribitrary and not currently consistent across platforms |
---|---|
Parameters: |
|
Called when size of the window changes.
Parameters: |
|
---|
Called when a game controller is connected.
Parameters: | controller – the Controller that is now available for polling and events |
---|
Called when a game controller is disconnected. You should use the controller parameter only to identify a previously used controller; its properties and values will no longer be available.
Parameters: | controller – the Controller that was disconnected |
---|
Called when a button on a game controller is pressed or released.
Parameters: |
|
---|
Called when an axis on a game controller is moved.
Parameters: |
|
---|
Start running the game. The window is created and shown at this point, and then the main event loop is entered. ‘game.on_tick’ and other event handlers are called repeatedly until the game exits.
If a game is already running, this function replaces the Game instance that receives events.
Stop the game loop and exit the application before the next on_tick() is called.
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
Represents the state of a connected game controller. Controller instances are created automatically when a physical game controller device is detected, and destroyed when they are disconnected. To obtain a reference to a Controller, override Game.on_controller_connected().
A numeric vendor ID that can be used to identify the type of device, when combined with the product_id.
A numeric product ID that can be used to identify the type of device, when combined with the vendor_id.
A human-readable name of the device that can be used to identify it to the user.
The supported profile of the device, a member of the enumeration GameControllerProfiles. Game controllers with the generic profile do not provide semantic meanings to any of the buttons or axes, and must usually be configured by the player unless the device type is known by the game.
The standard profile describes a game controller with no analogue sticks or triggers.
The extended profile describes a game controller with a layout compatible with an Xbox 360 controller.
For a game controller to appear in the standard or extended profiles, it must have been discovered by a suitable SDK on the host platform: on Windows, this is XInput, which only supports the Xbox 360 controller. On OS X and iOS, this is the GameController SDK, which supports a limited range of new devices.
The index of the controller, between 0 and 4 (read-only). Typically this is assigned in the order the controllers are detected, however some controllers may have an intrinsic “player number” that is exposed through this number. No two controllers will have the same controller index.
Returns True if the controller has the requested axis, a value of enumeration ControllerAxes.
Get the absolute value of the requested axis.
Parameters: | axis – An axis, one of the values in ControllerAxes. |
---|---|
Returns: | The absolute position of the axis, between -1.0 and 0.0. |
Returns True if the controller has the requested button, a value of enumeration ControllerButtons.
Get the pressed state of the requested button.
Parameters: | button – A button, one of the values in ControllerButtons. |
---|---|
Returns: | True` if the button is currently pressed, otherwise False. |
True if the controller is still connected; False if it has been disconnected.
Once a controller has been disconnected, it is never reconnected (if the same physical device is reconnected, a new Controller instance is created).
The absolute X axis value of the left thumb-stick, or the main stick on a joystick.
The absolute Y axis value of the left thumb-stick, or the main stick on a joystick.
The absolute X axis value of the right thumb-stick, or the twist axis on a joystick.
The absolute Y axis value of the right thumb-stick, or the throttle control on a joystick.
The absolute left trigger value, between 0.0 and 1.0. Available only on game controllers with the extended profile.
The absolute right trigger value, between 0.0 and 1.0. Available only on game controllers with the extended profile.
True if the start button is pressed. Available only on game controllers with the standard or extended profiles.
True if the back button is pressed. Available only on the Xbox 360 controller on Windows.
True if the select button is pressed.
True if the up action button (“Y” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.
True if the down action button (“A” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.
True if the left action button (“X” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.
True if the right action button (“B” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.
True if the up directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.
True if the down directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.
True if the left directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.
True if the right directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.
True if the left shoulder button is pressed. Available only on game controllers with the standard or extended profiles.
True if the right shoulder button is pressed. Available only on game controllers with the standard or extended profiles.
True if the left thumb stick is depressed. Available only on game controllers with the extended profile.
True if the right thumb stick is depressed. Available only on game controllers with the extended profile.
Map buttons and axes on a device controller to game button and axes. Typically used to map generic inputs to semantic inputs associated with a controller profile.
Parameters: |
|
---|
Register a mapping for controllers with the given vendor and product IDs. The mapping will replace any existing mapping for these IDs for controllers not yet connected.
Parameters: |
|
---|
Find a mapping that can apply to the given controller. Returns None if unsuccessful.
Parameters: | controller – Controller to look up |
---|---|
Returns: | ControllerMapping |
Game controller events:
Clear the current target to the given RGBA color. Each color component must be in the range 0.0 to 1.0. You should clear the window at the beginning of each frame. Failure to do so may cause visual artifacts and/or poor performance on some platforms.
Draw a line from coordinates (x1, y1) to (x2, y2).
No texture is applied.
Draw a rectangle bounding coordinates (x1, y1) to (x2, y2).
No texture is applied.
Fill a rectangle bounding coordinates (x1, y1) to (x2, y2).
No texture is applied.
Set the current graphics blend mode. All subsequent drawing commands will be rendered with this blend mode.
The default blend mode is (BlendFlags.one, BlendFlags.one_minus_src_alpha), which is appropriate for premultiplied alpha.
Parameters: |
|
---|
Translate the current graphics transform by (x, y) units.
Scale the current graphics transform by multiplying through (sx, sy).
Rotate the current graphics transform by radians counter-clockwise.
Save the current graphics transform by pushing it on the transform stack. It can be restored by calling pop_transform().
Restore a previously saved transform by popping it off the transform stack.
Replace the current graphics transform with the given 4x4 matrix. For example, to replace the transform with a translation by (x, y):
bacon.set_transform([1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, 0,
0, 0, 0, 1])
Parameters: | matrix – a 4x4 matrix in column major order, represented as a flat 16 element sequence. |
---|
Set the current graphics color to the given RGBA values. Typically each component has a value between 0.0 and 1.0, however out-of-range values are permitted and may be used for special effects with an appropriate shader.
The color is reset to white at the beginning of each frame.
Multiplies the current graphics color component-wise by the given RGBA values.
Save the current graphics color by pushing it on the color stack. It can be restored with pop_color().
The color stack is cleared at the beginning of each frame, and the default color reset to white.
Restore a previously saved graphics color by popping it off the color stack.
An image that can be passed to draw_image() and other rendering functions.
There are two forms to the Image constructor. The first loads an image from a file:
Image(file, premultiply_alpha=True, discard_bitmap=True)
The other creates an empty image which can then be rendered to using set_frame_buffer():
Image(width, height)
There may be GPU limits on the maximum size of an image that can be uploaded to the GPU (typically 2048x2048 is a safe upper bound for current generation mobile devices; desktops may support up to 8192x8192). There is no diagnostic if the device limit is exceeded, the image will not render.
Images are retained by the renderer until unload() is explicitly called.
Parameters: |
|
---|
Releases renderer resources associated with this image.
The width of the image, in texels (read-only).
The height of the image, in texels (read-only).
The content scale applied to the image (read-only).
Get an image that refers to the given rectangle within this image. The image data is not actually copied; if the image region is rendered into, it will affect this image.
Parameters: |
|
---|---|
Returns: |
Draw an image.
The image’s top-left corner is drawn at (x1, y1), and its lower-left at (x2, y2). If x2 and y2 are omitted, they are calculated to render the image at its native resoultion.
Note that images can be flipped and scaled by providing alternative values for x2 and y2.
Parameters: | image – an Image to draw |
---|
Draw a rectangular region of an image.
The part of the image contained by the rectangle in texel-space by the coordinates (ix1, iy1) to (ix2, iy2) is drawn at coordinates (x1, y1) to (x2, y2). All coordinates have the origin (0, 0) at the upper-left corner.
For example, to draw the left half of a 100x100 image at coordinates (x, y):
bacon.draw_image_region(image, x, y, x + 50, y + 100,
0, 0, 50, 100)
Parameters: | image – an Image to draw |
---|
A font that can be used for rendering text. Fonts are loaded from TrueType (.ttf) files at a particular point size:
font = Font('res/DejaVuSans.ttf', 24.0)
Note that the point size of a font has a complex relationship to its height in pixels, affected by the design of the font, grid-fitting, and device DPI (always 96 in Bacon). Once a font is loaded, its metrics can be queried to get the font’s design measurements in pixels.
Fonts are never unloaded.
Parameters: |
|
---|
Retrieves the pixel-space design metrics of the font.
Returns: | FontMetrics |
---|
The ascent of the font above the baseline, in pixels; typically negative.
The descent of the font below the baseline, in pixels; typically positive.
Retrieves a Glyph that renders the given character.
Parameters: | char – the character (a string) |
---|
Retrieves a list of Glyph for the given string.
Parameters: | str – the string to render |
---|
Calculates the width of the given string in this font.
Parameters: | str – the string to measure |
---|---|
Return float: | width of the string, in pixels |
Draw a string with the given font.
Note: | Text alignment and word-wrapping is not yet implemented. The text is rendered with the left edge and baseline at (x, y). |
---|---|
Parameters: |
|
Set the current graphics shader. All subsequent drawing commands will be rendered with this shader. To reset to the default shader, pass None as the argument.
The shader is automatically reset to the default shader at the beginning of each frame.
Parameters: | shader – a Shader to render with |
---|
A GPU shader object that can be passed to set_shader().
The default shader is as follows, and demonstrates the available vertex attributes and uniforms:
default_shader = Shader(vertex_source=
"""
precision highp float;
attribute vec3 a_Position;
attribute vec2 a_TexCoord0;
attribute vec4 a_Color;
varying vec2 v_TexCoord0;
varying vec4 v_Color;
uniform mat4 g_Projection;
void main()
{
gl_Position = g_Projection * vec4(a_Position, 1.0);
v_TexCoord0 = a_TexCoord0;
v_Color = a_Color;
}
""",
fragment_source=
"""
precision highp float;
uniform sampler2D g_Texture0;
varying vec2 v_TexCoord0;
varying vec4 v_Color;
void main()
{
gl_FragColor = v_Color * texture2D(g_Texture0, v_TexCoord0);
}
""")
The shading language is OpenGL-ES SL 2. The shader will be translated automatically into HLSL on Windows, and into GLSL on other desktop platforms.
Parameters: |
|
---|
Map of shader uniforms available on this shader.
Type: | read-only dictionary of string to ShaderUniform |
---|
Get the vertex shader source
Type: | str |
---|
Get the fragment shader source
Type: | str |
---|
A uniform variable, either shared between all shaders (if its name begins with g_), specific to a particular shader.
See: | |
---|---|
Parameters: |
|
Boolean indicating if this shader uniform’s value is shared between all shaders
Type: | bool |
---|
Current value of the uniform as seen by the shader.
Uniforms with names beginning with g_ (e.g., g_Projection) share their value across all shaders. Otherwise, the uniform value is unique to this shader.
The type of the value depends on the type of the uniform:
For uniform arrays, the value is a sequence of the above types. For example, a uniform of type vec2[3] can be assigned:
value = ((0, 1), (2, 3), (4, 5))
Name of the uniform, as it appears in the shader.
Type: | str |
---|
Type of the uniform, or, if the uniform is an array, the element type of the array.
Type: | an enumeration of ShaderUniformType |
---|
The size of the array, or 1 if this uniform is not an array.
Type: | int |
---|
Exposes functions for the system mouse or trackpad.
Do not construct an instance of this class, use the singleton mouse.
Location of the mouse in the window along the X axis, in pixels.
Location of the mouse in the window along the Y axis, from top to bottom, in pixels.
True if the left mouse button is currently pressed.
True if the middle mouse button is currently pressed.
True if the right mouse button is currently pressed.
State of the system mouse or trackpad; an instance of Mouse.
For example, to query the current mouse position within the window:
x, y = mouse.x, mouse.y
To query if the left mouse button is currently pressed:
if mouse.left:
pass
Mouse events:
Path to resources. Set to the script directory by default during development, and the executable directory for frozen applications.
Properties of the game window.
The window is constructed automatically when run() is called. The window singleton provides access to the members of this class both before and after run is called.
For example, to set up some common window properties for a game:
bacon.window.title = 'Destiny of Swords'
bacon.window.width = 800
bacon.window.height = 600
All properties can be modified at runtime, for example to toggle in and out of fullscreen.
Get or set the width of the drawable part of the window, in pixels.
Get or set the height of the drawable part of the window, in pixels.
Get or set the title of the window (a string)
If True the window can be resized and maximized by the user. See Game.on_resize().
Set to True to make the game fullscreen, False to play in a window.
Optional image to use as the default render target.
If set, all rendering will be to this image, which will appear scaled and letterboxed if necessary in the center of the window. width, height and content_scale will return the dimensions of this target instead of the window dimensions.
Type: | Image |
---|
The scaling factor applied to the window. On Windows this is always 1.0. On OS X with a retina display attached, content_scale will default to 2.0.
Fonts and offscreen render targets are created at this content scale by default, to match the pixel density.
You can explicitly set content_scale to 1.0, disabling the high-resolution framebuffer. You should do so before loading any assets.
Type: | float |
---|