Explorar o código

We save/load galaxy.GameData as jsonlines.

Steve Thielemann %!s(int64=5) %!d(string=hai) anos
pai
achega
063a58772c
Modificáronse 3 ficheiros con 94 adicións e 11 borrados
  1. 1 0
      flexible.py
  2. 69 0
      galaxy.py
  3. 24 11
      tcp-proxy.py

+ 1 - 0
flexible.py

@@ -281,6 +281,7 @@ class CIMWarpReport(object):
         sector = parts.pop(0)
         # tuples are nicer on memory, and the warpdata map isn't going to be changing.
         self.warpdata[sector] = tuple(parts)
+        self.game.gamedata.warp_to(sector, *parts)
 
     def __del__(self):
         log.msg("CIMWarpReport {0} RIP".format(self))

+ 69 - 0
galaxy.py

@@ -0,0 +1,69 @@
+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)

+ 24 - 11
tcp-proxy.py

@@ -7,6 +7,7 @@ from twisted.internet import defer
 from twisted.internet import protocol
 from twisted.internet import reactor
 from twisted.internet import task
+from twisted.internet.task import coiterate
 from twisted.python import log
 from twisted.python.logfile import DailyLogFile
 import pendulum
@@ -18,15 +19,17 @@ from pprint import pformat
 
 import yaml
 
+
 def config_load(filename):
     global config
-    with open(filename, 'r') as fp:
+    with open(filename, "r") as fp:
         config = yaml.safe_load(fp)
 
-if os.path.exists('config_dev.yaml'):
-    config_load('config_dev.yaml')
+
+if os.path.exists("config_dev.yaml"):
+    config_load("config_dev.yaml")
 else:
-    config_load('config.yaml')
+    config_load("config.yaml")
 
 # Extract the version information from git.
 # The match gives us only tags starting with v[0-9]*  Using anything else trips up on double digits.
@@ -77,8 +80,8 @@ def cleanANSI(line):
 
 
 from observer import Observer
-
 from flexible import PlayerInput, ProxyMenu
+from galaxy import GameData
 
 
 class Game(protocol.Protocol):
@@ -86,6 +89,7 @@ class Game(protocol.Protocol):
         self.buffer = ""
         self.game = None
         self.usergame = (None, None)
+        self.gamedata = None
         self.to_player = True
 
     def connectionMade(self):
@@ -101,12 +105,20 @@ class Game(protocol.Protocol):
         self.usergame = game
         log.msg("## User-Game:", game)
         if game[1] is None:
+            if self.gamedata is not None:
+                # start the save
+                coiterate(self.gamedata.save())
+            self.gamedata = None
             if hasattr(self, "portdata"):
                 log.msg("Clearing out old portdata.")
                 self.portdata = {}
             if hasattr(self, "warpdata"):
                 log.msg("Clearing out old warpdata.")
                 self.warpdata = {}
+        else:
+            # Load the game data (if any)
+            self.gamedata = GameData(game)
+            coiterate(self.gamedata.load())
 
     def setPlayerReceived(self):
         """ Get deferred from client queue, callback clientDataReceived. """
@@ -131,7 +143,7 @@ class Game(protocol.Protocol):
 
     def lineReceived(self, line):
         """ line received from the game. """
-        if 'log_lines' in config and config['log_lines']:
+        if "log_lines" in config and config["log_lines"]:
             log.msg("<< [{0}]".format(line))
 
         # if "TWGS v2.20b" in line and "www.eisonline.com" in line:
@@ -296,7 +308,7 @@ class Player(protocol.Protocol):
         self.glue = factory
 
         # Make connection to the game server
-        reactor.connectTCP(config['host'], config['port'], factory, 5)
+        reactor.connectTCP(config["host"], config["port"], factory, 5)
 
     def setGameReceived(self):
         """ Get deferred from client queue, callback clientDataReceived. """
@@ -386,7 +398,7 @@ class Player(protocol.Protocol):
 
 
 if __name__ == "__main__":
-    if 'logfile' in config and config['logfile']:
+    if "logfile" in config and config["logfile"]:
         log.startLogging(DailyLogFile("proxy.log", "."))
     else:
         log.startLogging(sys.stdout)
@@ -394,12 +406,13 @@ if __name__ == "__main__":
     log.msg("This is version: %s" % version)
     factory = protocol.Factory()
     factory.protocol = Player
-    reactor.listenTCP(config['listen_port'], factory, interface=config['listen_on'])
+    reactor.listenTCP(config["listen_port"], factory, interface=config["listen_on"])
     reactor.run()
 else:
-    # I can't seem to get twistd -y tcp-proxy.py 
+    # I can't seem to get twistd -y tcp-proxy.py
     # to work.  Missing imports?
     application = service.Application("TradeWarsGameServer-Proxy")
     factory = protocol.Factory()
     factory.protocol = Player
-    internet.TCPServer(config['listen_port'], factory).setServiceParent(application)
+    internet.TCPServer(config["listen_port"], factory).setServiceParent(application)
+