Table Of Contents

Previous topic

Diagnostics

Next topic

Key code reference

This Page

Reference

Audio

class bacon.Sound(file, stream=False)

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:
  • file – path to the sound file to load. The sound format is deduced from the file extension.
  • stream – if True, the sound is streamed from disk; otherwise it is fully cached in memory.
unload()

Release all resources associated with the sound.

play(gain=None, pan=None, pitch=None)

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:
  • gain – optional volume level to play the sound back at, between 0.0 and 1.0 (defaults to 1.0)
  • pan – optional stereo pan, between -1.0 (left) and 1.0 (right)
  • pitch – optional sampling rate modification, between 0.4 and 16.0, where 1.0 represents the original pitch
class bacon.Voice(sound, loop=False)

Handle to a single instance of a sound. Voices can be used to:

  • Modify the parameters of a sound while it’s playing (for example, its gain, pan, or pitch)
  • Pause and resume playback
  • Determine the current playback head position and seek to a different position
  • Provide a callback for when the sound finishes playing
  • Create and control a sound that loops automatically

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:
  • sound – a Sound to play
  • loop – if True, the voice will be set to looping playback
destroy()

Destroy a voice. Required if a sound is stopped before completing to free associated resources.

play()

Being or resume playing the sound.

stop()

Pause playback of the sound.

gain

Get or set the gain (volume) of the sound, between 0.0 and 1.0. Defaults to 1.0

pitch

Get or set the pitch (sample rate) of the sound, between 0.4 and 16.0, with 1.0 being normal playback speed.

pan

Get or set the stereo pan of the sound, between -1.0 and 1.0.

playing

True if the sound is currently playing, False if it has finished.

set_loop_points(start_sample=-1, end_sample=0)

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:
  • start_sample – sample number to loop back to
  • end_sample – sample number to loop at
callback

Set a callback function to be called when the sound finishes. The function takes no arguments.

position

Get or set the current sample position within the sound.

Note:There is currently no API for converting sample numbers to times.

Keyboard

class bacon.Keys

See: Key code reference

bacon.keys

Set of keyboard keys that are currently pressed. Each element is a enumerator of Keys.

Keyboard events:

Game

class bacon.Game

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())
on_init()

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.

on_tick()

Called once per frame to update and render the game. You may only call drawing functions within the scope of this method.

on_key(key, pressed)

Called when a key on the keyboard is pressed or released.

Parameters:
  • key – key code, one of Keys enumeration
  • pressedTrue if the key was pressed, otherwise False
on_mouse_button(button, pressed)

Called when a mouse button is pressed or released.

Parameters:
  • button – button index, of MouseButton enumeration
  • pressedTrue if the button was pressed, otherwise False
on_mouse_scroll(dx, dy)

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:
  • dx – relative scroll amount along the x axis
  • dy – relative scroll amount along the y axis
on_resize(width, height)

Called when size of the window changes.

Parameters:
  • width – width of the drawable area of the window, in pixels
  • height – height of the drawable area of the window, in pixels
on_controller_connected(controller)

Called when a game controller is connected.

Parameters:controller – the Controller that is now available for polling and events
on_controller_disconnected(controller)

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
on_controller_button(controller, button, pressed)

Called when a button on a game controller is pressed or released.

Parameters:
  • controller – the Controller containing the button
  • button – button index, of ControllerButtons enumeration
  • pressedTrue if the button was pressed, otherwise False
on_controller_axis(controller, axis, value)

Called when an axis on a game controller is moved.

Parameters:
  • controller – the Controller containing the axis
  • button – axis index, of ControllerAxes enumeration
  • value – absolute position of the axis, between -1.0 and 1.0
bacon.run(game)

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.

bacon.quit()

Stop the game loop and exit the application before the next on_tick() is called.

bacon.timestep = 0.0

float(x) -> floating point number

Convert a string or number to a floating point number, if possible.

Game Controllers

class bacon.Controller(controller_index)

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().

vendor_id = None

A numeric vendor ID that can be used to identify the type of device, when combined with the product_id.

product_id = None

A numeric product ID that can be used to identify the type of device, when combined with the vendor_id.

name = None

A human-readable name of the device that can be used to identify it to the user.

profile = None

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.

controller_index

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.

has_axis(axis)

Returns True if the controller has the requested axis, a value of enumeration ControllerAxes.

get_axis(axis)

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.
has_button(button)

Returns True if the controller has the requested button, a value of enumeration ControllerButtons.

get_button_state(button)

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.
connected

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).

left_thumb_x

The absolute X axis value of the left thumb-stick, or the main stick on a joystick.

left_thumb_y

The absolute Y axis value of the left thumb-stick, or the main stick on a joystick.

right_thumb_x

The absolute X axis value of the right thumb-stick, or the twist axis on a joystick.

right_thumb_y

The absolute Y axis value of the right thumb-stick, or the throttle control on a joystick.

left_trigger

The absolute left trigger value, between 0.0 and 1.0. Available only on game controllers with the extended profile.

right_trigger

The absolute right trigger value, between 0.0 and 1.0. Available only on game controllers with the extended profile.

start

True if the start button is pressed. Available only on game controllers with the standard or extended profiles.

back

True if the back button is pressed. Available only on the Xbox 360 controller on Windows.

select

True if the select button is pressed.

action_up

True if the up action button (“Y” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.

action_down

True if the down action button (“A” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.

action_left

True if the left action button (“X” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.

action_right

True if the right action button (“B” on Xbox 360) is pressed. Available only on game controllers with the standard or extended profiles.

dpad_up

True if the up directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.

dpad_down

True if the down directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.

dpad_left

True if the left directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.

dpad_right

True if the right directional pad button is pressed. The d-pad also corresponds to the POV or hat control on a joystick.

left_shoulder

True if the left shoulder button is pressed. Available only on game controllers with the standard or extended profiles.

right_shoulder

True if the right shoulder button is pressed. Available only on game controllers with the standard or extended profiles.

left_thumb

True if the left thumb stick is depressed. Available only on game controllers with the extended profile.

right_thumb

True if the right thumb stick is depressed. Available only on game controllers with the extended profile.

class bacon.ControllerButtons
start = 1
back = 2
select = 4
action_up = 8
action_down = 16
action_left = 32
action_right = 64
dpad_up = 128
dpad_down = 256
dpad_left = 512
dpad_right = 1024
left_shoulder = 2048
right_shoulder = 4096
left_thumb = 8192
right_thumb = 16384
button1 = 32768
button2 = 65536
button3 = 131072
button4 = 262144
button5 = 524288
button6 = 1048576
button7 = 2097152
button8 = 4194304
button9 = 8388608
button10 = 16777216
button11 = 33554432
button12 = 67108864
button13 = 134217728
button14 = 268435456
button15 = 536870912
button16 = 1073741824
button17 = 2147483648
classmethod parse(names)
classmethod tostring(value)
class bacon.ControllerAxes
left_thumb_x = 1
left_thumb_y = 2
right_thumb_x = 4
right_thumb_y = 8
left_trigger = 16
right_trigger = 32
axis1 = 256
axis2 = 512
axis3 = 1024
axis4 = 2048
axis5 = 4096
axis6 = 8192
axis7 = 16384
axis8 = 32768
classmethod parse(names)
classmethod tostring(value)
class bacon.ControllerProfiles
generic = 0
standard = 1
extended = 2
classmethod parse(name)
classmethod tostring(value)
class bacon.ControllerMapping(buttons={}, axes={}, dead_zones={}, profile=0)

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:
  • buttons – dictionary mapping button to button, each key and value is either a string or enum from GameControllerButtons
  • axes – dictionary mapping axis to axis, each key and value is either a string or enum from GameControllerAxes
  • dead_zones – dictionary mapping axis to its dead zone. Axis input is rescaled to zero out +/- the dead zone.
  • profile – the mapped profile, a string or enum from GameControllerProfiles
classmethod register(vendor_id, product_id, mapping)

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:
classmethod get(controller)

Find a mapping that can apply to the given controller. Returns None if unsuccessful.

Parameters:controllerController to look up
Returns:ControllerMapping

Game controller events:

Graphics

Drawing

bacon.clear(r, g, b, a)

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.

bacon.draw_line(x1, y1, x2, y2)

Draw a line from coordinates (x1, y1) to (x2, y2).

No texture is applied.

bacon.draw_rect(x1, y1, x2, y2)

Draw a rectangle bounding coordinates (x1, y1) to (x2, y2).

No texture is applied.

bacon.fill_rect(x1, y1, x2, y2)

Fill a rectangle bounding coordinates (x1, y1) to (x2, y2).

No texture is applied.

bacon.set_blending(src_blend, dest_blend)

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:
  • src_blend – a value from the BlendFlags enumeration, specifying the blend contribution from the source fragment
  • dest_blend – a value from the BlendFlags enumeration, specifying the blend contribution from the destination fragment
class bacon.BlendFlags
zero = 0
one = 1
src_color = 2
one_minus_src_color = 3
dst_color = 4
one_minus_dst_color = 5
src_alpha = 6
one_minus_src_alpha = 7
dst_alpha = 8
one_minus_dst_alpha = 9
classmethod parse(name)
classmethod tostring(value)

Transform

bacon.translate(x, y)

Translate the current graphics transform by (x, y) units.

bacon.scale(sx, sy)

Scale the current graphics transform by multiplying through (sx, sy).

bacon.rotate(radians)

Rotate the current graphics transform by radians counter-clockwise.

bacon.push_transform()

Save the current graphics transform by pushing it on the transform stack. It can be restored by calling pop_transform().

bacon.pop_transform()

Restore a previously saved transform by popping it off the transform stack.

bacon.set_transform(matrix)

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.

Color

bacon.set_color(r, g, b, a)

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.

bacon.multiply_color(r, g, b, a)

Multiplies the current graphics color component-wise by the given RGBA values.

bacon.push_color()

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.

bacon.pop_color()

Restore a previously saved graphics color by popping it off the color stack.

Images

class bacon.Image(file=None, premultiply_alpha=True, discard_bitmap=True, sample_nearest=False, wrap=False, atlas=1, width=None, height=None, content_scale=None, handle=None)

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:
  • file – path to an image file to load. Supported formats include PNG, JPEG, BMP, TIF, etc.
  • premultiply_alpha – if True (the default), the color channels are multiplied by the alpha channel when image is loaded. This allows the image to be alpha blended with bilinear interpolation between texels correctly. This paramater should be set to False if the original image data is required and won’t be blended (for example, if it will be used as a mask).
  • discard_bitmap – if True (the default), the bitmap data backing the image will be discarded after a GPU texture has been created (which happens automatically the first time the image is rendered). This saves memory. The parameter should be set to False if the source data will be required for reasons besides rendering (there is currently no API for using an image this way).
  • sample_nearest (bool) – if True, the image is sampled with nearest (point) filtering. This gives a “pixellated” effect when images are scaled or rotated.
  • wrap (bool) – if True, the image is sampled with wraparound texture coordinates, and the image is packed into its own texture. The image must have power of two dimensions (i.e., 32x32, 64x64, etc.). Use draw_image_region() with image coordinates that extend past the bounds of the image to render it with a repeating pattern.
  • atlas – group index of the atlas to pack this image into. If zero, the image is not packed into an atlas; otherwise, the image is permitted to be packed into other images with the same atlas number (although this is not guaranteed).
  • width – width of the image to create, in texels
  • height – height of the image to create, in texels
  • content_scale (float) – optional scale factor for backing texture. Defaults to 1.0 for images loaded from a file, defaults to Window.content_scale for empty images. The effect of setting content_scale to 2.0 is that the width and height properties will be half the actual pixel values.
unload()

Releases renderer resources associated with this image.

width

The width of the image, in texels (read-only).

height

The height of the image, in texels (read-only).

content_scale

The content scale applied to the image (read-only).

get_region(x1, y1, x2, y2)

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:
  • x1 (int) – left edge of the image region to return
  • y1 (int) – top edge of the image region to return
  • x2 (int) – right edge of the image region to return
  • y2 (int) – bottom edge of the image region to return
Returns:

Image

bacon.draw_image(image, x1, y1, x2=None, y2=None)

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
bacon.draw_image_region(image, x1, y1, x2, y2, ix1, iy1, ix2, iy2)

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

Fonts

class bacon.Font(file, size, light_hinting=False, content_scale=None)

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:
  • file (str) – path to a font file to load. Supported formats include TrueType, OpenType, PostScript, etc. If None, a default font is used
  • size (float) – the point size to load the font at
  • light_hinting (bool) – applies minimal autohinting to the outline; suitable for fonts designed for OS X
  • content_scale (float) – optional scaling factor for backing textures of glyphs. Defaults to to Window.content_scale.
metrics

Retrieves the pixel-space design metrics of the font.

Returns:FontMetrics
ascent

The ascent of the font above the baseline, in pixels; typically negative.

descent

The descent of the font below the baseline, in pixels; typically positive.

get_glyph(char)

Retrieves a Glyph that renders the given character.

Parameters:char – the character (a string)
get_glyphs(str)

Retrieves a list of Glyph for the given string.

Parameters:str – the string to render
measure_string(str)

Calculates the width of the given string in this font.

Parameters:str – the string to measure
Return float:width of the string, in pixels
bacon.draw_string(font, text, x, y, width=None, height=None, align=0, vertical_align=0)

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:
  • font – the Font to render text with
  • text – a string of text to render.

Shaders

bacon.set_shader(shader)

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
class bacon.Shader(vertex_source, fragment_source)

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:
  • vertex_source – string of source code for the vertex shader
  • fragment_source – string of source code for the fragment shader
uniforms

Map of shader uniforms available on this shader.

Type:read-only dictionary of string to ShaderUniform
vertex_source

Get the vertex shader source

Type:str
fragment_source

Get the fragment shader source

Type:str
class bacon.ShaderUniform(name, type, array_count=1, _shader=None, _uniform=None)

A uniform variable, either shared between all shaders (if its name begins with g_), specific to a particular shader.

See:

Shader.uniforms

Parameters:
  • name – name of the shared shader uniform to create, must begin with g_
  • type – type of the uniform variable, a member of ShaderUniformType
  • array_count – number of elements in the uniform array, or 1 if the uniform is not an array
shared

Boolean indicating if this shader uniform’s value is shared between all shaders

Type:bool
value

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:

  • float, int, bool: their equivalent Python types
  • vec[2-4], ivec[2-4], bvec[2-4]: a sequence of equivalent Python types (e.g., a sequence of 3 floats for vec3)
  • mat2, mat3, mat4: a sequence of 4, 9 or 16 floats, respectively
  • sampler2D: an Image

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

Name of the uniform, as it appears in the shader.

Type:str
type

Type of the uniform, or, if the uniform is an array, the element type of the array.

Type:an enumeration of ShaderUniformType
array_count

The size of the array, or 1 if this uniform is not an array.

Type:int
class bacon.ShaderUniformType
none = 0
int_ = 5124
float_ = 5126
vec2 = 35664
vec3 = 35665
vec4 = 35666
ivec2 = 35667
ivec3 = 35668
ivec4 = 35669
bool_ = 35670
bvec2 = 35671
bvec3 = 35672
bvec4 = 35673
mat2 = 35674
mat3 = 35675
mat4 = 35676
sampler2D = 35678
samplerCube = 35680
sampler2DRect = 35683
samplerExternal = 36198
classmethod parse(name)
classmethod tostring(value)

Mouse

class bacon.Mouse

Exposes functions for the system mouse or trackpad.

Do not construct an instance of this class, use the singleton mouse.

x = None

Location of the mouse in the window along the X axis, in pixels.

y = None

Location of the mouse in the window along the Y axis, from top to bottom, in pixels.

left

True if the left mouse button is currently pressed.

middle

True if the middle mouse button is currently pressed.

right

True if the right mouse button is currently pressed.

class bacon.MouseButtons
left = 0
middle = 1
right = 2
classmethod parse(name)
classmethod tostring(value)
bacon.mouse = Mouse()

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:

Resources

bacon.resource_dir

Path to resources. Set to the script directory by default during development, and the executable directory for frozen applications.

bacon.get_resource_path(filename)

Get a path to the given filename to load as a resource. All non-absolute filenames passed to Image, Font, Sound, etc are transformed through this function.

Parameters:filename (str) – a relative path to a resource file
Return str:an absolute path to the file

Window

class bacon.Window

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.

width

Get or set the width of the drawable part of the window, in pixels.

height

Get or set the height of the drawable part of the window, in pixels.

title

Get or set the title of the window (a string)

resizable

If True the window can be resized and maximized by the user. See Game.on_resize().

fullscreen

Set to True to make the game fullscreen, False to play in a window.

target

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
content_scale

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