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