1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 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):
- """ return filename
- username.lower _ game.upper.json
- """
- 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, *_):
- """ save gamedata as jsonlines.
- Enable sort_keys=True to provide stable json data output.
- We also sorted(.keys()) to keep records in order.
- Note: There's a "bug" when serializing to json, keys must be strings!
- """
- filename = self.storage_filename()
- with jsonlines.open(filename, mode="w", sort_keys=True) as writer:
- # for warp, sectors in self.warps.items():
- for warp in sorted(self.warps.keys()):
- sectors = self.warps[warp]
- # log.msg("save:", warp, sectors)
- sects = sorted(list(sectors)) # make a list
- w = {"warp": {warp: sects}}
- # log.msg(w)
- writer.write(w)
- yield
- # for sector, port in self.ports.items():
- for sector in sorted(self.ports.keys()):
- port = self.ports[sector]
- p = {"port": {sector: port}}
- writer.write(p)
- yield
- log.msg("Saved {0} {1}/{2}".format(filename, len(self.ports), len(self.warps)))
- 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.
- """
- log.msg("Warp {0} to {1}".format(source, dest))
- 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)
- def set_port(self, sector, data):
- log.msg("Port {0} : {1}".format(sector, data))
- if sector not in self.ports:
- self.ports[sector] = dict()
- self.ports[sector].update(data)
|