0

I'm working on a game in pygame-ce as a hobby, for scene management I've implemented a finite state machine. The problem is, it currently only kind of works, as the scene object is not garbage collected and then reinitialized in between "state flips". Which results in attributes not being reset etc. The most elegant way to deal with this is (imo) to define the scene class as a singleton, except that it doesn't keep a new instance from being created and instead always replaces the previous instance.

The idea would be something along these lines, meant as pseudo code:

class MySpecialSingleton:
instance = [0]
    def __init__(self):
        instance[0] = MySpecialSingleton.__init__

So basically when MainMenu(MySpecialSingleton) is created, Splashscreen(MySpecialSingleton) is garbage collected.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19

1 Answers1

0

You'd probably be best off adding a function to that class to forcibly create a new instance of your singleton.

Something along the lines of:


class ReplaceableSingleton(object):
  _instance: "ReplaceableSingleton" = None

  def __new__(cls, *args, **kwargs):
    if (cls._instance is None):
      # only create it if it doesn't exist
      cls._instance = super(ReplaceableSingleton, cls).__new__(cls)
      # initialisation code here
    return cls._instance

  @classmethod
  def instance (cls):
    return cls._instance

  @classmethod
  def replace(cls, *args, **kwargs):
    """
    this method gets gets rid of existing instance + replaces it
    :returns: new initialised instance
    """
    cls._instance = None # we can now make a new one
    return ReplaceableSingleton(*args, **kwargs)

If you ever want to get rid of the existing instance, just call ReplaceableSingleton.replace() and then a new instance will replace the old one.

However, you need to remember that existing references to the old singleton object will still reference that object.

11belowstudio
  • 137
  • 11