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