Skip to content

Instantly share code, notes, and snippets.

@izxxr
Created July 14, 2024 05:56
Show Gist options
  • Save izxxr/d28dd9229d845e4707de4f5cfb04eb1d to your computer and use it in GitHub Desktop.
Save izxxr/d28dd9229d845e4707de4f5cfb04eb1d to your computer and use it in GitHub Desktop.
A basic scenes manager for Pyglet
from typing import Any, Type
import pyglet
class Scene:
"""Base class for a scene."""
def __init__(self, window: pyglet.window.Window, state: Any = None) -> None:
self.window = window
self.state = state
def draw(self) -> None:
"""Draws the scene.
This method is called on every frame similar to `pyglet.window.Window.draw()`
and is used to draw the scene.
"""
def on_load(self) -> None:
"""Hook for when scene is loaded.
This method is called when a scene is initially loaded
and could be overridden for any kind of preprocessing.
"""
def on_unload(self) -> None:
"""Hook for when scene is unloaded.
This method is called when a scene is unloaded (i.e. another
scene is loaded) and could be overridden for any kind of
preprocessing.
"""
class ScenesManager:
"""Scenes manager managing transitions between scenes.
Parameters
----------
window: pyglet.window.Window
The pyglet window instance.
"""
def __init__(self, window: pyglet.window.Window) -> None:
self._window = window
self._current_scene = None
def get_current_scene(self) -> Scene:
"""Gets current scene.
Raises ValueError if no scene is set.
"""
if self._current_scene is None:
raise ValueError("no scene set")
return self._current_scene
def load(self, scene: Type[Scene], state: Any = None) -> None:
"""Loads a scene.
The previous scene is unloaded and its `Scene.on_unload` hook
is called and the scene being loaded is setup and its `Scene.on_load`
hook is called.
Parameters
----------
scene: Type[Scene]
The scene class to load.
"""
if self._current_scene:
self._current_scene.on_unload()
self._current_scene = scene(self._window, state)
self._current_scene.on_load()
def draw(self, clear_window: bool = True) -> None:
"""Calls the draw method of the current scene.
This also clears the window before drawing the scene
unless `clear_window` is set to `False`.
If no scene is set, this method does nothing.
"""
if self._current_scene is None:
return
if clear_window:
self._window.clear()
self._current_scene.draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment