我对pygame有点陌生,在试图回到它的时候,我发现了“用多态性替换你的条件”的建议。大多数 pygame 教程建议使用“for event in pygame.event.get()”循环,然后使用条件来确定是否发生了任何特定事件。
1:如何使用多态函数编写该代码 2:是否值得重构代码,或者只是将条件保持原样
以下是大多数教程推荐的内容
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()
以下是我想如何做到这一点
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)
BIG阳
慕码人8056858
慕妹3242003
相关分类