ggame Core API¶
ggame Application Classes¶
App¶
-
class
ggame.app.
App
(*args)[source]¶ The
App
class is a (typically subclassed) class that encapsulates handling of the display system, and processing user events. TheApp
class also manages lists of allSprite
instances in the application.When subclassing
App
you may elect to instantiate most of your sprite objects in the initialization section.Processing that must occur on a per-frame basis may be included by overriding the
run()
method. This is also an appropriate location to call similar ‘step’ methods for your various customized sprite classes.Once your application class has been instantiated, begin the frame drawing process by calling its
run()
method.The
App
class is instantiated either by specifying the desired app window size in pixels, as two parameters::myapp = App(640,480)
or by providing no size parameters at all::
myapp = App()
in which case, the full browser window size is used.
NOTE: Only one instance of an
App
class or subclass may be instantiated at a time.-
spritelist
= []¶ List of all sprites currently active in the application.
-
classmethod
getSpritesbyClass
(sclass)[source]¶ Returns a list of all active sprites of a given class.
Parameters: sclass (class) – A class name (e.g. ‘Sprite’) or subclass. Returns: A (potentially empty) list of sprite references.
-
classmethod
listenKeyEvent
(eventtype, key, callback)[source]¶ Register to receive keyboard events.
Parameters: - eventtype (str) – The type of key event to receive (value is one of: ‘keydown’, ‘keyup’ or ‘keypress’).
- key (str) – Identify the keyboard key (e.g. ‘space’, ‘left arrow’, etc.) to receive events for.
- callback (function) – The function or method that will be
called with the
KeyEvent
object when the event occurs.
Returns: Nothing
See the source for
KeyEvent
for a list of key names to use with the key paramter.
-
classmethod
listenMouseEvent
(eventtype, callback)[source]¶ Register to receive mouse events.
Parameters: - eventtype (str) – The type of mouse event to receive (value is one of: ‘mousemove’, ‘mousedown’, ‘mouseup’, ‘click’, ‘dblclick’ or ‘mousewheel’).
- callback (function) – The function or method that will be
called with the
ggame.event.MouseEvent
object when the event occurs.
Returns: Nothing
-
classmethod
unlistenKeyEvent
(eventtype, key, callback)[source]¶ Use this method to remove a registration to receive a particular keyboard event. Arguments must exactly match those used when registering for the event.
Parameters: - eventtype (str) – The type of key event to stop receiving (value is one of: ‘keydown’, ‘keyup’ or ‘keypress’).
- key (str) – The keyboard key (e.g. ‘space’, ‘left arrow’, etc.) to stop receiving events for.
- callback (function) – The function or method that will no longer
be called with the
KeyEvent
object when the event occurs.
Returns: Nothing
See the source for
KeyEvent
for a list of key names to use with the key paramter.
-
classmethod
unlistenMouseEvent
(eventtype, callback)[source]¶ Use this method to remove a registration to receive a particular mouse event. Arguments must exactly match those used when registering for the event.
Parameters: - eventtype (str) – The type of mouse event to stop receiving events for (value is one of: ‘mousemove’, ‘mousedown’, ‘mouseup’, ‘click’, ‘dblclick’ or ‘mousewheel’).
- callback (function) – The function or method that will no longer be
called with the
ggame.event.MouseEvent
object when the event occurs.
Returns: Nothing
-
run
(userfunc=None)[source]¶ Calling the
run()
method begins the animation process whereby thestep()
method is called once per animation frame.Parameters: userfunc (function) – Any function or method which shall be called once per animation frame. Returns: Nothing
-
step
()[source]¶ The
step()
method is called once per animation frame. Override this method in your own subclass ofApp
to perform periodic calculations, such as checking for sprite collisions, or calling ‘step’ functions in your own customized sprite classes.The base class
step()
method is empty and is intended to be overriden.Returns: Nothing
-
Events¶
ggame events are objects that are created by the ggame system as a result of
some user action (mouse, keyboard). If the ggame application has called
listenKeyEvent()
or listenMouseEvent()
then
an appropriate Event object is instantiated by ggame and returned to a
user-provided handler function. The ggame user code should examine the
attributes of the Event object to find out more information about the event that
occurred.
-
class
ggame.event.
MouseEvent
(app, hwevent)[source]¶ A MouseEvent object encapsulates information about a user mouse action that is being reported by the system. This class is not instantiated by the ggame user.
-
wheeldelta
= None¶ Integer representing up/down motion of the scroll wheel.
-
x
= None¶ The window x-coordinate of the mouse pointer when the event occurred.
-
y
= None¶ The window y-coordinate of the mouse pointer when the event occurred.
-
route
(evtlist)¶ Execute all callbacks configured for this event.
-
-
class
ggame.event.
KeyEvent
(hwevent)[source]¶ A KeyEvent object encapsulates information regarding a user keyboard action that is being reported by the system. This class is not instantiated by the ggame user.
-
route
(evtlist)¶ Execute all callbacks configured for this event.
-
keynum
= None¶ The keynum attribute identifies a keycode (number).
-
key
= None¶ The key attribute identifes the key in text form (e.g. ‘back slash’).
The list of key numbers and description strings follows:
8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 19: 'pause/break', 20: 'caps lock', 27: 'escape', 32: 'space', 33: 'page up', 34: 'page down', 35: 'end', 36: 'home', 37: 'left arrow', 38: 'up arrow', 39: 'right arrow', 40: 'down arrow', 45: 'insert', 46: 'delete', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', 54: '6', 55: '7', 56: '8', 57: '9', 65: 'a', 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o', 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', 87: 'w', 88: 'x', 89: 'y', 90: 'z', 91: 'left window key', 92: 'right window key', 93: 'select key', 96: 'numpad 0', 97: 'numpad 1', 98: 'numpad 2', 99: 'numpad 3', 100: 'numpad 4', 101: 'numpad 5', 102: 'numpad 6', 103: 'numpad 7', 104: 'numpad 8', 105: 'numpad 9', 106: 'multiply', 107: 'add', 109: 'subtract', 110: 'decimal point', 111: 'divide', 112: 'f1', 113: 'f2', 114: 'f3', 115: 'f4', 116: 'f5', 117: 'f6', 118: 'f7', 119: 'f8', 120: 'f9', 121: 'f10', 122: 'f11', 123: 'f12', 144: 'num lock', 145: 'scroll lock', 186: 'semicolon', 187: 'equal sign', 188: 'comma', 189: 'dash', 190: 'period', 191: 'forward slash', 192: 'grave accent', 219: 'open bracket', 220: 'back slash', 221: 'close bracket', 222: 'single quote'
-
ggame Assets¶
ggame assets and related objects (Color
and LineStyle
) are
classes that encapsulate and represent displayable images. A single asset
may be used in multiple sprites. Animated assets may be created from any
image that includes multiple images within it (i.e. a sprite sheet).
Frame¶
-
class
ggame.asset.
Frame
(x, y, w, h)[source]¶ Frame is a utility class for expressing the idea of a rectangular region.
Initializing parameters describe the position of the upper-left corner of the frame, and the frame’s width and height. The units are typically in pixels, though a frame can be generic.
Parameters: - x (int) – X-coordinate of frame upper-left corner
- y (int) – Y-coordinate of frame upper-left corner
- w (int) – Width of the frame
- h (int) – Height of the frame
-
x
¶ X-coordinate of the upper left hand corner of this frame.
-
y
¶ Y-coordinate of the upper left hand corner of this frame.
-
w
¶ Width of the frame.
-
h
¶ Height of the frame.
-
center
¶ The center property computes a coordinate pair (tuple) for the center of the frame.
The center property, when set, redefines the x and y properties of the frame in order to make the center agree with the coordinates (tuple) assigned to it.
Color¶
-
class
ggame.asset.
Color
(color, alpha)[source]¶ The Color class is used to represent colors and/or colors with transparency.
Parameters: - color (int) – an integer in the conventional format (usually as a hexadecimal literal, e.g. 0xffbb33 that represents the three color components, red, green and blue)
- alpha (float) – a transparency value, or alpha as a floating-point number in the range of 0.0 to 1.0 where 0.0 represents completely transparent and 1.0 represents completely opaque.
Example:
""" Example of using Color class. """ from ggame import Color RED = Color(0xFF0000, 1.0)
LineStyle¶
-
class
ggame.asset.
LineStyle
(width, color)[source]¶ The LineStyle class is used to represent line style when drawing geometrical objects such as rectangles, ellipses, etc.
Parameters: Example:
""" Example of using LineStyle class. """ from ggame import LineStyle, Color LINE = LineStyle(3, Color(0x00FF00, 1.0))
This defines a 3-pixel wide green line.
Predefined Colors and Lines¶
-
ggame.asset.
BLACK
= BLACK¶ Default black color
-
ggame.asset.
WHITE
= WHITE¶ Default white color
-
ggame.asset.
BLACKLINE
= LineStyle(1, BLACK)¶ Default thin black line
-
ggame.asset.
WHITELINE
= LineStyle(1, WHITE)¶ Default thin white line
ImageAsset¶
-
class
ggame.asset.
ImageAsset
(url, frame=None, qty=1, direction='horizontal', margin=0)[source]¶ The ImageAsset class connects ggame to a specific image file.
Parameters: - url (str) – All ImageAsset instances must specify a file name or url where a jpg or png image is located.
- frame (Frame) – If the desired sprite image exists in only a smaller
sub-section of the original image, then specify an area within the
image using frame parameter, which must be a valid
Frame
instance. - qty=0 (int) – If the image file actually is a collection of images, such as a so-called sprite sheet, then the ImageAsset class supports defining a list of images, provided they exist in the original image as a row of evenly spaced images or a column of images. To specify this, provide the qty (quantity) of images in the row or column.
- direction='horizontal' (str) – For an image sprite sheet, specify whether the images are oriented in a ‘vertical’ or ‘horizontal’ arrangement.
- margin=0 (int) – If there is a gap between successive images in an image sprite sheet, then specify the size of the gap (in pixels). When used in this way, the frame parameter must define the area of only the first image in the collection; all subsequent images in the list are assumed to be the same size, but separated by the margin value.
Example:
""" Example of using ImageAsset class. """ from ggame import ImageAsset IMG = ImageAsset("bunny.png")
-
url
= None¶ A string that represents the path or url of the original file.
-
append
(url, frame=None, qty=1, direction='horizontal', margin=0)[source]¶ Append a texture asset from a new image file (or url). This method allows you to build a collection of images into an asset (such as you might need for an animated sprite), but without using a single sprite sheet image.
The parameters for the append method are identical to those supplied to the
ImageAsset
initialization method.This method allows you to build up an asset that consists of multiple rows or columns of images in a sprite sheet or sheets.
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
gfx
¶ gfx property represents the underlying system object used to represent this asset. If this asset is composed of multiple assets, then the first asset is referenced by gfx.
RectangleAsset¶
-
class
ggame.asset.
RectangleAsset
(width, height, line=LineStyle(1, BLACK), fill=BLACK)[source]¶ The RectangleAsset is a “virtual” asset that is created on the fly without requiring creation of an image file.
Parameters: -
gfx
¶ The gfx property represents the underlying system object.
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
CircleAsset¶
-
class
ggame.asset.
CircleAsset
(radius, line=LineStyle(1, BLACK), fill=BLACK)[source]¶ The ggame.CircleAsset is a “virtual” asset that is created on the fly without requiring creation of an image file.
Parameters: -
gfx
¶ The gfx property represents the underlying system object.
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
EllipseAsset¶
-
class
ggame.asset.
EllipseAsset
(halfw, halfh, line=LineStyle(1, BLACK), fill=BLACK)[source]¶ The ggame.EllipseAsset is a “virtual” asset that is created on the fly without requiring creation of an image file.
Parameters: - halfw (int) – Ellipse semi-axis dimension in the horizontal direction (half the width of the ellipse), in pixels
- halfh (int) – Ellipse semi-axis dimension in the vertical direction (half the height of the ellipse), in pixels
- line=BLACKLINE (LineStyle) – The color and width of the ellipse border
- fill=BLACK (Color) – The color of the ellipse body
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
gfx
¶ The gfx property represents the underlying system object.
PolygonAsset¶
-
class
ggame.asset.
PolygonAsset
(path, line=LineStyle(1, BLACK), fill=BLACK)[source]¶ The PolygonAsset is a “virtual” asset that is created on the fly without requiring creation of an image file.
Note: you should not specificy absolute screen coordinates for this asset, since you will use the
Sprite
position to locate your polygon on the screen.Parameters: - path (list) – A list of pixel-coordinate tuples. These coordinates
should not be in absolute screen coordinates, but should be relative to
the desired ‘center’ of the resulting
Sprite
. The final coordinate pair in the list must be the same as the first. - line=BLACKLINE (LineStyle) – The color and width of the ellipse border
- fill=BLACK (Color) – The color of the ellipse body
Example:
""" Example of using the PolygonAsset class. """ from ggame import PolygonAsset, LineStyle, Color, BLACK POLY = PolygonAsset( [(0, 0), (50, 50), (50, 100), (0, 0)], LineStyle(4, BLACK), Color(0x80FF00, 0.8) )
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
gfx
¶ The gfx property represents the underlying system object.
- path (list) – A list of pixel-coordinate tuples. These coordinates
should not be in absolute screen coordinates, but should be relative to
the desired ‘center’ of the resulting
LineAsset¶
-
class
ggame.asset.
LineAsset
(x, y, line=LineStyle(1, BLACK))[source]¶ The LineAsset is a “virtual” asset that is created on the fly without requiring creation of an image file. A LineAsset instance represents a single line segment.
Note: you should not specificy absolute screen coordinates for this asset, since you will use the
Sprite
position to locate your line on the screen. The line segment will begin at pixel coordinates (0,0), and will end at the (x,y) coordinates given below.As the LineAsset does not cover a region, only a
LineStyle
argument must be supplied (line) to specify the color.Parameters: - x (int) – x-coordinate of the line endpoint, in pixel units
- y (int) – y-coordinate of the line endpoint, in pixel units
- line=BLACKLINE (LineStyle) – The color and width of the ellipse border
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
delta_x
= None¶ This attribute represents the x parameter supplied during instantiation.
-
delta_y
= None¶ This attribute represents the y parameter supplied during instantiation.
-
gfx
¶ The gfx property represents the underlying system object.
TextAsset¶
-
class
ggame.asset.
TextAsset
(text, **kwargs)[source]¶ The TextAsset is a “virtual” asset that is created on the fly without requiring creation of an image file. A TextAsset instance represents a block of text, together with its styling (font, color, etc.).
Parameters: - text (str) – The text that should be displayed
- **kwargs – Optional formatting and style attributes (below)
- style='20px Arial' (str) –
Text style, size and typeface. Example:
'italic 20pt Helvetica'
- width=100 (int) – Width of the text block on screen, in pixels.
- fill=BLACK (Color) –
Color
instance to specify color and transparency of the text. - align='left' (str) – Alignment style of the block. One of ‘left’, ‘center’, or ‘right’.
Full example:
""" Example of using TextAsset class. """ from ggame import TextAsset, Color TA = TextAsset( "Sample Text", style="bold 40pt Arial", width=250, fill=Color(0x1122FF, 1.0) )
-
destroy
()¶ Destroy or deallocate any underlying graphics resources used by the asset. Call this method on any asset that is no longer being used.
-
gfx
¶ gfx property represents the underlying system object used to represent this asset. If this asset is composed of multiple assets, then the first asset is referenced by gfx.
-
clone
()[source]¶ Create a duplicate asset with the current style settings.
Returns: A text asset that is identical to the original, but with current styles. Return type: TextAsset
-
width
¶ Width of the rendered text asset in pixels
-
height
¶ Height of the rendered text asset in pixels
Sounds¶
Tools for loading and playing sound resources in ggame applications.
SoundAsset¶
-
class
ggame.sound.
SoundAsset
(url)[source]¶ Class representing a single sound asset (sound file, such as .mp3 or .wav).
Parameters: url (str) – The URL or file name of the desired sound. Sound file formats may include .wav or .mp3, subject to browser compatibility. Returns: The asset instance -
url
= None¶ A string containing the url or name of the asset file.
-
Sound¶
-
class
ggame.sound.
Sound
(asset)[source]¶ The Sound class represents a sound, with methods for controlling when and how the sound is played in the application.
Parameters: asset (SoundAsset) – A valid SoundAsset
instance.Returns: the Sound instance -
volume
¶ The volume property is a number ranging from 0-100 that represents the volume or intensity of the sound when it is playing.
-
Sprites¶
Sprite class for encapsulating all visible objects in ggame applications.
Sprite¶
-
class
ggame.sprite.
Sprite
(asset, pos=(0, 0), edgedef=None)[source]¶ The Sprite class combines the idea of a visual/graphical asset, a position on the screen, and behavior. Although the Sprite can be used as-is, it is generally subclassed to give it some desired behavior.
When subclassing the Sprite class, you may customize the initialization code to use a specific asset. A ‘step’ or ‘poll’ method may be added for handling per-frame actions (e.g. checking for collisions). Step or poll functions are not automatically called by the
App
class, but you may subclass theApp
class in order to do this.Furthermore, you may wish to define event callback methods in your customized sprite class. With customized creation, event handling, and periodic processing you can achieve fully autonomous behavior for your sprite objects.
Parameters: - asset (asset) – An existing graphical asset
- pos (tuple(int,int)) – The sprite position may be provided, which
specifies the starting (x,y) coordinates of the sprite on the screen.
By default, the position of a sprite defines the location of its upper-left
hand corner. This behavior can be modified by customizing its
center
. - edgedef (asset) – An edge definition asset may be provided, which specifies an asset that will be used to define the boundaries of the sprite for the purpose of collision detection. If no edgedef asset is given, the required asset is used, which will be a rectangular asset in the case of an image texture. This option is typically used to define a visible image outline for a texture-based sprite that has a transparent texture image background.
Returns: Nothing. If the position is on screen the sprite will be displayed in the browser.
Example of use:
""" Example of using Sprite class. """ from ggame.sprite import Sprite from ggame.asset import ImageAsset, CircleAsset from ggame.app import App PLAYER = Sprite(ImageAsset("bunny.png"), (100, 100), CircleAsset(50)) App().run()
This creates a sprite using the ‘player.png’ image, positioned with its upper-left corner at coordinates (100,100) and with a 50 pixel radius circular collision border.
-
firstImage
()[source]¶ Select and display the first image used by this sprite. This only does something useful if the asset is an
ImageAsset
defined with multiple images.
-
lastImage
()[source]¶ Select and display the last image used by this sprite. This only does something useful if the asset is an
ImageAsset
defined with multiple images.
-
nextImage
(wrap=False)[source]¶ Select and display the next image used by this sprite. If the current image is already the last image, then the image is not advanced.
Parameters: wrap (boolean) – If True, then calling nextImage()
on the last image will cause the first image to be loaded.This only does something useful if the asset is an
ImageAsset
defined with multiple images.
-
prevImage
(wrap=False)[source]¶ Select and display the previous image used by this sprite. If the current image is already the first image, then the image is not changed.
Parameters: wrap (boolean) – If True, then calling prevImage()
on the first image will cause the last image to be loaded.This only does something useful if the asset is an
ImageAsset
defined with multiple images.
-
setImage
(index=0)[source]¶ Select the image to display by giving its index.
Parameters: index (int) – An index to specify the image to display. A value of zero represents the first image in the asset. This is equivalent to setting the
index
property directly.This only does something useful if the asset is an
ImageAsset
defined with multiple images.
-
index
¶ This is an integer index into the list of images available for this sprite.
-
width
¶ This is an integer representing the display width of the sprite. Assigning a value to the width will scale the image horizontally.
-
height
¶ This is an integer representing the display height of the sprite. Assigning a value to the height will scale the image vertically.
-
x
¶ This represents the x-coordinate of the sprite on the screen. Assigning a value to this attribute will move the sprite horizontally.
-
y
¶ This represents the y-coordinate of the sprite on the screen. Assigning a value to this attribute will move the sprite vertically.
-
position
¶ Tuple indicates the position of the sprite on the screen.
-
fxcenter
¶ This represents the horizontal position of the sprite “center”, as a floating point number between 0.0 and 1.0. A value of 0.0 means that the x-coordinate of the sprite refers to its left hand edge. A value of 1.0 refers to its right hand edge. Any value in between may be specified. Values may be assigned to this attribute.
-
fycenter
¶ This represents the vertical position of the sprite “center”, as a floating point number between 0.0 and 1.0. A value of 0.0 means that the x-coordinate of the sprite refers to its top edge. A value of 1.0 refers to its bottom edge. Any value in between may be specified. Values may be assigned to this attribute.
-
center
¶ This attribute represents the horizontal and vertical position of the sprite “center” as a tuple of floating point numbers. See the descriptions for
fxcenter
andfycenter
for more details.
-
visible
¶ This boolean attribute may be used to change the visibility of the sprite. Setting ~ggame.Sprite.visible to False will prevent the sprite from rendering on the screen.
-
scale
¶ This attribute may be used to change the size of the sprite (‘scale’ it) on the screen. Value may be a floating point number. A value of 1.0 means that the sprite image will keep its original size. A value of 2.0 would double it, etc.
-
rotation
¶ This attribute may be used to change the rotation of the sprite on the screen. Value may be a floating point number. A value of 0.0 means no rotation. A value of 1.0 means a rotation of 1 radian in a counter-clockwise direction. One radian is 180/pi or approximately 57.3 degrees.
-
classmethod
collidingCircleWithPoly
(circ, poly)[source]¶ Determine if a CircleAsset sprite overlaps with a PolygonAsset sprite. This method is called after determining that the two objects are overlapping in their overall extents.
Parameters: Returns: True if the sprites are overlapping, False otherwise.
Return type: boolean
-
collidingPolyWithPoly
(obj)[source]¶ Determine if a pair of PolygonAsset-based sprites are overlapping. This method is called after determining that the two objects are overlapping in their overall extents. This should onlyb e called if self is a PolygonAsset-based sprite.
Parameters: obj (Sprite) – A PolygonAsset-based sprite. Returns: True if slef overlaps with obj, False otherwise. Return type: boolean
-
collidingWith
(obj)[source]¶ Determine if this sprite is currently overlapping another sprite object.
Parameters: obj (Sprite) – A reference to another Sprite object. Return type: boolean Returns: True if this the sprites are overlapping, False otherwise.
-
collidingWithSprites
(sclass=None)[source]¶ Determine if this sprite is colliding with any other sprites of a certain class.
Parameters: sclass (class) – A class identifier that is either Sprite
or a subclass of it that identifies the class of sprites to check for collisions. If None then all objects that are subclassed from theSprite
class are checked.Return type: list Returns: A (potentially empty) list of sprite objects of the given class that are overlapping with this sprite.
-
static
getImagePath
(imagename)[source]¶ Determine a path to the ggame-provided image that will work for both online (runpython.org) and locally installed ggame libraries. Do not use this with user-provided images.
Parameters: imagename (str) – The name of an image file found inside the ggame/images folder.