galaxy.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import jsonlines
  2. import os
  3. from twisted.python import log
  4. from pprint import pprint
  5. class GameData(object):
  6. def __init__(self, usergame):
  7. # Construct the GameData storage object
  8. self.usergame = usergame
  9. self.warps = {}
  10. self.ports = {}
  11. def storage_filename(self):
  12. user, game = self.usergame
  13. return "{0}_{1}.json".format(user.lower(), game.upper())
  14. def display(self):
  15. pprint(self.warps)
  16. pprint(self.ports)
  17. def save(self, *_):
  18. filename = self.storage_filename()
  19. with jsonlines.open(filename, mode="w") as writer:
  20. for warp, sectors in self.warps.items():
  21. log.msg("save:", warp, sectors)
  22. sects = list(sectors) # make a list
  23. w = {"warp": {warp: sects}}
  24. log.msg(w)
  25. writer.write(w)
  26. yield
  27. for sector, port in self.ports.items():
  28. p = {"port": {sector: port}}
  29. writer.write(p)
  30. yield
  31. def load(self):
  32. filename = self.storage_filename()
  33. self.warps = {}
  34. self.ports = {}
  35. if os.path.exists(filename):
  36. # Load it
  37. with jsonlines.open(filename) as reader:
  38. for obj in reader:
  39. if "warp" in obj:
  40. for s, w in obj["warp"].items():
  41. log.msg(s, w)
  42. self.warps[int(s)] = set(w)
  43. # self.warps.update(obj["warp"])
  44. if "port" in obj:
  45. for s, p in obj["port"].items():
  46. self.ports[int(s)] = p
  47. # self.ports.update(obj["port"])
  48. yield
  49. log.msg("Loaded {0} {1}/{2}".format(filename, len(self.ports), len(self.warps)))
  50. def warp_to(self, source, *dest):
  51. """ connect sector source to destination.
  52. Note: There's a "bug" with json, keys must be strings!
  53. """
  54. if source not in self.warps:
  55. self.warps[source] = set()
  56. for d in dest:
  57. if d not in self.warps[source]:
  58. self.warps[source].add(d)