Switch to shipper packaging.
[super-star-trek.git] / sst.py
1 #!/usr/bin/env python
2 """
3 sst.py -- Super Star Trek 2K
4
5 SST2K is a Python translation of a C translation of a FORTRAN
6 original dating back to 1973.  Beautiful Python it is not, but it
7 works.  Translation by Eric S. Raymond; original game by David Matuszek
8 and Paul Reynolds, with modifications by Don Smith, Tom Almy,
9 Stas Sergeev, and Eric S. Raymond.
10
11 See the doc/HACKING file in the distribution for designers notes and advice
12 on how to modify (and how not to modify!) this code.
13 """
14 import os, sys, math, curses, time, pickle, random, copy, gettext, getpass
15 import getopt, socket, locale
16
17 # This import only works on Unixes.  The intention is to enable
18 # Ctrl-P, Ctrl-N, and friends in Cmd.
19 try:
20     import readline
21 except ImportError:
22     pass
23
24 # Prevent lossage under Python 3
25 try:
26     my_input = raw_input
27 except NameError:
28     my_input = input
29
30
31 version = "2.1"
32
33 docpath         = (".", "doc/", "/usr/share/doc/sst/")
34
35 def _(st):
36     return gettext.gettext(st)
37
38 GALSIZE         = 8             # Galaxy size in quadrants
39 NINHAB          = (GALSIZE * GALSIZE // 2)      # Number of inhabited worlds
40 MAXUNINHAB      = 10            # Maximum uninhabited worlds
41 QUADSIZE        = 10            # Quadrant size in sectors
42 BASEMIN         = 2                             # Minimum starbases
43 BASEMAX         = (GALSIZE * GALSIZE // 12)     # Maximum starbases
44 MAXKLGAME       = 127           # Maximum Klingons per game
45 MAXKLQUAD       = 9             # Maximum Klingons per quadrant
46 FULLCREW        = 428           # Crew size. BSD Trek was 387, that's wrong
47 FOREVER         = 1e30          # Time for the indefinite future
48 MAXBURST        = 3             # Max # of torps you can launch in one turn
49 MINCMDR         = 10            # Minimum number of Klingon commanders
50 DOCKFAC         = 0.25          # Repair faster when docked
51 PHASEFAC        = 2.0           # Unclear what this is, it was in the C version
52
53 ALGERON         = 2311          # Date of the Treaty of Algeron
54
55
56 DEFAULT      = -1
57 BLACK        = 0
58 BLUE         = 1
59 GREEN        = 2
60 CYAN         = 3
61 RED          = 4
62 MAGENTA      = 5
63 BROWN        = 6
64 LIGHTGRAY    = 7
65 DARKGRAY     = 8
66 LIGHTBLUE    = 9
67 LIGHTGREEN   = 10
68 LIGHTCYAN    = 11
69 LIGHTRED     = 12
70 LIGHTMAGENTA = 13
71 YELLOW       = 14
72 WHITE        = 15
73
74 class TrekError(Exception):
75     pass
76
77 class JumpOut(Exception):
78     pass
79
80 class Coord:
81     def __init__(self, x=None, y=None):
82         self.i = x
83         self.j = y
84     def valid_quadrant(self):
85         return self.i >= 0 and self.i < GALSIZE and self.j >= 0 and self.j < GALSIZE
86     def valid_sector(self):
87         return self.i >= 0 and self.i < QUADSIZE and self.j >= 0 and self.j < QUADSIZE
88     def invalidate(self):
89         self.i = self.j = None
90     def is_valid(self):
91         return self.i != None and self.j != None
92     def __eq__(self, other):
93         return other != None and self.i == other.i and self.j == other.j
94     def __ne__(self, other):
95         return other is None or self.i != other.i or self.j != other.j
96     def __add__(self, other):
97         return Coord(self.i+other.i, self.j+other.j)
98     def __sub__(self, other):
99         return Coord(self.i-other.i, self.j-other.j)
100     def __mul__(self, other):
101         return Coord(self.i*other, self.j*other)
102     def __rmul__(self, other):
103         return Coord(self.i*other, self.j*other)
104     def __div__(self, other):
105         return Coord(self.i/other, self.j/other)
106     def __mod__(self, other):
107         return Coord(self.i % other, self.j % other)
108     def __rdiv__(self, other):
109         return Coord(self.i/other, self.j/other)
110     def roundtogrid(self):
111         return Coord(int(round(self.i)), int(round(self.j)))
112     def distance(self, other=None):
113         if not other:
114             other = Coord(0, 0)
115         return math.sqrt((self.i - other.i)**2 + (self.j - other.j)**2)
116     def bearing(self):
117         return 1.90985*math.atan2(self.j, self.i)
118     def sgn(self):
119         s = Coord()
120         if self.i == 0:
121             s.i = 0
122         else:
123             s.i = self.i / abs(self.i)
124         if self.j == 0:
125             s.j = 0
126         else:
127             s.j = self.j / abs(self.j)
128         return s
129     def quadrant(self):
130         #print "Location %s -> %s" % (self, (self / QUADSIZE).roundtogrid())
131         return self.roundtogrid() / QUADSIZE
132     def sector(self):
133         return self.roundtogrid() % QUADSIZE
134     def scatter(self):
135         s = Coord()
136         s.i = self.i + randrange(-1, 2)
137         s.j = self.j + randrange(-1, 2)
138         return s
139     def __str__(self):
140         if self.i is None or self.j is None:
141             return "Nowhere"
142         return "%s - %s" % (self.i+1, self.j+1)
143     __repr__ = __str__
144
145 class Thingy(Coord):
146     "Do not anger the Space Thingy!"
147     def __init__(self):
148         Coord.__init__(self)
149         self.angered = False
150     def angry(self):
151         self.angered = True
152     def at(self, q):
153         return (q.i, q.j) == (self.i, self.j)
154
155 class Planet:
156     def __init__(self):
157         self.name = None        # string-valued if inhabited
158         self.quadrant = Coord()        # quadrant located
159         self.pclass = None        # could be ""M", "N", "O", or "destroyed"
160         self.crystals = "absent"# could be "mined", "present", "absent"
161         self.known = "unknown"        # could be "unknown", "known", "shuttle_down"
162         self.inhabited = False        # is it inhabited?
163     def __str__(self):
164         return self.name
165
166 class Quadrant:
167     def __init__(self):
168         self.stars = 0
169         self.planet = None
170         self.starbase = False
171         self.klingons = 0
172         self.romulans = 0
173         self.supernova = False
174         self.charted = False
175         self.status = "secure"        # Could be "secure", "distressed", "enslaved"
176     def __str__(self):
177         return "<Quadrant: %(klingons)d>" % self.__dict__
178     __repr__ = __str__
179
180 class Page:
181     def __init__(self):
182         self.stars = None
183         self.starbase = False
184         self.klingons = None
185     def __repr__(self):
186         return "<%s,%s,%s>" % (self.klingons, self.starbase, self.stars)
187
188 def fill2d(size, fillfun):
189     "Fill an empty list in 2D."
190     lst = []
191     for i in range(size):
192         lst.append([])
193         for j in range(size):
194             lst[i].append(fillfun(i, j))
195     return lst
196
197 class Snapshot:
198     def __init__(self):
199         self.snap = False       # snapshot taken
200         self.crew = 0           # crew complement
201         self.nscrem = 0         # remaining super commanders
202         self.starkl = 0         # destroyed stars
203         self.basekl = 0         # destroyed bases
204         self.nromrem = 0        # Romulans remaining
205         self.nplankl = 0        # destroyed uninhabited planets
206         self.nworldkl = 0        # destroyed inhabited planets
207         self.planets = []        # Planet information
208         self.date = 0.0           # stardate
209         self.remres = 0         # remaining resources
210         self.remtime = 0        # remaining time
211         self.baseq = []         # Base quadrant coordinates
212         self.kcmdr = []         # Commander quadrant coordinates
213         self.kscmdr = Coord()        # Supercommander quadrant coordinates
214         # the galaxy
215         self.galaxy = fill2d(GALSIZE, lambda i_unused, j_unused: Quadrant())
216         # the starchart
217         self.chart = fill2d(GALSIZE, lambda i_unused, j_unused: Page())
218     def traverse(self):
219         for i in range(GALSIZE):
220             for j in range(GALSIZE):
221                 yield (i, j, self.galaxy[i][j])
222
223 class Event:
224     def __init__(self):
225         self.date = None        # A real number
226         self.quadrant = None        # A coord structure
227
228 # game options
229 OPTION_ALL        = 0xffffffff
230 OPTION_TTY        = 0x00000001        # old interface
231 OPTION_CURSES     = 0x00000002        # new interface
232 OPTION_IOMODES    = 0x00000003        # cover both interfaces
233 OPTION_PLANETS    = 0x00000004        # planets and mining
234 OPTION_THOLIAN    = 0x00000008        # Tholians and their webs (UT 1979 version)
235 OPTION_THINGY     = 0x00000010        # Space Thingy can shoot back (Stas, 2005)
236 OPTION_PROBE      = 0x00000020        # deep-space probes (DECUS version, 1980)
237 OPTION_SHOWME     = 0x00000040        # bracket Enterprise in chart
238 OPTION_RAMMING    = 0x00000080        # enemies may ram Enterprise (Almy)
239 OPTION_MVBADDY    = 0x00000100        # more enemies can move (Almy)
240 OPTION_BLKHOLE    = 0x00000200        # black hole may timewarp you (Stas, 2005)
241 OPTION_BASE       = 0x00000400        # bases have good shields (Stas, 2005)
242 OPTION_WORLDS     = 0x00000800        # logic for inhabited worlds (ESR, 2006)
243 OPTION_AUTOSCAN   = 0x00001000        # automatic LRSCAN before CHART (ESR, 2006)
244 OPTION_CAPTURE    = 0x00002000        # Enable BSD-Trek capture (Almy, 2013).
245 OPTION_CLOAK      = 0x80004000        # Enable BSD-Trek capture (Almy, 2013).
246 OPTION_PLAIN      = 0x01000000        # user chose plain game
247 OPTION_ALMY       = 0x02000000        # user chose Almy variant
248 OPTION_COLOR      = 0x04000000        # enable color display (ESR, 2010)
249
250 # Define devices
251 DSRSENS         = 0
252 DLRSENS         = 1
253 DPHASER         = 2
254 DPHOTON         = 3
255 DLIFSUP         = 4
256 DWARPEN         = 5
257 DIMPULS         = 6
258 DSHIELD         = 7
259 DRADIO          = 8
260 DSHUTTL         = 9
261 DCOMPTR         = 10
262 DNAVSYS         = 11
263 DTRANSP         = 12
264 DSHCTRL         = 13
265 DDRAY           = 14
266 DDSP            = 15
267 DCLOAK          = 16
268 NDEVICES        = 17        # Number of devices
269
270 SKILL_NONE      = 0
271 SKILL_NOVICE    = 1
272 SKILL_FAIR      = 2
273 SKILL_GOOD      = 3
274 SKILL_EXPERT    = 4
275 SKILL_EMERITUS  = 5
276
277 def damaged(dev):
278     return (game.damage[dev] != 0.0)
279 def communicating():
280     return not damaged(DRADIO) or game.condition=="docked"
281
282 # Define future events
283 FSPY    = 0        # Spy event happens always (no future[] entry)
284                    # can cause SC to tractor beam Enterprise
285 FSNOVA  = 1        # Supernova
286 FTBEAM  = 2        # Commander tractor beams Enterprise
287 FSNAP   = 3        # Snapshot for time warp
288 FBATTAK = 4        # Commander attacks base
289 FCDBAS  = 5        # Commander destroys base
290 FSCMOVE = 6        # Supercommander moves (might attack base)
291 FSCDBAS = 7        # Supercommander destroys base
292 FDSPROB = 8        # Move deep space probe
293 FDISTR  = 9        # Emit distress call from an inhabited world
294 FENSLV  = 10       # Inhabited word is enslaved */
295 FREPRO  = 11       # Klingons build a ship in an enslaved system
296 NEVENTS = 12
297
298 # Abstract out the event handling -- underlying data structures will change
299 # when we implement stateful events
300 def findevent(evtype):
301     return game.future[evtype]
302
303 class Enemy:
304     def __init__(self, etype=None, loc=None, power=None):
305         self.type = etype
306         self.location = Coord()
307         self.kdist = None
308         self.kavgd = None
309         if loc:
310             self.move(loc)
311         self.power = power        # enemy energy level
312         game.enemies.append(self)
313     def move(self, loc):
314         motion = (loc != self.location)
315         if self.location.i is not None and self.location.j is not None:
316             if motion:
317                 if self.type == 'T':
318                     game.quad[self.location.i][self.location.j] = '#'
319                 else:
320                     game.quad[self.location.i][self.location.j] = '.'
321         if loc:
322             self.location = copy.copy(loc)
323             game.quad[self.location.i][self.location.j] = self.type
324             self.kdist = self.kavgd = (game.sector - loc).distance()
325         else:
326             self.location = Coord()
327             self.kdist = self.kavgd = None
328             # Guard prevents failure on Tholian or thingy
329             if self in game.enemies:
330                 game.enemies.remove(self)
331         return motion
332     def __repr__(self):
333         return "<%s,%s.%f>" % (self.type, self.location, self.power)        # For debugging
334
335 class Gamestate:
336     def __init__(self):
337         self.options = None        # Game options
338         self.state = Snapshot()        # A snapshot structure
339         self.snapsht = Snapshot()        # Last snapshot taken for time-travel purposes
340         self.quad = None        # contents of our quadrant
341         self.damage = [0.0] * NDEVICES        # damage encountered
342         self.future = []        # future events
343         i = NEVENTS
344         while i > 0:
345             i -= 1
346             self.future.append(Event())
347         self.passwd  = None        # Self Destruct password
348         self.enemies = []
349         self.quadrant = None        # where we are in the large
350         self.sector = None        # where we are in the small
351         self.tholian = None        # Tholian enemy object
352         self.base = None        # position of base in current quadrant
353         self.battle = None        # base coordinates being attacked
354         self.plnet = None        # location of planet in quadrant
355         self.gamewon = False        # Finished!
356         self.ididit = False        # action taken -- allows enemy to attack
357         self.alive = False        # we are alive (not killed)
358         self.justin = False        # just entered quadrant
359         self.shldup = False        # shields are up
360         self.shldchg = False        # shield is changing (affects efficiency)
361         self.iscate = False        # super commander is here
362         self.ientesc = False        # attempted escape from supercommander
363         self.resting = False        # rest time
364         self.icraft = False        # Kirk in Galileo
365         self.landed = False        # party on planet (true), on ship (false)
366         self.alldone = False        # game is now finished
367         self.neutz = False        # Romulan Neutral Zone
368         self.isarmed = False        # probe is armed
369         self.inorbit = False        # orbiting a planet
370         self.imine = False        # mining
371         self.icrystl = False        # dilithium crystals aboard
372         self.iseenit = False        # seen base attack report
373         self.thawed = False        # thawed game
374         self.condition = None        # "green", "yellow", "red", "docked", "dead"
375         self.iscraft = None        # "onship", "offship", "removed"
376         self.skill = None        # Player skill level
377         self.inkling = 0        # initial number of klingons
378         self.inbase = 0                # initial number of bases
379         self.incom = 0                # initial number of commanders
380         self.inscom = 0                # initial number of commanders
381         self.inrom = 0                # initial number of commanders
382         self.instar = 0                # initial stars
383         self.intorps = 0        # initial/max torpedoes
384         self.torps = 0                # number of torpedoes
385         self.ship = 0                # ship type -- 'E' is Enterprise
386         self.abandoned = 0        # count of crew abandoned in space
387         self.length = 0                # length of game
388         self.klhere = 0                # klingons here
389         self.casual = 0                # causalties
390         self.nhelp = 0                # calls for help
391         self.nkinks = 0                # count of energy-barrier crossings
392         self.iplnet = None        # planet # in quadrant
393         self.inplan = 0                # initial planets
394         self.irhere = 0                # Romulans in quadrant
395         self.isatb = 0                # =2 if super commander is attacking base
396         self.tourn = None        # tournament number
397         self.nprobes = 0        # number of probes available
398         self.inresor = 0.0        # initial resources
399         self.intime = 0.0        # initial time
400         self.inenrg = 0.0        # initial/max energy
401         self.inshld = 0.0        # initial/max shield
402         self.inlsr = 0.0        # initial life support resources
403         self.indate = 0.0        # initial date
404         self.energy = 0.0        # energy level
405         self.shield = 0.0        # shield level
406         self.warpfac = 0.0        # warp speed
407         self.lsupres = 0.0        # life support reserves
408         self.optime = 0.0        # time taken by current operation
409         self.damfac = 0.0        # damage factor
410         self.lastchart = 0.0        # time star chart was last updated
411         self.cryprob = 0.0        # probability that crystal will work
412         self.probe = None        # object holding probe course info
413         self.height = 0.0        # height of orbit around planet
414         self.score = 0.0        # overall score
415         self.perdate = 0.0        # rate of kills
416         self.idebug = False        # Debugging instrumentation enabled?
417         self.statekscmdr = None # No SuperCommander coordinates yet.
418         self.brigcapacity = 400     # Enterprise brig capacity
419         self.brigfree = 400       # How many klingons can we put in the brig?
420         self.kcaptured = 0      # Total Klingons captured, for scoring.
421         self.iscloaked = False  # Cloaking device on?
422         self.ncviol = 0         # Algreon treaty violations
423         self.isviolreported = False # We have been warned
424     def remkl(self):
425         return sum([q.klingons for (_i, _j, q) in list(self.state.traverse())])
426     def recompute(self):
427         # Stas thinks this should be (C expression):
428         # game.remkl() + len(game.state.kcmdr) > 0 ?
429         #        game.state.remres/(game.remkl() + 4*len(game.state.kcmdr)) : 99
430         # He says the existing expression is prone to divide-by-zero errors
431         # after killing the last klingon when score is shown -- perhaps also
432         # if the only remaining klingon is SCOM.
433         self.state.remtime = self.state.remres/(self.remkl() + 4*len(self.state.kcmdr))
434     def unwon(self):
435         "Are there Klingons remaining?"
436         return self.remkl() + len(self.state.kcmdr) + self.state.nscrem
437
438 FWON = 0
439 FDEPLETE = 1
440 FLIFESUP = 2
441 FNRG = 3
442 FBATTLE = 4
443 FNEG3 = 5
444 FNOVA = 6
445 FSNOVAED = 7
446 FABANDN = 8
447 FDILITHIUM = 9
448 FMATERIALIZE = 10
449 FPHASER = 11
450 FLOST = 12
451 FMINING = 13
452 FDPLANET = 14
453 FPNOVA = 15
454 FSSC = 16
455 FSTRACTOR = 17
456 FDRAY = 18
457 FTRIBBLE = 19
458 FHOLE = 20
459 FCREW = 21
460 FCLOAK = 22
461
462 def withprob(p):
463     return random.random() < p
464
465 def randrange(*args):
466     return random.randrange(*args)
467
468 def randreal(*args):
469     v = random.random()
470     if len(args) == 1:
471         v *= args[0]                 # from [0, args[0])
472     elif len(args) == 2:
473         v = args[0] + v*(args[1]-args[0])        # from [args[0], args[1])
474     return v
475
476 # Code from ai.c begins here
477
478 def welcoming(iq):
479     "Would this quadrant welcome another Klingon?"
480     return iq.valid_quadrant() and \
481         not game.state.galaxy[iq.i][iq.j].supernova and \
482         game.state.galaxy[iq.i][iq.j].klingons < MAXKLQUAD
483
484 def tryexit(enemy, look, irun):
485     "A bad guy attempts to bug out."
486     iq = Coord()
487     iq.i = game.quadrant.i+(look.i+(QUADSIZE-1))/QUADSIZE - 1
488     iq.j = game.quadrant.j+(look.j+(QUADSIZE-1))/QUADSIZE - 1
489     if not welcoming(iq):
490         return False
491     if enemy.type == 'R':
492         return False # Romulans cannot escape!
493     if not irun:
494         # avoid intruding on another commander's territory
495         if enemy.type == 'C':
496             if iq in game.state.kcmdr:
497                 return []
498             # refuse to leave if currently attacking starbase
499             if game.battle == game.quadrant:
500                 return []
501         # don't leave if over 1000 units of energy
502         if enemy.power > 1000.0:
503             return []
504     oldloc = copy.copy(enemy.location)
505     # handle local matters related to escape
506     enemy.move(None)
507     game.klhere -= 1
508     if game.condition != "docked":
509         newcnd()
510     # Handle global matters related to escape
511     game.state.galaxy[game.quadrant.i][game.quadrant.j].klingons -= 1
512     game.state.galaxy[iq.i][iq.j].klingons += 1
513     if enemy.type == 'S':
514         game.iscate = False
515         game.ientesc = False
516         game.isatb = 0
517         schedule(FSCMOVE, 0.2777)
518         unschedule(FSCDBAS)
519         game.state.kscmdr = iq
520     else:
521         for cmdr in game.state.kcmdr:
522             if cmdr == game.quadrant:
523                 game.state.kcmdr.append(iq)
524                 break
525     # report move out of quadrant.
526     return [(True, enemy, oldloc, iq)]
527
528 # The bad-guy movement algorithm:
529 #
530 # 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
531 # If both are operating full strength, force is 1000. If both are damaged,
532 # force is -1000. Having shields down subtracts an additional 1000.
533 #
534 # 2. Enemy has forces equal to the energy of the attacker plus
535 # 100*(K+R) + 500*(C+S) - 400 for novice through good levels OR
536 # 346*K + 400*R + 500*(C+S) - 400 for expert and emeritus.
537 #
538 # Attacker Initial energy levels (nominal):
539 # Klingon   Romulan   Commander   Super-Commander
540 # Novice    400        700        1200
541 # Fair      425        750        1250
542 # Good      450        800        1300        1750
543 # Expert    475        850        1350        1875
544 # Emeritus  500        900        1400        2000
545 # VARIANCE   75        200         200         200
546 #
547 # Enemy vessels only move prior to their attack. In Novice - Good games
548 # only commanders move. In Expert games, all enemy vessels move if there
549 # is a commander present. In Emeritus games all enemy vessels move.
550 #
551 # 3. If Enterprise is not docked, an aggressive action is taken if enemy
552 # forces are 1000 greater than Enterprise.
553 #
554 # Agressive action on average cuts the distance between the ship and
555 # the enemy to 1/4 the original.
556 #
557 # 4.  At lower energy advantage, movement units are proportional to the
558 # advantage with a 650 advantage being to hold ground, 800 to move forward
559 # 1, 950 for two, 150 for back 4, etc. Variance of 100.
560 #
561 # If docked, is reduced by roughly 1.75*game.skill, generally forcing a
562 # retreat, especially at high skill levels.
563 #
564 # 5.  Motion is limited to skill level, except for SC hi-tailing it out.
565
566 def movebaddy(enemy):
567     "Tactical movement for the bad guys."
568     goto = Coord()
569     look = Coord()
570     irun = False
571     # This should probably be just (game.quadrant in game.state.kcmdr) + (game.state.kscmdr==game.quadrant)
572     if game.skill >= SKILL_EXPERT:
573         nbaddys = (((game.quadrant in game.state.kcmdr)*2 + (game.state.kscmdr==game.quadrant)*2+game.klhere*1.23+game.irhere*1.5)/2.0)
574     else:
575         nbaddys = (game.quadrant in game.state.kcmdr) + (game.state.kscmdr==game.quadrant)
576     old_dist = enemy.kdist
577     mdist = int(old_dist + 0.5) # Nearest integer distance
578     # If SC, check with spy to see if should hi-tail it
579     if enemy.type == 'S' and \
580         (enemy.power <= 500.0 or (game.condition=="docked" and not damaged(DPHOTON))):
581         irun = True
582         motion = -QUADSIZE
583     else:
584         # decide whether to advance, retreat, or hold position
585         forces = enemy.power+100.0*len(game.enemies)+400*(nbaddys-1)
586         if not game.shldup:
587             forces += 1000 # Good for enemy if shield is down!
588         if not damaged(DPHASER) or not damaged(DPHOTON):
589             if damaged(DPHASER): # phasers damaged
590                 forces += 300.0
591             else:
592                 forces -= 0.2*(game.energy - 2500.0)
593             if damaged(DPHOTON): # photon torpedoes damaged
594                 forces += 300.0
595             else:
596                 forces -= 50.0*game.torps
597         else:
598             # phasers and photon tubes both out!
599             forces += 1000.0
600         motion = 0
601         if forces <= 1000.0 and game.condition != "docked": # Typical situation
602             motion = ((forces + randreal(200))/150.0) - 5.0
603         else:
604             if forces > 1000.0: # Very strong -- move in for kill
605                 motion = (1.0 - randreal())**2 * old_dist + 1.0
606             if game.condition == "docked" and (game.options & OPTION_BASE): # protected by base -- back off !
607                 motion -= game.skill*(2.0-randreal()**2)
608         if game.idebug:
609             proutn("=== MOTION = %d, FORCES = %1.2f, " % (motion, forces))
610         # don't move if no motion
611         if motion == 0:
612             return []
613         # Limit motion according to skill
614         if abs(motion) > game.skill:
615             if motion < 0:
616                 motion = -game.skill
617             else:
618                 motion = game.skill
619     # calculate preferred number of steps
620     nsteps = abs(int(motion))
621     if motion > 0 and nsteps > mdist:
622         nsteps = mdist # don't overshoot
623     if nsteps > QUADSIZE:
624         nsteps = QUADSIZE # This shouldn't be necessary
625     if nsteps < 1:
626         nsteps = 1 # This shouldn't be necessary
627     if game.idebug:
628         proutn("NSTEPS = %d:" % nsteps)
629     # Compute preferred values of delta X and Y
630     m = game.sector - enemy.location
631     if 2.0 * abs(m.i) < abs(m.j):
632         m.i = 0
633     if 2.0 * abs(m.j) < abs(game.sector.i-enemy.location.i):
634         m.j = 0
635     m = (motion * m).sgn()
636     goto = enemy.location
637     # main move loop
638     for ll in range(nsteps):
639         if game.idebug:
640             proutn(" %d" % (ll+1))
641         # Check if preferred position available
642         look = goto + m
643         if m.i < 0:
644             krawli = 1
645         else:
646             krawli = -1
647         if m.j < 0:
648             krawlj = 1
649         else:
650             krawlj = -1
651         success = False
652         attempts = 0 # Settle mysterious hang problem
653         while attempts < 20 and not success:
654             attempts += 1
655             if look.i < 0 or look.i >= QUADSIZE:
656                 if motion < 0:
657                     return tryexit(enemy, look, irun)
658                 if krawli == m.i or m.j == 0:
659                     break
660                 look.i = goto.i + krawli
661                 krawli = -krawli
662             elif look.j < 0 or look.j >= QUADSIZE:
663                 if motion < 0:
664                     return tryexit(enemy, look, irun)
665                 if krawlj == m.j or m.i == 0:
666                     break
667                 look.j = goto.j + krawlj
668                 krawlj = -krawlj
669             elif (game.options & OPTION_RAMMING) and game.quad[look.i][look.j] != '.':
670                 # See if enemy should ram ship
671                 if game.quad[look.i][look.j] == game.ship and \
672                     (enemy.type == 'C' or enemy.type == 'S'):
673                     collision(rammed=True, enemy=enemy)
674                     return []
675                 if krawli != m.i and m.j != 0:
676                     look.i = goto.i + krawli
677                     krawli = -krawli
678                 elif krawlj != m.j and m.i != 0:
679                     look.j = goto.j + krawlj
680                     krawlj = -krawlj
681                 else:
682                     break # we have failed
683             else:
684                 success = True
685         if success:
686             goto = look
687             if game.idebug:
688                 proutn(repr(goto))
689         else:
690             break # done early
691     if game.idebug:
692         skip(1)
693     # Enemy moved, but is still in sector
694     return [(False, enemy, old_dist, goto)]
695
696 def moveklings():
697     "Sequence Klingon tactical movement."
698     if game.idebug:
699         prout("== MOVCOM")
700     # Figure out which Klingon is the commander (or Supercommander)
701     # and do move
702     tacmoves = []
703     if game.quadrant in game.state.kcmdr:
704         for enemy in game.enemies:
705             if enemy.type == 'C':
706                 tacmoves += movebaddy(enemy)
707     if game.state.kscmdr == game.quadrant:
708         for enemy in game.enemies:
709             if enemy.type == 'S':
710                 tacmoves += movebaddy(enemy)
711                 break
712     # If skill level is high, move other Klingons and Romulans too!
713     # Move these last so they can base their actions on what the
714     # commander(s) do.
715     if game.skill >= SKILL_EXPERT and (game.options & OPTION_MVBADDY):
716         for enemy in game.enemies:
717             if enemy.type in ('K', 'R'):
718                 tacmoves += movebaddy(enemy)
719     return tacmoves
720
721 def movescom(iq, avoid):
722     "Supercommander movement helper."
723     # Avoid quadrants with bases if we want to avoid Enterprise
724     if not welcoming(iq) or (avoid and iq in game.state.baseq):
725         return False
726     if game.justin and not game.iscate:
727         return False
728     # do the move
729     game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].klingons -= 1
730     game.state.kscmdr = iq
731     game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].klingons += 1
732     if game.state.kscmdr == game.quadrant:
733         # SC has scooted, remove him from current quadrant
734         game.iscate = False
735         game.isatb = 0
736         game.ientesc = False
737         unschedule(FSCDBAS)
738         for enemy in game.enemies:
739             if enemy.type == 'S':
740                 enemy.move(None)
741         game.klhere -= 1
742         if game.condition != "docked":
743             newcnd()
744         sortenemies()
745     # check for a helpful planet
746     for i in range(game.inplan):
747         if game.state.planets[i].quadrant == game.state.kscmdr and \
748             game.state.planets[i].crystals == "present":
749             # destroy the planet
750             game.state.planets[i].pclass = "destroyed"
751             game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].planet = None
752             if communicating():
753                 announce()
754                 prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
755                 proutn(_("   a planet in Quadrant %s has been destroyed") % game.state.kscmdr)
756                 prout(_("   by the Super-commander.\""))
757             break
758     return True # looks good!
759
760 def supercommander():
761     "Move the Super Commander."
762     iq = Coord()
763     sc = Coord()
764     ibq = Coord()
765     idelta = Coord()
766     basetbl = []
767     if game.idebug:
768         prout("== SUPERCOMMANDER")
769     # Decide on being active or passive
770     avoid = ((game.incom - len(game.state.kcmdr) + game.inkling - game.remkl())/(game.state.date+0.01-game.indate) < 0.1*game.skill*(game.skill+1.0) or \
771             (game.state.date-game.indate) < 3.0)
772     if not game.iscate and avoid:
773         # compute move away from Enterprise
774         idelta = game.state.kscmdr-game.quadrant
775         if idelta.distance() > 2.0:
776             # circulate in space
777             idelta.i = game.state.kscmdr.j-game.quadrant.j
778             idelta.j = game.quadrant.i-game.state.kscmdr.i
779     else:
780         # compute distances to starbases
781         if not game.state.baseq:
782             # nothing left to do
783             unschedule(FSCMOVE)
784             return
785         sc = game.state.kscmdr
786         for (i, base) in enumerate(game.state.baseq):
787             basetbl.append((i, (base - sc).distance()))
788         if game.state.baseq > 1:
789             basetbl.sort(key=lambda x: x[1])
790         # look for nearest base without a commander, no Enterprise, and
791         # without too many Klingons, and not already under attack.
792         ifindit = iwhichb = 0
793         for (i2, base) in enumerate(game.state.baseq):
794             i = basetbl[i2][0]        # bug in original had it not finding nearest
795             if base == game.quadrant or base == game.battle or not welcoming(base):
796                 continue
797             # if there is a commander, and no other base is appropriate,
798             # we will take the one with the commander
799             for cmdr in game.state.kcmdr:
800                 if base == cmdr and ifindit != 2:
801                     ifindit = 2
802                     iwhichb = i
803                     break
804             else:        # no commander -- use this one
805                 ifindit = 1
806                 iwhichb = i
807                 break
808         if ifindit == 0:
809             return # Nothing suitable -- wait until next time
810         ibq = game.state.baseq[iwhichb]
811         # decide how to move toward base
812         idelta = ibq - game.state.kscmdr
813     # Maximum movement is 1 quadrant in either or both axes
814     idelta = idelta.sgn()
815     # try moving in both x and y directions
816     # there was what looked like a bug in the Almy C code here,
817     # but it might be this translation is just wrong.
818     iq = game.state.kscmdr + idelta
819     if not movescom(iq, avoid):
820         # failed -- try some other maneuvers
821         if idelta.i == 0 or idelta.j == 0:
822             # attempt angle move
823             if idelta.i != 0:
824                 iq.j = game.state.kscmdr.j + 1
825                 if not movescom(iq, avoid):
826                     iq.j = game.state.kscmdr.j - 1
827                     movescom(iq, avoid)
828             elif idelta.j != 0:
829                 iq.i = game.state.kscmdr.i + 1
830                 if not movescom(iq, avoid):
831                     iq.i = game.state.kscmdr.i - 1
832                     movescom(iq, avoid)
833         else:
834             # try moving just in x or y
835             iq.j = game.state.kscmdr.j
836             if not movescom(iq, avoid):
837                 iq.j = game.state.kscmdr.j + idelta.j
838                 iq.i = game.state.kscmdr.i
839                 movescom(iq, avoid)
840     # check for a base
841     if len(game.state.baseq) == 0:
842         unschedule(FSCMOVE)
843     else:
844         for ibq in game.state.baseq:
845             if ibq == game.state.kscmdr and game.state.kscmdr == game.battle:
846                 # attack the base
847                 if avoid:
848                     return # no, don't attack base!
849                 game.iseenit = False
850                 game.isatb = 1
851                 schedule(FSCDBAS, randreal(1.0, 3.0))
852                 if is_scheduled(FCDBAS):
853                     postpone(FSCDBAS, scheduled(FCDBAS)-game.state.date)
854                 if not communicating():
855                     return # no warning
856                 game.iseenit = True
857                 announce()
858                 prout(_("Lt. Uhura-  \"Captain, the starbase in Quadrant %s") \
859                       % game.state.kscmdr)
860                 prout(_("   reports that it is under attack from the Klingon Super-commander."))
861                 proutn(_("   It can survive until stardate %d.\"") \
862                        % int(scheduled(FSCDBAS)))
863                 if not game.resting:
864                     return
865                 prout(_("Mr. Spock-  \"Captain, shall we cancel the rest period?\""))
866                 if not ja():
867                     return
868                 game.resting = False
869                 game.optime = 0.0 # actually finished
870                 return
871     # Check for intelligence report
872     if not game.idebug and \
873         (withprob(0.8) or \
874          (not communicating()) or \
875          not game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].charted):
876         return
877     announce()
878     prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
879     proutn(_("   the Super-commander is in Quadrant %s,") % game.state.kscmdr)
880     return
881
882 def movetholian():
883     "Move the Tholian."
884     if not game.tholian or game.justin:
885         return
886     tid = Coord()
887     if game.tholian.location.i == 0 and game.tholian.location.j == 0:
888         tid.i = 0
889         tid.j = QUADSIZE-1
890     elif game.tholian.location.i == 0 and game.tholian.location.j == QUADSIZE-1:
891         tid.i = QUADSIZE-1
892         tid.j = QUADSIZE-1
893     elif game.tholian.location.i == QUADSIZE-1 and game.tholian.location.j == QUADSIZE-1:
894         tid.i = QUADSIZE-1
895         tid.j = 0
896     elif game.tholian.location.i == QUADSIZE-1 and game.tholian.location.j == 0:
897         tid.i = 0
898         tid.j = 0
899     else:
900         # something is wrong!
901         game.tholian.move(None)
902         prout("***Internal error: Tholian in a bad spot.")
903         return
904     # do nothing if we are blocked
905     if game.quad[tid.i][tid.j] not in ('.', '#'):
906         return
907     here = copy.copy(game.tholian.location)
908     delta = (tid - game.tholian.location).sgn()
909     # move in x axis
910     while here.i != tid.i:
911         here.i += delta.i
912         if game.quad[here.i][here.j] == '.':
913             game.tholian.move(here)
914     # move in y axis
915     while here.j != tid.j:
916         here.j += delta.j
917         if game.quad[here.i][here.j] == '.':
918             game.tholian.move(here)
919     # check to see if all holes plugged
920     for i in range(QUADSIZE):
921         if game.quad[0][i] != '#' and game.quad[0][i] != 'T':
922             return
923         if game.quad[QUADSIZE-1][i] != '#' and game.quad[QUADSIZE-1][i] != 'T':
924             return
925         if game.quad[i][0] != '#' and game.quad[i][0] != 'T':
926             return
927         if game.quad[i][QUADSIZE-1] != '#' and game.quad[i][QUADSIZE-1] != 'T':
928             return
929     # All plugged up -- Tholian splits
930     game.quad[game.tholian.location.i][game.tholian.location.j] = '#'
931     dropin(' ')
932     prout(crmena(True, 'T', "sector", game.tholian) + _(" completes web."))
933     game.tholian.move(None)
934     return
935
936 # Code from battle.c begins here
937
938 def cloak():
939     "Change cloaking-device status."
940     if game.ship == 'F':
941         prout(_("Ye Faerie Queene hath no cloaking device."));
942         return
943
944     key = scanner.nexttok()
945
946     if key == "IHREAL":
947         huh()
948         return
949
950     action = None
951     if key == "IHALPHA":
952         if scanner.sees("on"):
953             if game.iscloaked:
954                 prout(_("The cloaking device has already been switched on."))
955                 return
956             action = "CLON"
957         elif scanner.sees("off"):
958             if not game.iscloaked:
959                 prout(_("The cloaking device has already been switched off."))
960                 return
961             action = "CLOFF"
962         else:
963             huh()
964             return
965     else:
966         if not game.iscloaked:
967             proutn(_("Switch cloaking device on? "))
968             if not ja():
969                 return
970             action = "CLON"
971         else:
972             proutn(_("Switch cloaking device off? "))
973             if not ja():
974                 return
975             action = "CLOFF"
976     if action == None:
977         return;
978
979     if action == "CLOFF":
980         if game.irhere and game.state.date >= ALGERON and not game.isviolreported:
981             prout(_("Spock- \"Captain, the Treaty of Algeron is in effect.\n   Are you sure this is wise?\""))
982             if not ja():
983                 return;
984         prout("Engineer Scott- \"Aye, Sir.\"");
985         game.iscloaked = False;
986         if game.irhere and game.state.date >= ALGERON and not game.isviolreported:
987             prout(_("The Romulan ship discovers you are breaking the Treaty of Algeron!"))
988             game.ncviol += 1
989             game.isviolreported = True
990
991             #if (neutz and game.state.date >= ALGERON) finish(FCLOAK);
992             return;
993
994     if action == "CLON":
995         if damaged(DCLOAK):
996             prout(_("Engineer Scott- \"The cloaking device is damaged, Sir.\""))
997             return;
998
999         if game.condition == "docked":
1000             prout(_("You cannot cloak while docked."))
1001
1002         if game.state.date >= ALGERON and not game.isviolreported:
1003             prout(_("Spock- \"Captain, using the cloaking device is a violation"))
1004             prout(_("  of the Treaty of Algeron. Considering the alternatives,"))
1005             proutn(_("  are you sure this is wise? "))
1006             if not ja():
1007                 return
1008         prout(_("Engineer Scott- \"Cloaking device has engaging, Sir...\""))
1009         attack(True)
1010         prout(_("Engineer Scott- \"Cloaking device has engaged, Sir.\""))
1011         game.iscloaked = True
1012
1013         if game.irhere and game.state.date >= ALGERON and not game.isviolreported:
1014             prout(_("The Romulan ship discovers you are breaking the Treaty of Algeron!"))
1015             game.ncviol += 1
1016             game.isviolreported = True
1017
1018 def doshield(shraise):
1019     "Change shield status."
1020     action = "NONE"
1021     game.ididit = False
1022     if shraise:
1023         action = "SHUP"
1024     else:
1025         key = scanner.nexttok()
1026         if key == "IHALPHA":
1027             if scanner.sees("transfer"):
1028                 action = "NRG"
1029             else:
1030                 if damaged(DSHIELD):
1031                     prout(_("Shields damaged and down."))
1032                     return
1033                 if scanner.sees("up"):
1034                     action = "SHUP"
1035                 elif scanner.sees("down"):
1036                     action = "SHDN"
1037         if action == "NONE":
1038             proutn(_("Do you wish to change shield energy? "))
1039             if ja():
1040                 action = "NRG"
1041             elif damaged(DSHIELD):
1042                 prout(_("Shields damaged and down."))
1043                 return
1044             elif game.shldup:
1045                 proutn(_("Shields are up. Do you want them down? "))
1046                 if ja():
1047                     action = "SHDN"
1048                 else:
1049                     scanner.chew()
1050                     return
1051             else:
1052                 proutn(_("Shields are down. Do you want them up? "))
1053                 if ja():
1054                     action = "SHUP"
1055                 else:
1056                     scanner.chew()
1057                     return
1058     if action == "SHUP": # raise shields
1059         if game.shldup:
1060             prout(_("Shields already up."))
1061             return
1062         game.shldup = True
1063         game.shldchg = True
1064         if game.condition != "docked":
1065             game.energy -= 50.0
1066         prout(_("Shields raised."))
1067         if game.energy <= 0:
1068             skip(1)
1069             prout(_("Shields raising uses up last of energy."))
1070             finish(FNRG)
1071             return
1072         game.ididit = True
1073         return
1074     elif action == "SHDN":
1075         if not game.shldup:
1076             prout(_("Shields already down."))
1077             return
1078         game.shldup = False
1079         game.shldchg = True
1080         prout(_("Shields lowered."))
1081         game.ididit = True
1082         return
1083     elif action == "NRG":
1084         while scanner.nexttok() != "IHREAL":
1085             scanner.chew()
1086             proutn(_("Energy to transfer to shields- "))
1087         nrg = scanner.real
1088         scanner.chew()
1089         if nrg == 0:
1090             return
1091         if nrg > game.energy:
1092             prout(_("Insufficient ship energy."))
1093             return
1094         game.ididit = True
1095         if game.shield+nrg >= game.inshld:
1096             prout(_("Shield energy maximized."))
1097             if game.shield+nrg > game.inshld:
1098                 prout(_("Excess energy requested returned to ship energy"))
1099             game.energy -= game.inshld-game.shield
1100             game.shield = game.inshld
1101             return
1102         if nrg < 0.0 and game.energy-nrg > game.inenrg:
1103             # Prevent shield drain loophole
1104             skip(1)
1105             prout(_("Engineering to bridge--"))
1106             prout(_("  Scott here. Power circuit problem, Captain."))
1107             prout(_("  I can't drain the shields."))
1108             game.ididit = False
1109             return
1110         if game.shield+nrg < 0:
1111             prout(_("All shield energy transferred to ship."))
1112             game.energy += game.shield
1113             game.shield = 0.0
1114             return
1115         proutn(_("Scotty- \""))
1116         if nrg > 0:
1117             prout(_("Transferring energy to shields.\""))
1118         else:
1119             prout(_("Draining energy from shields.\""))
1120         game.shield += nrg
1121         game.energy -= nrg
1122         return
1123
1124 def randdevice():
1125     "Choose a device to damage, at random."
1126     weights = (
1127         105,       # DSRSENS: short range scanners         10.5%
1128         105,       # DLRSENS: long range scanners          10.5%
1129         120,       # DPHASER: phasers                      12.0%
1130         120,       # DPHOTON: photon torpedoes             12.0%
1131         25,        # DLIFSUP: life support                  2.5%
1132         65,        # DWARPEN: warp drive                    6.5%
1133         70,        # DIMPULS: impulse engines               6.5%
1134         135,       # DSHIELD: deflector shields            13.5%
1135         30,        # DRADIO:  subspace radio                3.0%
1136         45,        # DSHUTTL: shuttle                       4.5%
1137         15,        # DCOMPTR: computer                      1.5%
1138         20,        # NAVCOMP: navigation system             2.0%
1139         75,        # DTRANSP: transporter                   7.5%
1140         20,        # DSHCTRL: high-speed shield controller  2.0%
1141         10,        # DDRAY: death ray                       1.0%
1142         30,        # DDSP: deep-space probes                3.0%
1143         10,        # DCLOAK: the cloaking device            1.0
1144     )
1145     assert(sum(weights) == 1000)
1146     idx = randrange(1000)
1147     wsum = 0
1148     for (i, w) in enumerate(weights):
1149         wsum += w
1150         if idx < wsum:
1151             return i
1152     return None        # we should never get here
1153
1154 def collision(rammed, enemy):
1155     "Collision handling for rammong events."
1156     prouts(_("***RED ALERT!  RED ALERT!"))
1157     skip(1)
1158     prout(_("***COLLISION IMMINENT."))
1159     skip(2)
1160     proutn("***")
1161     proutn(crmshp())
1162     hardness = {'R':1.5, 'C':2.0, 'S':2.5, 'T':0.5, '?':4.0}.get(enemy.type, 1.0)
1163     if rammed:
1164         proutn(_(" rammed by "))
1165     else:
1166         proutn(_(" rams "))
1167     proutn(crmena(False, enemy.type, "sector", enemy.location))
1168     if rammed:
1169         proutn(_(" (original position)"))
1170     skip(1)
1171     deadkl(enemy.location, enemy.type, game.sector)
1172     proutn("***" + crmshp() + " heavily damaged.")
1173     icas = randrange(10, 30)
1174     prout(_("***Sickbay reports %d casualties") % icas)
1175     game.casual += icas
1176     game.state.crew -= icas
1177     # In the pre-SST2K version, all devices got equiprobably damaged,
1178     # which was silly.  Instead, pick up to half the devices at
1179     # random according to our weighting table,
1180     ncrits = randrange(NDEVICES/2)
1181     while ncrits > 0:
1182         ncrits -= 1
1183         dev = randdevice()
1184         if game.damage[dev] < 0:
1185             continue
1186         extradm = (10.0*hardness*randreal()+1.0)*game.damfac
1187         # Damage for at least time of travel!
1188         game.damage[dev] += game.optime + extradm
1189     game.shldup = False
1190     prout(_("***Shields are down."))
1191     if game.unwon():
1192         announce()
1193         damagereport()
1194     else:
1195         finish(FWON)
1196     return
1197
1198 def torpedo(origin, bearing, dispersion, number, nburst):
1199     "Let a photon torpedo fly"
1200     if not damaged(DSRSENS) or game.condition == "docked":
1201         setwnd(srscan_window)
1202     else:
1203         setwnd(message_window)
1204     ac = bearing + 0.25*dispersion        # dispersion is a random variable
1205     bullseye = (15.0 - bearing)*0.5235988
1206     track = course(bearing=ac, distance=QUADSIZE, origin=cartesian(origin))
1207     bumpto = Coord(0, 0)
1208     # Loop to move a single torpedo
1209     setwnd(message_window)
1210     for step in range(1, QUADSIZE*2):
1211         if not track.nexttok():
1212             break
1213         w = track.sector()
1214         if not w.valid_sector():
1215             break
1216         iquad = game.quad[w.i][w.j]
1217         tracktorpedo(w, step, number, nburst, iquad)
1218         if iquad == '.':
1219             continue
1220         # hit something
1221         setwnd(message_window)
1222         if not damaged(DSRSENS) or game.condition == "docked":
1223             skip(1)        # start new line after text track
1224         if iquad in ('E', 'F'): # Hit our ship
1225             skip(1)
1226             prout(_("Torpedo hits %s.") % crmshp())
1227             hit = 700.0 + randreal(100) - \
1228                 1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-track.angle))
1229             newcnd() # we're blown out of dock
1230             if game.landed or game.condition == "docked":
1231                 return hit # Cheat if on a planet
1232             # In the C/FORTRAN version, dispersion was 2.5 radians, which
1233             # is 143 degrees, which is almost exactly 4.8 clockface units
1234             displacement = course(track.bearing+randreal(-2.4, 2.4), distance=2**0.5)
1235             displacement.nexttok()
1236             bumpto = displacement.sector()
1237             if not bumpto.valid_sector():
1238                 return hit
1239             if game.quad[bumpto.i][bumpto.j] == ' ':
1240                 finish(FHOLE)
1241                 return hit
1242             if game.quad[bumpto.i][bumpto.j] != '.':
1243                 # can't move into object
1244                 return hit
1245             game.sector = bumpto
1246             proutn(crmshp())
1247             game.quad[w.i][w.j] = '.'
1248             game.quad[bumpto.i][bumpto.j] = iquad
1249             prout(_(" displaced by blast to Sector %s ") % bumpto)
1250             for enemy in game.enemies:
1251                 enemy.kdist = enemy.kavgd = (game.sector-enemy.location).distance()
1252             sortenemies()
1253             return None
1254         elif iquad in ('C', 'S', 'R', 'K'): # Hit a regular enemy
1255             # find the enemy
1256             if iquad in ('C', 'S') and withprob(0.05):
1257                 prout(crmena(True, iquad, "sector", w) + _(" uses anti-photon device;"))
1258                 prout(_("   torpedo neutralized."))
1259                 return None
1260             for enemy in game.enemies:
1261                 if w == enemy.location:
1262                     kp = math.fabs(enemy.power)
1263                     h1 = 700.0 + randrange(100) - \
1264                         1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-track.angle))
1265                     h1 = math.fabs(h1)
1266                     if kp < h1:
1267                         h1 = kp
1268                     if enemy.power < 0:
1269                         enemy.power -= -h1
1270                     else:
1271                         enemy.power -= h1
1272                     if enemy.power == 0:
1273                         deadkl(w, iquad, w)
1274                         return None
1275                     proutn(crmena(True, iquad, "sector", w))
1276                     displacement = course(track.bearing+randreal(-2.4, 2.4), distance=2**0.5)
1277                     displacement.nexttok()
1278                     bumpto = displacement.sector()
1279                     if not bumpto.valid_sector():
1280                         prout(_(" damaged but not destroyed."))
1281                         return
1282                     if game.quad[bumpto.i][bumpto.j] == ' ':
1283                         prout(_(" buffeted into black hole."))
1284                         deadkl(w, iquad, bumpto)
1285                     if game.quad[bumpto.i][bumpto.j] != '.':
1286                         prout(_(" damaged but not destroyed."))
1287                     else:
1288                         prout(_(" damaged-- displaced by blast to Sector %s ")%bumpto)
1289                         enemy.location = bumpto
1290                         game.quad[w.i][w.j] = '.'
1291                         game.quad[bumpto.i][bumpto.j] = iquad
1292                         for enemy in game.enemies:
1293                             enemy.kdist = enemy.kavgd = (game.sector-enemy.location).distance()
1294                         sortenemies()
1295                     break
1296             else:
1297                 prout("Internal error, no enemy where expected!")
1298                 raise SystemExit(1)
1299             return None
1300         elif iquad == 'B': # Hit a base
1301             skip(1)
1302             prout(_("***STARBASE DESTROYED.."))
1303             game.state.baseq = [x for x in game.state.baseq if x != game.quadrant]
1304             game.quad[w.i][w.j] = '.'
1305             game.base.invalidate()
1306             game.state.galaxy[game.quadrant.i][game.quadrant.j].starbase = False
1307             game.state.chart[game.quadrant.i][game.quadrant.j].starbase = False
1308             game.state.basekl += 1
1309             newcnd()
1310             return None
1311         elif iquad == 'P': # Hit a planet
1312             prout(crmena(True, iquad, "sector", w) + _(" destroyed."))
1313             game.state.nplankl += 1
1314             game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
1315             game.iplnet.pclass = "destroyed"
1316             game.iplnet = None
1317             game.plnet.invalidate()
1318             game.quad[w.i][w.j] = '.'
1319             if game.landed:
1320                 # captain perishes on planet
1321                 finish(FDPLANET)
1322             return None
1323         elif iquad == '@': # Hit an inhabited world -- very bad!
1324             prout(crmena(True, iquad, "sector", w) + _(" destroyed."))
1325             game.state.nworldkl += 1
1326             game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
1327             game.iplnet.pclass = "destroyed"
1328             game.iplnet = None
1329             game.plnet.invalidate()
1330             game.quad[w.i][w.j] = '.'
1331             if game.landed:
1332                 # captain perishes on planet
1333                 finish(FDPLANET)
1334             prout(_("The torpedo destroyed an inhabited planet."))
1335             return None
1336         elif iquad == '*': # Hit a star
1337             if withprob(0.9):
1338                 nova(w)
1339             else:
1340                 prout(crmena(True, '*', "sector", w) + _(" unaffected by photon blast."))
1341             return None
1342         elif iquad == '?': # Hit a thingy
1343             if not (game.options & OPTION_THINGY) or withprob(0.3):
1344                 skip(1)
1345                 prouts(_("AAAAIIIIEEEEEEEEAAAAAAAAUUUUUGGGGGHHHHHHHHHHHH!!!"))
1346                 skip(1)
1347                 prouts(_("    HACK!     HACK!    HACK!        *CHOKE!*  "))
1348                 skip(1)
1349                 proutn(_("Mr. Spock-"))
1350                 prouts(_("  \"Fascinating!\""))
1351                 skip(1)
1352                 deadkl(w, iquad, w)
1353             else:
1354                 # Stas Sergeev added the possibility that
1355                 # you can shove the Thingy and piss it off.
1356                 # It then becomes an enemy and may fire at you.
1357                 thing.angry()
1358             return None
1359         elif iquad == ' ': # Black hole
1360             skip(1)
1361             prout(crmena(True, ' ', "sector", w) + _(" swallows torpedo."))
1362             return None
1363         elif iquad == '#': # hit the web
1364             skip(1)
1365             prout(_("***Torpedo absorbed by Tholian web."))
1366             return None
1367         elif iquad == 'T':  # Hit a Tholian
1368             h1 = 700.0 + randrange(100) - \
1369                 1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-track.angle))
1370             h1 = math.fabs(h1)
1371             if h1 >= 600:
1372                 game.quad[w.i][w.j] = '.'
1373                 deadkl(w, iquad, w)
1374                 game.tholian = None
1375                 return None
1376             skip(1)
1377             proutn(crmena(True, 'T', "sector", w))
1378             if withprob(0.05):
1379                 prout(_(" survives photon blast."))
1380                 return None
1381             prout(_(" disappears."))
1382             game.tholian.move(None)
1383             game.quad[w.i][w.j] = '#'
1384             dropin(' ')
1385             return None
1386         else: # Problem!
1387             skip(1)
1388             proutn("Don't know how to handle torpedo collision with ")
1389             proutn(crmena(True, iquad, "sector", w))
1390             skip(1)
1391             return None
1392         break
1393     skip(1)
1394     setwnd(message_window)
1395     prout(_("Torpedo missed."))
1396     return None
1397
1398 def fry(hit):
1399     "Critical-hit resolution."
1400     if hit < (275.0-25.0*game.skill)*randreal(1.0, 1.5):
1401         return
1402     ncrit = int(1.0 + hit/(500.0+randreal(100)))
1403     proutn(_("***CRITICAL HIT--"))
1404     # Select devices and cause damage
1405     cdam = []
1406     while ncrit > 0:
1407         while True:
1408             j = randdevice()
1409             # Cheat to prevent shuttle damage unless on ship
1410             if not (game.damage[j]<0.0 or (j == DSHUTTL and game.iscraft != "onship") or (j == DCLOAK and game.ship != 'E' or j == DDRAY)):
1411                 break
1412         cdam.append(j)
1413         extradm = (hit*game.damfac)/(ncrit*randreal(75, 100))
1414         game.damage[j] += extradm
1415         ncrit -= 1
1416     skipcount = 0
1417     for (i, j) in enumerate(cdam):
1418         proutn(device[j])
1419         if skipcount % 3 == 2 and i < len(cdam)-1:
1420             skip(1)
1421         skipcount += 1
1422         if i < len(cdam)-1:
1423             proutn(_(" and "))
1424     prout(_(" damaged."))
1425     if damaged(DSHIELD) and game.shldup:
1426         prout(_("***Shields knocked down."))
1427         game.shldup = False
1428     if damaged(DCLOAK) and game.iscloaked:
1429         prout(_("***Cloaking device rendered inoperative."))
1430         game.iscloaked = False
1431
1432 def attack(torps_ok):
1433     # bad guy attacks us
1434     # torps_ok == False forces use of phasers in an attack
1435     if game.iscloaked:
1436         return
1437     # game could be over at this point, check
1438     if game.alldone:
1439         return
1440     attempt = False
1441     ihurt = False
1442     hitmax = 0.0
1443     hittot = 0.0
1444     chgfac = 1.0
1445     where = "neither"
1446     if game.idebug:
1447         prout("=== ATTACK!")
1448     # Tholian gets to move before attacking
1449     if game.tholian:
1450         movetholian()
1451     # if you have just entered the RNZ, you'll get a warning
1452     if game.neutz: # The one chance not to be attacked
1453         game.neutz = False
1454         return
1455     # commanders get a chance to tac-move towards you
1456     if (((game.quadrant in game.state.kcmdr or game.state.kscmdr == game.quadrant) and not game.justin) or game.skill == SKILL_EMERITUS) and torps_ok:
1457         for (bugout, enemy, old, goto) in  moveklings():
1458             if bugout:
1459                 # we know about this if either short or long range
1460                 # sensors are working
1461                 if damaged(DSRSENS) and damaged(DLRSENS) \
1462                        and game.condition != "docked":
1463                     prout(crmena(True, enemy.type, "sector", old) + \
1464                           (_(" escapes to Quadrant %s (and regains strength).") % goto))
1465             else: # Enemy still in-sector
1466                 if enemy.move(goto):
1467                     if not damaged(DSRSENS) or game.condition == "docked":
1468                         proutn(_("*** %s from Sector %s") % (cramen(enemy.type), enemy.location))
1469                         if enemy.kdist < old:
1470                             proutn(_(" advances to "))
1471                         else:
1472                             proutn(_(" retreats to "))
1473                         prout("Sector %s." % goto)
1474         sortenemies()
1475     # if no enemies remain after movement, we're done
1476     if len(game.enemies) == 0 or (len(game.enemies) == 1 and thing.at(game.quadrant) and not thing.angered):
1477         return
1478     # set up partial hits if attack happens during shield status change
1479     pfac = 1.0/game.inshld
1480     if game.shldchg:
1481         chgfac = 0.25 + randreal(0.5)
1482     skip(1)
1483     # message verbosity control
1484     if game.skill <= SKILL_FAIR:
1485         where = "sector"
1486     for enemy in game.enemies:
1487         if enemy.power < 0:
1488             continue        # too weak to attack
1489         # compute hit strength and diminish shield power
1490         r = randreal()
1491         # Increase chance of photon torpedos if docked or enemy energy is low
1492         if game.condition == "docked":
1493             r *= 0.25
1494         if enemy.power < 500:
1495             r *= 0.25
1496         if enemy.type == 'T' or (enemy.type == '?' and not thing.angered):
1497             continue
1498         # different enemies have different probabilities of throwing a torp
1499         usephasers = not torps_ok or \
1500             (enemy.type == 'K' and r > 0.0005) or \
1501             (enemy.type == 'C' and r > 0.015) or \
1502             (enemy.type == 'R' and r > 0.3) or \
1503             (enemy.type == 'S' and r > 0.07) or \
1504             (enemy.type == '?' and r > 0.05)
1505         if usephasers:            # Enemy uses phasers
1506             if game.condition == "docked":
1507                 continue # Don't waste the effort!
1508             attempt = True # Attempt to attack
1509             dustfac = randreal(0.8, 0.85)
1510             hit = enemy.power*math.pow(dustfac, enemy.kavgd)
1511             enemy.power *= 0.75
1512         else: # Enemy uses photon torpedo
1513             # We should be able to make the bearing() method work here
1514             pcourse = 1.90985*math.atan2(game.sector.j-enemy.location.j, enemy.location.i-game.sector.i)
1515             hit = 0
1516             proutn(_("***TORPEDO INCOMING"))
1517             if not damaged(DSRSENS):
1518                 proutn(_(" From ") + crmena(False, enemy.type, where, enemy.location))
1519             attempt = True
1520             prout("  ")
1521             dispersion = (randreal()+randreal())*0.5 - 0.5
1522             dispersion += 0.002*enemy.power*dispersion
1523             hit = torpedo(enemy.location, pcourse, dispersion, number=1, nburst=1)
1524             if game.unwon() == 0:
1525                 finish(FWON) # Klingons did themselves in!
1526             if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova or game.alldone:
1527                 return # Supernova or finished
1528             if hit is None:
1529                 continue
1530         # incoming phaser or torpedo, shields may dissipate it
1531         if game.shldup or game.shldchg or game.condition == "docked":
1532             # shields will take hits
1533             propor = pfac * game.shield
1534             if game.condition == "docked":
1535                 propor *= 2.1
1536             if propor < 0.1:
1537                 propor = 0.1
1538             hitsh = propor*chgfac*hit+1.0
1539             absorb = 0.8*hitsh
1540             if absorb > game.shield:
1541                 absorb = game.shield
1542             game.shield -= absorb
1543             hit -= hitsh
1544             # taking a hit blasts us out of a starbase dock
1545             if game.condition == "docked":
1546                 dock(False)
1547             # but the shields may take care of it
1548             if propor > 0.1 and hit < 0.005*game.energy:
1549                 continue
1550         # hit from this opponent got through shields, so take damage
1551         ihurt = True
1552         proutn(_("%d unit hit") % int(hit))
1553         if (damaged(DSRSENS) and usephasers) or game.skill<=SKILL_FAIR:
1554             proutn(_(" on the ") + crmshp())
1555         if not damaged(DSRSENS) and usephasers:
1556             prout(_(" from ") + crmena(False, enemy.type, where, enemy.location))
1557         skip(1)
1558         # Decide if hit is critical
1559         if hit > hitmax:
1560             hitmax = hit
1561         hittot += hit
1562         fry(hit)
1563         game.energy -= hit
1564     if game.energy <= 0:
1565         # Returning home upon your shield, not with it...
1566         finish(FBATTLE)
1567         return
1568     if not attempt and game.condition == "docked":
1569         prout(_("***Enemies decide against attacking your ship."))
1570     percent = 100.0*pfac*game.shield+0.5
1571     if not ihurt:
1572         # Shields fully protect ship
1573         proutn(_("Enemy attack reduces shield strength to "))
1574     else:
1575         # Emit message if starship suffered hit(s)
1576         skip(1)
1577         proutn(_("Energy left %2d    shields ") % int(game.energy))
1578         if game.shldup:
1579             proutn(_("up "))
1580         elif not damaged(DSHIELD):
1581             proutn(_("down "))
1582         else:
1583             proutn(_("damaged, "))
1584     prout(_("%d%%,   torpedoes left %d") % (percent, game.torps))
1585     # Check if anyone was hurt
1586     if hitmax >= 200 or hittot >= 500:
1587         icas = randrange(int(hittot * 0.015))
1588         if icas >= 2:
1589             skip(1)
1590             prout(_("Mc Coy-  \"Sickbay to bridge.  We suffered %d casualties") % icas)
1591             prout(_("   in that last attack.\""))
1592             game.casual += icas
1593             game.state.crew -= icas
1594     # After attack, reset average distance to enemies
1595     for enemy in game.enemies:
1596         enemy.kavgd = enemy.kdist
1597     sortenemies()
1598     return
1599
1600 def deadkl(w, etype, mv):
1601     "Kill a Klingon, Tholian, Romulan, or Thingy."
1602     # Added mv to allow enemy to "move" before dying
1603     proutn(crmena(True, etype, "sector", mv))
1604     # Decide what kind of enemy it is and update appropriately
1605     if etype == 'R':
1606         # Chalk up a Romulan
1607         game.state.galaxy[game.quadrant.i][game.quadrant.j].romulans -= 1
1608         game.irhere -= 1
1609         game.state.nromrem -= 1
1610     elif etype == 'T':
1611         # Killed a Tholian
1612         game.tholian = None
1613     elif etype == '?':
1614         # Killed a Thingy
1615         global thing
1616         thing = None
1617     else:
1618         # Killed some type of Klingon
1619         game.state.galaxy[game.quadrant.i][game.quadrant.j].klingons -= 1
1620         game.klhere -= 1
1621         if etype == 'C':
1622             game.state.kcmdr.remove(game.quadrant)
1623             unschedule(FTBEAM)
1624             if game.state.kcmdr:
1625                 schedule(FTBEAM, expran(1.0*game.incom/len(game.state.kcmdr)))
1626             if is_scheduled(FCDBAS) and game.battle == game.quadrant:
1627                 unschedule(FCDBAS)
1628         elif etype ==  'K':
1629             pass
1630         elif etype ==  'S':
1631             game.state.nscrem -= 1
1632             game.state.kscmdr.invalidate()
1633             game.isatb = 0
1634             game.iscate = False
1635             unschedule(FSCMOVE)
1636             unschedule(FSCDBAS)
1637     # For each kind of enemy, finish message to player
1638     prout(_(" destroyed."))
1639     if game.unwon() == 0:
1640         return
1641     game.recompute()
1642     # Remove enemy ship from arrays describing local conditions
1643     for e in game.enemies:
1644         if e.location == w:
1645             e.move(None)
1646             break
1647     return
1648
1649 def targetcheck(w):
1650     "Return None if target is invalid, otherwise return a course angle."
1651     if not w.valid_sector():
1652         huh()
1653         return None
1654     delta = Coord()
1655     # C code this was translated from is wacky -- why the sign reversal?
1656     delta.j = (w.j - game.sector.j)
1657     delta.i = (game.sector.i - w.i)
1658     if delta == Coord(0, 0):
1659         skip(1)
1660         prout(_("Spock-  \"Bridge to sickbay.  Dr. McCoy,"))
1661         prout(_("  I recommend an immediate review of"))
1662         prout(_("  the Captain's psychological profile.\""))
1663         scanner.chew()
1664         return None
1665     return delta.bearing()
1666
1667 def torps():
1668     "Launch photon torpedo salvo."
1669     tcourse = []
1670     game.ididit = False
1671     if damaged(DPHOTON):
1672         prout(_("Photon tubes damaged."))
1673         scanner.chew()
1674         return
1675     if game.torps == 0:
1676         prout(_("No torpedoes left."))
1677         scanner.chew()
1678         return
1679     # First, get torpedo count
1680     while True:
1681         scanner.nexttok()
1682         if scanner.token == "IHALPHA":
1683             huh()
1684             return
1685         elif scanner.token == "IHEOL" or not scanner.waiting():
1686             prout(_("%d torpedoes left.") % game.torps)
1687             scanner.chew()
1688             proutn(_("Number of torpedoes to fire- "))
1689             continue        # Go back around to get a number
1690         else: # key == "IHREAL"
1691             n = scanner.int()
1692             if n <= 0: # abort command
1693                 scanner.chew()
1694                 return
1695             if n > MAXBURST:
1696                 scanner.chew()
1697                 prout(_("Maximum of %d torpedoes per burst.") % MAXBURST)
1698                 return
1699             if n > game.torps:
1700                 scanner.chew()        # User requested more torps than available
1701                 continue        # Go back around
1702             break        # All is good, go to next stage
1703     # Next, get targets
1704     target = []
1705     for i in range(n):
1706         key = scanner.nexttok()
1707         if i == 0 and key == "IHEOL":
1708             break        # no coordinate waiting, we will try prompting
1709         if i == 1 and key == "IHEOL":
1710             # direct all torpedoes at one target
1711             while i < n:
1712                 target.append(target[0])
1713                 tcourse.append(tcourse[0])
1714                 i += 1
1715             break
1716         scanner.push(scanner.token)
1717         target.append(scanner.getcoord())
1718         if target[-1] is None:
1719             return
1720         tcourse.append(targetcheck(target[-1]))
1721         if tcourse[-1] is None:
1722             return
1723     scanner.chew()
1724     if len(target) == 0:
1725         # prompt for each one
1726         for i in range(n):
1727             proutn(_("Target sector for torpedo number %d- ") % (i+1))
1728             scanner.chew()
1729             target.append(scanner.getcoord())
1730             if target[-1] is None:
1731                 return
1732             tcourse.append(targetcheck(target[-1]))
1733             if tcourse[-1] is None:
1734                 return
1735     game.ididit = True
1736     # Loop for moving <n> torpedoes
1737     for i in range(n):
1738         if game.condition != "docked":
1739             game.torps -= 1
1740         dispersion = (randreal()+randreal())*0.5 -0.5
1741         if math.fabs(dispersion) >= 0.47:
1742             # misfire!
1743             dispersion *= randreal(1.2, 2.2)
1744             if n > 0:
1745                 prouts(_("***TORPEDO NUMBER %d MISFIRES") % (i+1))
1746             else:
1747                 prouts(_("***TORPEDO MISFIRES."))
1748             skip(1)
1749             if i < n:
1750                 prout(_("  Remainder of burst aborted."))
1751             if withprob(0.2):
1752                 prout(_("***Photon tubes damaged by misfire."))
1753                 game.damage[DPHOTON] = game.damfac * randreal(1.0, 3.0)
1754             break
1755         if game.iscloaked:
1756             dispersion *= 1.2
1757         elif game.shldup or game.condition == "docked":
1758             dispersion *= 1.0 + 0.0001*game.shield
1759         torpedo(game.sector, tcourse[i], dispersion, number=i, nburst=n)
1760         if game.alldone or game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
1761             return
1762     if game.unwon()<=0:
1763         finish(FWON)
1764
1765 def overheat(rpow):
1766     "Check for phasers overheating."
1767     if rpow > 1500:
1768         checkburn = (rpow-1500.0)*0.00038
1769         if withprob(checkburn):
1770             prout(_("Weapons officer Sulu-  \"Phasers overheated, sir.\""))
1771             game.damage[DPHASER] = game.damfac* randreal(1.0, 2.0) * (1.0+checkburn)
1772
1773 def checkshctrl(rpow):
1774     "Check shield control."
1775     skip(1)
1776     if withprob(0.998):
1777         prout(_("Shields lowered."))
1778         return False
1779     # Something bad has happened
1780     prouts(_("***RED ALERT!  RED ALERT!"))
1781     skip(2)
1782     hit = rpow*game.shield/game.inshld
1783     game.energy -= rpow+hit*0.8
1784     game.shield -= hit*0.2
1785     if game.energy <= 0.0:
1786         prouts(_("Sulu-  \"Captain! Shield malf***********************\""))
1787         skip(1)
1788         stars()
1789         finish(FPHASER)
1790         return True
1791     prouts(_("Sulu-  \"Captain! Shield malfunction! Phaser fire contained!\""))
1792     skip(2)
1793     prout(_("Lt. Uhura-  \"Sir, all decks reporting damage.\""))
1794     icas = randrange(int(hit*0.012))
1795     skip(1)
1796     fry(0.8*hit)
1797     if icas:
1798         skip(1)
1799         prout(_("McCoy to bridge- \"Severe radiation burns, Jim."))
1800         prout(_("  %d casualties so far.\"") % icas)
1801         game.casual += icas
1802         game.state.crew -= icas
1803     skip(1)
1804     prout(_("Phaser energy dispersed by shields."))
1805     prout(_("Enemy unaffected."))
1806     overheat(rpow)
1807     return True
1808
1809 def hittem(hits):
1810     "Register a phaser hit on Klingons and Romulans."
1811     w = Coord()
1812     skip(1)
1813     kk = 0
1814     for wham in hits:
1815         if wham == 0:
1816             continue
1817         dustfac = randreal(0.9, 1.0)
1818         hit = wham*math.pow(dustfac, game.enemies[kk].kdist)
1819         kpini = game.enemies[kk].power
1820         kp = math.fabs(kpini)
1821         if PHASEFAC*hit < kp:
1822             kp = PHASEFAC*hit
1823         if game.enemies[kk].power < 0:
1824             game.enemies[kk].power -= -kp
1825         else:
1826             game.enemies[kk].power -= kp
1827         kpow = game.enemies[kk].power
1828         w = game.enemies[kk].location
1829         if hit > 0.005:
1830             if not damaged(DSRSENS):
1831                 boom(w)
1832             proutn(_("%d unit hit on ") % int(hit))
1833         else:
1834             proutn(_("Very small hit on "))
1835         ienm = game.quad[w.i][w.j]
1836         if ienm == '?':
1837             thing.angry()
1838         proutn(crmena(False, ienm, "sector", w))
1839         skip(1)
1840         if kpow == 0:
1841             deadkl(w, ienm, w)
1842             if game.unwon()==0:
1843                 finish(FWON)
1844             if game.alldone:
1845                 return
1846             continue
1847         else: # decide whether or not to emasculate klingon
1848             if kpow > 0 and withprob(0.9) and kpow <= randreal(0.4, 0.8)*kpini:
1849                 prout(_("***Mr. Spock-  \"Captain, the vessel at Sector %s")%w)
1850                 prout(_("   has just lost its firepower.\""))
1851                 game.enemies[kk].power = -kpow
1852         kk += 1
1853     return
1854
1855 def phasers():
1856     "Fire phasers at bad guys."
1857     hits = []
1858     kz = 0
1859     k = 1
1860     irec = 0 # Cheating inhibitor
1861     ifast = False
1862     no = False
1863     itarg = True
1864     msgflag = True
1865     rpow = 0.0
1866     automode = "NOTSET"
1867     key = ""
1868     skip(1)
1869     # SR sensors and Computer are needed for automode
1870     if damaged(DSRSENS) or damaged(DCOMPTR):
1871         itarg = False
1872     if game.condition == "docked":
1873         prout(_("Phasers can't be fired through base shields."))
1874         scanner.chew()
1875         return
1876     if damaged(DPHASER):
1877         prout(_("Phaser control damaged."))
1878         scanner.chew()
1879         return
1880     if game.shldup:
1881         if damaged(DSHCTRL):
1882             prout(_("High speed shield control damaged."))
1883             scanner.chew()
1884             return
1885         if game.energy <= 200.0:
1886             prout(_("Insufficient energy to activate high-speed shield control."))
1887             scanner.chew()
1888             return
1889         prout(_("Weapons Officer Sulu-  \"High-speed shield control enabled, sir.\""))
1890         ifast = True
1891     # Original code so convoluted, I re-did it all
1892     # (That was Tom Almy talking about the C code, I think -- ESR)
1893     while automode == "NOTSET":
1894         key = scanner.nexttok()
1895         if key == "IHALPHA":
1896             if scanner.sees("manual"):
1897                 if len(game.enemies)==0:
1898                     prout(_("There is no enemy present to select."))
1899                     scanner.chew()
1900                     key = "IHEOL"
1901                     automode = "AUTOMATIC"
1902                 else:
1903                     automode = "MANUAL"
1904                     key = scanner.nexttok()
1905             elif scanner.sees("automatic"):
1906                 if (not itarg) and len(game.enemies) != 0:
1907                     automode = "FORCEMAN"
1908                 else:
1909                     if len(game.enemies)==0:
1910                         prout(_("Energy will be expended into space."))
1911                     automode = "AUTOMATIC"
1912                     key = scanner.nexttok()
1913             elif scanner.sees("no"):
1914                 no = True
1915             else:
1916                 huh()
1917                 return
1918         elif key == "IHREAL":
1919             if len(game.enemies)==0:
1920                 prout(_("Energy will be expended into space."))
1921                 automode = "AUTOMATIC"
1922             elif not itarg:
1923                 automode = "FORCEMAN"
1924             else:
1925                 automode = "AUTOMATIC"
1926         else:
1927             # "IHEOL"
1928             if len(game.enemies)==0:
1929                 prout(_("Energy will be expended into space."))
1930                 automode = "AUTOMATIC"
1931             elif not itarg:
1932                 automode = "FORCEMAN"
1933             else:
1934                 proutn(_("Manual or automatic? "))
1935                 scanner.chew()
1936     avail = game.energy
1937     if ifast:
1938         avail -= 200.0
1939     if automode == "AUTOMATIC":
1940         if key == "IHALPHA" and scanner.sees("no"):
1941             no = True
1942             key = scanner.nexttok()
1943         if key != "IHREAL" and len(game.enemies) != 0:
1944             prout(_("Phasers locked on target. Energy available: %.2f")%avail)
1945         irec = 0
1946         while True:
1947             scanner.chew()
1948             if not kz:
1949                 for i in range(len(game.enemies)):
1950                     irec += math.fabs(game.enemies[i].power)/(PHASEFAC*math.pow(0.90, game.enemies[i].kdist))*randreal(1.01, 1.06) + 1.0
1951             kz = 1
1952             proutn(_("%d units required. ") % irec)
1953             scanner.chew()
1954             proutn(_("Units to fire= "))
1955             key = scanner.nexttok()
1956             if key != "IHREAL":
1957                 return
1958             rpow = scanner.real
1959             if rpow > avail:
1960                 proutn(_("Energy available= %.2f") % avail)
1961                 skip(1)
1962                 key = "IHEOL"
1963             if not rpow > avail:
1964                 break
1965         if rpow <= 0:
1966             # chicken out
1967             scanner.chew()
1968             return
1969         key = scanner.nexttok()
1970         if key == "IHALPHA" and scanner.sees("no"):
1971             no = True
1972         if ifast:
1973             game.energy -= 200 # Go and do it!
1974             if checkshctrl(rpow):
1975                 return
1976         scanner.chew()
1977         game.energy -= rpow
1978         extra = rpow
1979         if len(game.enemies):
1980             extra = 0.0
1981             powrem = rpow
1982             for i in range(len(game.enemies)):
1983                 hits.append(0.0)
1984                 if powrem <= 0:
1985                     continue
1986                 hits[i] = math.fabs(game.enemies[i].power)/(PHASEFAC*math.pow(0.90, game.enemies[i].kdist))
1987                 over = randreal(1.01, 1.06) * hits[i]
1988                 temp = powrem
1989                 powrem -= hits[i] + over
1990                 if powrem <= 0 and temp < hits[i]:
1991                     hits[i] = temp
1992                 if powrem <= 0:
1993                     over = 0.0
1994                 extra += over
1995             if powrem > 0.0:
1996                 extra += powrem
1997             hittem(hits)
1998             game.ididit = True
1999         if extra > 0 and not game.alldone:
2000             if game.tholian:
2001                 proutn(_("*** Tholian web absorbs "))
2002                 if len(game.enemies)>0:
2003                     proutn(_("excess "))
2004                 prout(_("phaser energy."))
2005             else:
2006                 prout(_("%d expended on empty space.") % int(extra))
2007     elif automode == "FORCEMAN":
2008         scanner.chew()
2009         key = "IHEOL"
2010         if damaged(DCOMPTR):
2011             prout(_("Battle computer damaged, manual fire only."))
2012         else:
2013             skip(1)
2014             prouts(_("---WORKING---"))
2015             skip(1)
2016             prout(_("Short-range-sensors-damaged"))
2017             prout(_("Insufficient-data-for-automatic-phaser-fire"))
2018             prout(_("Manual-fire-must-be-used"))
2019             skip(1)
2020     elif automode == "MANUAL":
2021         rpow = 0.0
2022         for k in range(len(game.enemies)):
2023             aim = game.enemies[k].location
2024             ienm = game.quad[aim.i][aim.j]
2025             if msgflag:
2026                 proutn(_("Energy available= %.2f") % (avail-0.006))
2027                 skip(1)
2028                 msgflag = False
2029                 rpow = 0.0
2030             if damaged(DSRSENS) and \
2031                not game.sector.distance(aim)<2**0.5 and ienm in ('C', 'S'):
2032                 prout(cramen(ienm) + _(" can't be located without short range scan."))
2033                 scanner.chew()
2034                 key = "IHEOL"
2035                 hits[k] = 0 # prevent overflow -- thanks to Alexei Voitenko
2036                 k += 1
2037                 continue
2038             if key == "IHEOL":
2039                 scanner.chew()
2040                 if itarg and k > kz:
2041                     irec = (abs(game.enemies[k].power)/(PHASEFAC*math.pow(0.9, game.enemies[k].kdist))) *        randreal(1.01, 1.06) + 1.0
2042                 kz = k
2043                 proutn("(")
2044                 if not damaged(DCOMPTR):
2045                     proutn("%d" % irec)
2046                 else:
2047                     proutn("??")
2048                 proutn(")  ")
2049                 proutn(_("units to fire at %s-  ") % crmena(False, ienm, "sector", aim))
2050                 key = scanner.nexttok()
2051             if key == "IHALPHA" and scanner.sees("no"):
2052                 no = True
2053                 key = scanner.nexttok()
2054                 continue
2055             if key == "IHALPHA":
2056                 huh()
2057                 return
2058             if key == "IHEOL":
2059                 if k == 1: # Let me say I'm baffled by this
2060                     msgflag = True
2061                 continue
2062             if scanner.real < 0:
2063                 # abort out
2064                 scanner.chew()
2065                 return
2066             hits[k] = scanner.real
2067             rpow += scanner.real
2068             # If total requested is too much, inform and start over
2069             if rpow > avail:
2070                 prout(_("Available energy exceeded -- try again."))
2071                 scanner.chew()
2072                 return
2073             key = scanner.nexttok() # scan for next value
2074             k += 1
2075         if rpow == 0.0:
2076             # zero energy -- abort
2077             scanner.chew()
2078             return
2079         if key == "IHALPHA" and scanner.sees("no"):
2080             no = True
2081         game.energy -= rpow
2082         scanner.chew()
2083         if ifast:
2084             game.energy -= 200.0
2085             if checkshctrl(rpow):
2086                 return
2087         hittem(hits)
2088         game.ididit = True
2089      # Say shield raised or malfunction, if necessary
2090     if game.alldone:
2091         return
2092     if ifast:
2093         skip(1)
2094         if no == 0:
2095             if withprob(0.01):
2096                 prout(_("Sulu-  \"Sir, the high-speed shield control has malfunctioned . . ."))
2097                 prouts(_("         CLICK   CLICK   POP  . . ."))
2098                 prout(_(" No response, sir!"))
2099                 game.shldup = False
2100             else:
2101                 prout(_("Shields raised."))
2102         else:
2103             game.shldup = False
2104     overheat(rpow)
2105
2106
2107 def capture():
2108     game.ididit = False # Nothing if we fail
2109     game.optime = 0.0;
2110
2111     # Make sure there is room in the brig */
2112     if game.brigfree == 0:
2113         prout(_("Security reports the brig is already full."))
2114         return;
2115
2116     if damaged(DRADIO):
2117         prout(_("Uhura- \"We have no subspace radio communication, sir.\""))
2118         return
2119
2120     if damaged(DTRANSP):
2121         prout(_("Scotty- \"Transporter damaged, sir.\""))
2122         return
2123
2124     # find out if there are any at all
2125     if game.klhere < 1:
2126         prout(_("Uhura- \"Getting no response, sir.\""))
2127         return
2128
2129     # if there is more than one Klingon, find out which one */
2130     #   Cruddy, just takes one at random.  Should ask the captain.
2131     #   Nah, just select the weakest one since it is most likely to
2132     #   surrender (Tom Almy mod)
2133     klingons = [e for e in game.enemies if e.type == 'K']
2134     weakest = sorted(klingons, key=lambda e: e.power)[0]
2135     game.optime = 0.05          # This action will take some time
2136     game.ididit = True #  So any others can strike back
2137
2138     # check out that Klingon
2139     # The algorithm isn't that great and could use some more
2140     # intelligent design
2141     # x = 300 + 25*skill;
2142     x = game.energy / (weakest.power * len(klingons))
2143     #prout(_("Stats: energy = %s, kpower = %s, klingons = %s")
2144     #      % (game.energy, weakest.power, len(klingons))) 
2145     x *= 2.5  # would originally have been equivalent of 1.4,
2146                # but we want command to work more often, more humanely */
2147     #prout(_("Prob = %.4f" % x))
2148     #   x = 100; // For testing, of course!
2149     if x < randreal(100):
2150         # guess what, he surrendered!!! */
2151         prout(_("Klingon captain at %s surrenders.") % weakest.location)
2152         i = randreal(200)
2153         if i > 0:
2154             prout(_("%d Klingons commit suicide rather than be taken captive.") % (200 - i))
2155         if i > game.brigfree:
2156             prout(_("%d Klingons die because there is no room for them in the brig.") % (i-brigfree))
2157             i = game.brigfree
2158         game.brigfree -= i
2159         prout(_("%d captives taken") % i)
2160         deadkl(weakest.location, weakest.type, game.sector)
2161         if game.unwon()<=0:
2162             finish(FWON)
2163         return
2164
2165         # big surprise, he refuses to surrender */
2166     prout(_("Fat chance, captain!"))
2167
2168 # Code from events.c begins here.
2169
2170 # This isn't a real event queue a la BSD Trek yet -- you can only have one
2171 # event of each type active at any given time.  Mostly these means we can
2172 # only have one FDISTR/FENSLV/FREPRO sequence going at any given time
2173 # BSD Trek, from which we swiped the idea, can have up to 5.
2174
2175 def unschedule(evtype):
2176     "Remove an event from the schedule."
2177     game.future[evtype].date = FOREVER
2178     return game.future[evtype]
2179
2180 def is_scheduled(evtype):
2181     "Is an event of specified type scheduled."
2182     return game.future[evtype].date != FOREVER
2183
2184 def scheduled(evtype):
2185     "When will this event happen?"
2186     return game.future[evtype].date
2187
2188 def schedule(evtype, offset):
2189     "Schedule an event of specified type."
2190     game.future[evtype].date = game.state.date + offset
2191     return game.future[evtype]
2192
2193 def postpone(evtype, offset):
2194     "Postpone a scheduled event."
2195     game.future[evtype].date += offset
2196
2197 def cancelrest():
2198     "Rest period is interrupted by event."
2199     if game.resting:
2200         skip(1)
2201         proutn(_("Mr. Spock-  \"Captain, shall we cancel the rest period?\""))
2202         if ja():
2203             game.resting = False
2204             game.optime = 0.0
2205             return True
2206     return False
2207
2208 def events():
2209     "Run through the event queue looking for things to do."
2210     i = 0
2211     fintim = game.state.date + game.optime
2212     yank = 0
2213     ictbeam = False
2214     istract = False
2215     w = Coord()
2216     hold = Coord()
2217     ev = Event()
2218     ev2 = Event()
2219
2220     def tractorbeam(yank):
2221         "Tractor-beaming cases merge here."
2222         announce()
2223         game.optime = (10.0/(7.5*7.5))*yank # 7.5 is yank rate (warp 7.5)
2224         skip(1)
2225         prout("***" + crmshp() + _(" caught in long range tractor beam--"))
2226         # If Kirk & Co. screwing around on planet, handle
2227         atover(True) # atover(true) is Grab
2228         if game.alldone:
2229             return
2230         if game.icraft: # Caught in Galileo?
2231             finish(FSTRACTOR)
2232             return
2233         # Check to see if shuttle is aboard
2234         if game.iscraft == "offship":
2235             skip(1)
2236             if withprob(0.5):
2237                 prout(_("Galileo, left on the planet surface, is captured"))
2238                 prout(_("by aliens and made into a flying McDonald's."))
2239                 game.damage[DSHUTTL] = -10
2240                 game.iscraft = "removed"
2241             else:
2242                 prout(_("Galileo, left on the planet surface, is well hidden."))
2243         if evcode == FSPY:
2244             game.quadrant = game.state.kscmdr
2245         else:
2246             game.quadrant = game.state.kcmdr[i]
2247         game.sector = randplace(QUADSIZE)
2248         prout(crmshp() + _(" is pulled to Quadrant %s, Sector %s") \
2249                % (game.quadrant, game.sector))
2250         if game.resting:
2251             prout(_("(Remainder of rest/repair period cancelled.)"))
2252             game.resting = False
2253         if not game.shldup:
2254             if not damaged(DSHIELD) and game.shield > 0:
2255                 doshield(shraise=True) # raise shields
2256                 game.shldchg = False
2257             else:
2258                 prout(_("(Shields not currently useable.)"))
2259         newqad()
2260         # Adjust finish time to time of tractor beaming?
2261         # fintim = game.state.date+game.optime
2262         attack(torps_ok=False)
2263         if not game.state.kcmdr:
2264             unschedule(FTBEAM)
2265         else:
2266             schedule(FTBEAM, game.optime+expran(1.5*game.intime/len(game.state.kcmdr)))
2267
2268     def destroybase():
2269         "Code merges here for any commander destroying a starbase."
2270         # Not perfect, but will have to do
2271         # Handle case where base is in same quadrant as starship
2272         if game.battle == game.quadrant:
2273             game.state.chart[game.battle.i][game.battle.j].starbase = False
2274             game.quad[game.base.i][game.base.j] = '.'
2275             game.base.invalidate()
2276             newcnd()
2277             skip(1)
2278             prout(_("Spock-  \"Captain, I believe the starbase has been destroyed.\""))
2279         elif game.state.baseq and communicating():
2280             # Get word via subspace radio
2281             announce()
2282             skip(1)
2283             prout(_("Lt. Uhura-  \"Captain, Starfleet Command reports that"))
2284             proutn(_("   the starbase in Quadrant %s has been destroyed by") % game.battle)
2285             if game.isatb == 2:
2286                 prout(_("the Klingon Super-Commander"))
2287             else:
2288                 prout(_("a Klingon Commander"))
2289             game.state.chart[game.battle.i][game.battle.j].starbase = False
2290         # Remove Starbase from galaxy
2291         game.state.galaxy[game.battle.i][game.battle.j].starbase = False
2292         game.state.baseq = [x for x in game.state.baseq if x != game.battle]
2293         if game.isatb == 2:
2294             # reinstate a commander's base attack
2295             game.battle = hold
2296             game.isatb = 0
2297         else:
2298             game.battle.invalidate()
2299     if game.idebug:
2300         prout("=== EVENTS from %.2f to %.2f:" % (game.state.date, fintim))
2301         for i in range(1, NEVENTS):
2302             if   i == FSNOVA:  proutn("=== Supernova       ")
2303             elif i == FTBEAM:  proutn("=== T Beam          ")
2304             elif i == FSNAP:   proutn("=== Snapshot        ")
2305             elif i == FBATTAK: proutn("=== Base Attack     ")
2306             elif i == FCDBAS:  proutn("=== Base Destroy    ")
2307             elif i == FSCMOVE: proutn("=== SC Move         ")
2308             elif i == FSCDBAS: proutn("=== SC Base Destroy ")
2309             elif i == FDSPROB: proutn("=== Probe Move      ")
2310             elif i == FDISTR:  proutn("=== Distress Call   ")
2311             elif i == FENSLV:  proutn("=== Enslavement     ")
2312             elif i == FREPRO:  proutn("=== Klingon Build   ")
2313             if is_scheduled(i):
2314                 prout("%.2f" % (scheduled(i)))
2315             else:
2316                 prout("never")
2317     radio_was_broken = damaged(DRADIO)
2318     hold.i = hold.j = 0
2319     while True:
2320         # Select earliest extraneous event, evcode==0 if no events
2321         evcode = FSPY
2322         if game.alldone:
2323             return
2324         datemin = fintim
2325         for l in range(1, NEVENTS):
2326             if game.future[l].date < datemin:
2327                 evcode = l
2328                 if game.idebug:
2329                     prout("== Event %d fires" % evcode)
2330                 datemin = game.future[l].date
2331         xtime = datemin-game.state.date
2332         if game.iscloaked:
2333             game.energy -= xtime*500.0
2334             if game.energy <= 0:
2335                 finish(FNRG)
2336                 return
2337         game.state.date = datemin
2338         # Decrement Federation resources and recompute remaining time
2339         game.state.remres -= (game.remkl()+4*len(game.state.kcmdr))*xtime
2340         game.recompute()
2341         if game.state.remtime <= 0:
2342             finish(FDEPLETE)
2343             return
2344         # Any crew left alive?
2345         if game.state.crew <= 0:
2346             finish(FCREW)
2347             return
2348         # Is life support adequate?
2349         if damaged(DLIFSUP) and game.condition != "docked":
2350             if game.lsupres < xtime and game.damage[DLIFSUP] > game.lsupres:
2351                 finish(FLIFESUP)
2352                 return
2353             game.lsupres -= xtime
2354             if game.damage[DLIFSUP] <= xtime:
2355                 game.lsupres = game.inlsr
2356         # Fix devices
2357         repair = xtime
2358         if game.condition == "docked":
2359             repair /= DOCKFAC
2360         # Don't fix Deathray here
2361         for l in range(NDEVICES):
2362             if game.damage[l] > 0.0 and l != DDRAY:
2363                 if game.damage[l]-repair > 0.0:
2364                     game.damage[l] -= repair
2365                 else:
2366                     game.damage[l] = 0.0
2367         # If radio repaired, update star chart and attack reports
2368         if radio_was_broken and not damaged(DRADIO):
2369             prout(_("Lt. Uhura- \"Captain, the sub-space radio is working and"))
2370             prout(_("   surveillance reports are coming in."))
2371             skip(1)
2372             if not game.iseenit:
2373                 attackreport(False)
2374                 game.iseenit = True
2375             rechart()
2376             prout(_("   The star chart is now up to date.\""))
2377             skip(1)
2378         # Cause extraneous event EVCODE to occur
2379         game.optime -= xtime
2380         if evcode == FSNOVA: # Supernova
2381             announce()
2382             supernova(None)
2383             schedule(FSNOVA, expran(0.5*game.intime))
2384             if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
2385                 return
2386         elif evcode == FSPY: # Check with spy to see if SC should tractor beam
2387             if game.state.nscrem == 0 or game.iscloaked or \
2388                 ictbeam or istract or \
2389                 game.condition == "docked" or game.isatb == 1 or game.iscate:
2390                 return
2391             if game.ientesc or \
2392                 (game.energy<2000 and game.torps<4 and game.shield < 1250) or \
2393                 (damaged(DPHASER) and (damaged(DPHOTON) or game.torps<4)) or \
2394                 (damaged(DSHIELD) and \
2395                  (game.energy < 2500 or damaged(DPHASER)) and \
2396                  (game.torps < 5 or damaged(DPHOTON))):
2397                 # Tractor-beam her!
2398                 istract = ictbeam = True
2399                 tractorbeam((game.state.kscmdr-game.quadrant).distance())
2400             else:
2401                 return
2402         elif evcode == FTBEAM: # Tractor beam
2403             if not game.state.kcmdr:
2404                 unschedule(FTBEAM)
2405                 continue
2406             i = randrange(len(game.state.kcmdr))
2407             yank = (game.state.kcmdr[i]-game.quadrant).distance()
2408             if istract or game.condition == "docked" or game.iscloaked or yank == 0:
2409                 # Drats! Have to reschedule
2410                 schedule(FTBEAM,
2411                          game.optime + expran(1.5*game.intime/len(game.state.kcmdr)))
2412                 continue
2413             ictbeam = True
2414             tractorbeam(yank)
2415         elif evcode == FSNAP: # Snapshot of the universe (for time warp)
2416             game.snapsht = copy.deepcopy(game.state)
2417             game.state.snap = True
2418             schedule(FSNAP, expran(0.5 * game.intime))
2419         elif evcode == FBATTAK: # Commander attacks starbase
2420             if not game.state.kcmdr or not game.state.baseq:
2421                 # no can do
2422                 unschedule(FBATTAK)
2423                 unschedule(FCDBAS)
2424                 continue
2425             ibq = None  # Force battle location to persist past loop
2426             try:
2427                 for ibq in game.state.baseq:
2428                     for cmdr in game.state.kcmdr:
2429                         if ibq == cmdr and ibq != game.quadrant and ibq != game.state.kscmdr:
2430                             raise JumpOut
2431                 # no match found -- try later
2432                 schedule(FBATTAK, expran(0.3*game.intime))
2433                 unschedule(FCDBAS)
2434                 continue
2435             except JumpOut:
2436                 pass
2437             # commander + starbase combination found -- launch attack
2438             game.battle = ibq
2439             schedule(FCDBAS, randreal(1.0, 4.0))
2440             if game.isatb: # extra time if SC already attacking
2441                 postpone(FCDBAS, scheduled(FSCDBAS)-game.state.date)
2442             game.future[FBATTAK].date = game.future[FCDBAS].date + expran(0.3*game.intime)
2443             game.iseenit = False
2444             if not communicating():
2445                 continue # No warning :-(
2446             game.iseenit = True
2447             announce()
2448             skip(1)
2449             prout(_("Lt. Uhura-  \"Captain, the starbase in Quadrant %s") % game.battle)
2450             prout(_("   reports that it is under attack and that it can"))
2451             prout(_("   hold out only until stardate %d.\"") % (int(scheduled(FCDBAS))))
2452             if cancelrest():
2453                 return
2454         elif evcode == FSCDBAS: # Supercommander destroys base
2455             unschedule(FSCDBAS)
2456             game.isatb = 2
2457             if not game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].starbase:
2458                 continue # WAS RETURN!
2459             hold = game.battle
2460             game.battle = game.state.kscmdr
2461             destroybase()
2462         elif evcode == FCDBAS: # Commander succeeds in destroying base
2463             if evcode == FCDBAS:
2464                 unschedule(FCDBAS)
2465                 if not game.state.baseq() \
2466                        or not game.state.galaxy[game.battle.i][game.battle.j].starbase:
2467                     game.battle.invalidate()
2468                     continue
2469                 # find the lucky pair
2470                 for cmdr in game.state.kcmdr:
2471                     if cmdr == game.battle:
2472                         break
2473                 else:
2474                     # No action to take after all
2475                     continue
2476             destroybase()
2477         elif evcode == FSCMOVE: # Supercommander moves
2478             schedule(FSCMOVE, 0.2777)
2479             if not game.ientesc and not istract and game.isatb != 1 and \
2480                    (not game.iscate or not game.justin):
2481                 supercommander()
2482         elif evcode == FDSPROB: # Move deep space probe
2483             schedule(FDSPROB, 0.01)
2484             if not game.probe.nexttok():
2485                 if not game.probe.quadrant().valid_quadrant() or \
2486                     game.state.galaxy[game.probe.quadrant().i][game.probe.quadrant().j].supernova:
2487                     # Left galaxy or ran into supernova
2488                     if communicating():
2489                         announce()
2490                         skip(1)
2491                         proutn(_("Lt. Uhura-  \"The deep space probe "))
2492                         if not game.probe.quadrant().valid_quadrant():
2493                             prout(_("has left the galaxy.\""))
2494                         else:
2495                             prout(_("is no longer transmitting.\""))
2496                     unschedule(FDSPROB)
2497                     continue
2498                 if communicating():
2499                     #announce()
2500                     skip(1)
2501                     prout(_("Lt. Uhura-  \"The deep space probe is now in Quadrant %s.\"") % game.probe.quadrant())
2502             pquad = game.probe.quadrant()
2503             pdest = game.state.galaxy[pquad.i][pquad.j]
2504             if communicating():
2505                 game.state.chart[pquad.i][pquad.j].klingons = pdest.klingons
2506                 game.state.chart[pquad.i][pquad.j].starbase = pdest.starbase
2507                 game.state.chart[pquad.i][pquad.j].stars = pdest.stars
2508                 pdest.charted = True
2509             game.probe.moves -= 1 # One less to travel
2510             if game.probe.arrived() and game.isarmed and pdest.stars:
2511                 supernova(game.probe)                # fire in the hole!
2512                 unschedule(FDSPROB)
2513                 if game.state.galaxy[pquad.i][pquad.j].supernova:
2514                     return
2515         elif evcode == FDISTR: # inhabited system issues distress call
2516             unschedule(FDISTR)
2517             # try a whole bunch of times to find something suitable
2518             for i in range(100):
2519                 # need a quadrant which is not the current one,
2520                 # which has some stars which are inhabited and
2521                 # not already under attack, which is not
2522                 # supernova'ed, and which has some Klingons in it
2523                 w = randplace(GALSIZE)
2524                 q = game.state.galaxy[w.i][w.j]
2525                 if not (game.quadrant == w or q.planet is None or \
2526                       not q.planet.inhabited or \
2527                       q.supernova or q.status!="secure" or q.klingons<=0):
2528                     break
2529             else:
2530                 # can't seem to find one; ignore this call
2531                 if game.idebug:
2532                     prout("=== Couldn't find location for distress event.")
2533                 continue
2534             # got one!!  Schedule its enslavement
2535             ev = schedule(FENSLV, expran(game.intime))
2536             ev.quadrant = w
2537             q.status = "distressed"
2538             # tell the captain about it if we can
2539             if communicating():
2540                 prout(_("Uhura- Captain, %s in Quadrant %s reports it is under attack") \
2541                         % (q.planet, repr(w)))
2542                 prout(_("by a Klingon invasion fleet."))
2543                 if cancelrest():
2544                     return
2545         elif evcode == FENSLV:                # starsystem is enslaved
2546             ev = unschedule(FENSLV)
2547             # see if current distress call still active
2548             q = game.state.galaxy[ev.quadrant.i][ev.quadrant.j]
2549             if q.klingons <= 0:
2550                 q.status = "secure"
2551                 continue
2552             q.status = "enslaved"
2553
2554             # play stork and schedule the first baby
2555             ev2 = schedule(FREPRO, expran(2.0 * game.intime))
2556             ev2.quadrant = ev.quadrant
2557
2558             # report the disaster if we can
2559             if communicating():
2560                 prout(_("Uhura- We've lost contact with starsystem %s") % \
2561                         q.planet)
2562                 prout(_("in Quadrant %s.\n") % ev.quadrant)
2563         elif evcode == FREPRO:                # Klingon reproduces
2564             # If we ever switch to a real event queue, we'll need to
2565             # explicitly retrieve and restore the x and y.
2566             ev = schedule(FREPRO, expran(1.0 * game.intime))
2567             # see if current distress call still active
2568             q = game.state.galaxy[ev.quadrant.i][ev.quadrant.j]
2569             if q.klingons <= 0:
2570                 q.status = "secure"
2571                 continue
2572             if game.remkl() >= MAXKLGAME:
2573                 continue                # full right now
2574             # reproduce one Klingon
2575             w = ev.quadrant
2576             m = Coord()
2577             if game.klhere >= MAXKLQUAD:
2578                 try:
2579                     # this quadrant not ok, pick an adjacent one
2580                     for m.i in range(w.i - 1, w.i + 2):
2581                         for m.j in range(w.j - 1, w.j + 2):
2582                             if not m.valid_quadrant():
2583                                 continue
2584                             q = game.state.galaxy[m.i][m.j]
2585                             # check for this quad ok (not full & no snova)
2586                             if q.klingons >= MAXKLQUAD or q.supernova:
2587                                 continue
2588                             raise JumpOut
2589                     # search for eligible quadrant failed
2590                     continue
2591                 except JumpOut:
2592                     w = m
2593             # deliver the child
2594             q.klingons += 1
2595             if game.quadrant == w:
2596                 game.klhere += 1
2597                 game.enemies.append(newkling())
2598             # recompute time left
2599             game.recompute()
2600             if communicating():
2601                 if game.quadrant == w:
2602                     prout(_("Spock- sensors indicate the Klingons have"))
2603                     prout(_("launched a warship from %s.") % q.planet)
2604                 else:
2605                     prout(_("Uhura- Starfleet reports increased Klingon activity"))
2606                     if q.planet != None:
2607                         proutn(_("near %s ") % q.planet)
2608                     prout(_("in Quadrant %s.") % w)
2609
2610 def wait():
2611     "Wait on events."
2612     game.ididit = False
2613     while True:
2614         key = scanner.nexttok()
2615         if key  != "IHEOL":
2616             break
2617         proutn(_("How long? "))
2618         scanner.chew()
2619     if key != "IHREAL":
2620         huh()
2621         return
2622     origTime = delay = scanner.real
2623     if delay <= 0.0:
2624         return
2625     if delay >= game.state.remtime or len(game.enemies) != 0:
2626         proutn(_("Are you sure? "))
2627         if not ja():
2628             return
2629     # Alternate resting periods (events) with attacks
2630     game.resting = True
2631     while True:
2632         if delay <= 0:
2633             game.resting = False
2634         if not game.resting:
2635             prout(_("%d stardates left.") % int(game.state.remtime))
2636             return
2637         temp = game.optime = delay
2638         if len(game.enemies):
2639             rtime = randreal(1.0, 2.0)
2640             if rtime < temp:
2641                 temp = rtime
2642             game.optime = temp
2643         if game.optime < delay:
2644             attack(torps_ok=False)
2645         if game.alldone:
2646             return
2647         events()
2648         game.ididit = True
2649         if game.alldone:
2650             return
2651         delay -= temp
2652         # Repair Deathray if long rest at starbase
2653         if origTime-delay >= 9.99 and game.condition == "docked":
2654             game.damage[DDRAY] = 0.0
2655         # leave if quadrant supernovas
2656         if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
2657             break
2658     game.resting = False
2659     game.optime = 0.0
2660
2661 def nova(nov):
2662     "Star goes nova."
2663     ncourse = (0.0, 10.5, 12.0, 1.5, 9.0, 0.0, 3.0, 7.5, 6.0, 4.5)
2664     newc = Coord(); neighbor = Coord(); bump = Coord(0, 0)
2665     if withprob(0.05):
2666         # Wow! We've supernova'ed
2667         supernova(game.quadrant)
2668         return
2669     # handle initial nova
2670     game.quad[nov.i][nov.j] = '.'
2671     prout(crmena(False, '*', "sector", nov) + _(" novas."))
2672     game.state.galaxy[game.quadrant.i][game.quadrant.j].stars -= 1
2673     game.state.starkl += 1
2674     # Set up queue to recursively trigger adjacent stars
2675     hits = [nov]
2676     kount = 0
2677     while hits:
2678         offset = Coord()
2679         start = hits.pop()
2680         for offset.i in range(-1, 1+1):
2681             for offset.j in range(-1, 1+1):
2682                 if offset.j == 0 and offset.i == 0:
2683                     continue
2684                 neighbor = start + offset
2685                 if not neighbor.valid_sector():
2686                     continue
2687                 iquad = game.quad[neighbor.i][neighbor.j]
2688                 # Empty space ends reaction
2689                 if iquad in ('.', '?', ' ', 'T', '#'):
2690                     pass
2691                 elif iquad == '*': # Affect another star
2692                     if withprob(0.05):
2693                         # This star supernovas
2694                         supernova(game.quadrant)
2695                         return
2696                     else:
2697                         hits.append(neighbor)
2698                         game.state.galaxy[game.quadrant.i][game.quadrant.j].stars -= 1
2699                         game.state.starkl += 1
2700                         proutn(crmena(True, '*', "sector", neighbor))
2701                         prout(_(" novas."))
2702                         game.quad[neighbor.i][neighbor.j] = '.'
2703                         kount += 1
2704                 elif iquad in ('P', '@'): # Destroy planet
2705                     game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
2706                     if iquad == 'P':
2707                         game.state.nplankl += 1
2708                     else:
2709                         game.state.nworldkl += 1
2710                     prout(crmena(True, 'B', "sector", neighbor) + _(" destroyed."))
2711                     game.iplnet.pclass = "destroyed"
2712                     game.iplnet = None
2713                     game.plnet.invalidate()
2714                     if game.landed:
2715                         finish(FPNOVA)
2716                         return
2717                     game.quad[neighbor.i][neighbor.j] = '.'
2718                 elif iquad == 'B': # Destroy base
2719                     game.state.galaxy[game.quadrant.i][game.quadrant.j].starbase = False
2720                     game.state.baseq = [x for x in game.state.baseq if x!= game.quadrant]
2721                     game.base.invalidate()
2722                     game.state.basekl += 1
2723                     newcnd()
2724                     prout(crmena(True, 'B', "sector", neighbor) + _(" destroyed."))
2725                     game.quad[neighbor.i][neighbor.j] = '.'
2726                 elif iquad in ('E', 'F'): # Buffet ship
2727                     prout(_("***Starship buffeted by nova."))
2728                     if game.shldup:
2729                         if game.shield >= 2000.0:
2730                             game.shield -= 2000.0
2731                         else:
2732                             diff = 2000.0 - game.shield
2733                             game.energy -= diff
2734                             game.shield = 0.0
2735                             game.shldup = False
2736                             prout(_("***Shields knocked out."))
2737                             game.damage[DSHIELD] += 0.005*game.damfac*randreal()*diff
2738                     else:
2739                         game.energy -= 2000.0
2740                     if game.energy <= 0:
2741                         finish(FNOVA)
2742                         return
2743                     # add in course nova contributes to kicking starship
2744                     bump += (game.sector-hits[-1]).sgn()
2745                 elif iquad == 'K': # kill klingon
2746                     deadkl(neighbor, iquad, neighbor)
2747                 elif iquad in ('C','S','R'): # Damage/destroy big enemies
2748                     target = None
2749                     for ll in range(len(game.enemies)):
2750                         if game.enemies[ll].location == neighbor:
2751                             target = game.enemies[ll]
2752                             break
2753                     if target is not None:
2754                         target.power -= 800.0 # If firepower is lost, die
2755                         if target.power <= 0.0:
2756                             deadkl(neighbor, iquad, neighbor)
2757                             continue    # neighbor loop
2758                         # Else enemy gets flung by the blast wave
2759                         newc = neighbor + neighbor - start
2760                         proutn(crmena(True, iquad, "sector", neighbor) + _(" damaged"))
2761                         if not newc.valid_sector():
2762                             # can't leave quadrant
2763                             skip(1)
2764                             continue
2765                         iquad1 = game.quad[newc.i][newc.j]
2766                         if iquad1 == ' ':
2767                             proutn(_(", blasted into ") + crmena(False, ' ', "sector", newc))
2768                             skip(1)
2769                             deadkl(neighbor, iquad, newc)
2770                             continue
2771                         if iquad1 != '.':
2772                             # can't move into something else
2773                             skip(1)
2774                             continue
2775                         proutn(_(", buffeted to Sector %s") % newc)
2776                         game.quad[neighbor.i][neighbor.j] = '.'
2777                         game.quad[newc.i][newc.j] = iquad
2778                         target.move(newc)
2779     # Starship affected by nova -- kick it away.
2780     dist = kount*0.1
2781     direc = ncourse[3*(bump.i+1)+bump.j+2]
2782     if direc == 0.0:
2783         dist = 0.0
2784     if dist == 0.0:
2785         return
2786     scourse = course(bearing=direc, distance=dist)
2787     game.optime = scourse.time(w=4)
2788     skip(1)
2789     prout(_("Force of nova displaces starship."))
2790     imove(scourse, noattack=True)
2791     game.optime = scourse.time(w=4)
2792     return
2793
2794 def supernova(w):
2795     "Star goes supernova."
2796     num = 0; npdead = 0
2797     if w != None:
2798         nq = copy.copy(w)
2799     else:
2800         # Scheduled supernova -- select star at random.
2801         nstars = 0
2802         nq = Coord()
2803         for nq.i in range(GALSIZE):
2804             for nq.j in range(GALSIZE):
2805                 nstars += game.state.galaxy[nq.i][nq.j].stars
2806         if stars == 0:
2807             return # nothing to supernova exists
2808         num = randrange(nstars) + 1
2809         for nq.i in range(GALSIZE):
2810             for nq.j in range(GALSIZE):
2811                 num -= game.state.galaxy[nq.i][nq.j].stars
2812                 if num <= 0:
2813                     break
2814             if num <=0:
2815                 break
2816         if game.idebug:
2817             proutn("=== Super nova here?")
2818             if ja():
2819                 nq = game.quadrant
2820     if not nq == game.quadrant or game.justin:
2821         # it isn't here, or we just entered (treat as enroute)
2822         if communicating():
2823             skip(1)
2824             prout(_("Message from Starfleet Command       Stardate %.2f") % game.state.date)
2825             prout(_("     Supernova in Quadrant %s; caution advised.") % nq)
2826     else:
2827         ns = Coord()
2828         # we are in the quadrant!
2829         num = randrange(game.state.galaxy[nq.i][nq.j].stars) + 1
2830         for ns.i in range(QUADSIZE):
2831             for ns.j in range(QUADSIZE):
2832                 if game.quad[ns.i][ns.j]=='*':
2833                     num -= 1
2834                     if num==0:
2835                         break
2836             if num==0:
2837                 break
2838         skip(1)
2839         prouts(_("***RED ALERT!  RED ALERT!"))
2840         skip(1)
2841         prout(_("***Incipient supernova detected at Sector %s") % ns)
2842         if (ns.i-game.sector.i)**2 + (ns.j-game.sector.j)**2 <= 2.1:
2843             proutn(_("Emergency override attempts t"))
2844             prouts("***************")
2845             skip(1)
2846             stars()
2847             game.alldone = True
2848     # destroy any Klingons in supernovaed quadrant
2849     game.state.galaxy[nq.i][nq.j].klingons = 0
2850     if nq == game.state.kscmdr:
2851         # did in the Supercommander!
2852         game.state.nscrem = game.state.kscmdr.i = game.state.kscmdr.j = game.isatb =  0
2853         game.iscate = False
2854         unschedule(FSCMOVE)
2855         unschedule(FSCDBAS)
2856     survivors = filter(lambda w: w != nq, game.state.kcmdr)
2857     comkills = len(game.state.kcmdr) - len(survivors)
2858     game.state.kcmdr = survivors
2859     if not game.state.kcmdr:
2860         unschedule(FTBEAM)
2861     # destroy Romulans and planets in supernovaed quadrant
2862     nrmdead = game.state.galaxy[nq.i][nq.j].romulans
2863     game.state.galaxy[nq.i][nq.j].romulans = 0
2864     game.state.nromrem -= nrmdead
2865     # Destroy planets
2866     for loop in range(game.inplan):
2867         if game.state.planets[loop].quadrant == nq:
2868             game.state.planets[loop].pclass = "destroyed"
2869             npdead += 1
2870     # Destroy any base in supernovaed quadrant
2871     game.state.baseq = [x for x in game.state.baseq if x != nq]
2872     # If starship caused supernova, tally up destruction
2873     if w != None:
2874         game.state.starkl += game.state.galaxy[nq.i][nq.j].stars
2875         game.state.basekl += game.state.galaxy[nq.i][nq.j].starbase
2876         game.state.nplankl += npdead
2877     # mark supernova in galaxy and in star chart
2878     if game.quadrant == nq or communicating():
2879         game.state.galaxy[nq.i][nq.j].supernova = True
2880     # If supernova destroys last Klingons give special message
2881     if game.unwon()==0 and not nq == game.quadrant:
2882         skip(2)
2883         if w is None:
2884             prout(_("Lucky you!"))
2885         proutn(_("A supernova in %s has just destroyed the last Klingons.") % nq)
2886         finish(FWON)
2887         return
2888     # if some Klingons remain, continue or die in supernova
2889     if game.alldone:
2890         finish(FSNOVAED)
2891     return
2892
2893 # Code from finish.c ends here.
2894
2895 def selfdestruct():
2896     "Self-destruct maneuver. Finish with a BANG!"
2897     scanner.chew()
2898     if damaged(DCOMPTR):
2899         prout(_("Computer damaged; cannot execute destruct sequence."))
2900         return
2901     prouts(_("---WORKING---")); skip(1)
2902     prouts(_("SELF-DESTRUCT-SEQUENCE-ACTIVATED")); skip(1)
2903     prouts("   10"); skip(1)
2904     prouts("       9"); skip(1)
2905     prouts("          8"); skip(1)
2906     prouts("             7"); skip(1)
2907     prouts("                6"); skip(1)
2908     skip(1)
2909     prout(_("ENTER-CORRECT-PASSWORD-TO-CONTINUE-"))
2910     skip(1)
2911     prout(_("SELF-DESTRUCT-SEQUENCE-OTHERWISE-"))
2912     skip(1)
2913     prout(_("SELF-DESTRUCT-SEQUENCE-WILL-BE-ABORTED"))
2914     skip(1)
2915     scanner.nexttok()
2916     if game.passwd != scanner.token:
2917         prouts(_("PASSWORD-REJECTED;"))
2918         skip(1)
2919         prouts(_("CONTINUITY-EFFECTED"))
2920         skip(2)
2921         return
2922     prouts(_("PASSWORD-ACCEPTED")); skip(1)
2923     prouts("                   5"); skip(1)
2924     prouts("                      4"); skip(1)
2925     prouts("                         3"); skip(1)
2926     prouts("                            2"); skip(1)
2927     prouts("                              1"); skip(1)
2928     if withprob(0.15):
2929         prouts(_("GOODBYE-CRUEL-WORLD"))
2930         skip(1)
2931     kaboom()
2932
2933 def kaboom():
2934     stars()
2935     if game.ship=='E':
2936         prouts("***")
2937     prouts(_("********* Entropy of %s maximized *********") % crmshp())
2938     skip(1)
2939     stars()
2940     skip(1)
2941     if len(game.enemies) != 0:
2942         whammo = 25.0 * game.energy
2943         for l in range(len(game.enemies)):
2944             if game.enemies[l].power*game.enemies[l].kdist <= whammo:
2945                 deadkl(game.enemies[l].location, game.quad[game.enemies[l].location.i][game.enemies[l].location.j], game.enemies[l].location)
2946     finish(FDILITHIUM)
2947
2948 def killrate():
2949     "Compute our rate of kils over time."
2950     elapsed = game.state.date - game.indate
2951     if elapsed == 0:        # Avoid divide-by-zero error if calculated on turn 0
2952         return 0
2953     else:
2954         starting = (game.inkling + game.incom + game.inscom)
2955         remaining = game.unwon()
2956         return (starting - remaining)/elapsed
2957
2958 def badpoints():
2959     "Compute demerits."
2960     badpt = 5.0*game.state.starkl + \
2961             game.casual + \
2962             10.0*game.state.nplankl + \
2963             300*game.state.nworldkl + \
2964             45.0*game.nhelp +\
2965             100.0*game.state.basekl +\
2966             3.0*game.abandoned +\
2967             100*game.ncviol
2968     if game.ship == 'F':
2969         badpt += 100.0
2970     elif game.ship is None:
2971         badpt += 200.0
2972     return badpt
2973
2974 def finish(ifin):
2975     # end the game, with appropriate notifications
2976     igotit = False
2977     game.alldone = True
2978     skip(3)
2979     prout(_("It is stardate %.1f.") % game.state.date)
2980     skip(1)
2981     if ifin == FWON: # Game has been won
2982         if game.state.nromrem != 0:
2983             prout(_("The remaining %d Romulans surrender to Starfleet Command.") %
2984                   game.state.nromrem)
2985
2986         prout(_("You have smashed the Klingon invasion fleet and saved"))
2987         prout(_("the Federation."))
2988         if game.alive and game.brigcapacity-game.brigfree > 0:
2989             game.kcaptured += game.brigcapacity-game.brigfree
2990             prout(_("The %d captured Klingons are transferred to Star Fleet Command.") % (game.brigcapacity-game.brigfree))
2991         game.gamewon = True
2992         if game.alive:
2993             badpt = badpoints()
2994             if badpt < 100.0:
2995                 badpt = 0.0        # Close enough!
2996             # killsPerDate >= RateMax
2997             if game.state.date-game.indate < 5.0 or \
2998                 killrate() >= 0.1*game.skill*(game.skill+1.0) + 0.1 + 0.008*badpt:
2999                 skip(1)
3000                 prout(_("In fact, you have done so well that Starfleet Command"))
3001                 if game.skill == SKILL_NOVICE:
3002                     prout(_("promotes you one step in rank from \"Novice\" to \"Fair\"."))
3003                 elif game.skill == SKILL_FAIR:
3004                     prout(_("promotes you one step in rank from \"Fair\" to \"Good\"."))
3005                 elif game.skill == SKILL_GOOD:
3006                     prout(_("promotes you one step in rank from \"Good\" to \"Expert\"."))
3007                 elif game.skill == SKILL_EXPERT:
3008                     prout(_("promotes you to Commodore Emeritus."))
3009                     skip(1)
3010                     prout(_("Now that you think you're really good, try playing"))
3011                     prout(_("the \"Emeritus\" game. It will splatter your ego."))
3012                 elif game.skill == SKILL_EMERITUS:
3013                     skip(1)
3014                     proutn(_("Computer-  "))
3015                     prouts(_("ERROR-ERROR-ERROR-ERROR"))
3016                     skip(2)
3017                     prouts(_("  YOUR-SKILL-HAS-EXCEEDED-THE-CAPACITY-OF-THIS-PROGRAM"))
3018                     skip(1)
3019                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3020                     skip(1)
3021                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3022                     skip(1)
3023                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3024                     skip(1)
3025                     prouts(_("  THIS-PROGRAM-MUST?- MUST ? - SUR? ? -?  VI"))
3026                     skip(2)
3027                     prout(_("Now you can retire and write your own Star Trek game!"))
3028                     skip(1)
3029                 elif game.skill >= SKILL_EXPERT:
3030                     if game.thawed and not game.idebug:
3031                         prout(_("You cannot get a citation, so..."))
3032                     else:
3033                         proutn(_("Do you want your Commodore Emeritus Citation printed? "))
3034                         scanner.chew()
3035                         if ja():
3036                             igotit = True
3037             # Only grant long life if alive (original didn't!)
3038             skip(1)
3039             prout(_("LIVE LONG AND PROSPER."))
3040         score()
3041         if igotit:
3042             plaque()
3043         return
3044     elif ifin == FDEPLETE: # Federation Resources Depleted
3045         prout(_("Your time has run out and the Federation has been"))
3046         prout(_("conquered.  Your starship is now Klingon property,"))
3047         prout(_("and you are put on trial as a war criminal.  On the"))
3048         proutn(_("basis of your record, you are "))
3049         if game.unwon()*3.0 > (game.inkling + game.incom + game.inscom):
3050             prout(_("acquitted."))
3051             skip(1)
3052             prout(_("LIVE LONG AND PROSPER."))
3053         else:
3054             prout(_("found guilty and"))
3055             prout(_("sentenced to death by slow torture."))
3056             game.alive = False
3057         score()
3058         return
3059     elif ifin == FLIFESUP:
3060         prout(_("Your life support reserves have run out, and"))
3061         prout(_("you die of thirst, starvation, and asphyxiation."))
3062         prout(_("Your starship is a derelict in space."))
3063     elif ifin == FNRG:
3064         prout(_("Your energy supply is exhausted."))
3065         skip(1)
3066         prout(_("Your starship is a derelict in space."))
3067     elif ifin == FBATTLE:
3068         prout(_("The %s has been destroyed in battle.") % crmshp())
3069         skip(1)
3070         prout(_("Dulce et decorum est pro patria mori."))
3071     elif ifin == FNEG3:
3072         prout(_("You have made three attempts to cross the negative energy"))
3073         prout(_("barrier which surrounds the galaxy."))
3074         skip(1)
3075         prout(_("Your navigation is abominable."))
3076         score()
3077     elif ifin == FNOVA:
3078         prout(_("Your starship has been destroyed by a nova."))
3079         prout(_("That was a great shot."))
3080         skip(1)
3081     elif ifin == FSNOVAED:
3082         prout(_("The %s has been fried by a supernova.") % crmshp())
3083         prout(_("...Not even cinders remain..."))
3084     elif ifin == FABANDN:
3085         prout(_("You have been captured by the Klingons. If you still"))
3086         prout(_("had a starbase to be returned to, you would have been"))
3087         prout(_("repatriated and given another chance. Since you have"))
3088         prout(_("no starbases, you will be mercilessly tortured to death."))
3089     elif ifin == FDILITHIUM:
3090         prout(_("Your starship is now an expanding cloud of subatomic particles"))
3091     elif ifin == FMATERIALIZE:
3092         prout(_("Starbase was unable to re-materialize your starship."))
3093         prout(_("Sic transit gloria mundi"))
3094     elif ifin == FPHASER:
3095         prout(_("The %s has been cremated by its own phasers.") % crmshp())
3096     elif ifin == FLOST:
3097         prout(_("You and your landing party have been"))
3098         prout(_("converted to energy, dissipating through space."))
3099     elif ifin == FMINING:
3100         prout(_("You are left with your landing party on"))
3101         prout(_("a wild jungle planet inhabited by primitive cannibals."))
3102         skip(1)
3103         prout(_("They are very fond of \"Captain Kirk\" soup."))
3104         skip(1)
3105         prout(_("Without your leadership, the %s is destroyed.") % crmshp())
3106     elif ifin == FDPLANET:
3107         prout(_("You and your mining party perish."))
3108         skip(1)
3109         prout(_("That was a great shot."))
3110         skip(1)
3111     elif ifin == FSSC:
3112         prout(_("The Galileo is instantly annihilated by the supernova."))
3113         prout(_("You and your mining party are atomized."))
3114         skip(1)
3115         prout(_("Mr. Spock takes command of the %s and") % crmshp())
3116         prout(_("joins the Romulans, wreaking terror on the Federation."))
3117     elif ifin == FPNOVA:
3118         prout(_("You and your mining party are atomized."))
3119         skip(1)
3120         prout(_("Mr. Spock takes command of the %s and") % crmshp())
3121         prout(_("joins the Romulans, wreaking terror on the Federation."))
3122     elif ifin == FSTRACTOR:
3123         prout(_("The shuttle craft Galileo is also caught,"))
3124         prout(_("and breaks up under the strain."))
3125         skip(1)
3126         prout(_("Your debris is scattered for millions of miles."))
3127         prout(_("Without your leadership, the %s is destroyed.") % crmshp())
3128     elif ifin == FDRAY:
3129         prout(_("The mutants attack and kill Spock."))
3130         prout(_("Your ship is captured by Klingons, and"))
3131         prout(_("your crew is put on display in a Klingon zoo."))
3132     elif ifin == FTRIBBLE:
3133         prout(_("Tribbles consume all remaining water,"))
3134         prout(_("food, and oxygen on your ship."))
3135         skip(1)
3136         prout(_("You die of thirst, starvation, and asphyxiation."))
3137         prout(_("Your starship is a derelict in space."))
3138     elif ifin == FHOLE:
3139         prout(_("Your ship is drawn to the center of the black hole."))
3140         prout(_("You are crushed into extremely dense matter."))
3141     elif ifin == FCLOAK:
3142         game.ncviol += 1
3143         prout(_("You have violated the Treaty of Algeron."))
3144         prout(_("The Romulan Empire can never trust you again."))
3145     elif ifin == FCREW:
3146         prout(_("Your last crew member has died."))
3147     if ifin != FWON and ifin != FCLOAK and game.iscloaked:
3148         prout(_("Your ship was cloaked so your subspace radio did not receive anything."))
3149         prout(_("You may have missed some warning messages."))
3150         skip(1)
3151     if game.ship == 'F':
3152         game.ship = None
3153     elif game.ship == 'E':
3154         game.ship = 'F'
3155     game.alive = False
3156     if game.unwon() != 0:
3157         goodies = game.state.remres/game.inresor
3158         baddies = (game.remkl() + 2.0*len(game.state.kcmdr))/(game.inkling+2.0*game.incom)
3159         if goodies/baddies >= randreal(1.0, 1.5):
3160             prout(_("As a result of your actions, a treaty with the Klingon"))
3161             prout(_("Empire has been signed. The terms of the treaty are"))
3162             if goodies/baddies >= randreal(3.0):
3163                 prout(_("favorable to the Federation."))
3164                 skip(1)
3165                 prout(_("Congratulations!"))
3166             else:
3167                 prout(_("highly unfavorable to the Federation."))
3168         else:
3169             prout(_("The Federation will be destroyed."))
3170     else:
3171         prout(_("Since you took the last Klingon with you, you are a"))
3172         prout(_("martyr and a hero. Someday maybe they'll erect a"))
3173         prout(_("statue in your memory. Rest in peace, and try not"))
3174         prout(_("to think about pigeons."))
3175         game.gamewon = True
3176     score()
3177     scanner.chew()      # Clean up leftovers
3178
3179 def score():
3180     "Compute player's score."
3181     timused = game.state.date - game.indate
3182     if (timused == 0 or game.unwon() != 0) and timused < 5.0:
3183         timused = 5.0
3184     game.perdate = killrate()
3185     ithperd = 500*game.perdate + 0.5
3186     iwon = 0
3187     if game.gamewon:
3188         iwon = 100*game.skill
3189     if game.ship == 'E':
3190         klship = 0
3191     elif game.ship == 'F':
3192         klship = 1
3193     else:
3194         klship = 2
3195     game.score = 10*(game.inkling - game.remkl()) \
3196              + 50*(game.incom - len(game.state.kcmdr)) \
3197              + ithperd + iwon \
3198              + 20*(game.inrom - game.state.nromrem) \
3199              + 200*(game.inscom - game.state.nscrem) \
3200                  - game.state.nromrem \
3201              + 3 * game.kcaptured \
3202              - badpoints()
3203     if not game.alive:
3204         game.score -= 200
3205     skip(2)
3206     prout(_("Your score --"))
3207     if game.inrom - game.state.nromrem:
3208         prout(_("%6d Romulans destroyed                 %5d") %
3209               (game.inrom - game.state.nromrem, 20*(game.inrom - game.state.nromrem)))
3210     if game.state.nromrem and game.gamewon:
3211         prout(_("%6d Romulans captured                  %5d") %
3212               (game.state.nromrem, game.state.nromrem))
3213     if game.inkling - game.remkl():
3214         prout(_("%6d ordinary Klingons destroyed        %5d") %
3215               (game.inkling - game.remkl(), 10*(game.inkling - game.remkl())))
3216     if game.incom - len(game.state.kcmdr):
3217         prout(_("%6d Klingon commanders destroyed       %5d") %
3218               (game.incom - len(game.state.kcmdr), 50*(game.incom - len(game.state.kcmdr))))
3219     if game.kcaptured:
3220         prout(_("%d Klingons captured                   %5d") %
3221               (game.kcaptured, 3 * game.kcaptured))
3222     if game.inscom - game.state.nscrem:
3223         prout(_("%6d Super-Commander destroyed          %5d") %
3224               (game.inscom - game.state.nscrem, 200*(game.inscom - game.state.nscrem)))
3225     if ithperd:
3226         prout(_("%6.2f Klingons per stardate              %5d") %
3227               (game.perdate, ithperd))
3228     if game.state.starkl:
3229         prout(_("%6d stars destroyed by your action     %5d") %
3230               (game.state.starkl, -5*game.state.starkl))
3231     if game.state.nplankl:
3232         prout(_("%6d planets destroyed by your action   %5d") %
3233               (game.state.nplankl, -10*game.state.nplankl))
3234     if (game.options & OPTION_WORLDS) and game.state.nworldkl:
3235         prout(_("%6d inhabited planets destroyed by your action   %5d") %
3236               (game.state.nworldkl, -300*game.state.nworldkl))
3237     if game.state.basekl:
3238         prout(_("%6d bases destroyed by your action     %5d") %
3239               (game.state.basekl, -100*game.state.basekl))
3240     if game.nhelp:
3241         prout(_("%6d calls for help from starbase       %5d") %
3242               (game.nhelp, -45*game.nhelp))
3243     if game.casual:
3244         prout(_("%6d casualties incurred                %5d") %
3245               (game.casual, -game.casual))
3246     if game.abandoned:
3247         prout(_("%6d crew abandoned in space            %5d") %
3248               (game.abandoned, -3*game.abandoned))
3249     if klship:
3250         prout(_("%6d ship(s) lost or destroyed          %5d") %
3251               (klship, -100*klship))
3252     if game.ncviol > 0:
3253         if ncviol == 1:
3254             prout(_("1 Treaty of Algeron violation          -100"))
3255         else:
3256             prout(_("%6d Treaty of Algeron violations       %5d\n") %
3257                   (ncviol, -100*ncviol))
3258     if not game.alive:
3259         prout(_("Penalty for getting yourself killed        -200"))
3260     if game.gamewon:
3261         proutn(_("Bonus for winning "))
3262         if game.skill   == SKILL_NOVICE:        proutn(_("Novice game  "))
3263         elif game.skill == SKILL_FAIR:          proutn(_("Fair game    "))
3264         elif game.skill ==  SKILL_GOOD:         proutn(_("Good game    "))
3265         elif game.skill ==  SKILL_EXPERT:        proutn(_("Expert game  "))
3266         elif game.skill ==  SKILL_EMERITUS:        proutn(_("Emeritus game"))
3267         prout("           %5d" % iwon)
3268     skip(1)
3269     prout(_("TOTAL SCORE                               %5d") % game.score)
3270
3271 def plaque():
3272     "Emit winner's commemmorative plaque."
3273     skip(2)
3274     while True:
3275         proutn(_("File or device name for your plaque: "))
3276         winner = cgetline()
3277         try:
3278             fp = open(winner, "w")
3279             break
3280         except IOError:
3281             prout(_("Invalid name."))
3282
3283     proutn(_("Enter name to go on plaque (up to 30 characters): "))
3284     winner = cgetline()
3285     # The 38 below must be 64 for 132-column paper
3286     nskip = 38 - len(winner)/2
3287     # This is where the ASCII art picture was emitted.
3288     # It got garbled somewhere in the chain of transmission to the Almy version.
3289     # We should restore it if we can find old enough FORTRAN sources.
3290     fp.write("\n\n\n")
3291     fp.write(_("                                                       U. S. S. ENTERPRISE\n"))
3292     fp.write("\n\n\n\n")
3293     fp.write(_("                                  For demonstrating outstanding ability as a starship captain\n"))
3294     fp.write("\n")
3295     fp.write(_("                                                Starfleet Command bestows to you\n"))
3296     fp.write("\n")
3297     fp.write("%*s%s\n\n" % (nskip, "", winner))
3298     fp.write(_("                                                           the rank of\n\n"))
3299     fp.write(_("                                                       \"Commodore Emeritus\"\n\n"))
3300     fp.write("                                                          ")
3301     if game.skill ==  SKILL_EXPERT:
3302         fp.write(_(" Expert level\n\n"))
3303     elif game.skill == SKILL_EMERITUS:
3304         fp.write(_("Emeritus level\n\n"))
3305     else:
3306         fp.write(_(" Cheat level\n\n"))
3307     timestring = time.ctime()
3308     fp.write(_("                                                 This day of %.6s %.4s, %.8s\n\n") %
3309              (timestring+4, timestring+20, timestring+11))
3310     fp.write(_("                                                        Your score:  %d\n\n") % game.score)
3311     fp.write(_("                                                    Klingons per stardate:  %.2f\n") % game.perdate)
3312     fp.close()
3313
3314 # Code from io.c begins here
3315
3316 rows = linecount = 0        # for paging
3317 stdscr = None
3318 replayfp = None
3319 fullscreen_window = None
3320 srscan_window     = None   # Short range scan
3321 report_window     = None   # Report legends for status window
3322 status_window     = None   # The status window itself
3323 lrscan_window     = None   # Long range scan
3324 message_window    = None   # Main window for scrolling text
3325 prompt_window     = None   # Prompt window at bottom of display
3326 curwnd = None
3327
3328 def iostart():
3329     global stdscr, rows