ggMath Mathematics¶
These mathematics and geometry extensions subclass the App
and Sprite
classes to create a framework for building
apps that mimic some of the functionality of online math tools like Geogebra.
This mathapp
module implements base classes for
Sprite
-based classes defined in this module.
These extensions are very experimental and are not fully developed!
ggMath Application¶
MathApp¶
- class ggame.mathapp.MathApp(scale=200)[source]¶
MathApp is a subclass of the ggame
App
class. It incorporates the following extensions:Support for zooming the display using the mouse wheel
Support for click-dragging the display using the mouse button
- Automatic execution of step functions in all objects and sprites
sub-classed from
_MathDynamic
.
- Parameters:
scale (float) – Optional parameter sets the initial scale of the display in units of pixels per logical unit. The default is 200.
- Returns:
MathApp instance
- view_position¶
Attribute is used to get or set the current logical coordinates at the center of the screen as a tuple of floats (x,y).
- scale = 200¶
- classmethod getSpritesbyClass(sclass)¶
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)¶
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)¶
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)¶
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)¶
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
- classmethod logicalToPhysical(lp)[source]¶
Transform screen coordinates from logical to physical space. Output depends on the current ‘zoom’ and ‘pan’ of the screen.
- Parameters:
lp (tuple(float,float)) – Logical screen coordinates (x, y)
- Return type:
tuple(float,float)
- Returns:
Physical screen coordinates (x, y)
- classmethod physicalToLogical(pp)[source]¶
Transform screen coordinates from physical to logical space. Output depends on the current ‘zoom’ and ‘pan’ of the screen.
- Parameters:
lp (tuple(float,float)) – Physical screen coordinates (x, y)
- Return type:
tuple(float,float)
- Returns:
Logical screen coordinates (x, y)
- classmethod translateLogicalToPhysical(pp)[source]¶
Transform screen translation from logical to physical space. Output only depends on the current ‘zoom’ of the screen.
- Parameters:
lp (tuple(float,float)) – Logical screen translation pair (delta x, delta y)
- Return type:
tuple(float,float)
- Returns:
Physical screen translation ordered pair (delta x, delta y)
- classmethod translatePhysicalToLogical(pp)[source]¶
Transform screen translation from physical to logical space. Output only depends on the current ‘zoom’ of the screen.
- Parameters:
lp (tuple(float,float)) – Physical screen translation pair (delta x, delta y)
- Return type:
tuple(float,float)
- Returns:
Logical screen translation ordered pair (delta x, delta y)
- classmethod distance(pos1, pos2)[source]¶
Utility for calculating the distance between any two points.
- Parameters:
pos1 (tuple(float,float)) – The first point
pos2 (tuple(float,float)) – The second point
- Return type:
float
- Returns:
The distance between the two points (using Pythagoras)
- classmethod addViewNotification(handler)[source]¶
Register a function or method to be called in the event the view position or zoom changes.
- Parameters:
handler (function) – The function or method to be called
- Returns:
Nothing
- classmethod removeViewNotification(handler)[source]¶
Remove a function or method from the list of functions to be called in the event of a view position or zoom change.
- Parameters:
handler (function) – The function or method to be removed
- Returns:
Nothing
- run(userfunc=None)¶
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
ggMath Base Class for Visual Objects¶
- class ggame.mathapp._MathVisual(asset, *args, **kwargs)[source]¶
Abstract Base Class for all visual, potentially dynamic objects.
- Parameters:
asset (Asset) – A valid ggame asset object.
args (list) – A list of required positional or non-positional arguments as named in the _posinputsdef and _nonposinputsdef lists overridden by child classes.
**kwargs – See below
- Optional Keyword Arguments:
- selected¶
True if object is currently selected by the UI.
- mouseisdown¶
True if object is tracking UI mouse button as down.
- destroy()[source]¶
Prevent the sprite from being displayed or checked in collision detection. Once this is called, the sprite can no longer be displayed or used. If you only want to prevent a sprite from being displayed, set the
visible
attribute to False.
- property positioning¶
Whether object was created with ‘logical’ or ‘physical’ positioning.
- property movable¶
Whether object can be moved. Set-able and get-able.
- property selectable¶
Whether object can be selected by the UI. Set-able and get-able.
- property strokable¶
Whether the object supports a click-drag input from the UI mouse. Set-able and get-able.
- processEvent(event)[source]¶
Inform the object of a generic ggame event.
- Parameters:
event – The ggame event object to receive and process.
- Returns:
None
This method is intended to be overridden.
- abstract physicalPointTouching(ppos)[source]¶
Determine if a physical point is considered to be touching this object.
- Parameters:
ppos (tuple(int,int)) – Physical screen coordinates.
- Return type:
boolean
- Returns:
True if touching, False otherwise.
This method must be overridden.
- abstract translate(pdisp)[source]¶
Perform necessary processing in response to being moved by the mouse/UI.
- Parameters:
pdisp (tuple(int,int)) – Translation vector (x,y) in physical screen units.
- Returns:
None
This method must be overridden.
- stroke(ppos, pdisp)[source]¶
Perform necessary processing in response to click-drag action by the mouse/UI.
- Parameters:
ppos (tuple(int,int)) – Physical coordinates of stroke start.
pdisp (tuple(int,int)) – Translation vector of stroke action in physical screen units.
- Returns:
None
This method is intended to be overridden.
MathApp classes for representing geometric points
Point Objects¶
These classes are subclasses of Sprite
and are used
to represent points in geometry and mathematics.
_Point¶
This is the abstract base class for all point classes.
- class ggame.point._Point(asset, *args, **kwargs)[source]¶
Abstract base class for all point classes.
- Parameters:
asset (Asset) – A valid ggame Asset object
pos (tuple(float,float)) – The position (physical or logical)
- physicalPointTouching(ppos)[source]¶
Determine if a physical point is considered to be touching this point.
- Parameters:
ppos (tuple(int,int)) – Physical screen coordinates.
- Return type:
boolean
- Returns:
True if touching, False otherwise.
Point¶
- class ggame.point.Point(*args, **kwargs)[source]¶
Basic point object representing any point in a geometrical sense. An instantiated Point object is callable and will return a tuple with its logical position as an (x,y) pair.
- Parameters:
pos (tuple(float,float)) – Position in physical or logical units.
**kwargs – See below
- Optional Keyword Arguments:
Example:
""" Example of using MathApp Point class. """ from ggame.asset import Color from ggame.point import Point from ggame.mathapp import MathApp P1 = Point((0, 1), color=Color(0xFF8000, 1.0)) P1.movable = True # An orange point that can be moved P2 = Point(lambda: (P1()[0], P1()[1] + 1)) # A point position based on P1 P3 = Point((1, 0)) # A third, fixed point MathApp().run()
ImagePoint¶
- class ggame.point.ImagePoint(url, *args, **kwargs)[source]¶
Point
object that uses an image as its on-screenrepresentation.
- Parameters:
url (str) – Location of an image file (png, jpg)
*args – See below
**kwargs – See below
- Required Arguments:
pos (tuple(float,float)) Position in physical or logical units.
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ (default) or ‘physical’
frame (Frame) The sub-frame location of image within the image file
qty (int) The number of sub-frames, when used as a sprite sheet
direction (str) One of ‘horizontal’ (default) or ‘vertical’
margin (int) Pixels between sub-frames if sprite sheet
Line objects for MathApp applications
Line Objects¶
This category currently only has one class: LineSegment
, but will
eventually be extended to include at least Line
and Ray
.
LineSegment¶
- class ggame.line.LineSegment(*args, **kwargs)[source]¶
Create a line segment on the screen. This is a subclass of
Sprite
and_MathVisual
but most of the inherited members are of little use and are not shown in the documentation.- Parameters:
*args – See below
**kwargs – See below
- Required Arguments:
- pos (tuple(float,float)) Starting point of the segment, which may
be a literal tuple of floats, or a reference to any object or function that returns or evaluates to a tuple of floats.
end (tuple(float,float)) Ending point of the segment (see above)
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ or ‘physical’
style (LineStyle) Valid
LineStyle
object
Example:
from ggame.point import Point from ggame.line import LineSegment from ggame.mathapp import MathApp p1 = Point((2,1)) ls = LineSegment(p1, Point((1,1))) MathApp().run()
Circle¶
Circle object for MathApp applications
- class ggame.circle.Circle(*args, **kwargs)[source]¶
Create a circle on the screen. This is a subclass of
Sprite
and_MathVisual
but most of the inherited members are of little use and are not shown in the documentation.- Parameters:
*args – See below
**kwargs – See below
- Required Arguments:
- pos (tuple(float,float)) Center point of the circle, which may
be a literal tuple of floats, or a reference to any object or function that returns or evaluates to a tuple of floats.
- radius [float or Point] Radius of the circle (logical units)
or a
Point
on the circle.
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ or ‘physical’
style (LineStyle) Valid
LineStyle
objectcolor (Color) Valid
Color
object`
Example:
""" Example of using MathApp Circle class. """ from ggame.point import Point from ggame.circle import Circle from ggame.mathapp import MathApp # P1 is the center of the circle P1 = Point((0.5, 1)) # P2 is on the perimeter P2 = Point((1.3, 1)) # define a circle from center and perimeter points C = Circle(P1, P2) # allow the user to drag the perimeter point to resize the circle P2.movable = True MathApp().run()
- property center¶
An ordered pair (x,y) or
Point
that represents the (logical) circle center. This attribute is only get-able.
- property radius¶
A float that represents the radius of the circle. This attribugte is only get-able.
Text Objects¶
Label¶
MathApp label classes for displaying text.
- class ggame.label.Label(*args, **kwargs)[source]¶
Create a text label on the screen. This is a subclass of
Sprite
and_MathVisual
but most of the inherited members are of little use and are not shown in the documentation.- Parameters:
*args – See below
**kwargs – See below
- Required Arguments:
- pos (tuple(float,float)) Screen position of the label, which may
be a literal tuple of floats, or a reference to any object or function that returns or evaluates to a tuple of floats.
- text (str) Text to appear in the label. This may be a literal
string or a reference to any object or function that returns or evaluates to a string.
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ or ‘physical’
size (int) Size of text font (in pixels)
width (int) Width of the label (in pixels)
color (Color) Valid
Color
object
Example:
""" Example of using the Label class. """ from ggame.asset import Color from ggame.label import Label from ggame.mathapp import MathApp L = Label( (20, 80), # physical location on screen "Initial Speed (m/s)", # text to display size=15, # text size (pixels) positioning="physical", # use physical coordinates color=Color(0x202000, 1.0), ) # text color MathApp().run()
Indicators¶
MathApp indicator classes for displaying two-state or boolean values.
ImageIndicator¶
- class ggame.indicator.ImageIndicator(url, *args, **kwargs)[source]¶
Use a sprite sheet image to indicate integer or boolean values.
Required Inputs
- Parameters:
url (str) – Location of image file consisting of a multi-image sprite sheet.
pos ((float,float)) – Position in physical or logical units. May be a
ggame.point.Point
instance, a literal (x,y) pair, or a function that returns an (x,y) pair.value (int) – The state of the indicator. May be a function that returns a suitable (integer) value.
**kwargs – See below
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ (default) or ‘physical’
- frame (:class:`ggame.asset.Frame`) Sub-frame location of sub-image within
the main image.
qty (int) The number of sub-frames, when used as sprite sheet.
direction (str) One of ‘horizontal’ (default) or ‘vertical’.
margin (int) Number of pixels between sub-frames if sprite sheet.
Example:
""" Example of using ImageIndicator class. """ from ggame.mathapp import MathApp from ggame.indicator import ImageIndicator from ggame.inputpoint import InputImageButton from ggame.asset import Frame BUTTON = InputImageButton( "images/button-round.png", None, (40, 105), positioning="physical", frame=Frame(0, 0, 100, 100), qty=2, ) BUTTON.scale = 0.5 LIGHT = ImageIndicator( "images/red-led-off-on.png", (100, 100), BUTTON, # button object supplies the indicator state. positioning="physical", frame=Frame(0, 0, 600, 600), qty=2, ) LIGHT.scale = 0.1 MathApp().run()
LEDIndicator¶
- class ggame.indicator.LEDIndicator(*args, **kwargs)[source]¶
Subclass of ImageIndicator using a red LED on/off image.
Required Inputs
- Parameters:
pos ((float,float)) – Position in physical or logical units. May be a
ggame.point.Point
instance, a literal (x,y) pair, or a function that returns an (x,y) pair.value (int) – The state of the indicator. May be a function that returns a suitable (integer) value.
**kwargs – See below
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ (default) or ‘physical’
Example:
""" Example of using MathApp LEDIndicator class. """ from ggame.mathapp import MathApp from ggame.indicator import LEDIndicator from ggame.inputpoint import MetalToggle TOGGLE = MetalToggle(0, (-1, 0)) SWITCH = LEDIndicator((-1, 0.5), TOGGLE) MathApp().run()
Input Controls¶
Slider¶
MathApp input class for accepting user numeric input with a “slider” control.
- class ggame.slider.Slider(*args, **kwargs)[source]¶
Create a ‘slider’ style numeric input control on the screen. This is a subclass of
Sprite
and_MathVisual
but most of the inherited members are of little use and are not shown in the documentation.- Parameters:
*args – See below
**kwargs – See below
- Required Arguments:
- pos (tuple(float,float)) Screen position of the slider, which may
be a literal tuple of floats, or a reference to any object or function that returns or evaluates to a tuple of floats.
minval (float) The minimum value of the slider
maxval (float) The maximum value of the slider
initial (float) The initial value of the slider
- Optional Keyword Arguments:
steps (int) Number of steps between minval and maxval (default 50)
- leftkey (str) Name of a keyboard key that will make the
slider control step down (move left) (default None). See
KeyEvent
for a list of names.
- rightkey (str) Name of a keyboard key that will make the slider
control step up (move right) (default None)
- centerkey (str) Name of a keyboard key that will make the slider
move to its center position (default None)
positioning (str) One of ‘logical’ or ‘physical’
size (int) Width of the slider (in pixels)
color (Color) Valid
Color
objectstyle (LineStyle) Valid
LineStyle
object
Example:
""" Example of using Slider class. """ from ggame.slider import Slider from ggame.mathapp import MathApp S = Slider( (100, 150), # screen position 0, # minimum value 250, # maximum value 125, # initial value positioning="physical", # use physical coordinates for position steps=10, ) # 10 steps between 125 and 250 MathApp().run()
- property value¶
Report value of the slider. Attribute is get-able and set-able.
- increment(step)[source]¶
Increment the slider value.
- Parameters:
step (float) – The amount by which the slider control should be adjusted.
- Returns:
None
- canstroke(ppos)[source]¶
Function returns true if the given physical position corresponds with a part of the slider that can be dragged (i.e. the thumb).
- Parameters:
ppos ((float,float)) – Physical screen coordinates.
- Returns:
True if the position represents a draggable part of the control.
- Return type:
boolean
- stroke(ppos, pdisp)[source]¶
Function performs the action of stroking or click-dragging on the slider control (i.e. dragging the thumb).
- Parameters:
ppos ((float, float)) – Physical screen coordinates.
pdisp ((float, float)) – Physical displacement vector.
- Returns:
None
- physicalPointTouching(ppos)[source]¶
Determine if a physical point is considered to be touching this object.
- Parameters:
ppos (tuple(int,int)) – Physical screen coordinates.
- Return type:
boolean
- Returns:
True if touching, False otherwise.
This method must be overridden.
- physicalPointTouchingThumb(ppos)[source]¶
Determine if a physical screen location is touching the slider “thumb”.
- Parameters:
ppos ((float, float)) – Physical screen coordinates.
- Returns:
True if touching, False otherwise.
- Return type:
boolean
InputNumeric¶
MathApp input classes for accepting user numeric and pushbutton input.
- class ggame.input.InputNumeric(pos, val, **kwargs)[source]¶
Create a
Label
that can be selected to accept new numeric input from the keyboard. This is a subclass ofSprite
and_MathVisual
but most of the inherited members are of little use and are not shown in the documentation.- Parameters:
pos (tuple(float,float)) – Screen position of the control, which may be a literal tuple of floats, or a reference to any object or function that returns or evaluates to a tuple of floats.
val (float) – Initial value of the input text
**kwargs – See below
- Optional Keyword Arguments:
fmt (str) a Python format string (default is {0:.2f})
positioning (str) One of ‘logical’ or ‘physical’
size (int) Size of text font (in pixels)
width (int) Width of the label (in pixels)
color (Color) Valid
Color
object
Example:
""" Example of using InputNumeric class. """ from ggame.input import InputNumeric from ggame.mathapp import MathApp P = InputNumeric( (300, 275), # screen coordinates of input 3.14, # initial value positioning="physical", ) # use physical coordinates MathApp().run()
InputImageToggle¶
- class ggame.inputpoint.InputImageToggle(url, statelist, initindex, *args, **kwargs)[source]¶
Spritesheet-based input control that toggles through a set of states with each mouseclick.
- Required Inputs:
- Parameters:
url (str) – Location of image file consisting of a multi-image sprite sheet.
statelist (list) – List of values to correspond with toggle states.
initindex (int) – Index to initial toggle state.
pos ((float,float)) – Position in physical or logical units. May be a
ggame.point.Point
instance, a literal (x,y) pair, or a function that returns an (x,y) pair.**kwargs – See below
- Optional Keyword Arguments:
positioning (str) One of ‘logical’ (default) or ‘physical’
- frame (:class:`ggame.asset.Frame`) Sub-frame location of sub-image within
the main image.
direction (str) One of ‘horizontal’ (default) or ‘vertical’.
margin (int) Number of pixels between sub-frames if sprite sheet.
MetalToggle¶
- class ggame.inputpoint.MetalToggle(initindex, *args, **kwargs)[source]¶
Metal toggle input control that toggles through two states with each mouseclick.
- Required Inputs:
- Parameters:
initindex (int) – Index to initial toggle state (0 or 1).
pos ((float,float)) – Position in physical or logical units. May be a
ggame.point.Point
instance, a literal (x,y) pair, or a function that returns an (x,y) pair.
Example:
""" Example of using MathApp LEDIndicator class. """ from ggame.mathapp import MathApp from ggame.indicator import LEDIndicator from ggame.inputpoint import MetalToggle TOGGLE = MetalToggle(0, (-1, 0)) SWITCH = LEDIndicator((-1, 0.5), TOGGLE) MathApp().run()
Time Utility¶
MathApp class for creating periodic and timed callbacks.
Timer¶
- class ggame.timer.Timer[source]¶
The Timer class instantiates an object whose basic function is to report the number of seconds since its creation by calling the object as a function with an empty argument list.
The Timer class accepts no arguments during creation.
Example of use:
""" Example of using the Timer class. """ from ggame.timer import Timer from ggame.mathapp import MathApp def timercallback(t): """ Callback function to receive notification of timer expiration. """ print("time's up at", t.time, "seconds!") TIMER = Timer() # Execute timercallback after 5 seconds TIMER.callAfter(5, timercallback) MathApp().run()
- reset()[source]¶
Set the reference time to the MathApp current time. If the timer is reset before the app initializes then do nothing.
- Returns:
None
- property time¶
Attribute is always updated with the number of seconds since the timer was created.
- callAfter(delay, callback, periodic=False)[source]¶
Set a callback to occur either once or periodically. The callback function should accept a single parameter which will be a reference to the timer object that called it.
- Parameters:
delay (float) – The number of seconds to wait before executing the callback function
callback (function) – The callback function to call on timer expiration
periodic (boolean) – Set True if the callback function should be executed periodically
- Returns:
None
- callAt(calltime, callback)[source]¶
Set a callback to occur at a specific time (seconds since the Timer object was created or since its
reset()
method was called.- Parameters:
time (float) – The time to wait since timer creation or reset before calling the callback function.
callback (function) – The callback function to call
- Returns:
None
- callEvery(period, callback)[source]¶
Set a callback to occur periodically. The callback function should accept a single parameter which will be a reference to the timer object that called it.
- Parameters:
period (float) – The number of seconds to wait before each execution of the callback function
callback (function) – The callback function to call on timer expiration
- Returns:
None