X-Git-Url: https://jxself.org/git/?p=super-star-trek.git;a=blobdiff_plain;f=src%2Fsst.py;h=d3047cd7dd8b2d2e2e134ea02769505cc4f9f232;hp=4c365259009ae0ca8dd4ba506188b3aeae1549a0;hb=80a9f53a470b74014623901f67013b5be50a5552;hpb=7d2fa7a973f6e8a8927b36c87c172c91ec4b6ed5 diff --git a/src/sst.py b/src/sst.py index 4c36525..d3047cd 100644 --- a/src/sst.py +++ b/src/sst.py @@ -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 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 @@ -1057,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 @@ -1330,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 @@ -1725,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." @@ -2466,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")) @@ -2501,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 @@ -2653,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) @@ -3323,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: @@ -3355,7 +3317,6 @@ def iostart(): stdscr.keypad(True) curses.nonl() curses.cbreak() - curses.start_color() global fullscreen_window, srscan_window, report_window, status_window global lrscan_window, message_window, prompt_window (rows, columns) = stdscr.getmaxyx() @@ -3368,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) @@ -3422,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 @@ -3451,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: @@ -3837,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) @@ -3860,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 @@ -3945,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- ")) @@ -3987,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: @@ -4042,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) @@ -4221,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 @@ -4335,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: @@ -4350,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! @@ -4442,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 @@ -4457,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() @@ -5227,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("- ") @@ -5333,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() @@ -5372,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:")) @@ -5524,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" @@ -5789,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-")) @@ -6083,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(): @@ -6402,10 +6320,6 @@ class sstscanner: # 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) @@ -6534,6 +6448,7 @@ def debugme(): atover(True) if __name__ == '__main__': + import getopt, socket try: global line, thing, game, idebug game = None @@ -6585,6 +6500,8 @@ 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.append, arguments) @@ -6606,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? ")) @@ -6618,5 +6536,6 @@ if __name__ == '__main__': ioend() raise SystemExit, 0 except KeyboardInterrupt: + if logfp: + logfp.close() print "" - pass