The handling of keyboard and mouse events in pygame

The handling of keyboard and mouse events in pygame

The so-called event is what happens in the procedure. For example, when a user presses a key on the keyboard or clicks or moves the mouse, the game program needs to respond to these events. For example, in pygame image / graphics rendering, the program will continue to run until the user closes the window and generates a QUIT event. pygame will receive various operations of the user (such as pressing keys on the keyboard, moving the mouse, etc.) to generate events. Events may occur at any time, and the amount may be very large. pygame stores a series of events in a queue for processing one by one.

Pygame Event Get() to handle all events, if pygame Event Wait (), pyGame will wait until an event occurs before continuing. Generally, it is not practical in games, because games often need dynamic operation. Common events for pyGame are as follows:

event Generation pathway parameter
QUIT User presses "close" button None
ACTIVEEVENT pygame is activated or hidden gain ,state
KEYDOWN Keyboard pressed unicode ,key ,mod
KEYUP Keyboard is released key ,mod
MOUSEMOTION Mouse movement pos ,rel ,buttons
MOUSEBUTTONDOWN Mouse pressed pos ,button
MOUSEBUTTONUP Mouse is released pos ,button

1. keyboard event handling of pyGame

Usually pyagme Event Get() gets all events, if event Type = = Keydown, this is the keyboard event, and then judge the event of the key The type of key (i.e. K_a, K_b, K_LEFT). Users can also use pygame key. Get_ Pressed() to get all the pressed key values, corresponding to whether the key is pressed.

keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_SPACE]:
    # Space bar pressed
    fire()           # Fire a bullet

There are many functions under the key module, as follows:

  • key.get_focused(): Returns whether the current pygame window is activated.
  • Key Get_ Pressed(): get all pressed key values.
  • Key Get_ Mods (): key combinations pressed (Alt, Ctrl, Shift).
  • Key set_ Mods(): simulate the effect of pressing key combinations (KMOD_ALT, KMOD_CTRL, KMOD_SHIFT).

Use pygame to develop a game in which users control the movement of tanks. On the basis of the example in the previous section, the function of controlling tank movement through the direction key is added, and the background picture is added to the game. The codes are as follows:

import pygame


def tank_play():
    pygame,inite()
    tank_image = pygame.image.load("../images/tank.png")
    tank_rect = tank_image.get_rect()
    back_image = pygame.iamge.load("../images/background2.jpg")
    back_rect = back_image.get_rect()
    screen = pygame.display.set_mode(back_rect.size)
    pygame.display.set_caption("User direction keys control moving tanks")
    offset = 2      # Offset
    fps_clock = pygame.time.Clock()
    while True:
        fps_clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
        keys_pressed = pygame.key.get_presssed()
        if keys_pressed[pygame.K_RIGHT]:
            tank_rect.x += offset
        if keys_pressed[pygame.K_LEFT]:
            tank_rect.x -= offset
        if keys_pressed[oygame.K_UP]:
            tank_rect.y -= offset
        if keys_pressed[pygame.K_DOWN]:
            tank_rect.y += offset
        tank_rect.clamp_ip(back_rect)
        screen.blit(back_image, back_rect)
        screen.blit(tank_image, tank_rect)
        pygame.display.update()
        
     
if __name__ == '__main--':
    tank_play()

When the user presses the direction key, the tank moves in the specified direction. When the direction key is released, the tank stops moving. As follows:

2. pygame mouse event processing

Pygame The functions of mouse are as follows:

  • Pygame Mouse Get_ Pressed(): returns the pressed status of the key. The returned value is a tuple, which is the left key, the middle key, and the right key. If the key is pressed, it is True.

  • Pygame Mouse Get_ Rel(): returns a relative offset, that is, a tuple of (x-direction offset, y-direction offset).

  • Pygame Mouse Get_ Pos(): returns the current mouse position (x, y).

    For example: X, y = pygame Mouse Get_ Pos() is used to get the mouse position.

  • Pygame Mouse set_ POS (): set the mouse position.

  • Pygame Mouse Set_ Visible(): sets whether the mouse cursor is visible.

  • pygame Mouse Get_ Focused(): returns True if the mouse is valid in the pygame window.

  • Pygame Mouse set_ Cursor (): sets the default cursor style of the mouse.

  • Pygame Mouse Get_ Cursor (): returns the cursor style of the mouse.

Demonstrates the handler for mouse events. The code is as follows:

from math import pi
from random import randint
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
points = []
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
    	if event.type == pygame.KEYDOWN:
            # Press any key to clear the screen and restore the point to its original state
            points = []
            srceen.fill((255, 255, 255))      # Fill the window background with white
        if event.type == pygame.MOUSEBUTTONDOWN:	# Mouse down
            screen.fill((255, 255, 255))
            # Draw random rectangle
            rc = (255, 0, 0)	# gules
            rp = (randint(0, 639), randint(0, 479))
            rs = (639 - randint(rp[0], 639), 479 - randint(rp[1], 479))
            pygame.draw.rect(screen, rc, pygame.Rect(rp, rs))
            # Draw random circles
            rc = (0, 255, 0)	# green
            rp = (randint(0, 639), randint(0, 479))
            rr = randint(1, 200)
            pygame.draw.circle(screen, rc, rp, rr)
            # Get current mouse click position
            x, y = pygame.mouse.get_pos()
            points.append((x, y))
            # Draw an arc according to the click position
            angle = (x / 639) * pi * 2
            pygame.draw.arc(screen, (0, 0, 0), (0, 0, 639, 479), 0, angle, 3)
            # Draw an ellipse according to the click position
            pygame.draw.ellipse(screen, (0, 255, 0), (0, 0, x, y))
            # Draw two lines from the top left and bottom right to the click position
            pygame.draw.line(screen, (0, 0, 255), (0, 0), (x, y))
            pygame.draw.line(screen, (255, 0, 0), (640, 480), (x, y))
            # Draw a click trace
            if len(points) > 1:
                pygame.draw.lines(screen, (155, 155, 0), points, False, 2)
            # Draw a distinct dot for each dot you click
            for p in points:
                pygame.draw.circle(screen, (155, 155, 155), p, 3)
	pygame.display.update()

Run this program, click the mouse on the window and the graphics will come out. Press any key on the keyboard to clear the screen and start again. As follows:

Posted by fizzwizz on Wed, 01 Jun 2022 11:26:12 +0530