+ for i in range(8):
+ game.passwd += chr(ord('a')+randrange(26))
+
+# Code from sst.c begins here
+
+commands = {
+ "SRSCAN": OPTION_TTY,
+ "STATUS": OPTION_TTY,
+ "REQUEST": OPTION_TTY,
+ "LRSCAN": OPTION_TTY,
+ "PHASERS": 0,
+ "TORPEDO": 0,
+ "PHOTONS": 0,
+ "MOVE": 0,
+ "SHIELDS": 0,
+ "DOCK": 0,
+ "DAMAGES": 0,
+ "CHART": 0,
+ "IMPULSE": 0,
+ "REST": 0,
+ "WARP": 0,
+ "SCORE": 0,
+ "SENSORS": OPTION_PLANETS,
+ "ORBIT": OPTION_PLANETS,
+ "TRANSPORT": OPTION_PLANETS,
+ "MINE": OPTION_PLANETS,
+ "CRYSTALS": OPTION_PLANETS,
+ "SHUTTLE": OPTION_PLANETS,
+ "PLANETS": OPTION_PLANETS,
+ "REPORT": 0,
+ "COMPUTER": 0,
+ "COMMANDS": 0,
+ "EMEXIT": 0,
+ "PROBE": OPTION_PROBE,
+ "SAVE": 0,
+ "FREEZE": 0, # Synonym for SAVE
+ "ABANDON": 0,
+ "DESTRUCT": 0,
+ "DEATHRAY": 0,
+ "DEBUG": 0,
+ "MAYDAY": 0,
+ "SOS": 0, # Synonym for MAYDAY
+ "CALL": 0, # Synonym for MAYDAY
+ "QUIT": 0,
+ "HELP": 0,
+}
+
+def listCommands():
+ "Generate a list of legal commands."
+ prout(_("LEGAL COMMANDS ARE:"))
+ emitted = 0
+ for key in commands:
+ if not commands[key] or (commands[key] & game.options):
+ proutn("%-12s " % key)
+ emitted += 1
+ if emitted % 5 == 4:
+ skip(1)
+ skip(1)
+
+def helpme():
+ "Browse on-line help."
+ key = scanner.next()
+ while True:
+ if key == "IHEOL":
+ setwnd(prompt_window)
+ proutn(_("Help on what command? "))
+ key = scanner.next()
+ setwnd(message_window)
+ if key == "IHEOL":
+ return
+ if scanner.token in commands or scanner.token == "ABBREV":
+ break
+ skip(1)
+ listCommands()
+ key = "IHEOL"
+ scanner.chew()
+ skip(1)
+ cmd = scanner.token.upper()
+ try:
+ fp = open(SSTDOC, "r")
+ except IOError:
+ try:
+ fp = open(DOC_NAME, "r")
+ except IOError:
+ prout(_("Spock- \"Captain, that information is missing from the"))
+ proutn(_(" computer. You need to find "))
+ proutn(DOC_NAME)
+ prout(_(" and put it in the"))
+ proutn(_(" current directory or to "))
+ proutn(SSTDOC)
+ prout(".\"")
+ # This used to continue: "You need to find SST.DOC and put
+ # it in the current directory."
+ return
+ while True:
+ linebuf = fp.readline()
+ if linebuf == '':
+ prout(_("Spock- \"Captain, there is no information on that command.\""))
+ fp.close()
+ return
+ if linebuf[0] == '%' and linebuf[1] == '%' and linebuf[2] == ' ':
+ linebuf = linebuf[3:].strip()
+ if cmd == linebuf:
+ break
+ skip(1)
+ prout(_("Spock- \"Captain, I've found the following information:\""))
+ skip(1)
+ while linebuf in fp:
+ if "******" in linebuf:
+ break
+ proutn(linebuf)
+ fp.close()
+
+def makemoves():
+ "Command-interpretation loop."
+ clrscr()
+ setwnd(message_window)
+ while True: # command loop
+ drawmaps(1)
+ while True: # get a command
+ hitme = False
+ game.justin = False
+ game.optime = 0.0
+ scanner.chew()
+ setwnd(prompt_window)
+ clrscr()
+ proutn("COMMAND> ")
+ if scanner.next() == "IHEOL":
+ if game.options & OPTION_CURSES:
+ makechart()
+ continue
+ elif scanner.token == "":
+ continue
+ game.ididit = False
+ clrscr()
+ setwnd(message_window)
+ clrscr()
+ candidates = filter(lambda x: x.startswith(scanner.token.upper()),
+ commands)
+ if len(candidates) == 1:
+ cmd = candidates[0]
+ break
+ elif candidates and not (game.options & OPTION_PLAIN):
+ prout("Commands with prefix '%s': %s" % (scanner.token, " ".join(candidates)))
+ else:
+ listCommands()
+ continue
+ if cmd == "SRSCAN": # srscan
+ srscan()
+ elif cmd == "STATUS": # status
+ status()
+ elif cmd == "REQUEST": # status request
+ request()
+ elif cmd == "LRSCAN": # long range scan
+ lrscan(silent=False)
+ elif cmd == "PHASERS": # phasers
+ phasers()
+ if game.ididit:
+ hitme = True
+ elif cmd == "TORPEDO": # photon torpedos
+ photon()
+ if game.ididit:
+ hitme = True
+ elif cmd == "MOVE": # move under warp
+ warp(course=None, involuntary=False)
+ elif cmd == "SHIELDS": # shields
+ doshield(shraise=False)
+ if game.ididit:
+ hitme = True
+ game.shldchg = False
+ elif cmd == "DOCK": # dock at starbase
+ dock(True)
+ if game.ididit:
+ attack(torps_ok=False)
+ elif cmd == "DAMAGES": # damage reports
+ damagereport()
+ elif cmd == "CHART": # chart
+ makechart()
+ elif cmd == "IMPULSE": # impulse
+ impulse()
+ elif cmd == "REST": # rest
+ wait()
+ if game.ididit:
+ hitme = True
+ elif cmd == "WARP": # warp
+ setwarp()
+ elif cmd == "SCORE": # score
+ score()
+ elif cmd == "SENSORS": # sensors
+ sensor()
+ elif cmd == "ORBIT": # orbit
+ orbit()
+ if game.ididit:
+ hitme = True
+ elif cmd == "TRANSPORT": # transport "beam"
+ beam()
+ elif cmd == "MINE": # mine
+ mine()
+ if game.ididit:
+ hitme = True
+ elif cmd == "CRYSTALS": # crystals
+ usecrystals()
+ if game.ididit:
+ hitme = True
+ elif cmd == "SHUTTLE": # shuttle
+ shuttle()
+ if game.ididit:
+ hitme = True
+ elif cmd == "PLANETS": # Planet list
+ survey()
+ elif cmd == "REPORT": # Game Report
+ report()
+ elif cmd == "COMPUTER": # use COMPUTER!
+ eta()
+ elif cmd == "COMMANDS":
+ listCommands()
+ elif cmd == "EMEXIT": # Emergency exit
+ clrscr() # Hide screen
+ freeze(True) # forced save
+ raise SysExit,1 # And quick exit
+ elif cmd == "PROBE":
+ probe() # Launch probe
+ if game.ididit:
+ hitme = True
+ elif cmd == "ABANDON": # Abandon Ship
+ abandon()
+ elif cmd == "DESTRUCT": # Self Destruct
+ selfdestruct()
+ elif cmd == "SAVE": # Save Game
+ freeze(False)
+ clrscr()
+ if game.skill > SKILL_GOOD:
+ prout(_("WARNING--Saved games produce no plaques!"))
+ elif cmd == "DEATHRAY": # Try a desparation measure
+ deathray()
+ if game.ididit:
+ hitme = True
+ elif cmd == "DEBUGCMD": # What do we want for debug???
+ debugme()
+ elif cmd == "MAYDAY": # Call for help
+ mayday()
+ if game.ididit:
+ hitme = True
+ elif cmd == "QUIT":
+ game.alldone = True # quit the game
+ elif cmd == "HELP":
+ helpme() # get help
+ while True:
+ if game.alldone:
+ break # Game has ended
+ if game.optime != 0.0:
+ events()
+ if game.alldone:
+ break # Events did us in
+ if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
+ atover(False)
+ continue
+ if hitme and not game.justin:
+ attack(torps_ok=True)
+ if game.alldone:
+ break
+ if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
+ atover(False)
+ hitme = True
+ continue
+ break
+ if game.alldone:
+ break
+ if idebug:
+ prout("=== Ending")
+
+def cramen(type):
+ "Emit the name of an enemy or feature."
+ if type == IHR: s = _("Romulan")
+ elif type == IHK: s = _("Klingon")
+ elif type == IHC: s = _("Commander")
+ elif type == IHS: s = _("Super-commander")
+ elif type == IHSTAR: s = _("Star")
+ elif type == IHP: s = _("Planet")
+ elif type == IHB: s = _("Starbase")
+ elif type == IHBLANK: s = _("Black hole")
+ elif type == IHT: s = _("Tholian")
+ elif type == IHWEB: s = _("Tholian web")
+ elif type == IHQUEST: s = _("Stranger")
+ elif type == IHW: s = _("Inhabited World")
+ else: s = "Unknown??"
+ return s
+
+def crmena(stars, enemy, loctype, w):
+ "Emit the name of an enemy and his location."
+ buf = ""
+ if stars:
+ buf += "***"
+ buf += cramen(enemy) + _(" at ")
+ if loctype == "quadrant":
+ buf += _("Quadrant ")
+ elif loctype == "sector":
+ buf += _("Sector ")
+ return buf + `w`
+
+def crmshp():
+ "Emit our ship name."
+ return{IHE:_("Enterprise"),IHF:_("Faerie Queene")}.get(game.ship,"Ship???")
+
+def stars():
+ "Emit a line of stars"
+ prouts("******************************************************")
+ skip(1)
+
+def expran(avrage):
+ return -avrage*math.log(1e-7 + randreal())
+
+def randplace(size):
+ "Choose a random location."
+ w = coord()
+ w.i = randrange(size)
+ w.j = randrange(size)
+ return w
+
+class sstscanner:
+ def __init__(self):
+ self.type = None
+ self.token = None
+ self.real = 0.0
+ self.inqueue = []
+ def next(self):
+ # Get a token from the user
+ self.real = 0.0
+ self.token = ''
+ # Fill the token quue if nothing here
+ while not self.inqueue:
+ line = cgetline()
+ if curwnd==prompt_window:
+ clrscr()
+ setwnd(message_window)
+ clrscr()
+ if line == '':
+ return None
+ if not line:
+ continue
+ else:
+ self.inqueue = line.lstrip().split() + ["\n"]
+ # From here on in it's all looking at the queue
+ self.token = self.inqueue.pop(0)
+ if self.token == "\n":
+ self.type = "IHEOL"
+ return "IHEOL"
+ try:
+ self.real = float(self.token)
+ self.type = "IHREAL"
+ return "IHREAL"
+ except ValueError:
+ pass
+ # Treat as alpha
+ self.token = self.token.lower()
+ self.type = "IHALPHA"
+ self.real = None
+ return "IHALPHA"
+ 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 sees(self, s):
+ # compares s to item and returns true if it matches to the length of s
+ return s.startswith(self.token)
+ def int(self):
+ # Round token value to nearest integer
+ return int(round(scanner.real))
+ def getcoord(self):
+ s = coord()
+ scanner.next()
+ if scanner.type != "IHREAL":
+ huh()
+ return None
+ s.i = scanner.int()-1
+ scanner.next()
+ if scanner.type != "IHREAL":
+ huh()
+ return None
+ s.j = scanner.int()-1
+ return s
+ def __repr__(str):
+ return "<sstcanner: token=%s, type=%s, queue=%s>" % (scanner.token, scanner.type, scanner.inqueue)
+
+def ja():
+ "Yes-or-no confirmation."
+ scanner.chew()
+ while True:
+ scanner.next()
+ if scanner.token == 'y':
+ return True
+ if scanner.token == 'n':
+ return False
+ scanner.chew()
+ proutn(_("Please answer with \"y\" or \"n\": "))
+
+def huh():
+ "Complain about unparseable input."
+ scanner.chew()
+ skip(1)
+ prout(_("Beg your pardon, Captain?"))
+
+def debugme():
+ "Access to the internals for debugging."
+ proutn("Reset levels? ")
+ if ja() == True:
+ if game.energy < game.inenrg:
+ game.energy = game.inenrg
+ game.shield = game.inshld
+ game.torps = game.intorps
+ game.lsupres = game.inlsr
+ proutn("Reset damage? ")
+ if ja() == True:
+ for i in range(NDEVICES):
+ if game.damage[i] > 0.0:
+ game.damage[i] = 0.0
+ proutn("Toggle debug flag? ")
+ if ja() == True:
+ idebug = not idebug
+ if idebug:
+ prout("Debug output ON")
+ else:
+ prout("Debug output OFF")
+ proutn("Cause selective damage? ")
+ if ja() == True:
+ for i in range(NDEVICES):
+ proutn("Kill %s?" % device[i])
+ scanner.chew()
+ key = scanner.next()
+ if key == "IHALPHA" and scanner.sees("y"):
+ game.damage[i] = 10.0
+ proutn("Examine/change events? ")
+ if ja() == True:
+ ev = event()
+ w = coord()
+ legends = {
+ FSNOVA: "Supernova ",
+ FTBEAM: "T Beam ",
+ FSNAP: "Snapshot ",
+ FBATTAK: "Base Attack ",
+ FCDBAS: "Base Destroy ",
+ FSCMOVE: "SC Move ",
+ FSCDBAS: "SC Base Destroy ",
+ FDSPROB: "Probe Move ",
+ FDISTR: "Distress Call ",
+ FENSLV: "Enslavement ",
+ FREPRO: "Klingon Build ",
+ }
+ for i in range(1, NEVENTS):
+ proutn(legends[i])
+ if is_scheduled(i):
+ proutn("%.2f" % (scheduled(i)-game.state.date))
+ if i == FENSLV or i == FREPRO:
+ ev = findevent(i)
+ proutn(" in %s" % ev.quadrant)
+ else:
+ proutn("never")
+ proutn("? ")
+ scanner.chew()
+ key = scanner.next()
+ if key == 'n':
+ unschedule(i)
+ scanner.chew()
+ elif key == "IHREAL":
+ ev = schedule(i, scanner.real)
+ if i == FENSLV or i == FREPRO:
+ scanner.chew()
+ proutn("In quadrant- ")
+ key = scanner.next()
+ # "IHEOL" says to leave coordinates as they are
+ if key != "IHEOL":
+ if key != "IHREAL":
+ prout("Event %d canceled, no x coordinate." % (i))
+ unschedule(i)
+ continue
+ w.i = int(round(scanner.real))
+ key = scanner.next()
+ if key != "IHREAL":
+ prout("Event %d canceled, no y coordinate." % (i))
+ unschedule(i)
+ continue
+ w.j = int(round(scanner.real))
+ ev.quadrant = w
+ scanner.chew()
+ proutn("Induce supernova here? ")
+ if ja() == True:
+ game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova = True
+ atover(True)
+
+if __name__ == '__main__':
+ import getopt, socket
+ try:
+ global line, thing, game, idebug
+ game = None
+ thing = coord()
+ thing.angry = False
+ game = gamestate()
+ idebug = 0
+ game.options = OPTION_ALL &~ (OPTION_IOMODES | OPTION_PLAIN | OPTION_ALMY)
+ 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:
+ if switch == '-r':
+ try:
+ replayfp = open(val, "r")
+ except IOError:
+ sys.stderr.write("sst: can't open replay file %s\n" % val)
+ raise SystemExit, 1
+ try:
+ line = replayfp.readline().strip()
+ (leader, key, seed) = line.split()
+ seed = eval(seed)
+ sys.stderr.write("sst2k: seed set to %s\n" % seed)
+ line = replayfp.readline().strip()
+ arguments += line.split()[2:]
+ except ValueError:
+ sys.stderr.write("sst: replay file %s is ill-formed\n"% val)
+ raise SystemExit(1)
+ game.options |= OPTION_TTY
+ game.options &=~ OPTION_CURSES
+ elif switch == '-s':
+ seed = int(val)
+ elif switch == '-t':
+ game.options |= OPTION_TTY
+ game.options &=~ OPTION_CURSES
+ elif switch == '-x':
+ idebug = True
+ else:
+ sys.stderr.write("usage: sst [-t] [-x] [startcommand...].\n")
+ raise SystemExit, 1
+ # where to save the input in case of bugs
+ try:
+ logfp = open("/usr/tmp/sst-input.log", "w")
+ except IOError:
+ sys.stderr.write("sst: warning, can't open logfile\n")
+ 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.append, arguments)
+ try:
+ iostart()
+ while True: # Play a game
+ setwnd(fullscreen_window)
+ clrscr()
+ prelim()
+ setup()
+ if game.alldone:
+ score()
+ game.alldone = False
+ else:
+ makemoves()
+ skip(1)
+ stars()
+ skip(1)
+ if game.tourn and game.alldone:
+ proutn(_("Do you want your score recorded?"))
+ if ja() == True:
+ scanner.chew()
+ scanner.push("\n")
+ freeze(False)
+ scanner.chew()
+ proutn(_("Do you want to play again? "))
+ if not ja():
+ break
+ skip(1)
+ prout(_("May the Great Bird of the Galaxy roost upon your home planet."))
+ finally:
+ ioend()
+ raise SystemExit, 0
+ except KeyboardInterrupt:
+ if logfp:
+ logfp.close()
+ print ""