Welcome to pyghelpers’ documentation!

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 = myTimer.getTime() # gets time as a float

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

    theTime = myTimer.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, forceFullHHMMSS=False)

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 include nMillisecondsDigits of milliseconds digits
forceFullHHMMSS forces the output to be in full HH:MM:SS format (defaults to False)
getTimeInSeconds()

Returns the remaining time as an integer number of seconds

pause()

Pauses the timer

resume()

Resumes the timer after a pause

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 = myTimer.getTime() # gets time as a float

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

    theTime = myTimer.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, forceFullHHMMSS=False)

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 include nMillisecondsDigits of milliseconds digits
forceFullHHMMSS forces the output to be in full HH:MM:SS format (defaults to False)
getTimeInSeconds()

Returns the time elapsed as an integer number of seconds

pause()

Pauses the timer

resume()

Resumes the timer after a pause

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.

In the startup code for your application, you create an instance of each of the scenes that you want to be available. Then you build a dictionary like this

{<sceneKey1>:<sceneObject1>, <sceneKey2>:<sceneObject2>, …}

Then you pass this dictionary when you instantiate the Scene Manager. See the SceneMgr documentation for details.

To create a scene, you must write a subclass that inherits from this class. Your class must implement these methods

__init__(), handleInputs(), draw()

You will typically overwrite the update() method to do any processing in every frame.

Other methods can be overridden if you wish:

enter(), leave()

You can add any additional methods that your class requires. Additionally, there are other methods to allow you to get or set info, or navigate to other scenes:

goToScene(), quit(), request(), respond() and more.

In the __init__() method of your scene subclass, you will receive a window reference. You should copy this into an instance variable like this, and use it when drawing:

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

Before version 1.1 of pyghelpers you had to do the following, but as of version 1.1, this method is no longer needed. Instead, you now set the scene keys at start up (much more betterer!).

OLD: 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 null version in the Scene subclass will be used. (The Scene class’ default versions only execute a pass statement):

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()
addScene(sceneKey, oScene)

Call this method whenever you want to add a new scene dynamically. For example, you could have a game with many levels (each implemented as a scene), but only have the current level loaded. As the player completes a level, you could do a removeScene on the current level and do an addScene on the next level, then do a goToScene on the new level.

Parameters:
sceneKey - a key to uniquely identify this scene (typically a string)
oScene - an instance of the new scene to be added
(typically, you would instantiate the new scene, and pass in that reference to this call)
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

Parameter:
data - can be of any type agreed to by the old and new scenes
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
Optional keyword parameter:
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
removeScene(sceneKey)

Call this method whenever you want to remove an existing scene You can remove a scene to save memory - the scene object will be deleted. The SceneMgr delays removing the scene until the next time thru the main loop. Therefore, it is safe to call to removeScene from its own scene, if you immediately go to another scene.

Parameters:
sceneKey - the scene key (string) of the scene to remove
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

Your code will typically override this method.

SceneMgr

class pyghelpers.SceneMgr(scenesDictOrList, fps, oFrameRateDisplay=None)

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 = SomeOtherScene(window)
  2. Build a dictionary of these scenes:
    myScenesDict = {‘sceneKey1’: oScene1, ‘sceneKey2’: oScene2, ‘sceneKey3’: oScene3}

    The keys are any unique strings that you want to use.

    OLDER APPROACH: Before pyghelpers 1.1, but still works for backwards compatibility Build a list of the scenes: | myScenesList = [oScene1, oScene2, oScene3]

  3. Instantiate one SceneMgr (a singleton):
    oSceneMgr = SceneMgr(myScenesDict, 30) # First scene in the dict is the starting scene
    OLDER APPROACH: Before pyghelpers 1.1, but still works for backwards compatibility

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

    You can optionally pass a DisplayText object for showing the frame rate, e.g. | oDebugFrameRate = pygwidgets.DisplayText(window, (0, 0), ‘’, fontSize=24) | oSceneMgr = SceneMgr(scenesDictOrList, FRAMES_PER_SECOND, oDebugFrameRate)

  4. Call the run method to start the SceneMgr running:
    oSceneMgr.run() # First scene in the list is the starting scene
Parameters:
scenesDictOrList - is a dictionary or list that consists of:
{<sceneKey>: <sceneObject>, <sceneKey>: <sceneObject>, …}
OR older (before pyghelpers 1.1): [<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:
enter() # called once whenever the scene is entered
update() # called in every frame
leave() # called once whenever the scene is left

If any is not implemented, then the version in the Scene base class, which only performs a pass statement, will be used.

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 if a 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
pause()

Pauses the timer

resume()

Resumes the timer after a pause

start(newTimeInSeconds=None)

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

Optional keyword parameter: | newTimeInSeconds - a new duration for the timer (integer or float, default None)

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=None)

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.
Optional keyword parameter:
oNoButton - a CustomButton object (from pygwidgets) representing No or Cancel, etc. (default None)
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