Pārlūkot izejas kodu

Getting closer, I think.

Still needs to be refactored.  But, needs to be
working first.
Steve Thielemann 5 gadi atpakaļ
vecāks
revīzija
ecd3988268
2 mainītis faili ar 162 papildinājumiem un 133 dzēšanām
  1. 161 98
      flexible.py
  2. 1 35
      twgs-proxy.py

+ 161 - 98
flexible.py

@@ -1020,17 +1020,18 @@ class ScriptExplore(object):
         ask = PlayerInput(self.game)
         
         def settimes(*_):
-            times = int(ask.keep['times'].strip())
+            times = ask.keep['times'].strip()
             log.msg("settimes got '{0}'".format(times))
-            if times == None:
+            if times == '':
                 self.deactivate()
             else:
+                times = int(times)
                 self.times = times
                 self.maxtimes = times
                 self.send2game("D")
                 self.state = 1
             
-        d = ask.prompt("How many sectors would you lick to explode?", 5, name="times", digits=True)
+        d = ask.prompt("How many sectors would you like to explorer?", 5, name="times", digits=True)
         #d.addCallback(ask.output)
         #d.addCallback(lambda ignore: self.settimes(ask.keep))
         d.addCallback(settimes)
@@ -1095,12 +1096,12 @@ class ScriptExplore(object):
         if self.state == 2:
             if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
                 self.send2game("D")
-                self.state += 1
-        if self.state == 5:
+                # self.state += 1
+        elif self.state == 5:
             log.msg("dense is {0} sectors big".format(len(self.dense)))
             self.state += 1
             self.send2game("SH")
-        if self.state == 12:
+        elif self.state == 12:
             # Looking for "Engage the Autopilot?"
             if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
                 self.send2game("S")
@@ -1108,7 +1109,12 @@ class ScriptExplore(object):
             if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
                 self.send2game("SD")
                 self.state += 1
-        if self.state == 20:
+        elif self.state == 15:
+            if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
+                self.send2game("N")
+                self.travel_path.pop(0)
+                self.state = 12
+        elif self.state == 20:
             if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
                 # Stop in this sector / Yes!
                 self.send2game("Y")
@@ -1121,21 +1127,20 @@ class ScriptExplore(object):
         #    self.deactivate()
 
         if self.state == 1:
-            # Density Scan
-            if not self.didDense:
-                self.send2game("S")
-                self.didDense = True
-            
+            self.send2game("S")
+            self.state += 1
+        elif self.state == 2:            
             if "Relative Density Scan" in line:
                 self.state = 3
             elif "You don't have a long range scanner." in line:
                 log.msg("FATAL: No Long Range Scanner Installed!")
                 self.send2player(Boxes.alert("You need a Long Range Scanner!"))
                 self.deactivate()
-            elif "Long Range Scan" in line:
-                self.state += 1
-        
-        if self.state == 2:
+                return
+            # elif "Long Range Scan" in line:
+            #    self.state += 1
+
+        elif self.state == 3:
             # Get the Density Data!
             if line.startswith("Sector"):
                 new_sector = '(' in line
@@ -1148,20 +1153,27 @@ class ScriptExplore(object):
                 # New Sector?
                 if new_sector:
                     # Switch Anom into bool state
-                    if(work[8] == 'No'):
-                        temp = False
-                    else:
-                        temp = True
-                
-                    self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': temp} )
+                    # if(work[8] == 'No'):
+                    #     temp = False
+                    # else:
+                    #     temp = True
+                    #self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': temp} )
+
+                    self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': work[8] == 'Yes'} )
                     log.msg(self.dense)
                     # {'sector': 8192, 'density': 0, 'warps': 4, 'navhaz': 0, 'anom': False}
                 
             elif line == "":
                 self.state += 1
-        elif self.state == 4:
+
+        # yeah, this would be better in the above line...
+        # leaving it for now.
+        # Which is why I broke the elif chain. ...
+
+        if self.state == 4:
             # Begin Processing our data we got from density scan and find highest warp count in what sectors
             # Remove sectors with one warp
+            log.msg("state 4: {0}".format(self.dense))
 
             # Do we have a new place to go? (That is also worth going to)
             if not self.dense: # Dense contains no new sectors, abort
@@ -1169,24 +1181,34 @@ class ScriptExplore(object):
                 self.dead_end()
                 return
 
-                # self.send2player(Boxes.alert("Find a new area for me to search in!"))
-                # Attempt to resolve no new sectors!
-                # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
-                #     self.highsector = self.stacksector.pop()
-                # self.deactivate()
-
-            elif self.dense: # Dense does contain at least 1 new sector, continue on
-                # list comprehension
-                t = [d for d in self.dense if d['warps'] > 1]
-                # t = [] # Pre-Test to check if there are just a bunch of 1 warp sectors
-                # for d in self.dense:
-                #     if d['warps'] > 1:
-                #         t.append(d['sector'])
-
-                if not t: # If there are no sectors with more that 1 warp, abort
-                    log.msg("No Sectors Found except one move sector!")
-                    self.dead_end()
-                    return
+            # self.send2player(Boxes.alert("Find a new area for me to search in!"))
+            # Attempt to resolve no new sectors!
+            # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
+            #     self.highsector = self.stacksector.pop()
+            # self.deactivate()
+
+            # elif self.dense: # Dense does contain at least 1 new sector, continue on
+
+            # ugh, actually, we don't care about making a list
+            # we only want to know if there's any that have warps > 1.  :(
+            # see any:
+
+            # list comprehension
+            # t = [d for d in self.dense if d['warps'] > 1]
+            # t = [] # Pre-Test to check if there are just a bunch of 1 warp sectors
+            # for d in self.dense:
+            #     if d['warps'] > 1:
+            #         t.append(d['sector'])
+
+            # I don't care if there's only one warp.  if it's un-explorered then
+            # explore it!
+
+            # if not any( w['warps'] > 1 for w in self.dense):
+            #     # If there are no sectors with more that 1 warp, abort
+            #     log.msg("No Sectors Found except one move sector!")
+            #     self.dead_end()
+            #     return
+
                     # self.send2player(Boxes.alert("Find a new area for me to look at!"))
                     # Attempt to resolve no new sectors with more than 1 warp!
                     # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
@@ -1194,102 +1216,143 @@ class ScriptExplore(object):
                     # self.deactivate()
 
             # Is the sector safe to go into?
-            for d in self.dense:
-                if not d['anom']:
-                    # Sector does not contain a Anomoly
-                    if not d['navhaz']:
-                        # Sector does not contain Hazards
-                        if d['density'] in (0, 1, 100, 101):
-                            # Sector does contain empty space / a beacon / a port / or a beacon and port
-                            if d['warps'] > 1:
-                                # If Sector is worth checking out?
-                                self.clear.append(d['sector'])
+            # self.clear = [ x['sector'] for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) and x['warps'] > 1 ]
+            self.clear = [ x['sector'] for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) ]
+
+            # for d in self.dense:
+            #     if not d['anom']:
+            #         # Sector does not contain a Anomoly
+            #         if not d['navhaz']:
+            #             # Sector does not contain Hazards
+            #             if d['density'] in (0, 1, 100, 101):
+            #                 # Sector does contain empty space / a beacon / a port / or a beacon and port
+            #                 if d['warps'] > 1:
+            #                     # If Sector is worth checking out?
+            #                     self.clear.append(d['sector'])
             
             if self.clear: # We have sector(s) we can move to!
                 log.msg("Clear Sectors: {0}".format(len(self.clear)))
                 # This was state 5 but why can't we reduce number of states? ( Yeah let's kick California and New York out of the US, oh wrong states :P )
                 # Sort to find greatest warp count
-                for c in self.clear:
-                    for d in self.dense:
-                        if d['sector'] == c:
-                            if d['warps'] > self.highwarp:
-                                self.highwarp = d['warps']
-                                self.highsector = d['sector']
-                            elif d['warps'] == self.highwarp:
-                                    if d['sector'] > self.highsector:
-                                        self.highsector = d['sector']
+
+                self.highwarp, self.highsector = max( (x['warps'], x['sector']) for x in self.clear)
+
+                # for c in self.clear:
+                #     for d in self.dense:
+                #         if d['sector'] == c:
+                #             if d['warps'] > self.highwarp:
+                #                 self.highwarp = d['warps']
+                #                 self.highsector = d['sector']
+                #             elif d['warps'] == self.highwarp:
+                #                     if d['sector'] > self.highsector:
+                #                        self.highsector = d['sector']
                 
-                if self.highwarp and self.highsector:
-                    log.msg("Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp))
-                    self.state += 1
-        elif self.state == 5:
+                # if self.highwarp and self.highsector:
+                log.msg("Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp))
+                self.state += 1
+
+                # Another NOP state.  This also could be merged into above.
+                # break the elif chain.
+
+        if self.state == 5:
             # Add the dense scan of unknown sectors onto the stack of sectors, only save the ones we think are clear... for now.
             for c in self.clear:
-                self.stacksector.add(c)
+                if c != self.highsector:
+                    self.stacksector.add(c)
             
+            # Or simply not add it in the first place ...
             # Remove the sector we are just about to go to, we use discard so if the sector does not exist we don't throw a error!
-            self.stacksector.discard(self.highsector)
+            # self.stacksector.discard(self.highsector)
+
+            # Ok, we need to decide to stop exploring -- before we
+            # issue the sector move!  :P
+            #             
+            # Warning! Yes we can and will eat all the turns! :P
+            if self.times == 0:
+                self.send2player(Boxes.alert("Completed {0}".format(self.maxtimes), base="green"))
+                log.msg("Completed {0}".format(self.maxtimes))
+                self.deactivate()
+                return
 
+            self.times -= 1
             # Ok we know the sector we want to go to now let's move it!
-            self.send2game("m{0}\n\r".format(self.highsector))
+            self.send2game("m{0}\r".format(self.highsector))
 
             # Reset Variables for fresh data
             self.resetStuff()
             self.state = 1
-            
-            # Warning! Yes we can and will eat all the turns! :P
-            self.times -= 1
-            if self.times <= 0:
-                self.send2player(Boxes.alert("Completed {0}".format(self.maxtimes), base="green"))
-                log.msg("Completed {0}".format(self.maxtimes))
-                self.deactivate()
+
         elif self.state == 10:
+            if line.startswith("You are already in that sector!"):
+                log.msg("Already here.  (Whoops!)")
+                self.state = 1
+                return
+            if line.startswith("Sector  : {0}".format(self.highsector)):
+                log.msg("We're here!")
+                # Ok, we're already there!  no autopilot needed!
+                self.state = 1
+                return
             # Warping
             self.go_on = True
             if line.startswith('The shortest path ('):
                 # Ok, we've got a path.
                 self.state += 1
         elif self.state == 11:
-            self.travel_path = line.split(' > ')
+            self.travel_path = line.replace('(', '').replace(')', '').split(' > ')
+            log.msg("Travel path: {0}".format(self.travel_path))
             self.state += 1
+            self.travel_path.pop(0) # First sector is one we're in.
+            self.stophere = False
+            self.go_on = True
         elif self.state == 13:
             if 'Relative Density Scan' in line:
                 self.state += 1
         elif self.state == 14:
             if line == "":
+                log.msg("PATH: {0}".format(self.travel_path))
+
                 # end of the scan, decision time
                 if self.stophere:
+                    log.msg("STOPHERE")
                     # Ok, let's stop here!
                     # Re-save the sector we were trying to get to.  (we didn't make it there)
                     self.stacksector.add(self.highsector)
                     self.state = 20
                 else:
                     if self.go_on:
+                        log.msg("GO ON")
                         # Ok, carry on!
-                        self.state = 12
-                        self.travel_path.pop(0)                
+                        self.state = 15
+                    else:
+                        log.msg("...")
             else:
-                work = line.replace(' :', '').replace('%', '').replace(')', '').replace('==>', '')
-                # Does this contain something new? unseen?
-                stophere = '(' in work
-                work = work.replace('(','')
-                #Sector   XXXX  DENS Warps N NavHaz P Anom YN
-                parts = re.split(r'\s+', work)
-                # Don't bother stopping if there's only one warp
-                if stophere and parts[4] == '1':
-                    stophere = False
-                
-                if stophere:
-                    self.stophere = True
-
-                next_stop = travel_path[0]
-
-                if parts[1] == next_stop:
-                    # Ok, this is our next stop.  Is it safe to travel to?
-                    if parts[2] not in ('100', '0'):
-                        # Ok, it's not safe to go on.
-                        self.go_on = False
-                    # Check the rest navhav and anom ...
+                if line.strip('-') != '':
+                    work = line.replace(' :', '').replace('%', '').replace(')', '').replace('==>', '')
+                    # Does this contain something new? unseen?
+                    stophere = '(' in work
+                    work = work.replace('(','')
+                    #Sector   XXXX  DENS Warps N NavHaz P Anom YN
+                    parts = re.split(r'\s+', work)
+                    # Don't bother stopping if there's only one warp
+
+                    # YES!  Stop, even if there is just one warp!
+
+                    # if stophere and parts[4] == '1':
+                    #     stophere = False
+                    
+                    if stophere:
+                        self.stophere = True
+
+                    next_stop = self.travel_path[0]
+                    log.msg("next_stop {0} from {1}".format(next_stop, self.travel_path))
+                    log.msg("parts: {0}".format(parts))
+                    if parts[1] == next_stop:
+                        log.msg("next_stop {0} found...".format(next_stop))
+                        # Ok, this is our next stop.  Is it safe to travel to?
+                        if parts[2] not in ('100', '0', '1', '101'):
+                            # Ok, it's not safe to go on.
+                            self.go_on = False
+                        # Check the rest navhav and anom ...
 
 
 

+ 1 - 35
twgs-proxy.py

@@ -1,45 +1,11 @@
 #!/usr/bin/env python3
 
 import sys
-import os
-from subprocess import check_output
-
 from twisted.internet import reactor
 from twisted.internet import protocol
 from twisted.python import log
 from twisted.python.logfile import DailyLogFile
-import yaml
-
-
-def config_load(filename: str):
-    global config
-    with open(filename, "r") as fp:
-        config = yaml.safe_load(fp)
-
-
-if os.path.exists("config_dev.yaml"):
-    config_load("config_dev.yaml")
-else:
-    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.
-version = check_output(
-    [
-        "git",
-        "describe",
-        "--abbrev=8",
-        "--long",
-        "--tags",
-        "--dirty",
-        "--always",
-        "--match",
-        "v[0-9]*",
-    ],
-    universal_newlines=True,
-).strip()
-
-
+from config import config, version
 from proxy import Player
 
 if "logfile" in config and config["logfile"]: