Put a timestamp an email in lofiles. Add the replay debugging script.
[super-star-trek.git] / src / sst.py
index 1346b45466d3e9e1c4e84c47e5925133ffe6c633..74dcbaa3aee8ab27ce8b09f73e4e642330a0c2ca 100644 (file)
@@ -180,7 +180,7 @@ more:
 the LRSCAN command is no longer needed.  (Controlled by OPTION_AUTOSCAN
 and turned off if game type is "plain" or "almy".)
 """
-import os,sys,math,curses,time,atexit,readline,cPickle,random,getopt,copy
+import os, sys, math, curses, time, readline, cPickle, random, copy
 
 SSTDOC         = "/usr/share/doc/sst/sst.doc"
 DOC_NAME       = "sst.doc"
@@ -256,7 +256,7 @@ class coord:
         return math.sqrt((self.i - other.i)**2 + (self.j - other.j)**2)
     def bearing(self, other=None):
         if not other: other = coord(0, 0)
-        return 1.90985*math.atan2(self.i-other.i, self.j-other.j)
+        return 1.90985*math.atan2(self.j-other.j, self.i-other.i)
     def sgn(self):
         s = coord()
         if self.i == 0:
@@ -755,10 +755,7 @@ def movebaddy(enemy):
             else:
                 motion = game.skill
     # calculate preferred number of steps 
-    if motion < 0:
-        nsteps = -motion
-    else:
-        nsteps = motion
+    nsteps = abs(int(motion))
     if motion > 0 and nsteps > mdist:
        nsteps = mdist; # don't overshoot 
     if nsteps > QUADSIZE:
@@ -773,16 +770,7 @@ def movebaddy(enemy):
        m.i = 0
     if 2.0 * abs(m.j) < abs(game.sector.i-enemy.kloc.i):
        m.j = 0
-    if m.i != 0:
-        if m.i*motion < 0:
-            m.i = -1
-        else:
-            m.i = 1
-    if m.j != 0:
-        if m.j*motion < 0:
-            m.j = -1
-        else:
-            m.j = 1
+    m = (motion * m).sgn()
     next = enemy.kloc
     # main move loop 
     for ll in range(nsteps):
@@ -1069,11 +1057,11 @@ def movetholian():
     for i in range(QUADSIZE):
        if game.quad[0][i]!=IHWEB and game.quad[0][i]!=IHT:
            return
-       if game.quad[QUADSIZE][i]!=IHWEB and game.quad[QUADSIZE][i]!=IHT:
+       if game.quad[QUADSIZE-1][i]!=IHWEB and game.quad[QUADSIZE-1][i]!=IHT:
            return
        if game.quad[i][0]!=IHWEB and game.quad[i][0]!=IHT:
            return
-       if game.quad[i][QUADSIZE]!=IHWEB and game.quad[i][QUADSIZE]!=IHT:
+       if game.quad[i][QUADSIZE-1]!=IHWEB and game.quad[i][QUADSIZE-1]!=IHT:
            return
     # All plugged up -- Tholian splits 
     game.quad[game.tholian.kloc.i][game.tholian.kloc.j]=IHWEB
@@ -1285,6 +1273,10 @@ def collision(rammed, enemy):
 
 def torpedo(origin, course, dispersion, number, nburst):
     "Let a photon torpedo fly" 
+    if not damaged(DSRSENS) or game.condition=="docked":
+       setwnd(srscan_window)
+    else: 
+       setwnd(message_window)
     shoved = False
     ac = course + 0.25*dispersion
     angle = (15.0-ac)*0.5235988
@@ -1292,17 +1284,12 @@ def torpedo(origin, course, dispersion, number, nburst):
     delta = coord(-math.sin(angle), math.cos(angle))          
     bigger = max(abs(delta.i), abs(delta.j))
     delta /= bigger
-    x = origin.i; y = origin.j
     w = coord(0, 0); jw = coord(0, 0)
-    if not damaged(DSRSENS) or game.condition=="docked":
-       setwnd(srscan_window)
-    else: 
-       setwnd(message_window)
+    ungridded = copy.copy(origin)
     # Loop to move a single torpedo 
-    for step in range(1, 15+1):
-       x += delta.i
-       y += delta.j
-       w = coord(x, y).snaptogrid()
+    for step in range(1, QUADSIZE*2):
+       ungridded += delta
+       w = ungridded.snaptogrid()
        if not VALID_SECTOR(w.i, w.j):
            break
        iquad=game.quad[w.i][w.j]
@@ -1343,7 +1330,7 @@ def torpedo(origin, course, dispersion, number, nburst):
            shoved = True
        elif iquad in (IHC, IHS, IHR, IHK): # Hit a regular enemy 
            # find the enemy 
-           if withprob(0.05):
+           if iquad in (IHC, IHS) and withprob(0.05):
                prout(crmena(True, iquad, "sector", w) + _(" uses anti-photon device;"))
                prout(_("   torpedo neutralized."))
                return None
@@ -1586,7 +1573,7 @@ def attack(torps_ok):
            hit = enemy.kpower*math.pow(dustfac,enemy.kavgd)
            enemy.kpower *= 0.75
        else: # Enemy uses photon torpedo 
-           #course2 = (enemy.kloc-game.sector).bearing()
+           # We should be able to make the bearing() method work here
            course = 1.90985*math.atan2(game.sector.j-enemy.kloc.j, enemy.kloc.i-game.sector.i)
            hit = 0
            proutn(_("***TORPEDO INCOMING"))
@@ -1738,7 +1725,7 @@ def targetcheck(w):
        prout(_("  the Captain's psychological profile.\""))
        scanner.chew()
        return None
-    return 1.90985932*math.atan2(delta.j, delta.i)
+    return delta.bearing()
 
 def photon():
     "Launch photon torpedo."
@@ -1785,19 +1772,19 @@ def photon():
        if i==1 and key == "IHEOL":
            # direct all torpedoes at one target 
            while i < n:
-               target.append(targets[0])
+               target.append(target[0])
                course.append(course[0])
                i += 1
            break
-        scanner.push(key)
+        scanner.push(scanner.token)
         target.append(scanner.getcoord())
         if target[-1] == None:
             return
-        course.append(targetcheck(target[1]))
-        if course[i] == None:
+        course.append(targetcheck(target[-1]))
+        if course[-1] == None:
            return
     scanner.chew()
-    if i == 0:
+    if len(target) == 0:
        # prompt for each one 
        for i in range(n):
            proutn(_("Target sector for torpedo number %d- ") % (i+1))
@@ -3336,27 +3323,8 @@ message_window    = None
 prompt_window     = None
 curwnd = None
 
-def outro():
-    "Wrap up, either normally or due to signal"
-    if game.options & OPTION_CURSES:
-       #clear()
-       #curs_set(1)
-       #refresh()
-       #resetterm()
-       #echo()
-       curses.endwin()
-       sys.stdout.write('\n')
-    if logfp:
-       logfp.close()
-
 def iostart():
     global stdscr, rows
-    #setlocale(LC_ALL, "")
-    #bindtextdomain(PACKAGE, LOCALEDIR)
-    #textdomain(PACKAGE)
-    if atexit.register(outro):
-       sys.stderr.write("Unable to register outro(), exiting...\n")
-       raise SysExit,1
     if not (game.options & OPTION_CURSES):
        ln_env = os.getenv("LINES")
         if ln_env:
@@ -3366,19 +3334,8 @@ def iostart():
     else:
        stdscr = curses.initscr()
        stdscr.keypad(True)
-       #saveterm()
        curses.nonl()
        curses.cbreak()
-        curses.start_color()
-        curses.init_pair(curses.COLOR_BLACK, curses.COLOR_BLACK, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_GREEN, curses.COLOR_GREEN, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_RED, curses.COLOR_RED, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_CYAN, curses.COLOR_CYAN, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_WHITE, curses.COLOR_WHITE, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_MAGENTA, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_BLUE, curses.COLOR_BLUE, curses.COLOR_BLACK)
-        curses.init_pair(curses.COLOR_YELLOW, curses.COLOR_YELLOW, curses.COLOR_BLACK)
-       #noecho()
         global fullscreen_window, srscan_window, report_window, status_window
         global lrscan_window, message_window, prompt_window
         (rows, columns)   = stdscr.getmaxyx()
@@ -3391,20 +3348,18 @@ def iostart():
        prompt_window     = curses.newwin(1,  0,  rows-2,  0) 
        message_window.scrollok(True)
        setwnd(fullscreen_window)
-       textcolor(DEFAULT)
-
-def textcolor(color):
-    "Set text foreground color.  Presently a stub."
-    pass       # FIXME
 
 def ioend():
     "Wrap up I/O.  Presently a stub."
-    pass
+    stdscr.keypad(False)
+    curses.echo()
+    curses.nocbreak()
+    curses.endwin()
 
 def waitfor():
     "Wait for user action -- OK to do nothing if on a TTY"
     if game.options & OPTION_CURSES:
-       stsdcr.getch()
+       stdscr.getch()
 
 def announce():
     skip(1)
@@ -3445,7 +3400,10 @@ def skip(i):
                pause_game()
                clrscr()
            else:
-               proutn("\n")
+                try:
+                    curwnd.move(y+1, 0)
+                except curses.error:
+                    pass
        else:
             global linecount
            linecount += 1
@@ -3474,7 +3432,7 @@ def prouts(line):
             time.sleep(0.03)
        proutn(c)
        if game.options & OPTION_CURSES:
-           wrefresh(curwnd)
+           curwnd.refresh()
        else:
            sys.stdout.flush()
     if not replayfp or replayfp.closed:
@@ -3968,8 +3926,8 @@ def getcourse(isprobe, akey):
                prout(_("Ensign Chekov- \"Course laid in, Captain.\""))
         # the actual deltas get computed here
         delta = coord()
-       delta.i = dquad.j-game.quadrant.j + 0.1*(dsect.j-game.sector.j)
-       delta.j = game.quadrant.i-dquad.i + 0.1*(game.sector.i-dsect.i)
+       delta.j = dquad.j-game.quadrant.j + 0.1*(dsect.j-game.sector.j)
+       delta.i = game.quadrant.i-dquad.i + 0.1*(game.sector.i-dsect.i)
     else: # manual 
        while key == "IHEOL":
            proutn(_("X and Y displacements- "))
@@ -4465,13 +4423,13 @@ def mayday():
        elif m == 3: proutn(_("3rd"))
        proutn(_(" attempt to re-materialize ") + crmshp())
        game.quad[ix][iy]=(IHMATER0,IHMATER1,IHMATER2)[m-1]
-       textcolor("red")
+       #textcolor("red")
        warble()
        if randreal() > probf:
            break
        prout(_("fails."))
        curses.delay_output(500)
-       textcolor(None)
+       #textcolor(None)
     if m > 3:
        game.quad[ix][iy]=IHQUEST
        game.alive = False
@@ -4480,9 +4438,9 @@ def mayday():
        finish(FMATERIALIZE)
        return
     game.quad[ix][iy]=game.ship
-    textcolor("green")
+    #textcolor("green")
     prout(_("succeeds."))
-    textcolor(None)
+    #textcolor(None)
     dock(False)
     skip(1)
     prout(_("Lt. Uhura-  \"Captain, we made it!\""))
@@ -5250,15 +5208,15 @@ def sectscan(goodScan, i, j):
     "Light up an individual dot in a sector."
     if goodScan or (abs(i-game.sector.i)<= 1 and abs(j-game.sector.j) <= 1):
        if (game.quad[i][j]==IHMATER0) or (game.quad[i][j]==IHMATER1) or (game.quad[i][j]==IHMATER2) or (game.quad[i][j]==IHE) or (game.quad[i][j]==IHF):
-           if game.condition   == "red": textcolor("red")
-           elif game.condition == "green": textcolor("green")
-           elif game.condition == "yellow": textcolor("yellow")
-           elif game.condition == "docked": textcolor("cyan")
-           elif game.condition == "dead": textcolor("brown")
+           #if game.condition   == "red": textcolor("red")
+           #elif game.condition == "green": textcolor("green")
+           #elif game.condition == "yellow": textcolor("yellow")
+           #elif game.condition == "docked": textcolor("cyan")
+           #elif game.condition == "dead": textcolor("brown")
            if game.quad[i][j] != game.ship: 
                highvideo()
        proutn("%c " % game.quad[i][j])
-       textcolor(None)
+       #textcolor(None)
     else:
        proutn("- ")
 
@@ -5356,7 +5314,7 @@ def srscan():
        for j in range(QUADSIZE):
            sectscan(goodScan, i, j)
        skip(1)
-                       
+               
 def eta():
     "Use computer to get estimated time of arrival for a warp jump."
     w1 = coord(); w2 = coord()
@@ -6106,12 +6064,14 @@ commands = {
 
 def listCommands():
     "Generate a list of legal commands."
-    proutn(_("LEGAL COMMANDS ARE:"))
-    for (k, key) in enumerate(commands):
+    prout(_("LEGAL COMMANDS ARE:"))
+    emitted = 0
+    for key in commands:
        if not commands[key] or (commands[key] & game.options):
-            if k % 5 == 0:
+            proutn("%-12s " % key)
+            emitted += 1
+            if emitted % 5 == 4:
                 skip(1)
-            proutn("%-12s " % key) 
     skip(1)
 
 def helpme():
@@ -6395,8 +6355,6 @@ class sstscanner:
                 clrscr()
             if line == '':
                 return None
-            # Skip leading white space
-            line = line.lstrip()
             if not line:
                 continue
             else:
@@ -6417,8 +6375,10 @@ class sstscanner:
         self.type = "IHALPHA"
         self.real = None
         return "IHALPHA"
-    def push(self, tok):
+    def append(self, tok):
         self.inqueue.append(tok)
+    def push(self, tok):
+        self.inqueue.insert(0, tok)
     def waiting(self):
         return self.inqueue
     def chew(self):
@@ -6557,6 +6517,7 @@ def debugme():
        atover(True)
 
 if __name__ == '__main__':
+    import getopt, socket
     try:
         global line, thing, game, idebug
         game = None
@@ -6565,11 +6526,10 @@ if __name__ == '__main__':
         game = gamestate()
         idebug = 0
         game.options = OPTION_ALL &~ (OPTION_IOMODES | OPTION_PLAIN | OPTION_ALMY)
-        # Disable curses mode until the game logic is working.
-        #    if os.getenv("TERM"):
-        #      game.options |= OPTION_CURSES | OPTION_SHOWME
-        #    else:
-        game.options |= OPTION_TTY
+        if os.getenv("TERM"):
+            game.options |= OPTION_CURSES
+        else:
+            game.options |= OPTION_TTY
         seed = int(time.time())
         (options, arguments) = getopt.getopt(sys.argv[1:], "r:s:tx")
         for (switch, val) in options:
@@ -6609,9 +6569,11 @@ if __name__ == '__main__':
         if logfp:
             logfp.write("# seed %s\n" % seed)
             logfp.write("# options %s\n" % " ".join(arguments))
+            logfp.write("# recorded by %s@%s on %s\n" % \
+                    (os.getenv("LOGNAME"),socket.gethostname(),time.ctime()))
         random.seed(seed)
         scanner = sstscanner()
-        map(scanner.push, arguments)
+        map(scanner.append, arguments)
         try:
             iostart()
             while True: # Play a game 
@@ -6642,5 +6604,7 @@ if __name__ == '__main__':
             ioend()
         raise SystemExit, 0
     except KeyboardInterrupt:
-        print""
+        if logfp:
+            logfp.close()
+        print ""
         pass