[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Keyboard Events and Labels...



To Blind/Sightless users:

    I am doing this to learn but also to use the computer with sound in python and pygame. This is my latest version to capture key events and also say what I want for that key. The dictionary for this is ideal and will expand much more when this game gets into the game itself. 
    I noticed that some people had mentioned something about capturing keys but not knowing the sequence, but when having the keydown you can place things into a stack, (list,) that pushes on and off in the sequence you received them. Or in other words a FIFO which is a first in and first out stack that keeps things in line if you so wish.
    I have some labels now that will change later. The .wav files are my voice but those will change later.

    So this is an example on how to capture key events using both the manager and key events inside the captured keydown event. A dictionary is perfect for this. Which will store many modules in the future.

# TREK.PY WRITTEN: 10/06/2007 LAST MODIFY: 10/010/2007
# THIS PYTHON SCRIPT TESTS KEYS BY DICTIONARY KEY LOOK-UP.
# THE DICTIONARY IS CALLED KEY_DIC!
# ALL KEYS IN UPPER OR LOWER CASE USE WAV FILES TO SAY KEY!
# IF NOT IN DICTIONARY IT FAILS AND DOES NOT SAY KEY!
# DEFAULTS TO ESCAPE KEY IN DICTIONARY AND DISPLAYS - NOT ASSIGNED!
# IT STARTS WITH BACKGROUND BRIDGE SOUND LOADED WITH SCREEN 
# AND EXITS WITH A FAIL SOUND!

# Import the necessary ocempgui parts.
from ocempgui.object import ActionListener
from ocempgui.widgets import *
from ocempgui.widgets.Constants import *
from pygame.locals import *
import os.path
import sys
import pygame.mixer, pygame.time, pygame.key

# ALL GLOBAL VARIABLES ARE IN CAPS!
Q_MIXER = pygame.mixer
Q_TIME = pygame.time
Q_Key = pygame.key


# QUADRANT OR GALAXY DISPLAY LIST!
#QUADRANT[9][9] = ""
def Q4Display():
    """FUNCTION Q4DISPLAY WILL DISPLAY QUADRANT ON CONSOLE SCREEN!
    THE MATRIX WILL BE AN 8 X 8 GRID DISPLAYED.
    AT THE MOMENT IT IS ONLY A TEST!"""
    Sector_L = ""
    for i in range (1, 9):
        Sector_L += "   " + str(i) + "S   |"
    for i in range (1, 9):
        print str(i) + "|" + Sector_L


# DICTIONARY COMMANDS FOR KEYS PRESSED!
KEY_DIC = {chr(26):"- Not Assigned!", chr(K_ESCAPE):"Fail", 
"a":"LOC", "b":"BAS", "c":"COM", "d":"DIR", 
"e":"ENM", "f":"PRB", "g":"GAL", 
"k":"KLI", "l":"LRS", "n":"NAV", "p":"PHA", 
"r":"CAL", "s":"SRS", "t":"TOR", "w":"WARP"}

# choose a desired audio format
# (freq, size, stereo, buffersize)
# 1=mono, 2=stereo and 1024 buf size, 2050 for 16 bit
Q_MIXER.init(21024) #raises exception on fail

# playsound function
def play_sound (File4Sound, Repeats, Max4Time):
    """PLAY_SOUND IS THE AUDIO PLAY MIXER SOUND FUNCTION FOR ANY SOUND FILE.
    This function plays one mixer channel from the games path VOICE folder.
    It has 3 arguments: File Name, Repeats, and Milliseconds To Play."""
    File4Sound = os.path.join("Voice", File4Sound) # PLACE IN VOICE FOLDER!
    q_sound = Q_MIXER.Sound(File4Sound)
    channel = q_sound.play (Repeats, Max4Time) #(loops+1, max ms-time)
# RETURN CHANNEL IN FUTURE FOR PAUSE/STOP!
#    return (channel)


# Pressing a key will print the key its unicode representation to 
#the Pygame screen title bar.
# FUNCTION KEYDOWN_HANDLER CAPTURES ANY KEY PRESSED ON THE KEYBOARD AND 

PERFORMS PROGRAM!
def keydown_handler (keyevent):
    """KEYDOWN_HANDLER IS THE FUNCTION THAT CAPTURES THE EVENT OF ANY KEYS 

PRESSED.
    It will say the voice of any key pressed! which is in the dictionary."""

# THIS DELAY IS NOT REALLY NEEDED.
    Q_TIME.wait(200) # NEEDED FOR SCREEN READER AND TITLE BAR DISPLAY SOMETIMES!

# Initialise and Say voice of key pressed!
    Ord4Key = 0
    if len(keyevent.unicode) > 0: # IS THERE KEY CODE?
        Ord4Key = ord(keyevent.unicode)
#    else:
#        re.title = "No Key Pressed!"

# TESTING FOR THE KEY CODE OF MULTIKEYS!
    if Q_Key.get_pressed()[K_UP]:
        re.title = "Up Arrow Key Pressed!"
        play_sound("Pha.wav", 0, -1)
    if Q_Key.get_pressed()[K_DOWN]:
        re.title = "Down Arrow Key Pressed!"
        play_sound("Tor.wav", 0, -1)

# CHECK FOR CAPS IF ALPHA KEY PRESSED! IS BUILT-IN FASTER?
    if Ord4Key >= ord("A") and Ord4Key <= ord("Z"):
#     CONVERT ALPHABET ORDINAL VALUE TO LOWER CASE!
        Ord4Key = Ord4Key - ord("A") + K_a

#     CONVERT ALPHABET ORDINAL VALUE TO CHARACTER!
    Char4Key = chr( Ord4Key)

# DISPLAY GALAXY GRID ON CONSOLE!
    if Char4Key == "x":
        Q4Display()

# IDENTIFY DOCUMENT DESCRIPTION OF EACH FUNCTION!
    if Char4Key == "i":
        print play_sound.__doc__
        print keydown_handler.__doc__
        print object_focused.__doc__
        print Q4Display.__doc__

# IS KEY PRESSED IN DICTIONARY?
    if KEY_DIC.has_key( Char4Key):
#         THEN FETCH KEY DICTIONARY VALUE, SOUND FILE AND PLAY IT!
        Com4Key = KEY_DIC[ Char4Key]+ ".wav"
        play_sound (Com4Key, 0, -1)
    else:
        Com4Key = KEY_DIC[ chr(26)] # FAILED, NOT ON LIST!

# Exit game command!
    if Char4Key == chr(K_ESCAPE):
        re.title = "Pressing Escape Key!"
        Q_TIME.wait(3000) # DELAY FOR SOUND FADE!
#        pygame.quit() #Must be global defined.
        sys.exit()
    if Char4Key == chr(K_q):
        re.title = "Pressing Quit Key!"
#        pygame.quit() #Must be global defined.
        sys.exit()


# Function object_focused will print a widget's text to the Pygame screen.
def object_focused (gui_widget, SoundFile):
    """FUNCTION OBJECT_FOCUSED WILL CAPTURE THE OBJECT FOCUSED WITH THE TAB 

KEY!
    Displaying the object's name to the title bar and say it's description!
   This function passes in 2 arguments: The object and the sound file 

assigned to it."""

    re.title = " %s focused" % gui_widget.text
    play_sound (SoundFile, 0, -1)
# Message to console commented out!
#    print "Element %s is focused" % gui_widget.text


# Create the first button with no text and place it at screen offset 3,3
button_one = Button ()
button_one.topleft = 3, 3

# Create a red background color for the first button and assign it a red
# label with the text "Button number one".
label_one = Label ("Button one")
label_one.create_style()
label_one.style["bgcolor"][STATE_NORMAL] = (255, 0, 0)
button_one.create_style()
button_one.style["bgcolor"][STATE_NORMAL] = (255, 0, 0)
button_one.child = label_one

# Connect the focus event (for tab).
# Play name of object focused!
button_one.connect_signal (SIG_FOCUSED, object_focused, button_one, 

"Command-P.wav")

# Connect the mouse enter event to the button to have some "hover" effect.
# Play name of button hovered!
button_one.connect_signal (SIG_ENTER, object_focused, button_one, 

"Command-P.wav")

#  Now when clicked play name of action of button.
button_one.connect_signal (SIG_CLICKED, object_focused, button_one, 

"Command.wav")

#  Now when mouse over play name of action of button.
#button_one.connect_signal (SIG_MOUSEMOVE, object_focused, button_one, 

"Button_One.wav")


# Create the second button with no text and place it 14 pixels to the right
# of the first one.
button_two = Button ()
button_two.topleft = button_one.left, button_one.bottom - 50

# Create a green background color for the second button and assign it a
# green label with the text "Button number two".
label_two = Label ("Button two")
label_two.create_style()
label_two.style["bgcolor"][STATE_NORMAL] = (0, 255, 0)
button_two.create_style()
button_two.style["bgcolor"][STATE_NORMAL] = (0, 255, 0)
button_two.child = label_two

# Connect the focus event (for tab or mouse "hover") of the second button.
# Play name of button focused!
button_two.connect_signal (SIG_FOCUSED, object_focused, button_two, 

"LRS.wav")

# Connect the mouse movement event to the button to have some "hover" effect.
# Play name of button hovered!
button_two.connect_signal (SIG_ENTER, object_focused, button_two, "LRS.wav")

#  Now when clicked play name of action of button.
button_two.connect_signal (SIG_CLICKED, object_focused, button_two, 

"SRS.wav")

#  Now when mouse over play name of action of button.
#button_two.connect_signal (SIG_MOUSEMOVE, object_focused, button_two, 

"Button_Two.wav")


# Create the renderer object.
re = Renderer ()

# Create the action listener and register key presses.
listener = ActionListener ()
listener.connect_signal (SIG_KEYDOWN, keydown_handler)

# Assign the listener to the first event manager of the Renderer, so it
# recognizes key presses.
listener.manager = re.managers[0]

# Let the renderer create a pygame screen with 200 pixels width and 200
# pixels height.
re.create_screen (200, 200)

# Set the window title to "Two button demo".
re.title = "Key and Button Demo"

# Set the screen background color to a grey RGB value.
re.color = (200, 200, 200)

# Add the buttons to the screen.
re.add_widget (button_one, button_two)

# PLAY BRIDGE SOUND CONTINUOUSLY!
play_sound ("Bridge.Wav", -1, -1)

# Start the main loop for drawing and event processing.
re.start ()