BulletinBoard.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """Contains the BulletinBoard class."""
  2. __all__ = ['BulletinBoard']
  3. from direct.directnotify import DirectNotifyGlobal
  4. class BulletinBoard:
  5. """This class implements a global location for key/value pairs to be
  6. stored. Intended to prevent coders from putting global variables directly
  7. on showbase, so that potential name collisions can be more easily
  8. detected."""
  9. notify = DirectNotifyGlobal.directNotify.newCategory('BulletinBoard')
  10. def __init__(self):
  11. self._dict = {}
  12. def get(self, postName, default=None):
  13. return self._dict.get(postName, default)
  14. def has(self, postName):
  15. return postName in self._dict
  16. def getEvent(self, postName):
  17. return 'bboard-%s' % postName
  18. def getRemoveEvent(self, postName):
  19. return 'bboard-remove-%s' % postName
  20. def post(self, postName, value=None):
  21. if postName in self._dict:
  22. BulletinBoard.notify.warning('changing %s from %s to %s' % (
  23. postName, self._dict[postName], value))
  24. self.update(postName, value)
  25. def update(self, postName, value):
  26. """can use this to set value the first time"""
  27. if postName in self._dict:
  28. BulletinBoard.notify.info('update: posting %s' % (postName))
  29. self._dict[postName] = value
  30. messenger.send(self.getEvent(postName))
  31. def remove(self, postName):
  32. if postName in self._dict:
  33. del self._dict[postName]
  34. messenger.send(self.getRemoveEvent(postName))
  35. def removeIfEqual(self, postName, value):
  36. # only remove the post if its value is a particular value
  37. if self.has(postName):
  38. if self.get(postName) == value:
  39. self.remove(postName)
  40. def __repr__(self):
  41. str = 'Bulletin Board Contents\n'
  42. str += '======================='
  43. keys = list(self._dict.keys())
  44. keys.sort()
  45. for postName in keys:
  46. str += '\n%s: %s' % (postName, self._dict[postName])
  47. return str