Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

python - Pygame: how to write event-loop polymorphically

I'm some-what new to pygame, and while trying to get back into it, I found the advice "replace your conditionals with polymorphism." Most pygame tutorials recommend using the "for event in pygame.event.get()" loop and then using a conditional to determine if any particular event has occured.

1: How do I write that code using a polymorphic function 2: Is it worth it to re-factor the code, or just leave the conditional as-is

Below is what most tutorials recommend

def gameloop():
"""
Stuff that comes before the event-loop
"""

for event in pygame.event.get():
    if event.type == pygame.QUIT:   # This is the conditional I want to remove
        quit_functions()

Below is how I want to approach this

from abc import ABC, abstractmethod
import pygame


def detect_event(event_class_name):
    for event in pygame.event.get():
        # This is how I want to get the event and then assign it a function
        event_class_name.determine_event(event)


# Above: I want to use this function to detect events and call their functions

# Below: This is how I want to assign functions to the events


class EventHandler(ABC):
    @staticmethod
    @abstractmethod
    def determine_event(event): pass


class Exit(EventHandler):
    @staticmethod
    # How do I identify this with the event-type "pygame.QUIT," for example
    def determine_event(event):
        pygame.quit()
        quit(0)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to use classes with static methods, and to build on Rabbid76's answer, an (imho) elegant way to go about this is a decorator to register each event handler in the dict:

import pygame

event_handler_registry = {}


def register_event_handler(event):
    def decorator(fn):
        event_handler_registry[event] = fn
        return fn

    return decorator


@register_event_handler(pygame.QUIT)
def on_exit(event):
    pygame.quit()
    quit(0)


@register_event_handler(pygame.KEYDOWN)
def on_key_down(event):
    print(event.key)


while True:
    for event in pygame.event.get():
        event_handler = event_handler_registry.get(event.type)
        if event_handler:
            event_handler(event)
        else:
            print(f"No event handler for {event}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...