6.9: Checking for Keyboard Presses

Making Games with Python and Pygame · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    From LibreTexts, under CC BY-NC-SA 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.9: Checking for Keyboard Presses
               elif event.type == KEYDOWN:
                    if event.key == K_q:
                        clickedButton = YELLOW
                    elif event.key == K_w:
                        clickedButton = BLUE
                    elif event.key == K_a:
                        clickedButton = RED
                    elif event.key == K_s:
                        clickedButton = GREEN
    

    Lines 1 [85] to 9 [93] check for any KEYDOWN events (created when the user presses a key on the keyboard). The Q, W, A, and S keys correspond to the buttons because they are arranged in a square shape on the keyboard.

    The Q key is in the upper left of the four keyboard keys, just like the yellow button on the screen is in the upper left, so we will make pressing the Q key the same as clicking on the yellow button.

    We can do this by setting the clickedButton variable to the value in the constant variable YELLOW. We can do the same for the three other keys. This way, the user can play Simulate with either the mouse or keyboard.


    This page titled 6.9: Checking for Keyboard Presses was last modified on Thu, 14 Nov 2019 23:05:41 GMT and is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Al Sweigart via source content that was edited to the style and standards of the LibreTexts platform.