"""
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:
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
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
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:
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:
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):
# 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'
IHMATER1 = 'o'
IHMATER2 = '0'
-
-# From enumerated type 'FINTYPE'
FWON = 0
FDEPLETE = 1
FLIFESUP = 2
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:]))
break
return True; # success
-#
# The bad-guy movement algorithm:
#
# 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
# 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."
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:
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):
"Commander movement helper."
# Avoid quadrants with bases if we want to avoid Enterprise
if not welcoming(iq) or (avoid and iq in game.state.baseq):
- return True
+ return False
if game.justin and not game.iscate:
- return True
+ return False
# do the move
game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].klingons -= 1
game.state.kscmdr = iq
proutn(_(" a planet in Quadrant %s has been destroyed") % game.state.kscmdr)
prout(_(" by the Super-commander.\""))
break
- return False; # looks good!
+ return True; # looks good!
def supercommander():
"Move the Super Commander."
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
# there was what looked like a bug in the Almy C code here,
# but it might be this translation is just wrong.
iq = game.state.kscmdr + idelta
- if movescom(iq, avoid):
+ if not movescom(iq, avoid):
# failed -- try some other maneuvers
if idelta.i==0 or idelta.j==0:
# attempt angle move
if idelta.i != 0:
iq.j = game.state.kscmdr.j + 1
- if movescom(iq, avoid):
+ if not movescom(iq, avoid):
iq.j = game.state.kscmdr.j - 1
movescom(iq, avoid)
- else:
+ elif idelta.j != 0:
iq.i = game.state.kscmdr.i + 1
- if movescom(iq, avoid):
+ if not movescom(iq, avoid):
iq.i = game.state.kscmdr.i - 1
movescom(iq, avoid)
else:
# try moving just in x or y
iq.j = game.state.kscmdr.j
- if movescom(iq, avoid):
+ if not movescom(iq, avoid):
iq.j = game.state.kscmdr.j + idelta.j
iq.i = game.state.kscmdr.i
movescom(iq, avoid)
if len(game.state.baseq) == 0:
unschedule(FSCMOVE)
else:
- for (i, ibq) in enumerate(game.state.baseq):
+ for ibq in game.state.baseq:
if ibq == game.state.kscmdr and game.state.kscmdr == game.battle:
# attack the base
if avoid:
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
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
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]
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
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"))
proutn(crmena(True, type, "sector", mv))
# Decide what kind of enemy it is and update appropriately
if type == IHR:
- # chalk up a Romulan
+ # Chalk up a Romulan
game.state.galaxy[game.quadrant.i][game.quadrant.j].romulans -= 1
game.irhere -= 1
game.state.nromrem -= 1
global thing
thing = None
else:
- # Some type of a Klingon
+ # Killed some type of Klingon
game.state.galaxy[game.quadrant.i][game.quadrant.j].klingons -= 1
game.klhere -= 1
if type == IHC:
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."
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))
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)
- 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.probe += game.probein
+ newloc = (game.probe / float(QUADSIZE)).snaptogrid()
+ if newloc != game.probec:
+ game.probec = newloc
+ if not VALID_QUADRANT(game.probec.i, game.probec.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):
- proutn(_("has left the galaxy"))
+ if not VALID_QUADRANT(game.probec.i, game.probec.j):
+ proutn(_("has left the galaxy.\""))
else:
- proutn(_("is no longer transmitting"))
- prout(".\"")
+ proutn(_("is no longer transmitting.\""))
unschedule(FDSPROB)
continue
- if not communicating():
+ if communicating():
announce()
skip(1)
proutn(_("Lt. Uhura- \"The deep space probe is now in Quadrant %s.\"") % game.probec)
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
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)
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:
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()
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)
if game.options & OPTION_CURSES:
drawmaps(0)
setwnd(prompt_window)
- prompt_window.wclear()
+ prompt_window.clear()
prompt_window.addstr(prompt)
prompt_window.getstr()
prompt_window.clear()
pause_game()
clrscr()
else:
- proutn("\n")
+ try:
+ curwnd.move(y+1, 0)
+ except curses.error:
+ pass
else:
global linecount
linecount += 1
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:
def clreol():
"Clear to end of line -- can be a no-op in tty mode"
if game.options & OPTION_CURSES:
- wclrtoeol(curwnd)
- wrefresh(curwnd)
+ curwnd.clrtoeol()
+ curwnd.refresh()
def clrscr():
"Clear screen -- can be a no-op in tty mode."
# 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)
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
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- "))
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:
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)
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
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:
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!
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
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()
"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("- ")
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()
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:"))
def freeze(boss):
"Save game."
if boss:
- scanner.token = "emsave.trk"
- else:
+ scanner.push("emsave.trk")
+ key = scanner.next()
+ if key == "IHEOL":
+ proutn(_("File name: "))
key = scanner.next()
- if key == "IHEOL":
- proutn(_("File name: "))
- key = scanner.next()
- if key != "IHALPHA":
- huh()
- return
- scanner.chew()
- if '.' not in scanner.token:
- scanner.token += ".trk"
+ if key != "IHALPHA":
+ huh()
+ return
+ scanner.chew()
+ if '.' not in scanner.token:
+ scanner.token += ".trk"
try:
fp = open(scanner.token, "wb")
except IOError:
_("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"
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-"))
# Approximates Tom Almy's version.
game.options &=~ (OPTION_THINGY | OPTION_BLKHOLE | OPTION_BASE | OPTION_WORLDS)
game.options |= OPTION_ALMY
- elif scanner.sees("fancy"):
+ elif scanner.sees("fancy") or scanner.sees("\n"):
pass
elif len(scanner.token):
proutn(_("What is \"%s\"?") % scanner.token)
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():
clrscr()
if line == '':
return None
- # Skip leading white space
- line = line.lstrip()
if not line:
continue
else:
- self.inqueue = line.lstrip().split() + ["IHEOL"]
+ 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 == "IHEOL":
+ if self.token == "\n":
self.type = "IHEOL"
return "IHEOL"
try:
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)
atover(True)
if __name__ == '__main__':
+ import getopt, socket
try:
global line, thing, game, idebug
game = None
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:
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
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? "))
ioend()
raise SystemExit, 0
except KeyboardInterrupt:
- print""
- pass
+ if logfp:
+ logfp.close()
+ print ""