leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python Pygame event monitoring: keyboard events and mouse events

Estimated reading: 7 minutes 54 views

We have already introduced that any time the user performs an action such as pressing a button or moving the mouse, the Pygame library will create a pygame.event.Event object to record the action, which is an “event “.

We can call the pygame.event.get() function to find out what event happened. For example, the function that detects the close event was used earlier in this chapter to close the Pygame window. Next, let’s learn how to monitor keyboard events and mouse events.

keyboard event

We want the program to monitor the keyboard so that once a key is pressed, the program can do the corresponding thing. In Pygame, the event of pressing a keyboard is KEYDOWN, and the event of releasing a keyboard is KEYUP.

In the previous study, we know that the pygame.event.get() function can get a list of events. The for loop iterates through each event in this list, and when it sees the QUIT event, it sets the variable Running to False, which causes the while loop to end, and the program ends.

Now, we’re going to detect another type of event, the KEYDOWN and KEYUP events, and use the event object’s key property to identify which key on the keyboard was pressed.

We slightly modified the example in the previous section so that the text “Hello World!” can be moved by the arrow keys, and the window can be closed by pressing the Esc key, as shown in the code below.

import pygame
pygame.init()
windowSurface=pygame.display.set_mode((800,600))
BLACK=(0,0,0)
WHITE=(255,255,255)
myString="Hello World!"
font = pygame.font.SysFont("Times New Roman", 48)
text = font.render(myString, True, WHITE)
picX=0
picY=0
speed=1
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
Running=True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running=False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                Running=False
            if event.key == pygame.K_LEFT:
                moveLeft = True
            if event.key == pygame.K_RIGHT:
                moveRight = True
            if event.key == pygame.K_UP:
                moveUp = True
            if event.key == pygame.K_DOWN:
                moveDown = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                moveLeft = False
            if event.key == pygame.K_RIGHT:
                moveRight = False
            if event.key == pygame.K_UP:
                moveUp = False
            if event.key == pygame.K_DOWN:
                moveDown = False
    if moveDown and text.get_height()+picY < 600:
        picY+=speed
    if moveUp and picY > 0:
        picY -= speed
    if moveLeft and picX > 0:
        picX -= speed
    if moveRight and text.get_width()+picX < 800:
        picX += speed
    windowSurface.fill(BLACK)
    windowSurface.blit(text, (picX,picY))
    pygame.display.update()
pygame.quit()

We give some clarification on the newly added code (highlighted). The code below creates variables for moving in each direction, and these 4 boolean variables are used to keep track of which direction key was pressed. For example, set moveLeft to True when the user presses the left arrow key on the keyboard. When the key is released, set moveLeft to False.

moveLeft = False
moveRight = False
moveUp = False
moveDown = False

Then judge the event type in the event loop, if it is KEYDOWN, then the event object will have a key attribute to identify which key was pressed.

  • If the key attribute is equal to K_ESCAPE, it means that the user pressed the Esc key, which means that the player wants to end the program, then the processing method is the same as the detection of the click to close the window event, and the variable Running is also set to False, which causes the while loop to end and end program.
  • If the key attribute is equal to K_LEFT, indicating that the user pressed the left arrow key, then set the moveLeft variable moveLeft to True.
  • If other arrow keys are pressed, set the corresponding move variable to True.

This code is shown below.

 if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                Running=False
            if event.key == pygame.K_LEFT:
                moveLeft = True
            if event.key == pygame.K_RIGHT:
                moveRight = True
            if event.key == pygame.K_UP:
                moveUp = True
            if event.key == pygame.K_DOWN:
                moveDown = True

The KEYUP event is fired when the user releases the pressed key. If the left arrow key is released, the moveLeft variable moveLeft is set to False, causing the movement to stop. If other arrow keys are released, set the corresponding movement variable to False.

This code is shown below.

 if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                moveLeft = False
            if event.key == pygame.K_RIGHT:
                moveRight = False
            if event.key == pygame.K_UP:
                moveUp = False
            if event.key == pygame.K_DOWN:
                moveDown = False

We’ve set the movement variable based on the user’s keystrokes. Now, the variables picX and picY are adjusted accordingly according to these shift variables, thus modifying the coordinates of the text. If the variable moveDown is True, the down arrow is pressed, and if the bottom of the text is not lower than the bottom of the window, the variable picY is incremented by speed. Since we’re going to set picY to be the Y coordinate of the text, that means moving the text down. Basically the same thing is done for the other 3 directions.

This code is shown below.

if moveDown and text.get_height()+picY < 600:
        picY+=speed   
    if moveUp and picY > 0:
        picY -= speed
    if moveLeft and picX > 0:
        picX -= speed
    if moveRight and text.get_width()+picX < 800:
        picX += speed

Then pass windowSurface.fill(BLACK), indicating that the screen must be refilled every time the loop is performed. Finally, the blit() function is called to copy the pixels from one Surface to the other, and draw the text to the position where the X coordinate is picX and the Y coordinate is picY.

   windowSurface.fill(BLACK)       
    windowSurface.blit(text, (picX,picY))

Running this code, you can use the arrow keys to move the text “Hello World” in the window, as shown in Figure 1.

Python mouse events

mouse event

We learned how to handle keyboard events earlier, now let’s introduce how to handle mouse events and how to use mouse position information. In Pygame, the MOUSEBUTTONDOWN event is fired when the mouse is pressed in the window, the MOUSEBUTTONUP event is fired when the mouse is released, and the MOUSEMOTION event is fired when the mouse moves over the window.

Let’s look at an example. If the user clicks the left mouse button, a small yellow dot will be drawn on the clicked place. If the user clicks the right mouse button, the screen will be cleared. The code is as follows.

import pygame
pygame.init()
windowSurface=pygame.display.set_mode((800,600))
YELLOW=(255,255,0)
BLACK=(0,0,0)
Running=True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running=False
        if event.type == pygame.MOUSEBUTTONDOWN:
             if pygame.mouse.get_pressed()[0]:
                point = event.pos
                pygame.draw.circle(windowSurface, YELLOW, point, 10)
             if pygame.mouse.get_pressed()[2]:
                 windowSurface.fill(BLACK)
    pygame.display.update()
pygame.quit()

The other codes have been introduced before, so I won’t repeat them here, but let’s focus on the highlighted new codes. In the for loop that iterates over the event list obtained by the pygame.event.get() function, the MOUSEBUTTONDOWN event is detected, and the mouse button is obtained through mouse.get_pressed():

  • If the first button of the mouse is pressed, its index is 0, indicating that the left button is pressed;
  • If it is the third button, its index is 2, indicating that the right button is pressed.

If the left button is pressed, we can use event.pos to get the position of the mouse click event and assign it to the variable point. Then we draw a solid yellow circle with a radius of 10 at point on the windowSurface. In this way, the function of clicking the left mouse button and drawing a small yellow dot at the clicked place is realized.

If the right mouse button is pressed, windowSurface.fill(BLACK) is called to fill the Surface to be drawn with black, which is equivalent to clearing all the previously drawn content.

Running the code, we can draw a clock shape on the screen, as shown in Figure 2.

Python keyboard events

Leave a Comment

CONTENTS