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
  • fileExists - find out if a file at a given path exists
  • readFile - reads from a (text) file
  • writeFile - writes to a (text) file
  • openFileForWriting - opens a (text) file for writing line by line
  • writeALine - writes a line of text to an open file
  • openFileForReading - opens a text file for reading line by line
  • readALine - reads a line of text from an open file
  • closeFile - closes an open file
Many helpeers 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 on screen (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 also be used 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

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

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

getTime()

Returns the elapsed time as a float number of seconds

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 elapsed time as an integer number of seconds

start()

Start the timer running (starts at nStartingSeconds)

stop()

Stops the timer from running

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 on screen (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 from running

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.

Each scene must be created with a key (which is a unique string) to identify itself.

The code creating a scene does so by instantiating a scene object from your scene subclass. That code must pass in a windows to draw into, and a unique key to identify the scene. In the __init__ method of your scene subclass, you will receive a window and a sceneKey. You must copy those into instance variables by starting your __init__ method like this:

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

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()
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
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.)
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(infoType, info)

Receives information from another scene.

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

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

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) to ask for data
infoRequested - the data you want from the target scene (typically a string)
respond(infoRequested)

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:
infoRequested - the actual data to be sent back to the caller
send(targetSceneKey, infoType, 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) to ask for data
infoType - the type of data you are sending the target scene (typically a string)
info - the actual data to send (can be any type)
sendAll(infoType, 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:
infoType - 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(scenesDict, startingSceneKey, 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 = Scene(“StartingScene”)
    oScene2 = Scene(“MainScene”)
    oScene3 = Scene(‘SometherScene”)
  2. Build a dictionary of these scenes with unique keys:

    mySceneDict = {‘Splash’: oScene1, ‘Main’: oScene2, ‘Other’: oScene3}

  3. Instantiate one SceneMgr (a singleton):

    oSceneMgr = SceneMgr(mySceneDict, ‘Splash’, 30)

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

    oSceneMgr.run()

Parameters:
scenesDict - is a dictionary that consists of:
{<sceneKey>:<sceneObject>, <sceneKey:<sceneObject>, …}
where each sceneKey is a unique string identifying the scene
and each sceneObject is an object instantiated from a scene class
(For details on Scenes, see the Scene class)
startingSceneKey - is the string identifying which scene is the starting scene
fps - is the frames per second at which the program should run

Based on a 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. Therefore, all scenes must implement these 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 subclass 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
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
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()

Start the timer running (starts at zero)

stop()

Stops the timer from running

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:

closeFile

pyghelpers.closeFile(fileHandle)

Close a file that was opened earlier with openFileForWriting or openFileForReading

Parameter:
fileHandle - a handle to an already opened file

customAnswerDialog

pyghelpers.customAnswerDialog(theWindow, oDialogImage, oPromptText, oAnswerText, oTrueButton, oFalseButton)

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 InputDisplay object (from pygwidgets) where the user types their answer
oTrueButton - a CustomButton object (from pygwidgets) representing True or OK, etc.
oFalseButton - a CustomButton object (from pygwidgets) representing False or Cancel, etc.
Returns:
trueOrFalse - True means true button was pressed, False means false button was pressed
userText - if trueOrFalse above is True, then this contains the text that the user typed.

customYesNoDialog

pyghelpers.customYesNoDialog(theWindow, oDialogImage, oPromptText, oTrueButton, oFalseButton)

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
oTrueButton - a CustomButton object (from pygwidgets) representing True or OK, etc.
oFalseButton - a CustomButton object (from pygwidgets) representing False or Cancel, etc.
Note: If oFalseButton is None or the empty string, the false button will not be drawn
This way, you can present an “alert” box with only an ‘OK’ button
Returns:
trueOrFalse - True means true button was pressed, False means false button was pressed

fileExists

pyghelpers.fileExists(filePath)

Check if a file at a given path exists

Parameters:
filePath - a path to a file (typically a relative path)
Returns:
trueOrFalse - True if the file exists, False if the file does not exist

openFileForReading

pyghelpers.openFileForReading(filePath)

Opens a file for reading

Parameters:
filePath - a path to a file (typically a relative path)
Returns:
fileHandle - a file handle for the file that was opened
(this should be used in sutsequent calls to readALine and closeFile)

openFileForWriting

pyghelpers.openFileForWriting(filePath)

Opens a file for writing

Parameters:
filePath - a path to a file (typically a relative path)
Returns:
fileHandle - a file handle for the file that was opened
(this should be used in subsequent calls to writeALine and closeFile)

readALine

pyghelpers.readALine(fileHandle)

Writes a line of text to the already opened file

Parameters:
fileHandle - a fileHandle to an already opened file (from openFileForReading)
Returns:
lineOrFalse - if a line is available, returns the next line of text in the file
Otherwise, returns False to indicate end of file has been reached.

readFile

pyghelpers.readFile(filePath)

Read the contents of a text file into a string

Parameters:
filePath - a path to a file (typically a relative path)
Returns:
textRead - a string contaning the contents of the file
Note: If the file does not exist, an exception will be raised

textAnswerDialog

pyghelpers.textAnswerDialog(theWindow, theRect, prompt, trueButtonText='OK', falseButtonText='Cancel', backgroundColor=(0, 200, 200))

Puts up a text-based two-button answerable modal dialog (typically Yes/No or OK/Cancel)

Parameters:
theWindow - the window to draw in
theRect - the rectangle of the dialog box in the application window
prompt - prompt (title) string to be displayed in the dialog box
Optional keyword parameters:
trueButtonText - text on the True button (defaults to ‘OK’)
falseButtonText - text on the False button (defaults to ‘Cancel’)
backgroundColor - rgb background color for the dialog box (defaults to (0, 200, 200))
Returns:
trueOrFalse - True means true button was pressed, False means false button was pressed
userText - if above is True, then this contains the text that the user typed.

textYesNoDialog

pyghelpers.textYesNoDialog(theWindow, theRect, prompt, trueButtonText='OK', falseButtonText='Cancel', backgroundColor=(0, 200, 200))

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 of the dialog box in the application window
prompt - prompt (title) string to be displayed in the dialog box
Optional keyword parameters:
trueButtonText - text on the True button (defaults to ‘OK’)
falseButtonText - text on the False button (defaults to ‘Cancel’)
Note: If falseButtonText is None or the empty string, the false button will not be drawn
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))
Returns:
trueOrFalse - True means true button was pressed, False means false button was pressed

writeALine

pyghelpers.writeALine(fileHandle, lineToWrite)

Writes a line of text to the already opened file

Parameters:
fileHandle - a fileHandle to an already opened file (from openFileForWriting)
lineToWrite - a line of text to be written out

writeFile

pyghelpers.writeFile(filePath, textToWrite)

Writes a string to a file

The text can contain newline characters which will indicate separate lines

Parameters:
filePath - a path to a file (typically a relative path)
textToWrite - a string to be written out

Indices and tables