Enabled the gettext support.
[super-star-trek.git] / src / sst.py
index 60284f050717a67e9c9332c1482950f3064dbc5d..d3047cd7dd8b2d2e2e134ea02769505cc4f9f232 100644 (file)
@@ -2,10 +2,9 @@
 """
 sst.py =-- Super Star Trek in Python
 
-This code is a Python translation of a C translation of a FORTRAN original.
-The FORTRANness still shows in many ways, notably the use of a lot of
-parallel arrays where a more modern language would use structures
-or objects.  (However, 1-origin array indexing was fixed.)
+This code is a Python translation of a C translation of a FORTRAN
+original dating back to 1973.  Beautiful Python it is not.  But it
+works.
 
 Dave Matuszek says:
 
@@ -46,11 +45,11 @@ however mine had some feature it didn't have. So I merged its
 features that I liked. I also took a peek at the DECUS version (a
 port, less sources, to the PDP-10), and some other variations.
 
-1, Compared to the original UT version, I've changed the "help" command to
-"call" and the "terminate" command to "quit" to better match
-user expectations. The DECUS version apparently made those changes
-as well as changing "freeze" to "save". However I like "freeze".
-(Both "freeze" and "save" work in SST2K.)
+1, Compared to the original UT version, I've changed the "help"
+command to "call" and the "terminate" command to "quit" to better
+match user expectations. The DECUS version apparently made those
+changes as well as changing "freeze" to "save". However I like
+"freeze".  (Both "freeze" and "save" work in SST2K.)
 
 2. The experimental deathray originally had only a 5% chance of
 success, but could be used repeatedly. I guess after a couple
@@ -180,13 +179,12 @@ 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, gettext
 
 SSTDOC         = "/usr/share/doc/sst/sst.doc"
 DOC_NAME       = "sst.doc"
 
-# Stub to be replaced
-def _(str): return str
+def _(str): return gettext.gettext(str)
 
 PHASEFAC       = 2.0
 GALSIZE        = 8
@@ -256,7 +254,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:
@@ -336,9 +334,9 @@ class snapshot:
         self.baseq = []        # Base quadrant coordinates
         self.kcmdr = []        # Commander quadrant coordinates
        self.kscmdr = coord()   # Supercommander quadrant coordinates
-        # the galaxy (subscript 0 not used)
+        # the galaxy
         self.galaxy = fill2d(GALSIZE, lambda i, j: quadrant())
-        # the starchart (subscript 0 not used)
+        # the starchart
        self.chart = fill2d(GALSIZE, lambda i, j: page())
 
 class event:
@@ -525,10 +523,8 @@ class gamestate:
         self.damfac = 0.0      # damage factor
         self.lastchart = 0.0   # time star chart was last updated
         self.cryprob = 0.0     # probability that crystal will work
-        self.probex = 0.0      # location of probe
-        self.probey = 0.0      #
-        self.probeinx = 0.0    # probe x,y increment
-        self.probeiny = 0.0    #
+        self.probe = None      # location of probe
+        self.probein = None    # probe i,j increment
         self.height = 0.0      # height of orbit around planet
     def recompute(self):
         # Stas thinks this should be (C expression): 
@@ -538,7 +534,7 @@ class gamestate:
         # after killing the last klingon when score is shown -- perhaps also
         # if the only remaining klingon is SCOM.
         game.state.remtime = game.state.remres/(game.state.remkl + 4*len(game.state.kcmdr))
-# From enumerated type 'feature'
+
 IHR = 'R'
 IHK = 'K'
 IHC = 'C'
@@ -558,8 +554,6 @@ IHMATER0 = '-'
 IHMATER1 = 'o'
 IHMATER2 = '0'
 
-
-# From enumerated type 'FINTYPE'
 FWON = 0
 FDEPLETE = 1
 FLIFESUP = 2
@@ -583,10 +577,6 @@ FTRIBBLE = 19
 FHOLE = 20
 FCREW = 21
 
-# Log the results of pulling random numbers so we can check determinism.
-
-import traceback
-
 def withprob(p):
     v = random.random()
     #logfp.write("# withprob(%s) -> %f (%s) at %s\n" % (p, v, v<p, traceback.extract_stack()[-2][1:]))
@@ -662,7 +652,6 @@ def tryexit(enemy, look, irun):
                break
     return True; # success 
 
-#
 # The bad-guy movement algorithm:
 # 
 # 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
@@ -700,7 +689,6 @@ def tryexit(enemy, look, irun):
 # retreat, especially at high skill levels.
 # 
 # 5.  Motion is limited to skill level, except for SC hi-tailing it out.
-# 
 
 def movebaddy(enemy):
     "Tactical movement for the bad guys."
@@ -755,10 +743,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 +758,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):
@@ -925,7 +901,7 @@ def supercommander():
     if not game.iscate and avoid:
        # compute move away from Enterprise 
        idelta = game.state.kscmdr-game.quadrant
-       if math.sqrt(idelta.i*idelta.i+idelta.j*idelta.j) > 2.0:
+       if idelta.distance() > 2.0:
            # circulate in space 
            idelta.i = game.state.kscmdr.j-game.quadrant.j
            idelta.j = game.quadrant.i-game.state.kscmdr.i
@@ -1069,11 +1045,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 +1261,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 +1272,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 +1318,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 +1561,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 +1713,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 +1760,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))
@@ -2479,21 +2454,20 @@ def events():
                supercommander()
        elif evcode == FDSPROB: # Move deep space probe 
            schedule(FDSPROB, 0.01)
-           game.probex += game.probeinx
-           game.probey += game.probeiny
-           i = (int)(game.probex/QUADSIZE +0.05)
-           j = (int)(game.probey/QUADSIZE + 0.05)
+           game.probe += game.probein
+           i = int(round(game.probe.i/float(QUADSIZE)))
+           j = int(round(game.probe.j/float(QUADSIZE)))
            if game.probec.i != i or game.probec.j != j:
                game.probec.i = i
                game.probec.j = j
                if not VALID_QUADRANT(i, j) or \
                    game.state.galaxy[game.probec.i][game.probec.j].supernova:
                    # Left galaxy or ran into supernova
-                    if comunicating():
+                    if communicating():
                        announce()
                        skip(1)
                        proutn(_("Lt. Uhura-  \"The deep space probe "))
-                       if not VALID_QUADRANT(j, i):
+                       if not VALID_QUADRANT(i, j):
                            proutn(_("has left the galaxy"))
                        else:
                            proutn(_("is no longer transmitting"))
@@ -2514,8 +2488,7 @@ def events():
                pdest.charted = True
            game.proben -= 1 # One less to travel
            if game.proben == 0 and game.isarmed and pdest.stars:
-               # lets blow the sucker! 
-               supernova(game.probec)
+               supernova(game.probec)          # fire in the hole!
                unschedule(FDSPROB)
                if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova: 
                    return
@@ -2666,13 +2639,6 @@ def wait():
     game.resting = False
     game.optime = 0
 
-# A nova occurs.  It is the result of having a star hit with a
-# photon torpedo, or possibly of a probe warhead going off.
-# Stars that go nova cause stars which surround them to undergo
-# the same probabilistic process.  Klingons next to them are
-# destroyed.  And if the starship is next to it, it gets zapped.
-# If the zap is too much, it gets destroyed.
-        
 def nova(nov):
     "Star goes nova." 
     course = (0.0, 10.5, 12.0, 1.5, 9.0, 0.0, 3.0, 7.5, 6.0, 4.5)
@@ -3336,27 +3302,10 @@ 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
+    gettext.bindtextdomain("sst", "/usr/local/share/locale")
+    gettext.textdomain("sst")
     if not (game.options & OPTION_CURSES):
        ln_env = os.getenv("LINES")
         if ln_env:
@@ -3366,19 +3315,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 +3329,19 @@ 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
+    "Wrap up I/O."
+    if game.options & OPTION_CURSES:
+        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 +3382,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 +3414,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:
@@ -3860,7 +3800,7 @@ def dock(verbose):
 # because it involves giving x and y motions, yet the coordinates
 # are always displayed y - x, where +y is downward!
 
-def getcourse(isprobe, akey):
+def getcourse(isprobe):
     "Get a course and distance from the user."
     key = 0
     dquad = copy.copy(game.quadrant)
@@ -3883,12 +3823,7 @@ def getcourse(isprobe, akey):
            navmode = "manual"
            key = "IHEOL"
            break
-       if isprobe and akey != -1:
-           # For probe launch, use pre-scanned value first time 
-           key = akey
-           akey = -1
-       else: 
-           key = scanner.next()
+        key = scanner.next()
        if key == "IHEOL":
            proutn(_("Manual or automatic- "))
            iprompt = True
@@ -3968,8 +3903,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 + (dsect.j-game.sector.j)/(QUADSIZE*1.0)
+       delta.i = game.quadrant.i-dquad.i + (game.sector.i-dsect.i)/(QUADSIZE*1.0)
     else: # manual 
        while key == "IHEOL":
            proutn(_("X and Y displacements- "))
@@ -4010,7 +3945,7 @@ def impulse():
        prout(_("Engineer Scott- \"The impulse engines are damaged, Sir.\""))
        return
     if game.energy > 30.0:
-        if not getcourse(isprobe=False, akey=0):
+        if not getcourse(isprobe=False):
            return
        power = 20.0 + 100.0*game.dist
     else:
@@ -4065,7 +4000,7 @@ def warp(timewarp):
            prout(_("  is repaired, I can only give you warp 4.\""))
            return
                # Read in course and distance 
-        if not getcourse(isprobe=False, akey=0):
+        if not getcourse(isprobe=False):
            return
        # Make sure starship has enough energy for the trip 
        power = (game.dist+0.05)*game.warpfac*game.warpfac*game.warpfac*(game.shldup+1)
@@ -4090,7 +4025,7 @@ def warp(timewarp):
            return
                                                
        # Make sure enough time is left for the trip 
-       game.optime = 10.0*game.dist/game.wfacsq
+       game.optime = 10.0*game.dist/game.warpfac**2
        if game.optime >= 0.8*game.state.remtime:
            skip(1)
            prout(_("First Officer Spock- \"Captain, I compute that such"))
@@ -4150,7 +4085,7 @@ def warp(timewarp):
     game.energy -= game.dist*game.warpfac*game.warpfac*game.warpfac*(game.shldup+1)
     if game.energy <= 0:
        finish(FNRG)
-    game.optime = 10.0*game.dist/game.wfacsq
+    game.optime = 10.0*game.dist/game.warpfac**2
     if twarp:
        timwrp()
     if blooey:
@@ -4189,7 +4124,6 @@ def setwarp():
        return
     oldfac = game.warpfac
     game.warpfac = scanner.real
-    game.wfacsq=game.warpfac*game.warpfac
     if game.warpfac <= oldfac or game.warpfac <= 6.0:
        prout(_("Helmsman Sulu- \"Warp factor %d, Captain.\"") %
               int(game.warpfac))
@@ -4245,8 +4179,7 @@ def atover(igrab):
            proutn(_("The %s has stopped in a quadrant containing") % crmshp())
            prouts(_("   a supernova."))
            skip(2)
-       prout(_("***Emergency automatic override attempts to hurl ")+crmshp())
-       skip(1)
+       proutn(_("***Emergency automatic override attempts to hurl ")+crmshp())
        prout(_("safely out of quadrant."))
        if not damaged(DRADIO):
            game.state.galaxy[game.quadrant.i][game.quadrant.j].charted = True
@@ -4257,14 +4190,13 @@ def atover(igrab):
            finish(FSNOVAED)
            return
        game.warpfac = randreal(6.0, 8.0)
-       game.wfacsq = game.warpfac * game.warpfac
        prout(_("Warp factor set to %d") % int(game.warpfac))
        power = 0.75*game.energy
        game.dist = power/(game.warpfac*game.warpfac*game.warpfac*(game.shldup+1))
        distreq = randreal(math.sqrt(2))
        if distreq < game.dist:
            game.dist = distreq
-       game.optime = 10.0*game.dist/game.wfacsq
+       game.optime = 10.0*game.dist/game.warpfac**2
        game.direc = randreal(12)       # How dumb! 
        game.justin = False
        game.inorbit = False
@@ -4360,7 +4292,6 @@ def probe():
        return
     key = scanner.next()
     if key == "IHEOL":
-       # slow mode, so let Kirk know how many probes there are left
         if game.nprobes == 1:
             prout(_("1 probe left."))
         else:
@@ -4375,44 +4306,24 @@ def probe():
     elif key == "IHEOL":
        proutn(_("Arm NOVAMAX warhead? "))
        game.isarmed = ja()
-    if not getcourse(isprobe=True, akey=key):
+    elif key == "IHREAL":              # first element of course
+        scanner.push(scanner.token)
+    if not getcourse(isprobe=True):
        return
     game.nprobes -= 1
     angle = ((15.0 - game.direc) * 0.5235988)
-    game.probeinx = -math.sin(angle)
-    game.probeiny = math.cos(angle)
-    if math.fabs(game.probeinx) > math.fabs(game.probeiny):
-       bigger = math.fabs(game.probeinx)
-    else:
-       bigger = math.fabs(game.probeiny)
-    game.probeiny /= bigger
-    game.probeinx /= bigger
+    game.probein = coord(-math.sin(angle), math.cos(angle))
+    bigger = max(abs(game.probein.i), abs(game.probein.j))
+    game.probein /= bigger
     game.proben = 10.0*game.dist*bigger +0.5
-    game.probex = game.quadrant.i*QUADSIZE + game.sector.i - 1 # We will use better packing than original
-    game.probey = game.quadrant.j*QUADSIZE + game.sector.j - 1
-    game.probec = game.quadrant
+    game.probe = coord(game.quadrant.i*QUADSIZE + game.sector.i, 
+                       game.quadrant.j*QUADSIZE + game.sector.j)
+    game.probec = copy.copy(game.quadrant)
     schedule(FDSPROB, 0.01) # Time to move one sector
     prout(_("Ensign Chekov-  \"The deep space probe is launched, Captain.\""))
     game.ididit = True
     return
 
-# Here's how the mayday code works:
-# 
-# First, the closest starbase is selected.  If there is a a starbase
-# in your own quadrant, you are in good shape.  This distance takes
-# quadrant distances into account only.
-#
-# A magic number is computed based on the distance which acts as the
-# probability that you will be rematerialized.  You get three tries.
-#
-# When it is determined that you should be able to be rematerialized
-# (i.e., when the probability thing mentioned above comes up
-# positive), you are put into that quadrant (anywhere).  Then, we try
-# to see if there is a spot adjacent to the star- base.  If not, you
-# can't be rematerialized!!!  Otherwise, it drops you there.  It only
-# tries five times to find a spot to drop you.  After that, it's your
-# problem.
-
 def mayday():
     "Yell for help from nearest starbase."
     # There's more than one way to move in this game! 
@@ -4467,13 +4378,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
@@ -4482,31 +4393,13 @@ 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!\""))
 
-# Abandon Ship (the BSD-Trek description)
-# 
-# The ship is abandoned.  If your current ship is the Faire
-# Queene, or if your shuttlecraft is dead, you're out of
-# luck.  You need the shuttlecraft in order for the captain
-# (that's you!!) to escape.
-# 
-# Your crew can beam to an inhabited starsystem in the
-# quadrant, if there is one and if the transporter is working.
-# If there is no inhabited starsystem, or if the transporter
-# is out, they are left to die in outer space.
-# 
-# If there are no starbases left, you are captured by the
-# Klingons, who torture you mercilessly.  However, if there
-# is at least one starbase, you are returned to the
-# Federation in a prisoner of war exchange.  Of course, this
-# can't happen unless you have taken some prisoners.
-
 def abandon():
     "Abandon ship."
     scanner.chew()
@@ -4601,7 +4494,6 @@ def abandon():
     game.lsupres=game.inlsr=3.0
     game.shldup=False
     game.warpfac=5.0
-    game.wfacsq=25.0
     return
 
 # Code from planets.c begins here.
@@ -5253,15 +5145,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("- ")
 
@@ -5359,7 +5251,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()
@@ -5398,8 +5290,8 @@ def eta():
     if not VALID_QUADRANT(w1.i, w1.j) or not VALID_SECTOR(w2.i, w2.j):
        huh()
        return
-    game.dist = math.sqrt((w1.j-game.quadrant.j+0.1*(w2.j-game.sector.j))**2+
-               (w1.i-game.quadrant.i+0.1*(w2.i-game.sector.i))**2)
+    game.dist = math.sqrt((w1.j-game.quadrant.j+(w2.j-game.sector.j)/(QUADSIZE*1.0))**2+
+               (w1.i-game.quadrant.i+(w2.i-game.sector.i)/(QUADSIZE*1.0))**2)
     wfl = False
     if prompt:
        prout(_("Answer \"no\" if you don't know the value:"))
@@ -5550,11 +5442,11 @@ systnames = (
     _("Tellar Prime (Miracht)"),       # TOS: "Journey to Babel" 
     _("Vulcan (T'Khasi)"),     # many episodes 
     _("Medusa"),               # TOS: "Is There in Truth No Beauty?" 
-    _("Argelius II (Nelphia)"),# TOS: "Wolf in the Fold" ("IV" in BSD) 
+    _("Argelius II (Nelphia)"),        # TOS: "Wolf in the Fold" ("IV" in BSD) 
     _("Ardana"),               # TOS: "The Cloud Minders" 
     _("Catulla (Cendo-Prae)"), # TOS: "The Way to Eden" 
     _("Gideon"),               # TOS: "The Mark of Gideon" 
-    _("Aldebaran III"),        # TOS: "The Deadly Years" 
+    _("Aldebaran III"),                # TOS: "The Deadly Years" 
     _("Alpha Majoris I"),      # TOS: "Wolf in the Fold" 
     _("Altair IV"),            # TOS: "Amok Time 
     _("Ariannus"),             # TOS: "Let That Be Your Last Battlefield" 
@@ -5616,13 +5508,11 @@ def setup():
     if choose():
        return # frozen game
     # Prepare the Enterprise
-    game.alldone = game.gamewon = False
+    game.alldone = game.gamewon = game.shldchg = game.shldup = False
     game.ship = IHE
     game.state.crew = FULLCREW
     game.energy = game.inenrg = 5000.0
     game.shield = game.inshld = 2500.0
-    game.shldchg = False
-    game.shldup = False
     game.inlsr = 4.0
     game.lsupres = 4.0
     game.quadrant = randplace(GALSIZE)
@@ -5630,7 +5520,6 @@ def setup():
     game.torps = game.intorps = 10
     game.nprobes = randrange(2, 5)
     game.warpfac = 5.0
-    game.wfacsq = game.warpfac * game.warpfac
     for i in range(NDEVICES): 
        game.damage[i] = 0.0
     # Set up assorted game parameters
@@ -5818,8 +5707,6 @@ def choose():
        if not scanner.inqueue: # Can start with command line options 
            proutn(_("Would you like a regular, tournament, or saved game? "))
         scanner.next()
-       if len(scanner.token)==0: # Try again
-           continue
         if scanner.sees("tournament"):
            while scanner.next() == "IHEOL":
                proutn(_("Type in tournament number-"))
@@ -6112,12 +5999,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():
@@ -6401,8 +6290,6 @@ class sstscanner:
                 clrscr()
             if line == '':
                 return None
-            # Skip leading white space
-            line = line.lstrip()
             if not line:
                 continue
             else:
@@ -6423,18 +6310,16 @@ 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):
         # Demand input for next scan
         self.inqueue = []
         self.real = self.token = None
-    def chew2(self):
-        # return "IHEOL" next time 
-        self.inqueue = ["IHEOL"]
-        self.real = self.token = None
     def sees(self, s):
         # compares s to item and returns true if it matches to the length of s
         return s.startswith(self.token)
@@ -6563,6 +6448,7 @@ def debugme():
        atover(True)
 
 if __name__ == '__main__':
+    import getopt, socket
     try:
         global line, thing, game, idebug
         game = None
@@ -6571,11 +6457,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:
@@ -6615,9 +6500,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 
@@ -6636,7 +6523,8 @@ if __name__ == '__main__':
                 if game.tourn and game.alldone:
                     proutn(_("Do you want your score recorded?"))
                     if ja() == True:
-                        scanner.chew2()
+                        scanner.chew()
+                        scanner.push("\n")
                         freeze(False)
                 scanner.chew()
                 proutn(_("Do you want to play again? "))
@@ -6648,5 +6536,6 @@ if __name__ == '__main__':
             ioend()
         raise SystemExit, 0
     except KeyboardInterrupt:
-        print""
-        pass
+        if logfp:
+            logfp.close()
+        print ""