Introduction to Pygame Event Processing Mechanism - Introduction to MOOC Python Game Development 02

Table of contents

First explain a few questions:

1. Event processing requirements mainly include the following aspects:

2. Pygame event queue

3. Pygame events

4. Event type and attribute

 5. Important functions for event processing

 6. Keyboard events

7. Mouse events

8. Handling event function

9. Operation event queue

10. Generate events

Secondly, the code segment is given, which is conducive to everyone's study and analysis

Finally, make a summary:


As a game, on the one hand, whether the content of the game is attractive, on the other hand, it is to participate in it as a player, so how to interact with users is a problem that needs to be solved, so the second part is the event processing mechanism, which is the first part The event.type mentioned in the processing. Generally, it is keyboard and mouse input, and a joystick is required to develop more advanced games. Here we mainly talk about the processing of keyboard and mouse operations.

First explain a few questions:

1. Event processing requirements mainly include the following aspects:

• Respond to the user's keyboard, mouse and other peripheral operations
• Respond to screen size and mode changes
• Respond to specific trigger conditions of the game plot
• Generate some trigger conditions
• …

2. Pygame event queue

A queue is established to cache and dispatch all events.
In principle, first-come-first-served

3. Pygame events

pygame.event.EventType
• An event is essentially an encapsulated data type (object)
• EventType is a class of Pygame, which represents an event type
• An event type has only attributes and no methods
• Users can customize new event types

4. Event type and attribute

 5. Important functions for event processing

 6. Keyboard events

For event types, such as pressing on the keyboard, and then for different combinations of key values ​​and modifiers, a variety of operational feedback to the game can be realized, so as to realize the overall control of the game by people, but based on the playability of the game, try to Reducing the number of keys is good for gaming!


7. Mouse events

 (1) pygame.event.MOUSEMOTION Mouse movement event
• event.pos The current coordinate value of the mouse (x, y), relative to the upper left corner of the window
• event.rel The relative movement distance of the mouse (X, Y), relative to the last event
• event.buttons mouse button state (a, b, c), corresponding to the three keys of the mouse

(2) pygame.event.MOUSEBUTTONUP mouse button release event
• event.pos the current coordinate value of the mouse (x, y), relative to the upper left corner of the window
• event.button the number n of the mouse button pressed, the value is 0/1/2, corresponding to three keys

(3) pygame.event.MOUSEBUTTONDOWN mouse button press event
• event.pos current mouse coordinate value (x, y), relative to the upper left corner of the window
• event.button mouse button number n, the value is an integer, the left button 1, the right button is 3, device-related

8. Handling event function

(1)pygame.event.get()

• Get the event list from the event queue, that is, get all queued events

For example:

for event in pygame.event.get():
        if event.type == pygame.QUIT:
        sys.exit()
• You can add parameters to get a certain type or types of events:
pygame.event.get(type)
pygame. event. get(typelist)

(2)pygame.event.poll()

• get an event from the event queue

While True :
        event = pygame.event.poll()
• The event get will be removed from the event queue
• If the event queue is empty, return event.NOEVENT

(3)pygame.event.clear()

• Delete events from the event queue, all events are deleted by default
• This function is similar to pygame.event.get(), the difference is that the event is not processed
• You can add parameters to delete certain types or types of events:
pygame.event. clear(type)
pygame. event. clear(typelist)

9. Operation event queue

pygame.event.set_blocked(type or typelist)

• Control which types of events are not allowed to be saved in the event queue

pygame.event.set_allowed(type or typelist)

• Controls which types of events are allowed to be saved in the event queue

pygame.event.get_blocked(type)

• Test whether an event type is prohibited by the event queue
• Return True if the event type is prohibited, otherwise return False

10. Generate events

pygame.event.post(Event)

• Generate an event and put it into the event queue
• Generally used to place user-defined events (pygame.USEREVENT)
• Can also be used to place system-defined events (such as mouse or keyboard, etc.), given parameters

pygame.event.Event(type, dict)

• Create an event of a given type
• Among them, the attributes and values ​​of the event are copied in the dictionary type, and the attribute name is in the form of a string
• If an existing event is created, the attributes need to be consistent

Secondly, the code segment is given, which is conducive to everyone's study and analysis

# Unit PYG03: Pygame Wall Ball Game version 8  鼠标型
import pygame,sys

pygame.init()
size = width, height = 600, 400
speed = [1,1]
BLACK = 0, 0, 0
screen = pygame.display.set_mode(size, pygame.RESIZABLE)  #窗口大小可调

icon = pygame.image.load("PYG03-flower.png")
pygame.display.set_icon(icon)
pygame.display.set_caption("Pygame壁球")
ball = pygame.image.load("PYG02-ball.gif")
ballrect = ball.get_rect()
fps = 300
fclock = pygame.time.Clock()
still = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1)*int(speed[0]/abs(speed[0]))
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1)*int(speed[1]/abs(speed[1]))
            elif event.key == pygame.K_ESCAPE:
                sys.exit()
        elif event.type == pygame.VIDEORESIZE:
            size = width, height = event.size[0], event.size[1]
            screen = pygame.display.set_mode(size, pygame.RESIZABLE)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                still = True
        elif event.type == pygame.MOUSEBUTTONUP:
            still = False
            if event.button == 1:
                ballrect = ballrect.move(event.pos[0] - ballrect.left, event.pos[1] - ballrect.top)
        elif event.type == pygame.MOUSEMOTION:
            if event.buttons[0] == 1:
                ballrect = ballrect.move(event.pos[0] - ballrect.left, event.pos[1] - ballrect.top)
    if pygame.display.get_active() and not still:
        ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = - speed[0]
        if ballrect.right > width and ballrect.right + speed[0] > ballrect.right:
            speed[0] = - speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = - speed[1]
        if ballrect.bottom > height and ballrect.bottom + speed[1] > ballrect.bottom:
            speed[1] = - speed[1]

    screen.fill(BLACK)
    screen.blit(ball, ballrect)
    pygame.display.update()
    fclock.tick(fps)

The above code is used to obtain events, which handles closing, keyboard, mouse, window changes, etc., and can be used to analyze code usage

# Unit PYG04: Pygame Event Post
import pygame,sys

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame事件处理")
fps = 1
fclock = pygame.time.Clock()
num = 1

while True:
    uevent = pygame.event.Event(pygame.KEYDOWN, {"unicode": 123, "key":pygame.K_SPACE, "mod":pygame.KMOD_ALT})
    pygame.event.post(uevent)
    num = num + 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.unicode == "":
                print("[KEYDOWN {}]:".format(num), "#", event.key, event.mod)
            else:
                print("[KEYDOWN {}]:".format(num), event.unicode, event.key, event.mod)

    pygame.display.update()
    fclock.tick(fps)

The operation of creating and generating events in the above code segment can be used for learning and use. The code segment comes from MOOC

Finally, make a summary:

This article briefly introduces the event handling mechanism of pygame.

1. Event processing requirements In layman's terms, it is how the software responds to user operations, how to deal with which operations, which ones need to be responded to, which ones do not need to be responded to, which ones are important to respond to, which ones can be responded to later, and how to respond.

2. Generally speaking, the event queue is the problem that needs to be solved in queuing. Generally, it is processed later, but different processing methods can also be set.

3. The event type is the type that pygame can handle, and it will focus on explaining the keyboard, mouse, etc. These event types are applied to event processing and are queued in the event queue, but generally we do not need to manage the processing method of the event queue

4. The important function of event processing is the method of processing events, which ones need to be processed, which ones do not need to be processed, and how to handle them, and even generate events according to their own needs.

Note: Commonly used key values ​​and modified values ​​​​of the keyboard generally do not need to be memorized, just look it up when you use it! It’s a bit too much, just understand it and hit it!

Guess you like

Origin blog.csdn.net/sygoodman/article/details/124358615