123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import jsonlines
- import os
- from twisted.python import log
- from pprint import pprint
- class GameData(object):
- def __init__(self, usergame):
- # Construct the GameData storage object
- self.usergame = usergame
- self.warps = {}
- self.ports = {}
- def storage_filename(self):
- user, game = self.usergame
- return "{0}_{1}.json".format(user.lower(), game.upper())
- def display(self):
- pprint(self.warps)
- pprint(self.ports)
- def save(self, *_):
- filename = self.storage_filename()
- with jsonlines.open(filename, mode="w") as writer:
- for warp, sectors in self.warps.items():
- log.msg("save:", warp, sectors)
- sects = list(sectors) # make a list
- w = {"warp": {warp: sects}}
- log.msg(w)
- writer.write(w)
- yield
- for sector, port in self.ports.items():
- p = {"port": {sector: port}}
- writer.write(p)
- yield
- def load(self):
- filename = self.storage_filename()
- self.warps = {}
- self.ports = {}
- if os.path.exists(filename):
- # Load it
- with jsonlines.open(filename) as reader:
- for obj in reader:
- if "warp" in obj:
- for s, w in obj["warp"].items():
- log.msg(s, w)
- self.warps[int(s)] = set(w)
- # self.warps.update(obj["warp"])
- if "port" in obj:
- for s, p in obj["port"].items():
- self.ports[int(s)] = p
- # self.ports.update(obj["port"])
- yield
- log.msg("Loaded {0} {1}/{2}".format(filename, len(self.ports), len(self.warps)))
- def warp_to(self, source, *dest):
- """ connect sector source to destination.
-
- Note: There's a "bug" with json, keys must be strings!
- """
- if source not in self.warps:
- self.warps[source] = set()
- for d in dest:
- if d not in self.warps[source]:
- self.warps[source].add(d)
|