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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…