Welcome to pyghelpers’ documentation!

pyghelpers is a collection of classes and functions written in Python for use with Pygame.

pyghelpers is pronounced “pig helpers”.

Developed by Irv Kalb - Irv at furrypants.com

Full documentation at: https://pyghelpers.readthedocs.io/en/latest/

pyghelpers contains the following classes:

  • Timer - a simple timer

  • CountUpTimer - a timer that counts up from zero

  • CountDownTimer - a timer that counts down from a starting point

  • SceneMgr - allows for a Pygame program with multiple scenes

  • Scene - base class for a scene managed by the SceneMgr

pyghelpers also contains the following functions:

  • textYesNoDialog - a text-based dialog box allowing for one or two answers (yes/no, or just OK)

  • customYesNoDialog - a dialog box with custom graphics (yes/no, or just OK)

  • textAnswerDialog - a text-based dialog box allowing the user to enter a string

  • customAnswerDialog - a dialog box with custom graphics that allows the user to enter a string

Many helpers allow the use of a callback (a function or method to be called when an action happens)

Any widget that uses a callback should be set up like this: def <callbackMethodName>(self, nickName): When the appropriate action happens, the callback method will be called and the nickName will be passed. If you don’t need the nickname, you can just ignore that parameter

Classes

CountDownTimer

class pyghelpers.CountDownTimer(nStartingSeconds, stopAtZero=True, nickname=None, callBack=None)

This class is used to create a Timer that counts down from a given starting number of seconds.

Its intended use is where you want to continuously display the time in a window (using a DisplayText object).

Typical use:

  1. Create a CountDownTimer object:

    myTimer = pyghelpers.CountDownTimer(60) # start the timer at 60 seconds

  2. When you want the timer to start running, make this call:

    myTimer.start()

    This method can also be used to restart the timer.

  3. Whenever you want to get the remaining time (in seconds since start), you can call any of:

    theTime = pyghelpers.getTime() # gets time as a float

    theTime = pyghelpers.getTimeInSeconds() # gets the time as an integer number of seconds

    theTime = pyghelpers.getTimeInHHMMSS() # gets the time in HH:MM:SS string format

  4. If you want to stop the timer, call:

    myTimer.stop()

Parameters:
nStartingSeconds - the starting point for the timer, in seconds (integer or float)
Optional keyword parameters:
stopAtZero - should the timer stop when it reaches zero (defaults to True)
nickname - an internal name used to refer to this timer (defaults to None)
callback - a function or object.method to be called back when the timer is finished
The nickname of the timer will be passed in when the callback is made (defaults to None)
ended()

Call to see if the timer has reached zero. Should be called every time through the loop

getTime()

Returns the remaining time as a float number of seconds

getTimeInHHMMSS(nMillisecondsDigits=0)

Returns the remaining time as a HH:MM:SS.mmm formatted string

Parameters:

Optional keyword parameters:
nMillisecondsDigits - number of milliseconds digits to include (defaults to 0)
If specified, returned string will look like: HH:MM:SS.mmm
getTimeInSeconds()

Returns the remaining time as an integer number of seconds

start(newStartingSeconds=None)

Start the timer running starting at nStartingSeconds (or optional different setting)

stop()

Stops the timer

CountUpTimer

class pyghelpers.CountUpTimer

This class is used to create a Timer that counts up (starting at zero).

Its intended use is where you want to continuously display the time in a window (using a DisplayText object).

Typical use:

  1. Create a CountUpTimer object:

    myTimer = pyghelpers.CountUpTimer()

  2. When you want the timer to start running, make this call:

    myTimer.start()

    This method can also be called to restart the timer.

  3. Whenever you want to get the current time (in seconds since start), you can call any of:

    theTime = pyghelpers.getTime() # gets time as a float

    theTime = pyghelpers.getTimeInSeconds() # gets the time as an integer number of seconds

    theTime = pyghelpers.getTimeInHHMMSS() # gets the time in HH:MM:SS string format

    One of the above should be called every time through your main loop.

  4. If you want to stop the timer, call:

    myTimer.stop()

Parameters:
none
getTime()

Returns the time elapsed as a float

getTimeInHHMMSS(nMillisecondsDigits=0)

Returns the elapsed time as a HH:MM:SS.mmm formatted string

Parameters:

Optional keyword parameters:
nMillisecondsDigits - number of milliseconds digits to include (defaults to 0)
If specified, returned string will look like: HH:MM:SS.mmm
getTimeInSeconds()

Returns the time elapsed as an integer number of seconds

start()

Start the timer running (starts at zero). Can be called to restart the timer, for example to play a game multiple times

stop()

Stops the timer

Scene

class pyghelpers.Scene

The Scene class is an abstract class to be used as a base class for any scenes that you want to create.

At startup, you create an instance of each of your scenes, and pass a list of these scenes objects when you instantiate the scene manager.

In the __init__ method of your scene subclass, you will receive a window reference. You should copy this into an instance variable like this:

def __init__(self, window):
self.window = window
# Add any initialization you want to do here.

You also need to write a getSceneKey() method that returns a string or constant that uniquely identifies the scene. It is recommended that you build and import a Constants.py file that contains constants for each scene, and use the key associated with the current scene here.

def getSceneKey(self):
return <string or CONSTANT that identifies this scene>

When your scene is active, the SceneManager calls a standard set of methods in the current scene. Therefore, all scenes must implement these methods (polymorphism):

handleInputs # called in every frame
draw # called in every frame

The following methods can optionally be implemented in a scene. If they are not implemented, then the default version in the Scene subclass will be used. (The Scene class’ default versions do not do anything, they just return):

enter # called once whenever the scene is entered
update # called in every frame
leave # called once whenever the scene is left

When you want to go to a new scene:

Call self.goToScene() and pass in the sceneKey of the scene you want to go to,
and optionally, pass any data you want the next scene to receive in its enter() method.

If you want to quit the program from your scene, call:

self.quit()
abstract draw()

This method is called in every frame of the scene to draw anything that needs to be drawn

Your code must override this method.

enter(data)

This method is called whenever the user enters a scene.

Should be overridden if you expect data when your scene is entered. Add any code you need to start or re-start the scene

Parameters:
data - can be of any type agreed to by the old and new scenes
abstract getSceneKey()

This method must return the scene key for this scene

goToScene(nextSceneKey, data=None)

Call this method whenever you want to go to a new scene

Parameters:
nextSceneKey - the scene key (string) of the scene to go to
data - any data you want sent to the next scene (defaults to None)
(The data can be a single value, a list, dictionary, object, etc.)
abstract handleInputs(events, keyPressedList)

This method is called in every frame of the scene to handle events and key presses

Your code MUST override this method.

Parameters:
events - a list of events your method should handle.
keyPressedList - a list of keys that are pressed (a Boolean for each key).
leave()

This method is called whenever the user leaves a scene

Override this method, and add any code you need to clean up the scene before leaving

quit()

Call this method if you want to quit, from inside a scene

receive(receiveID, info)

Receives information from another scene.

You must override this method if your scene expects to receive information from other scenes sending information via calls to: send

Parameters:
receiveID - an identifier for what type of information is being received
info - the information sent from another scene
request(targetSceneKey, requestID)

Call this method to get information from another scene

The target scene must implement a method named: respond, it can return any info in any way the two scenes agree upon

Parameters:
targetSceneKey - the scene key (string) of the scene to ask for data
requestID - the data you want from the target scene (typically a string)
respond(requestID)

Respond to a request for information from some other scene

You must override this method if your scene expects to handle requests for information from other scenes via calls to: request()

Parameters:
requestID - identifier of what data to be sent back to the caller
send(targetSceneKey, sendID, info)

Call this method to send information to another scene

The other scene must implement a method named: receive(). You can pass any info the two scenes agree upon

Parameters:
targetSceneKey - the scene key (string) of the scene to ask for data
sendID - the type of data you are sending the target scene (typically a string)
info - the actual data to send (can be any type)
sendAll(sendID, info)

Call this method to send information to all other scenes

The other scenes must implement a method named: receive(). You can pass any info that the sender and all other scenes agree upon

Parameters:
sendID - the type of data you are sending the target scene (typically a string)
info - the actual data to send (can be any type)
update()

This method is called in every frame of the scene do any processing you need to do here

SceneMgr

class pyghelpers.SceneMgr(scenesList, fps)

SceneMgr (Scene Manager) allows you to build a program with multiple scenes.

The SceneMgr manages any number of scenes built as subclasses of the “Scene” class.

For more details, see the “Scene” class.

Typical use:

  1. Instantiate as many Scenes as you want:

    oScene1 = StartingScene(window)
    oScene2 = MainScene(window)
    oScene3 = SometherScene(window)
  2. Build a list of these scenes:

    myScenesList = [oScene1, oScene2, oScene3]

  3. Instantiate one SceneMgr (a singleton):

    oSceneMgr = SceneMgr(myScenesList, 30) # First scene in the list is the starting scene

  4. Call the run method to start the SceneMgr running:

    oSceneMgr.run() # First scene in the list is the starting scene

Parameters:
scenesList - is a list that consists of:
[<sceneObject>, <sceneObject>, …]
where each sceneObject is an object instantiated from a scene class
(For details on Scenes, see the Scene class)
fps - is the frames per second at which the program should run

Based on the concept of a “Scene Manager” by Blake O’Hare of Nerd Paradise (nerdparadise.com)

run()

This method implements the main pygame loop.

It should typically be called as the last line of your main program.

It is designed to call a standardized set of methods in the current scene.

All scenes must implement the following methods (polymorphism):

handleInputs # called in every frame
draw # called in every frame

The following methods can be implemented in a scene. If they are not implemented, then the default version in the Scene base class will be used. (Those methods do not do anything):

enter # called once whenever the scene is entered
update # called in every frame
leave # called once whenever the scene is left

Timer

class pyghelpers.Timer(timeInSeconds, nickname=None, callBack=None)

This class is used to create a very simple Timer.

Typical use:

  1. Create a Timer object:

    myTimer = pyghelpers.Timer(10)

  2. When you want the timer to start running, make this call:

    myTimer.start()

    You can also call this method to restart the timer after it finishes.

  3. In your big loop, check to see if the timer has finished:

    finished = myTimer.update()

    Normally returns False, but returns True when the timer is finished

Parameters:
timeInSeconds - the duration of the timer, in seconds (integer or float)
Optional keyword parameters:
nickname - an internal name to associate with this timer (defaults to None)
callback - a function or object.method to be called back when the timer is finished
The nickname of the timer will be passed in when the callback is made (defaults to None)
getTime()

Call this if you want to know how much has elapsed

Returns:
0 - if the Timer is not running
seconds elapsed since start, as a float
start(newTimeInSeconds=None)

Start the timer running (starts at zero). Allows you to optionally specify a different amount of time.

stop()

Stops the timer

update()

Call this in every frame to update the timer

Returns:
False - most of the time
True - when the timer is finished
(you can use this indication, or set up a callback)

Functions:

customAnswerDialog

pyghelpers.customAnswerDialog(theWindow, oDialogImage, oPromptText, oAnswerText, oOKButton, oCancelButton)

A function that puts up a custom two-button modal dialog (typically Yes/No or OK/Cancel)

Parameters:
theWindow - the window to draw in
oDialogImage - an Image object (from pygwidgets) containing the background of the dialog box
oPromptText - a TextDisplay object (from pygwidgets) containing the prompt to display
oAnswerText - an InputText object (from pygwidgets) where the user types their answer
oOKButton - a CustomButton object (from pygwidgets) representing OK, etc.
oCancelButton - a CustomButton object (from pygwidgets) representing Cancel, etc.
Returns:
userAnswer - If user presse OK, returns the text the user typed. Otherwise returns None

customYesNoDialog

pyghelpers.customYesNoDialog(theWindow, oDialogImage, oPromptText, oYesButton, oNoButton)

A function that puts up a custom two-button modal dialog (typically Yes/No or OK/Cancel)

It can also be used to put up a single button alert dialog (with a typcial OK button)

Parameters:
theWindow - the window to draw in
oDialogImage - an Image object (from pygwidgets) with the background of the dialog box
oPromptText - a TextDisplay object (from pygwidgets) containing the prompt to display
oYesButton - a CustomButton object (from pygwidgets) representing Yes or OK, etc.
oNoButton - a CustomButton object (from pygwidgets) representing No or Cancel, etc.
Note: If oNoButton is None, the No button will not be drawn
This way, you can present an “alert” box with only a single button, like ‘OK’
Returns:
True - meaning the Yes button was pressed
or
False - meaning the No button was pressed

(With an alert dialog, you can ignore the returned value, as it will always be True.)

textAnswerDialog

pyghelpers.textAnswerDialog(theWindow, theRect, prompt, okButtonText='OK', cancelButtonText='Cancel', backgroundColor=(0, 200, 200), promptTextColor=(0, 0, 0), inputTextColor=(0, 0, 0))

A function that puts up a text-based two-button answerable modal dialog (typically OK/Cancel)

Parameters:
theWindow - the window to draw in
theRect - the rectangle (or tuple) of the dialog box in the application window
prompt - prompt (title) string to be displayed in the dialog box
Optional keyword parameters:
okButtonText - text on the OK button (defaults to ‘OK’)
cancelButtonText - text on the Cancel button (defaults to ‘Cancel’)
backgroundColor - rgb background color for the dialog box (defaults to (0, 200, 200))
promptTextColor - rgb color of the prompt text (defaults to black)
inputTextColor - rgb color of the input text (defaults to black)
Returns:
userAnswer - If user presses OK, returns the text the user typed. Otherwise returns None

textYesNoDialog

pyghelpers.textYesNoDialog(theWindow, theRect, prompt, yesButtonText='Yes', noButtonText='No', backgroundColor=(0, 200, 200), textColor=(0, 0, 0))

A function that puts up a text-based two-button modal dialog (typically Yes/No or OK/Cancel)

It can also be used to put up a single button alert dialog (typically with an OK button)

Parameters:
theWindow - the window to draw in
theRect - the rectangle (or tuple) of the dialog box in the application window
prompt - prompt (title) string to be displayed in the dialog box
Optional keyword parameters:
yesButtonText - text on the Yes button (defaults to ‘Yes’)
noButtonText - text on the No button (defaults to ‘No’)
Note: If noButtonText is None, the nothing will be drawn for the No button
This way, you can present an “alert” box with only an ‘OK’ button
backgroundColor - rgb background color for the dialog box (defaults to (0, 200, 200))
textColor - rgb color for the prompt text (defaults to black)
Returns:
True - meaning the Yes button was pressed
or
False - meaning the No button was pressed

(With an alert dialog, you can ignore the returned value, as it will always be True.)

Indices and tables