import pygame class Screen: _instance = None _initialized = False """ todo(更改以适应引擎主循环)! """ def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(Screen, cls).__new__(cls) return cls._instance def __init__(self, width: int = 640, height: int = 480, title="Pydot", fps: int = 60, fullscreen: bool = False, icon_path: str = ""): if Screen._initialized: return self.width = width self.height = height self.title = title self.fps = fps self.fullscreen = fullscreen self.icon_path = icon_path self.icon = None self.clock = None self.running = False pygame.init() self._create_display() pygame.display.set_caption(self.title) if self.icon_path: try: self.icon = pygame.image.load(self.icon_path) pygame.display.set_icon(self.icon) except pygame.error: print(f"无法加载图标文件: {self.icon_path}") self.clock = pygame.time.Clock() Screen._initialized = True def _create_display(self, flags=0): if self.fullscreen: self.screen = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN | pygame.HWSURFACE) else: self.screen = pygame.display.set_mode((self.width, self.height), flags) def get_surface(self): return self.screen def get_size(self): return (self.width, self.height) def set_title(self, title): self.title = title pygame.display.set_caption(self.title) def set_icon(self, icon: pygame.Surface): pygame.display.set_icon(icon) def set_icon_from_path(self, icon_path: str): self.icon_path = icon_path try: self.icon = pygame.image.load(icon_path) pygame.display.set_icon(self.icon) except pygame.error: pass def toggle_fullscreen(self): self.fullscreen = not self.fullscreen pygame.display.quit() pygame.display.init() self._create_display() if self.icon_path: try: self.icon = pygame.image.load(self.icon_path) pygame.display.set_icon(self.icon) except pygame.error: pass pygame.display.set_caption(self.title) def fill(self, color): self.screen.fill(color) def update(self): pygame.display.flip() def tick(self): return self.clock.tick(self.fps) def get_fps(self) -> float: return self.clock.get_fps() def handle_events(self): return pygame.event.get() def is_running(self): return self.running def start(self): self.running = True def stop(self): self.running = False def quit(self): pygame.quit() Screen._instance = None Screen._initialized = False @classmethod def get_instance(cls): return cls._instance