galaxy.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. """ return filename
  13. username.lower _ game.upper.json
  14. """
  15. user, game = self.usergame
  16. return "{0}_{1}.json".format(user.lower(), game.upper())
  17. def display(self):
  18. pprint(self.warps)
  19. pprint(self.ports)
  20. def save(self, *_):
  21. """ save gamedata as jsonlines.
  22. Enable sort_keys=True to provide stable json data output.
  23. We also sorted(.keys()) to keep records in order.
  24. Note: There's a "bug" when serializing to json, keys must be strings!
  25. """
  26. filename = self.storage_filename()
  27. with jsonlines.open(filename, mode="w", sort_keys=True) as writer:
  28. # for warp, sectors in self.warps.items():
  29. for warp in sorted(self.warps.keys()):
  30. sectors = self.warps[warp]
  31. # log.msg("save:", warp, sectors)
  32. sects = sorted(list(sectors)) # make a list
  33. w = {"warp": {warp: sects}}
  34. # log.msg(w)
  35. writer.write(w)
  36. yield
  37. # for sector, port in self.ports.items():
  38. for sector in sorted(self.ports.keys()):
  39. port = self.ports[sector]
  40. p = {"port": {sector: port}}
  41. writer.write(p)
  42. yield
  43. log.msg("Saved {0} {1}/{2}".format(filename, len(self.ports), len(self.warps)))
  44. def load(self):
  45. filename = self.storage_filename()
  46. self.warps = {}
  47. self.ports = {}
  48. if os.path.exists(filename):
  49. # Load it
  50. with jsonlines.open(filename) as reader:
  51. for obj in reader:
  52. if "warp" in obj:
  53. for s, w in obj["warp"].items():
  54. # log.msg(s, w)
  55. self.warps[int(s)] = set(w)
  56. # self.warps.update(obj["warp"])
  57. if "port" in obj:
  58. for s, p in obj["port"].items():
  59. self.ports[int(s)] = p
  60. # self.ports.update(obj["port"])
  61. yield
  62. log.msg("Loaded {0} {1}/{2}".format(filename, len(self.ports), len(self.warps)))
  63. def warp_to(self, source, *dest):
  64. """ connect sector source to destination.
  65. """
  66. log.msg("Warp {0} to {1}".format(source, dest))
  67. if source not in self.warps:
  68. self.warps[source] = set()
  69. for d in dest:
  70. if d not in self.warps[source]:
  71. self.warps[source].add(d)
  72. def set_port(self, sector, data):
  73. log.msg("Port {0} : {1}".format(sector, data))
  74. if sector not in self.ports:
  75. self.ports[sector] = dict()
  76. self.ports[sector].update(data)