More of Stas's notes about the time recomputation bug.
[super-star-trek.git] / src / sst.py
1 """
2 sst.py =-- Super Star Trek in Python
3
4 This code is a Python translation of a C translation of a FORTRAN original.
5 The FORTRANness still shows in many ways, notably the use of 1-origin index
6 an a lot of parallel arrays where a more modern language would use structures
7 or objects.
8 """
9 import os, sys, math, curses
10
11 SSTDOC = "/usr/share/doc/sst/sst.doc"
12
13 # Stub to be replaced
14 def _(str): return str
15
16 PHASEFAC        = 2.0
17 GALSIZE         = 8
18 NINHAB          = (GALSIZE * GALSIZE / 2)
19 MAXUNINHAB      = 10
20 PLNETMAX        = (NINHAB + MAXUNINHAB)
21 QUADSIZE        = 10
22 BASEMAX         = (GALSIZE * GALSIZE / 12)
23 MAXKLGAME       = 127
24 MAXKLQUAD       = 9
25 FULLCREW        = 428   # BSD Trek was 387, that's wrong 
26 FOREVER         = 1e30
27
28 # These functions hide the difference between 0-origin and 1-origin addressing.
29 def VALID_QUADRANT(x, y):       return ((x)>=1 and (x)<=GALSIZE and (y)>=1 and (y)<=GALSIZE)
30 def VALID_SECTOR(x, y): return ((x)>=1 and (x)<=QUADSIZE and (y)>=1 and (y)<=QUADSIZE)
31
32 def square(i):          return ((i)*(i))
33 def distance(c1, c2):   return math.sqrt(square(c1.x - c2.x) + square(c1.y - c2.y))
34 def invalidate(w):      w.x = w.y = 0
35 def is_valid(w):        return (w.x != 0 and w.y != 0)
36
37 class coord:
38     def __init(self, x=None, y=None):
39         self.x = x
40         self.y = y
41     def invalidate(self):
42         self.x = self.y = None
43     def is_valid(self):
44         return self.x != None and self.y != None
45     def __eq__(self, other):
46         return self.x == other.y and self.x == other.y
47     def __add__(self, other):
48         return coord(self.x+self.x, self.y+self.y)
49     def __sub__(self, other):
50         return coord(self.x-self.x, self.y-self.y)
51     def distance(self, other):
52         return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
53     def sgn(self):
54         return coord(self.x / abs(x), self.y / abs(y));
55     def __hash__(self):
56         return hash((x, y))
57     def __str__(self):
58         return "%d - %d" % (self.x, self.y)
59
60 class planet:
61     def __init(self):
62         self.name = None        # string-valued if inhabited
63         self.w = coord()        # quadrant located
64         self.pclass = None      # could be ""M", "N", "O", or "destroyed"
65         self.crystals = None    # could be "mined", "present", "absent"
66         self.known = None       # could be "unknown", "known", "shuttle_down"
67
68 # How to represent features
69 IHR = 'R',
70 IHK = 'K',
71 IHC = 'C',
72 IHS = 'S',
73 IHSTAR = '*',
74 IHP = 'P',
75 IHW = '@',
76 IHB = 'B',
77 IHBLANK = ' ',
78 IHDOT = '.',
79 IHQUEST = '?',
80 IHE = 'E',
81 IHF = 'F',
82 IHT = 'T',
83 IHWEB = '#',
84 IHMATER0 = '-',
85 IHMATER1 = 'o',
86 IHMATER2 = '0'
87
88 NOPLANET = None
89 class quadrant:
90     def __init(self):
91         self.stars = None
92         self.planet = None
93         self.starbase = None
94         self.klingons = None
95         self.romulans = None
96         self.supernova = None
97         self.charted = None
98         self.status = None      # Could be "secure", "distressed", "enslaved"
99
100 class page:
101     def __init(self):
102         self.stars = None
103         self.starbase = None
104         self.klingons = None
105
106 class snapshot:
107     def __init(self):
108         self.snap = False       # snapshot taken
109         self.crew = None        # crew complement
110         self.remkl = None       # remaining klingons
111         self.remcom = None      # remaining commanders
112         self.nscrem = None      # remaining super commanders
113         self.rembase = None     # remaining bases
114         self.starkl = None      # destroyed stars
115         self.basekl = None      # destroyed bases
116         self.nromrem = None     # Romulans remaining
117         self.nplankl = None     # destroyed uninhabited planets
118         self.nworldkl = None    # destroyed inhabited planets
119         self.planets = []       # Planet information
120         for i in range(PLNETMAX):
121             self.planets.append(planet())
122         self.date = None        # stardate
123         self.remres = None      # remaining resources
124         self.remtime = None     # remaining time
125         self.baseq = []         # Base quadrant coordinates
126         for i in range(BASEMAX+1):
127             self.baseq.append(coord())
128         self.kcmdr = []         # Commander quadrant coordinates
129         for i in range(QUADSIZE+1):
130             self.kcmdr.append(coord())
131         self.kscmdr = coord()   # Supercommander quadrant coordinates
132         self.galaxy = []        # The Galaxy (subscript 0 not used)
133         for i in range(GALSIZE+1):
134             self.chart.append([])
135             for j in range(GALSIZE+1):
136                 self.galaxy[i].append(quadrant())
137         self.chart = []         # the starchart (subscript 0 not used)
138         for i in range(GALSIZE+1):
139             self.chart.append([])
140             for j in range(GALSIZE+1):
141                 self.chart[i].append(page())
142
143 class event:
144     def __init__(self):
145         self.date = None        # A real number
146         self.quadrant = None    # A coord structure
147
148 # game options 
149 OPTION_ALL      = 0xffffffff
150 OPTION_TTY      = 0x00000001    # old interface 
151 OPTION_CURSES   = 0x00000002    # new interface 
152 OPTION_IOMODES  = 0x00000003    # cover both interfaces 
153 OPTION_PLANETS  = 0x00000004    # planets and mining 
154 OPTION_THOLIAN  = 0x00000008    # Tholians and their webs 
155 OPTION_THINGY   = 0x00000010    # Space Thingy can shoot back 
156 OPTION_PROBE    = 0x00000020    # deep-space probes 
157 OPTION_SHOWME   = 0x00000040    # bracket Enterprise in chart 
158 OPTION_RAMMING  = 0x00000080    # enemies may ram Enterprise 
159 OPTION_MVBADDY  = 0x00000100    # more enemies can move 
160 OPTION_BLKHOLE  = 0x00000200    # black hole may timewarp you 
161 OPTION_BASE     = 0x00000400    # bases have good shields 
162 OPTION_WORLDS   = 0x00000800    # logic for inhabited worlds 
163 OPTION_PLAIN    = 0x01000000    # user chose plain game 
164 OPTION_ALMY     = 0x02000000    # user chose Almy variant 
165
166 # Define devices 
167 DSRSENS = 0
168 DLRSENS = 1
169 DPHASER = 2
170 DPHOTON = 3
171 DLIFSUP = 4
172 DWARPEN = 5
173 DIMPULS = 6
174 DSHIELD = 7
175 DRADIO  = 0
176 DSHUTTL = 9
177 DCOMPTR = 10
178 DNAVSYS = 11
179 DTRANSP = 12
180 DSHCTRL = 13
181 DDRAY   = 14
182 DDSP    = 15
183 NDEVICES= 16    # Number of devices
184
185 SKILL_NONE      = 0
186 SKILL_NOVICE    = 1
187 SKILL_FAIR      = 2
188 SKILL_GOOD      = 3
189 SKILL_EXPERT    = 4
190 SKILL_EMERITUS  = 5
191
192 def damaged(dev):       return (game.damage[dev] != 0.0)
193
194 # Define future events 
195 FSPY    = 0     # Spy event happens always (no future[] entry)
196                 # can cause SC to tractor beam Enterprise
197 FSNOVA  = 1     # Supernova
198 FTBEAM  = 2     # Commander tractor beams Enterprise
199 FSNAP   = 3     # Snapshot for time warp
200 FBATTAK = 4     # Commander attacks base
201 FCDBAS  = 5     # Commander destroys base
202 FSCMOVE = 6     # Supercommander moves (might attack base)
203 FSCDBAS = 7     # Supercommander destroys base
204 FDSPROB = 8     # Move deep space probe
205 FDISTR  = 9     # Emit distress call from an inhabited world 
206 FENSLV  = 10    # Inhabited word is enslaved */
207 FREPRO  = 11    # Klingons build a ship in an enslaved system
208 NEVENTS = 12
209
210 #
211 # abstract out the event handling -- underlying data structures will change
212 # when we implement stateful events
213
214 def findevent(evtype):  return game.future[evtype]
215
216 class gamestate:
217     def __init__(self):
218         self.options = None     # Game options
219         self.state = None       # A snapshot structure
220         self.snapsht = None     # Last snapshot taken for time-travel purposes
221         self.quad = [[IHDOT * (QUADSIZE+1)] * (QUADSIZE+1)]     # contents of our quadrant
222         self.kpower = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]       # enemy energy levels
223         self.kdist = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]        # enemy distances
224         self.kavgd = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]        # average distances
225         self.damage = [0] * NDEVICES    # damage encountered
226         self.future = [0.0] * NEVENTS   # future events
227         for i in range(NEVENTS):
228             self.future.append(event())
229         self.passwd  = None;            # Self Destruct password
230         self.ks = [[None * (QUADSIZE+1)] * (QUADSIZE+1)]        # enemy sector locations
231         self.quadrant = None    # where we are in the large
232         self.sector = None      # where we are in the small
233         self.tholian = None     # coordinates of Tholian
234         self.base = None        # position of base in current quadrant
235         self.battle = None      # base coordinates being attacked
236         self.plnet = None       # location of planet in quadrant
237         self.probec = None      # current probe quadrant
238         self.gamewon = False    # Finished!
239         self.ididit = False     # action taken -- allows enemy to attack
240         self.alive = False      # we are alive (not killed)
241         self.justin = False     # just entered quadrant
242         self.shldup = False     # shields are up
243         self.shldchg = False    # shield is changing (affects efficiency)
244         self.comhere = False    # commander here
245         self.ishere = False     # super-commander in quadrant
246         self.iscate = False     # super commander is here
247         self.ientesc = False    # attempted escape from supercommander
248         self.ithere = False     # Tholian is here 
249         self.resting = False    # rest time
250         self.icraft = False     # Kirk in Galileo
251         self.landed = False     # party on planet (true), on ship (false)
252         self.alldone = False    # game is now finished
253         self.neutz = False      # Romulan Neutral Zone
254         self.isarmed = False    # probe is armed
255         self.inorbit = False    # orbiting a planet
256         self.imine = False      # mining
257         self.icrystl = False    # dilithium crystals aboard
258         self.iseenit = False    # seen base attack report
259         self.thawed = False     # thawed game
260         self.condition = None   # "green", "yellow", "red", "docked", "dead"
261         self.iscraft = None     # "onship", "offship", "removed"
262         self.skill = None       # Player skill level
263         self.inkling = 0        # initial number of klingons
264         self.inbase = 0         # initial number of bases
265         self.incom = 0          # initial number of commanders
266         self.inscom = 0         # initial number of commanders
267         self.inrom = 0          # initial number of commanders
268         self.instar = 0         # initial stars
269         self.intorps = 0        # initial/max torpedoes
270         self.torps = 0          # number of torpedoes
271         self.ship = 0           # ship type -- 'E' is Enterprise
272         self.abandoned = 0      # count of crew abandoned in space
273         self.length = 0         # length of game
274         self.klhere = 0         # klingons here
275         self.casual = 0         # causalties
276         self.nhelp = 0          # calls for help
277         self.nkinks = 0         # count of energy-barrier crossings
278         self.iplnet = 0         # planet # in quadrant
279         self.inplan = 0         # initial planets
280         self.nenhere = 0        # number of enemies in quadrant
281         self.irhere = 0         # Romulans in quadrant
282         self.isatb = 0          # =1 if super commander is attacking base
283         self.tourn = 0          # tournament number
284         self.proben = 0         # number of moves for probe
285         self.nprobes = 0        # number of probes available
286         self.inresor = 0.0      # initial resources
287         self.intime = 0.0       # initial time
288         self.inenrg = 0.0       # initial/max energy
289         self.inshld = 0.0       # initial/max shield
290         self.inlsr = 0.0        # initial life support resources
291         self.indate = 0.0       # initial date
292         self.energy = 0.0       # energy level
293         self.shield = 0.0       # shield level
294         self.warpfac = 0.0      # warp speed
295         self.wfacsq = 0.0       # squared warp factor
296         self.lsupres = 0.0      # life support reserves
297         self.dist = 0.0         # movement distance
298         self.direc = 0.0        # movement direction
299         self.optime = 0.0       # time taken by current operation
300         self.docfac = 0.0       # repair factor when docking (constant?)
301         self.damfac = 0.0       # damage factor
302         self.lastchart = 0.0    # time star chart was last updated
303         self.cryprob = 0.0      # probability that crystal will work
304         self.probex = 0.0       # location of probe
305         self.probey = 0.0       #
306         self.probeinx = 0.0     # probe x,y increment
307         self.probeiny = 0.0     #
308         self.height = 0.0       # height of orbit around planet
309     def recompute(self):
310         # Stas thinks this should be (C expression): 
311         # game.state.remkl + game.state.remcom > 0 ?
312         #       game.state.remres/(game.state.remkl + 4*game.state.remcom) : 99
313         # He says the existing expression is prone to divide-by-zero errors
314         # after killing the last klingon when score is shown -- perhaps also
315         # if the only remaining klingon is SCOM.
316         game.state.remtime = game.state.remres/(game.state.remkl + 4*game.state.remcom)
317 # From enumerated type 'feature'
318 IHR = 'R'
319 IHK = 'K'
320 IHC = 'C'
321 IHS = 'S'
322 IHSTAR = '*'
323 IHP = 'P'
324 IHW = '@'
325 IHB = 'B'
326 IHBLANK = ' '
327 IHDOT = '.'
328 IHQUEST = '?'
329 IHE = 'E'
330 IHF = 'F'
331 IHT = 'T'
332 IHWEB = '#'
333 IHMATER0 = '-'
334 IHMATER1 = 'o'
335 IHMATER2 = '0'
336
337
338 # From enumerated type 'FINTYPE'
339 FWON = 0
340 FDEPLETE = 1
341 FLIFESUP = 2
342 FNRG = 3
343 FBATTLE = 4
344 FNEG3 = 5
345 FNOVA = 6
346 FSNOVAED = 7
347 FABANDN = 8
348 FDILITHIUM = 9
349 FMATERIALIZE = 10
350 FPHASER = 11
351 FLOST = 12
352 FMINING = 13
353 FDPLANET = 14
354 FPNOVA = 15
355 FSSC = 16
356 FSTRACTOR = 17
357 FDRAY = 18
358 FTRIBBLE = 19
359 FHOLE = 20
360 FCREW = 21
361
362 # From enumerated type 'COLORS'
363 DEFAULT = 0
364 BLACK = 1
365 BLUE = 2
366 GREEN = 3
367 CYAN = 4
368 RED = 5
369 MAGENTA = 6
370 BROWN = 7
371 LIGHTGRAY = 8
372 DARKGRAY = 9
373 LIGHTBLUE = 10
374 LIGHTGREEN = 11
375 LIGHTCYAN = 12
376 LIGHTRED = 13
377 LIGHTMAGENTA = 14
378 YELLOW = 15
379 WHITE = 16
380
381 # Code from ai.c begins here
382
383 def tryexit(look, ienm, loccom, irun):
384     # a bad guy attempts to bug out 
385     iq = coord()
386     iq.x = game.quadrant.x+(look.x+(QUADSIZE-1))/QUADSIZE - 1
387     iq.y = game.quadrant.y+(look.y+(QUADSIZE-1))/QUADSIZE - 1
388     if not VALID_QUADRANT(iq.x,iq.y) or \
389         game.state.galaxy[iq.x][iq.y].supernova or \
390         game.state.galaxy[iq.x][iq.y].klingons > MAXKLQUAD-1:
391         return False; # no can do -- neg energy, supernovae, or >MAXKLQUAD-1 Klingons 
392     if ienm == IHR:
393         return False; # Romulans cannot escape! 
394     if not irun:
395         # avoid intruding on another commander's territory 
396         if ienm == IHC:
397             for n in range(1, game.state.remcom+1):
398                 if same(game.state.kcmdr[n],iq):
399                     return False
400             # refuse to leave if currently attacking starbase 
401             if same(game.battle, game.quadrant):
402                 return False
403         # don't leave if over 1000 units of energy 
404         if game.kpower[loccom] > 1000.0:
405             return False
406     # print escape message and move out of quadrant.
407     # we know this if either short or long range sensors are working
408     if not damaged(DSRSENS) or not damaged(DLRSENS) or \
409         game.condition == docked:
410         crmena(True, ienm, "sector", game.ks[loccom])
411         prout(_(" escapes to Quadrant %s (and regains strength).") % q)
412     # handle local matters related to escape 
413     game.quad[game.ks[loccom].x][game.ks[loccom].y] = IHDOT
414     game.ks[loccom] = game.ks[game.nenhere]
415     game.kavgd[loccom] = game.kavgd[game.nenhere]
416     game.kpower[loccom] = game.kpower[game.nenhere]
417     game.kdist[loccom] = game.kdist[game.nenhere]
418     game.klhere -= 1
419     game.nenhere -= 1
420     if game.condition != docked:
421         newcnd()
422     # Handle global matters related to escape 
423     game.state.galaxy[game.quadrant.x][game.quadrant.y].klingons -= 1
424     game.state.galaxy[iq.x][iq.y].klingons += 1
425     if ienm==IHS:
426         game.ishere = False
427         game.iscate = False
428         game.ientesc = False
429         game.isatb = 0
430         schedule(FSCMOVE, 0.2777)
431         unschedule(FSCDBAS)
432         game.state.kscmdr=iq
433     else:
434         for n in range(1, game.state.remcom+1):
435             if same(game.state.kcmdr[n], game.quadrant):
436                 game.state.kcmdr[n]=iq
437                 break
438         game.comhere = False
439     return True; # success 
440
441 #
442 # The bad-guy movement algorithm:
443
444 # 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
445 # If both are operating full strength, force is 1000. If both are damaged,
446 # force is -1000. Having shields down subtracts an additional 1000.
447
448 # 2. Enemy has forces equal to the energy of the attacker plus
449 # 100*(K+R) + 500*(C+S) - 400 for novice through good levels OR
450 # 346*K + 400*R + 500*(C+S) - 400 for expert and emeritus.
451
452 # Attacker Initial energy levels (nominal):
453 # Klingon   Romulan   Commander   Super-Commander
454 # Novice    400        700        1200        
455 # Fair      425        750        1250
456 # Good      450        800        1300        1750
457 # Expert    475        850        1350        1875
458 # Emeritus  500        900        1400        2000
459 # VARIANCE   75        200         200         200
460
461 # Enemy vessels only move prior to their attack. In Novice - Good games
462 # only commanders move. In Expert games, all enemy vessels move if there
463 # is a commander present. In Emeritus games all enemy vessels move.
464
465 # 3. If Enterprise is not docked, an aggressive action is taken if enemy
466 # forces are 1000 greater than Enterprise.
467
468 # Agressive action on average cuts the distance between the ship and
469 # the enemy to 1/4 the original.
470
471 # 4.  At lower energy advantage, movement units are proportional to the
472 # advantage with a 650 advantage being to hold ground, 800 to move forward
473 # 1, 950 for two, 150 for back 4, etc. Variance of 100.
474
475 # If docked, is reduced by roughly 1.75*game.skill, generally forcing a
476 # retreat, especially at high skill levels.
477
478 # 5.  Motion is limited to skill level, except for SC hi-tailing it out.
479
480
481 def movebaddy(com, loccom, ienm):
482     # tactical movement for the bad guys 
483     next = coord(); look = coord()
484     irun = False
485     # This should probably be just game.comhere + game.ishere 
486     if game.skill >= SKILL_EXPERT:
487         nbaddys = ((game.comhere*2 + game.ishere*2+game.klhere*1.23+game.irhere*1.5)/2.0)
488     else:
489         nbaddys = game.comhere + game.ishere
490
491     dist1 = game.kdist[loccom]
492     mdist = int(dist1 + 0.5); # Nearest integer distance 
493
494     # If SC, check with spy to see if should hi-tail it 
495     if ienm==IHS and \
496         (game.kpower[loccom] <= 500.0 or (game.condition=="docked" and not damaged(DPHOTON))):
497         irun = True
498         motion = -QUADSIZE
499     else:
500         # decide whether to advance, retreat, or hold position 
501         forces = game.kpower[loccom]+100.0*game.nenhere+400*(nbaddys-1)
502         if not game.shldup:
503             forces += 1000; # Good for enemy if shield is down! 
504         if not damaged(DPHASER) or not damaged(DPHOTON):
505             if damaged(DPHASER): # phasers damaged 
506                 forces += 300.0
507             else:
508                 forces -= 0.2*(game.energy - 2500.0)
509             if damaged(DPHOTON): # photon torpedoes damaged 
510                 forces += 300.0
511             else:
512                 forces -= 50.0*game.torps
513         else:
514             # phasers and photon tubes both out! 
515             forces += 1000.0
516         motion = 0
517         if forces <= 1000.0 and game.condition != "docked": # Typical situation 
518             motion = ((forces+200.0*Rand())/150.0) - 5.0
519         else:
520             if forces > 1000.0: # Very strong -- move in for kill 
521                 motion = (1.0-square(Rand()))*dist1 + 1.0
522             if game.condition=="docked" and (game.options & OPTION_BASE): # protected by base -- back off ! 
523                 motion -= game.skill*(2.0-square(Rand()))
524         if idebug:
525             proutn("=== MOTION = %d, FORCES = %1.2f, " % (motion, forces))
526         # don't move if no motion 
527         if motion==0:
528             return
529         # Limit motion according to skill 
530         if abs(motion) > game.skill:
531             if motion < 0:
532                 motion = -game.skill
533             else:
534                 motion = game.skill
535     # calculate preferred number of steps 
536     if motion < 0:
537         msteps = -motion
538     else:
539         msteps = motion
540     if motion > 0 and nsteps > mdist:
541         nsteps = mdist; # don't overshoot 
542     if nsteps > QUADSIZE:
543         nsteps = QUADSIZE; # This shouldn't be necessary 
544     if nsteps < 1:
545         nsteps = 1; # This shouldn't be necessary 
546     if idebug:
547         proutn("NSTEPS = %d:" % nsteps)
548     # Compute preferred values of delta X and Y 
549     mx = game.sector.x - com.x
550     my = game.sector.y - com.y
551     if 2.0 * abs(mx) < abs(my):
552         mx = 0
553     if 2.0 * abs(my) < abs(game.sector.x-com.x):
554         my = 0
555     if mx != 0:
556         if mx*motion < 0:
557             mx = -1
558         else:
559             mx = 1
560     if my != 0:
561         if my*motion < 0:
562             my = -1
563         else:
564             my = 1
565     next = com
566     # main move loop 
567     for ll in range(nsteps):
568         if idebug:
569             proutn(" %d" % (ll+1))
570         # Check if preferred position available 
571         look.x = next.x + mx
572         look.y = next.y + my
573         if mx < 0:
574             krawlx = 1
575         else:
576             krawlx = -1
577         if my < 0:
578             krawly = 1
579         else:
580             krawly = -1
581         success = False
582         attempts = 0; # Settle mysterious hang problem 
583         while attempts < 20 and not success:
584             attempts += 1
585             if look.x < 1 or look.x > QUADSIZE:
586                 if motion < 0 and tryexit(look, ienm, loccom, irun):
587                     return
588                 if krawlx == mx or my == 0:
589                     break
590                 look.x = next.x + krawlx
591                 krawlx = -krawlx
592             elif look.y < 1 or look.y > QUADSIZE:
593                 if motion < 0 and tryexit(look, ienm, loccom, irun):
594                     return
595                 if krawly == my or mx == 0:
596                     break
597                 look.y = next.y + krawly
598                 krawly = -krawly
599             elif (game.options & OPTION_RAMMING) and game.quad[look.x][look.y] != IHDOT:
600                 # See if we should ram ship 
601                 if game.quad[look.x][look.y] == game.ship and \
602                     (ienm == IHC or ienm == IHS):
603                     ram(True, ienm, com)
604                     return
605                 if krawlx != mx and my != 0:
606                     look.x = next.x + krawlx
607                     krawlx = -krawlx
608                 elif krawly != my and mx != 0:
609                     look.y = next.y + krawly
610                     krawly = -krawly
611                 else:
612                     break; # we have failed 
613             else:
614                 success = True
615         if success:
616             next = look
617             if idebug:
618                 proutn(`next`)
619         else:
620             break; # done early 
621         
622     if idebug:
623         skip(1)
624     # Put commander in place within same quadrant 
625     game.quad[com.x][com.y] = IHDOT
626     game.quad[next.x][next.y] = ienm
627     if not same(next, com):
628         # it moved 
629         game.ks[loccom] = next
630         game.kdist[loccom] = game.kavgd[loccom] = distance(game.sector, next)
631         if not damaged(DSRSENS) or game.condition == docked:
632             proutn("***")
633             cramen(ienm)
634             proutn(_(" from Sector %s") % com)
635             if game.kdist[loccom] < dist1:
636                 proutn(_(" advances to "))
637             else:
638                 proutn(_(" retreats to "))
639             prout("Sector %s." % next)
640
641 def moveklings():
642     # Klingon tactical movement 
643     if idebug:
644         prout("== MOVCOM")
645     # Figure out which Klingon is the commander (or Supercommander)
646     # and do move
647     if game.comhere:
648         for i in range(1, game.nenhere+1):
649             w = game.ks[i]
650             if game.quad[w.x][w.y] == IHC:
651                 movebaddy(w, i, IHC)
652                 break
653     if game.ishere:
654         for i in range(1, game.nenhere+1):
655             w = game.ks[i]
656             if game.quad[w.x][w.y] == IHS:
657                 movebaddy(w, i, IHS)
658                 break
659     # If skill level is high, move other Klingons and Romulans too!
660     # Move these last so they can base their actions on what the
661     # commander(s) do.
662     if game.skill >= SKILL_EXPERT and (game.options & OPTION_MVBADDY):
663         for i in range(1, game.nenhere+1):
664             w = game.ks[i]
665             if game.quad[w.x][w.y] == IHK or game.quad[w.x][w.y] == IHR:
666                 movebaddy(w, i, game.quad[w.x][w.y])
667     sortklings();
668
669 def movescom(iq, avoid):
670     # commander movement helper 
671     if same(iq, game.quadrant) or not VALID_QUADRANT(iq.x, iq.y) or \
672         game.state.galaxy[iq.x][iq.y].supernova or \
673         game.state.galaxy[iq.x][iq.y].klingons > MAXKLQUAD-1:
674         return 1
675     if avoid:
676         # Avoid quadrants with bases if we want to avoid Enterprise 
677         for i in range(1, game.state.rembase+1):
678             if same(game.state.baseq[i], iq):
679                 return True
680     if game.justin and not game.iscate:
681         return True
682     # do the move 
683     game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].klingons -= 1
684     game.state.kscmdr = iq
685     game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].klingons += 1
686     if game.ishere:
687         # SC has scooted, Remove him from current quadrant 
688         game.iscate=False
689         game.isatb=0
690         game.ishere = False
691         game.ientesc = False
692         unschedule(FSCDBAS)
693         for i in range(1, game.nenhere+1):
694             if game.quad[game.ks[i].x][game.ks[i].y] == IHS:
695                 break
696         game.quad[game.ks[i].x][game.ks[i].y] = IHDOT
697         game.ks[i] = game.ks[game.nenhere]
698         game.kdist[i] = game.kdist[game.nenhere]
699         game.kavgd[i] = game.kavgd[game.nenhere]
700         game.kpower[i] = game.kpower[game.nenhere]
701         game.klhere -= 1
702         game.nenhere -= 1
703         if game.condition!=docked:
704             newcnd()
705         sortklings()
706     # check for a helpful planet 
707     for i in range(game.inplan):
708         if same(game.state.planets[i].w, game.state.kscmdr) and \
709             game.state.planets[i].crystals == present:
710             # destroy the planet 
711             game.state.planets[i].pclass = destroyed
712             game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].planet = NOPLANET
713             if not damaged(DRADIO) or game.condition == docked:
714                 announce()
715                 prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
716                 proutn(_("   a planet in Quadrant %s has been destroyed") % game.state.kscmdr)
717                 prout(_("   by the Super-commander.\""))
718             break
719     return False; # looks good! 
720                         
721 def supercommander():
722     # move the Super Commander 
723     iq = coord(); sc = coord(); ibq = coord(); idelta = coord()
724     basetbl = []
725     if idebug:
726         prout("== SUPERCOMMANDER")
727     # Decide on being active or passive 
728     avoid = ((game.incom - game.state.remcom + game.inkling - game.state.remkl)/(game.state.date+0.01-game.indate) < 0.1*game.skill*(game.skill+1.0) or \
729             (game.state.date-game.indate) < 3.0)
730     if not game.iscate and avoid:
731         # compute move away from Enterprise 
732         idelta = game.state.kscmdr-game.quadrant
733         if math.sqrt(idelta.x*idelta.x+idelta.y*idelta.y) > 2.0:
734             # circulate in space 
735             idelta.x = game.state.kscmdr.y-game.quadrant.y
736             idelta.y = game.quadrant.x-game.state.kscmdr.x
737     else:
738         # compute distances to starbases 
739         if game.state.rembase <= 0:
740             # nothing left to do 
741             unschedule(FSCMOVE)
742             return
743         sc = game.state.kscmdr
744         for i in range(1, game.state.rembase+1):
745             basetbl.append((i, distance(game.state.baseq[i], sc)))
746         if game.state.rembase > 1:
747             basetbl.sort(lambda x, y: cmp(x[1]. y[1]))
748         # look for nearest base without a commander, no Enterprise, and
749         # without too many Klingons, and not already under attack. 
750         ifindit = iwhichb = 0
751         for i2 in range(1, game.state.rembase+1):
752             i = basetbl[i2][0]; # bug in original had it not finding nearest
753             ibq = game.state.baseq[i]
754             if same(ibq, game.quadrant) or same(ibq, game.battle) or \
755                 game.state.galaxy[ibq.x][ibq.y].supernova or \
756                 game.state.galaxy[ibq.x][ibq.y].klingons > MAXKLQUAD-1:
757                 continue
758             # if there is a commander, and no other base is appropriate,
759             #   we will take the one with the commander
760             for j in range(1, game.state.remcom+1):
761                 if same(ibq, game.state.kcmdr[j]) and ifindit!= 2:
762                     ifindit = 2
763                     iwhichb = i
764                     break
765             if j > game.state.remcom: # no commander -- use this one 
766                 ifindit = 1
767                 iwhichb = i
768                 break
769         if ifindit==0:
770             return; # Nothing suitable -- wait until next time
771         ibq = game.state.baseq[iwhichb]
772         # decide how to move toward base 
773         idelta = ibq - game.state.kscmdr
774     # Maximum movement is 1 quadrant in either or both axes 
775     idelta = idelta.sgn()
776     # try moving in both x and y directions
777     # there was what looked like a bug in the Almy C code here,
778     # but it might be this translation is just wrong.
779     iq = game.state.kscmdr + idelta
780     if movescom(iq, avoid):
781         # failed -- try some other maneuvers 
782         if idelta.x==0 or idelta.y==0:
783             # attempt angle move 
784             if idelta.x != 0:
785                 iq.y = game.state.kscmdr.y + 1
786                 if movescom(iq, avoid):
787                     iq.y = game.state.kscmdr.y - 1
788                     movescom(iq, avoid)
789             else:
790                 iq.x = game.state.kscmdr.x + 1
791                 if movescom(iq, avoid):
792                     iq.x = game.state.kscmdr.x - 1
793                     movescom(iq, avoid)
794         else:
795             # try moving just in x or y 
796             iq.y = game.state.kscmdr.y
797             if movescom(iq, avoid):
798                 iq.y = game.state.kscmdr.y + idelta.y
799                 iq.x = game.state.kscmdr.x
800                 movescom(iq, avoid)
801     # check for a base 
802     if game.state.rembase == 0:
803         unschedule(FSCMOVE)
804     else:
805         for i in range(1, game.state.rembase+1):
806             ibq = game.state.baseq[i]
807             if same(ibq, game.state.kscmdr) and same(game.state.kscmdr, game.battle):
808                 # attack the base 
809                 if avoid:
810                     return; # no, don't attack base! 
811                 game.iseenit = False
812                 game.isatb = 1
813                 schedule(FSCDBAS, 1.0 +2.0*Rand())
814                 if is_scheduled(FCDBAS):
815                     postpone(FSCDBAS, scheduled(FCDBAS)-game.state.date)
816                 if damaged(DRADIO) and game.condition != docked:
817                     return; # no warning 
818                 game.iseenit = True
819                 announce()
820                 prout(_("Lt. Uhura-  \"Captain, the starbase in Quadrant %s") \
821                       % game.state.kscmdr)
822                 prout(_("   reports that it is under attack from the Klingon Super-commander."))
823                 proutn(_("   It can survive until stardate %d.\"") \
824                        % int(scheduled(FSCDBAS)))
825                 if not game.resting:
826                     return
827                 prout(_("Mr. Spock-  \"Captain, shall we cancel the rest period?\""))
828                 if ja() == False:
829                     return
830                 game.resting = False
831                 game.optime = 0.0; # actually finished 
832                 return
833     # Check for intelligence report 
834     if not idebug and \
835         (Rand() > 0.2 or \
836          (damaged(DRADIO) and game.condition != docked) or \
837          not game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].charted):
838         return
839     announce()
840     prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
841     proutn(_("   the Super-commander is in Quadrant %s,") % game.state.kscmdr)
842     return;
843
844 def movetholian():
845     # move the Tholian 
846     if not game.ithere or game.justin:
847         return
848
849     if game.tholian.x == 1 and game.tholian.y == 1:
850         idx = 1; idy = QUADSIZE
851     elif game.tholian.x == 1 and game.tholian.y == QUADSIZE:
852         idx = QUADSIZE; idy = QUADSIZE
853     elif game.tholian.x == QUADSIZE and game.tholian.y == QUADSIZE:
854         idx = QUADSIZE; idy = 1
855     elif game.tholian.x == QUADSIZE and game.tholian.y == 1:
856         idx = 1; idy = 1
857     else:
858         # something is wrong! 
859         game.ithere = False
860         return
861
862     # do nothing if we are blocked 
863     if game.quad[idx][idy]!= IHDOT and game.quad[idx][idy]!= IHWEB:
864         return
865     game.quad[game.tholian.x][game.tholian.y] = IHWEB
866
867     if game.tholian.x != idx:
868         # move in x axis 
869         im = math.fabs(idx - game.tholian.x)*1.0/(idx - game.tholian.x)
870         while game.tholian.x != idx:
871             game.tholian.x += im
872             if game.quad[game.tholian.x][game.tholian.y]==IHDOT:
873                 game.quad[game.tholian.x][game.tholian.y] = IHWEB
874     elif game.tholian.y != idy:
875         # move in y axis 
876         im = math.fabs(idy - game.tholian.y)*1.0/(idy - game.tholian.y)
877         while game.tholian.y != idy:
878             game.tholian.y += im
879             if game.quad[game.tholian.x][game.tholian.y]==IHDOT:
880                 game.quad[game.tholian.x][game.tholian.y] = IHWEB
881     game.quad[game.tholian.x][game.tholian.y] = IHT
882     game.ks[game.nenhere] = game.tholian
883
884     # check to see if all holes plugged 
885     for i in range(1, QUADSIZE+1):
886         if game.quad[1][i]!=IHWEB and game.quad[1][i]!=IHT:
887             return
888         if game.quad[QUADSIZE][i]!=IHWEB and game.quad[QUADSIZE][i]!=IHT:
889             return
890         if game.quad[i][1]!=IHWEB and game.quad[i][1]!=IHT:
891             return
892         if game.quad[i][QUADSIZE]!=IHWEB and game.quad[i][QUADSIZE]!=IHT:
893             return
894     # All plugged up -- Tholian splits 
895     game.quad[game.tholian.x][game.tholian.y]=IHWEB
896     dropin(IHBLANK)
897     crmena(True, IHT, "sector", game.tholian)
898     prout(_(" completes web."))
899     game.ithere = False
900     game.nenhere -= 1
901     return
902
903 # Code from battle.c begins here
904
905 def doshield(shraise):
906     # change shield status 
907     action = "NONE"
908     game.ididit = False
909     if shraise:
910         action = "SHUP"
911     else:
912         key = scan()
913         if key == IHALPHA:
914             if isit("transfer"):
915                 action = "NRG"
916             else:
917                 chew()
918                 if damaged(DSHIELD):
919                     prout(_("Shields damaged and down."))
920                     return
921                 if isit("up"):
922                     action = "SHUP"
923                 elif isit("down"):
924                     action = "SHDN"
925         if action=="NONE":
926             proutn(_("Do you wish to change shield energy? "))
927             if ja() == True:
928                 proutn(_("Energy to transfer to shields- "))
929                 action = "NRG"
930             elif damaged(DSHIELD):
931                 prout(_("Shields damaged and down."))
932                 return
933             elif game.shldup:
934                 proutn(_("Shields are up. Do you want them down? "))
935                 if ja() == True:
936                     action = "SHDN"
937                 else:
938                     chew()
939                     return
940             else:
941                 proutn(_("Shields are down. Do you want them up? "))
942                 if ja() == True:
943                     action = "SHUP"
944                 else:
945                     chew()
946                     return    
947     if action == "SHUP": # raise shields 
948         if game.shldup:
949             prout(_("Shields already up."))
950             return
951         game.shldup = True
952         game.shldchg = True
953         if game.condition != "docked":
954             game.energy -= 50.0
955         prout(_("Shields raised."))
956         if game.energy <= 0:
957             skip(1)
958             prout(_("Shields raising uses up last of energy."))
959             finish(FNRG)
960             return
961         game.ididit=True
962         return
963     elif action == "SHDN":
964         if not game.shldup:
965             prout(_("Shields already down."))
966             return
967         game.shldup=False
968         game.shldchg=True
969         prout(_("Shields lowered."))
970         game.ididit = True
971         return
972     elif action == "NRG":
973         while scan() != IHREAL:
974             chew()
975             proutn(_("Energy to transfer to shields- "))
976         chew()
977         if aaitem==0:
978             return
979         if aaitem > game.energy:
980             prout(_("Insufficient ship energy."))
981             return
982         game.ididit = True
983         if game.shield+aaitem >= game.inshld:
984             prout(_("Shield energy maximized."))
985             if game.shield+aaitem > game.inshld:
986                 prout(_("Excess energy requested returned to ship energy"))
987             game.energy -= game.inshld-game.shield
988             game.shield = game.inshld
989             return
990         if aaitem < 0.0 and game.energy-aaitem > game.inenrg:
991             # Prevent shield drain loophole 
992             skip(1)
993             prout(_("Engineering to bridge--"))
994             prout(_("  Scott here. Power circuit problem, Captain."))
995             prout(_("  I can't drain the shields."))
996             game.ididit = False
997             return
998         if game.shield+aaitem < 0:
999             prout(_("All shield energy transferred to ship."))
1000             game.energy += game.shield
1001             game.shield = 0.0
1002             return
1003         proutn(_("Scotty- \""))
1004         if aaitem > 0:
1005             prout(_("Transferring energy to shields.\""))
1006         else:
1007             prout(_("Draining energy from shields.\""))
1008         game.shield += aaitem
1009         game.energy -= aaitem
1010         return
1011
1012 def randdevice():
1013     # choose a device to damage, at random. 
1014     #
1015     # Quoth Eric Allman in the code of BSD-Trek:
1016     # "Under certain conditions you can get a critical hit.  This
1017     # sort of hit damages devices.  The probability that a given
1018     # device is damaged depends on the device.  Well protected
1019     # devices (such as the computer, which is in the core of the
1020     # ship and has considerable redundancy) almost never get
1021     # damaged, whereas devices which are exposed (such as the
1022     # warp engines) or which are particularly delicate (such as
1023     # the transporter) have a much higher probability of being
1024     # damaged."
1025     # 
1026     # This is one place where OPTION_PLAIN does not restore the
1027     # original behavior, which was equiprobable damage across
1028     # all devices.  If we wanted that, we'd return NDEVICES*Rand()
1029     # and have done with it.  Also, in the original game, DNAVYS
1030     # and DCOMPTR were the same device. 
1031     # 
1032     # Instead, we use a table of weights similar to the one from BSD Trek.
1033     # BSD doesn't have the shuttle, shield controller, death ray, or probes. 
1034     # We don't have a cloaking device.  The shuttle got the allocation
1035     # for the cloaking device, then we shaved a half-percent off
1036     # everything to have some weight to give DSHCTRL/DDRAY/DDSP.
1037     # 
1038     weights = (
1039         105,    # DSRSENS: short range scanners 10.5% 
1040         105,    # DLRSENS: long range scanners          10.5% 
1041         120,    # DPHASER: phasers                      12.0% 
1042         120,    # DPHOTON: photon torpedoes             12.0% 
1043         25,     # DLIFSUP: life support          2.5% 
1044         65,     # DWARPEN: warp drive                    6.5% 
1045         70,     # DIMPULS: impulse engines               6.5% 
1046         145,    # DSHIELD: deflector shields            14.5% 
1047         30,     # DRADIO:  subspace radio                3.0% 
1048         45,     # DSHUTTL: shuttle                       4.5% 
1049         15,     # DCOMPTR: computer                      1.5% 
1050         20,     # NAVCOMP: navigation system             2.0% 
1051         75,     # DTRANSP: transporter                   7.5% 
1052         20,     # DSHCTRL: high-speed shield controller 2.0% 
1053         10,     # DDRAY: death ray                       1.0% 
1054         30,     # DDSP: deep-space probes                3.0% 
1055     )
1056     idx = Rand() * 1000.0       # weights must sum to 1000 
1057     sum = 0
1058     for (i, w) in enumerate(weights):
1059         sum += w
1060         if idx < sum:
1061             return i
1062     return None;        # we should never get here
1063
1064 def ram(ibumpd, ienm, w):
1065     # make our ship ram something 
1066     prouts(_("***RED ALERT!  RED ALERT!"))
1067     skip(1)
1068     prout(_("***COLLISION IMMINENT."))
1069     skip(2)
1070     proutn("***")
1071     crmshp()
1072     hardness = {IHR:1.5, IHC:2.0, IHS:2.5, IHT:0.5, IHQUEST:4.0}.get(ienm, 1.0)
1073     if ibumpd:
1074         proutn(_(" rammed by "))
1075     else:
1076         proutn(_(" rams "))
1077     crmena(False, ienm, sector, w)
1078     if ibumpd:
1079         proutn(_(" (original position)"))
1080     skip(1)
1081     deadkl(w, ienm, game.sector)
1082     proutn("***")
1083     crmshp()
1084     prout(_(" heavily damaged."))
1085     icas = 10.0+20.0*Rand()
1086     prout(_("***Sickbay reports %d casualties"), icas)
1087     game.casual += icas
1088     game.state.crew -= icas
1089     #
1090     # In the pre-SST2K version, all devices got equiprobably damaged,
1091     # which was silly.  Instead, pick up to half the devices at
1092     # random according to our weighting table,
1093     # 
1094     ncrits = Rand() * (NDEVICES/2)
1095     for m in range(ncrits):
1096         dev = randdevice()
1097         if game.damage[dev] < 0:
1098             continue
1099         extradm = (10.0*hardness*Rand()+1.0)*game.damfac
1100         # Damage for at least time of travel! 
1101         game.damage[dev] += game.optime + extradm
1102     game.shldup = False
1103     prout(_("***Shields are down."))
1104     if game.state.remkl + game.state.remcom + game.state.nscrem:
1105         announce()
1106         damagereport()
1107     else:
1108         finish(FWON)
1109     return;
1110
1111 def torpedo(course, r, incoming, i, n):
1112     # let a photon torpedo fly 
1113     iquad = 0
1114     shoved = False
1115     ac = course + 0.25*r
1116     angle = (15.0-ac)*0.5235988
1117     bullseye = (15.0 - course)*0.5235988
1118     deltax = -math.sin(angle);
1119     deltay = math.cos(angle);
1120     x = incoming.x; y = incoming.y
1121     w = coord(); jw = coord()
1122     w.x = w.y = jw.x = jw.y = 0
1123     bigger = max(math.fabs(deltax), math.fabs(deltay))
1124     deltax /= bigger
1125     deltay /= bigger
1126     if not damaged(DSRSENS) or game.condition=="docked":
1127         setwnd(srscan_window)
1128     else: 
1129         setwnd(message_window)
1130     # Loop to move a single torpedo 
1131     for l in range(1, 15+1):
1132         x += deltax
1133         w.x = x + 0.5
1134         y += deltay
1135         w.y = y + 0.5
1136         if not VALID_SECTOR(w.x, w.y):
1137             break
1138         iquad=game.quad[w.x][w.y]
1139         tracktorpedo(w, l, i, n, iquad)
1140         if iquad==IHDOT:
1141             continue
1142         # hit something 
1143         setwnd(message_window)
1144         if damaged(DSRSENS) and not game.condition=="docked":
1145             skip(1);    # start new line after text track 
1146         if iquad in (IHE, IHF): # Hit our ship 
1147             skip(1)
1148             proutn(_("Torpedo hits "))
1149             crmshp()
1150             prout(".")
1151             hit = 700.0 + 100.0*Rand() - \
1152                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1153             newcnd(); # we're blown out of dock 
1154             # We may be displaced. 
1155             if game.landed or game.condition=="docked":
1156                 return hit # Cheat if on a planet 
1157             ang = angle + 2.5*(Rand()-0.5)
1158             temp = math.fabs(math.sin(ang))
1159             if math.fabs(math.cos(ang)) > temp:
1160                 temp = math.fabs(math.cos(ang))
1161             xx = -math.sin(ang)/temp
1162             yy = math.cos(ang)/temp
1163             jw.x=w.x+xx+0.5
1164             jw.y=w.y+yy+0.5
1165             if not VALID_SECTOR(jw.x, jw.y):
1166                 return hit
1167             if game.quad[jw.x][jw.y]==IHBLANK:
1168                 finish(FHOLE)
1169                 return hit
1170             if game.quad[jw.x][jw.y]!=IHDOT:
1171                 # can't move into object 
1172                 return hit
1173             game.sector = jw
1174             crmshp()
1175             shoved = True
1176         elif iquad in (IHC, IHS): # Hit a commander 
1177             if Rand() <= 0.05:
1178                 crmena(True, iquad, sector, w)
1179                 prout(_(" uses anti-photon device;"))
1180                 prout(_("   torpedo neutralized."))
1181                 return None
1182         elif iquad in (IHR, IHK): # Hit a regular enemy 
1183             # find the enemy 
1184             for ll in range(1, game.nenhere+1):
1185                 if same(w, game.ks[ll]):
1186                     break
1187             kp = math.fabs(game.kpower[ll])
1188             h1 = 700.0 + 100.0*Rand() - \
1189                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1190             h1 = math.fabs(h1)
1191             if kp < h1:
1192                 h1 = kp
1193             if game.kpower[ll] < 0:
1194                 game.kpower[ll] -= -h1
1195             else:
1196                 game.kpower[ll] -= h1
1197             if game.kpower[ll] == 0:
1198                 deadkl(w, iquad, w)
1199                 return None
1200             crmena(True, iquad, "sector", w)
1201             # If enemy damaged but not destroyed, try to displace 
1202             ang = angle + 2.5*(Rand()-0.5)
1203             temp = math.fabs(math.sin(ang))
1204             if math.fabs(math.cos(ang)) > temp:
1205                 temp = math.fabs(math.cos(ang))
1206             xx = -math.sin(ang)/temp
1207             yy = math.cos(ang)/temp
1208             jw.x=w.x+xx+0.5
1209             jw.y=w.y+yy+0.5
1210             if not VALID_SECTOR(jw.x, jw.y):
1211                 prout(_(" damaged but not destroyed."))
1212                 return
1213             if game.quad[jw.x][jw.y]==IHBLANK:
1214                 prout(_(" buffeted into black hole."))
1215                 deadkl(w, iquad, jw)
1216                 return None
1217             if game.quad[jw.x][jw.y]!=IHDOT:
1218                 # can't move into object 
1219                 prout(_(" damaged but not destroyed."))
1220                 return None
1221             proutn(_(" damaged--"))
1222             game.ks[ll] = jw
1223             shoved = True
1224             break
1225         elif iquad == IHB: # Hit a base 
1226             skip(1)
1227             prout(_("***STARBASE DESTROYED.."))
1228             for ll in range(1, game.state.rembase+1):
1229                 if same(game.state.baseq[ll], game.quadrant):
1230                     game.state.baseq[ll]=game.state.baseq[game.state.rembase]
1231                     break
1232             game.quad[w.x][w.y]=IHDOT
1233             game.state.rembase -= 1
1234             game.base.x=game.base.y=0
1235             game.state.galaxy[game.quadrant.x][game.quadrant.y].starbase -= 1
1236             game.state.chart[game.quadrant.x][game.quadrant.y].starbase -= 1
1237             game.state.basekl += 1
1238             newcnd()
1239             return None
1240         elif iquad == IHP: # Hit a planet 
1241             crmena(True, iquad, sector, w)
1242             prout(_(" destroyed."))
1243             game.state.nplankl += 1
1244             game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
1245             game.state.planets[game.iplnet].pclass = destroyed
1246             game.iplnet = 0
1247             invalidate(game.plnet)
1248             game.quad[w.x][w.y] = IHDOT
1249             if game.landed:
1250                 # captain perishes on planet 
1251                 finish(FDPLANET)
1252             return None
1253         elif iquad == IHW: # Hit an inhabited world -- very bad! 
1254             crmena(True, iquad, sector, w)
1255             prout(_(" destroyed."))
1256             game.state.nworldkl += 1
1257             game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
1258             game.state.planets[game.iplnet].pclass = destroyed
1259             game.iplnet = 0
1260             invalidate(game.plnet)
1261             game.quad[w.x][w.y] = IHDOT
1262             if game.landed:
1263                 # captain perishes on planet 
1264                 finish(FDPLANET)
1265             prout(_("You have just destroyed an inhabited planet."))
1266             prout(_("Celebratory rallies are being held on the Klingon homeworld."))
1267             return None
1268         elif iquad == IHSTAR: # Hit a star 
1269             if Rand() > 0.10:
1270                 nova(w)
1271                 return None
1272             crmena(True, IHSTAR, sector, w)
1273             prout(_(" unaffected by photon blast."))
1274             return None
1275         elif iquad == IHQUEST: # Hit a thingy 
1276             if not (game.options & OPTION_THINGY) or Rand()>0.7:
1277                 skip(1)
1278                 prouts(_("AAAAIIIIEEEEEEEEAAAAAAAAUUUUUGGGGGHHHHHHHHHHHH!!!"))
1279                 skip(1)
1280                 prouts(_("    HACK!     HACK!    HACK!        *CHOKE!*  "))
1281                 skip(1)
1282                 proutn(_("Mr. Spock-"))
1283                 prouts(_("  \"Fascinating!\""))
1284                 skip(1)
1285                 deadkl(w, iquad, w)
1286             else:
1287                 #
1288                 # Stas Sergeev added the possibility that
1289                 # you can shove the Thingy and piss it off.
1290                 # It then becomes an enemy and may fire at you.
1291                 # 
1292                 iqengry = True
1293                 shoved = True
1294             return None
1295         elif iquad == IHBLANK: # Black hole 
1296             skip(1)
1297             crmena(True, IHBLANK, sector, w)
1298             prout(_(" swallows torpedo."))
1299             return None
1300         elif iquad == IHWEB: # hit the web 
1301             skip(1)
1302             prout(_("***Torpedo absorbed by Tholian web."))
1303             return None
1304         elif iquad == IHT:  # Hit a Tholian 
1305             h1 = 700.0 + 100.0*Rand() - \
1306                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1307             h1 = math.fabs(h1)
1308             if h1 >= 600:
1309                 game.quad[w.x][w.y] = IHDOT
1310                 game.ithere = False
1311                 deadkl(w, iquad, w)
1312                 return None
1313             skip(1)
1314             crmena(True, IHT, sector, w)
1315             if Rand() > 0.05:
1316                 prout(_(" survives photon blast."))
1317                 return None
1318             prout(_(" disappears."))
1319             game.quad[w.x][w.y] = IHWEB
1320             game.ithere = False
1321             game.nenhere -= 1
1322             dropin(IHBLANK)
1323             return None
1324         else: # Problem!
1325             skip(1)
1326             proutn("Don't know how to handle torpedo collision with ")
1327             crmena(True, iquad, sector, w)
1328             skip(1)
1329             return None
1330         break
1331     if curwnd!=message_window:
1332         setwnd(message_window)
1333     if shoved:
1334         game.quad[w.x][w.y]=IHDOT
1335         game.quad[jw.x][jw.y]=iquad
1336         prout(_(" displaced by blast to %s "), cramlc(sector, jw))
1337         for ll in range(1, game.nenhere+1):
1338             game.kdist[ll] = game.kavgd[ll] = distance(game.sector,game.ks[ll])
1339         sortklings()
1340         return None
1341     skip(1)
1342     prout(_("Torpedo missed."))
1343     return None;
1344
1345 def fry(hit):
1346     # critical-hit resolution 
1347     ktr=1
1348     # a critical hit occured 
1349     if hit < (275.0-25.0*game.skill)*(1.0+0.5*Rand()):
1350         return
1351
1352     ncrit = 1.0 + hit/(500.0+100.0*Rand())
1353     proutn(_("***CRITICAL HIT--"))
1354     # Select devices and cause damage
1355     cdam = []
1356     for loop1 in range(ncrit):
1357         while True:
1358             j = randdevice()
1359             # Cheat to prevent shuttle damage unless on ship 
1360             if not (game.damage[j]<0.0 or (j==DSHUTTL and game.iscraft != "onship")):
1361                 break
1362         cdam.append(j)
1363         extradm = (hit*game.damfac)/(ncrit*(75.0+25.0*Rand()))
1364         game.damage[j] += extradm
1365         if loop1 > 0:
1366             for loop2 in range(loop1):
1367                 if j == cdam[loop2]:
1368                     break
1369             if loop2 < loop1:
1370                 continue
1371             ktr += 1
1372             if ktr==3:
1373                 skip(1)
1374             proutn(_(" and "))
1375         proutn(device[j])
1376     prout(_(" damaged."))
1377     if damaged(DSHIELD) and game.shldup:
1378         prout(_("***Shields knocked down."))
1379         game.shldup=False
1380
1381 def attack(torps_ok):
1382     # bad guy attacks us 
1383     # torps_ok == false forces use of phasers in an attack 
1384     atackd = False; attempt = False; ihurt = False;
1385     hitmax=0.0; hittot=0.0; chgfac=1.0
1386     jay = coord()
1387     where = "neither"
1388
1389     # game could be over at this point, check 
1390     if game.alldone:
1391         return
1392
1393     if idebug:
1394         prout("=== ATTACK!")
1395
1396     # Tholian gewts to move before attacking 
1397     if game.ithere:
1398         movetholian()
1399
1400     # if you have just entered the RNZ, you'll get a warning 
1401     if game.neutz: # The one chance not to be attacked 
1402         game.neutz = False
1403         return
1404
1405     # commanders get a chance to tac-move towards you 
1406     if (((game.comhere or game.ishere) and not game.justin) or game.skill == SKILL_EMERITUS) and torps_ok:
1407         moveklings()
1408
1409     # if no enemies remain after movement, we're done 
1410     if game.nenhere==0 or (game.nenhere==1 and iqhere and not iqengry):
1411         return
1412
1413     # set up partial hits if attack happens during shield status change 
1414     pfac = 1.0/game.inshld
1415     if game.shldchg:
1416         chgfac = 0.25+0.5*Rand()
1417
1418     skip(1)
1419
1420     # message verbosity control 
1421     if game.skill <= SKILL_FAIR:
1422         where = "sector"
1423
1424     for loop in range(1, game.nenhere+1):
1425         if game.kpower[loop] < 0:
1426             continue;   # too weak to attack 
1427         # compute hit strength and diminish shield power 
1428         r = Rand()
1429         # Increase chance of photon torpedos if docked or enemy energy low 
1430         if game.condition == "docked":
1431             r *= 0.25
1432         if game.kpower[loop] < 500:
1433             r *= 0.25; 
1434         jay = game.ks[loop]
1435         iquad = game.quad[jay.x][jay.y]
1436         if iquad==IHT or (iquad==IHQUEST and not iqengry):
1437             continue
1438         # different enemies have different probabilities of throwing a torp 
1439         usephasers = not torps_ok or \
1440             (iquad == IHK and r > 0.0005) or \
1441             (iquad==IHC and r > 0.015) or \
1442             (iquad==IHR and r > 0.3) or \
1443             (iquad==IHS and r > 0.07) or \
1444             (iquad==IHQUEST and r > 0.05)
1445         if usephasers:      # Enemy uses phasers 
1446             if game.condition == "docked":
1447                 continue; # Don't waste the effort! 
1448             attempt = True; # Attempt to attack 
1449             dustfac = 0.8+0.05*Rand()
1450             hit = game.kpower[loop]*math.pow(dustfac,game.kavgd[loop])
1451             game.kpower[loop] *= 0.75
1452         else: # Enemy uses photon torpedo 
1453             course = 1.90985*math.atan2(game.sector.y-jay.y, jay.x-game.sector.x)
1454             hit = 0
1455             proutn(_("***TORPEDO INCOMING"))
1456             if not damaged(DSRSENS):
1457                 proutn(_(" From "))
1458                 crmena(False, iquad, where, jay)
1459             attempt = True
1460             prout("  ")
1461             r = (Rand()+Rand())*0.5 -0.5
1462             r += 0.002*game.kpower[loop]*r
1463             hit = torpedo(course, r, jay, 1, 1)
1464             if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1465                 finish(FWON); # Klingons did themselves in! 
1466             if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova or game.alldone:
1467                 return; # Supernova or finished 
1468             if hit == None:
1469                 continue
1470         # incoming phaser or torpedo, shields may dissipate it 
1471         if game.shldup or game.shldchg or game.condition=="docked":
1472             # shields will take hits 
1473             propor = pfac * game.shield
1474             if game.condition =="docked":
1475                 propr *= 2.1
1476             if propor < 0.1:
1477                 propor = 0.1
1478             hitsh = propor*chgfac*hit+1.0
1479             absorb = 0.8*hitsh
1480             if absorb > game.shield:
1481                 absorb = game.shield
1482             game.shield -= absorb
1483             hit -= hitsh
1484             # taking a hit blasts us out of a starbase dock 
1485             if game.condition == "docked":
1486                 dock(False)
1487             # but the shields may take care of it 
1488             if propor > 0.1 and hit < 0.005*game.energy:
1489                 continue
1490         # hit from this opponent got through shields, so take damage 
1491         ihurt = True
1492         proutn(_("%d unit hit") % int(hit))
1493         if (damaged(DSRSENS) and usephasers) or game.skill<=SKILL_FAIR:
1494             proutn(_(" on the "))
1495             crmshp()
1496         if not damaged(DSRSENS) and usephasers:
1497             proutn(_(" from "))
1498             crmena(False, iquad, where, jay)
1499         skip(1)
1500         # Decide if hit is critical 
1501         if hit > hitmax:
1502             hitmax = hit
1503         hittot += hit
1504         fry(hit)
1505         game.energy -= hit
1506     if game.energy <= 0:
1507         # Returning home upon your shield, not with it... 
1508         finish(FBATTLE)
1509         return
1510     if not attempt and game.condition == "docked":
1511         prout(_("***Enemies decide against attacking your ship."))
1512     if not atackd:
1513         return
1514     percent = 100.0*pfac*game.shield+0.5
1515     if not ihurt:
1516         # Shields fully protect ship 
1517         proutn(_("Enemy attack reduces shield strength to "))
1518     else:
1519         # Print message if starship suffered hit(s) 
1520         skip(1)
1521         proutn(_("Energy left %2d    shields ") % int(game.energy))
1522         if game.shldup:
1523             proutn(_("up "))
1524         elif not damaged(DSHIELD):
1525             proutn(_("down "))
1526         else:
1527             proutn(_("damaged, "))
1528     prout(_("%d%%,   torpedoes left %d"), percent, game.torps)
1529     # Check if anyone was hurt 
1530     if hitmax >= 200 or hittot >= 500:
1531         icas= hittot*Rand()*0.015
1532         if icas >= 2:
1533             skip(1)
1534             prout(_("Mc Coy-  \"Sickbay to bridge.  We suffered %d casualties") % icas)
1535             prout(_("   in that last attack.\""))
1536             game.casual += icas
1537             game.state.crew -= icas
1538     # After attack, reset average distance to enemies 
1539     for loop in range(1, game.nenhere+1):
1540         game.kavgd[loop] = game.kdist[loop]
1541     sortklings()
1542     return;
1543                 
1544 def deadkl(w, type, mv):
1545     # kill a Klingon, Tholian, Romulan, or Thingy 
1546     # Added mv to allow enemy to "move" before dying 
1547
1548     crmena(True, type, sector, mv)
1549     # Decide what kind of enemy it is and update appropriately 
1550     if type == IHR:
1551         # chalk up a Romulan 
1552         game.state.galaxy[game.quadrant.x][game.quadrant.y].romulans -= 1
1553         game.irhere -= 1
1554         game.state.nromrem -= 1
1555     elif type == IHT:
1556         # Killed a Tholian 
1557         game.ithere = False
1558     elif type == IHQUEST:
1559         # Killed a Thingy 
1560         iqhere = iqengry = False
1561         invalidate(thing)
1562     else:
1563         # Some type of a Klingon 
1564         game.state.galaxy[game.quadrant.x][game.quadrant.y].klingons -= 1
1565         game.klhere -= 1
1566         if type == IHC:
1567             game.comhere = False
1568             for i in range(1, game.state.remcom+1):
1569                 if same(game.state.kcmdr[i], game.quadrant):
1570                     break
1571             game.state.kcmdr[i] = game.state.kcmdr[game.state.remcom]
1572             game.state.kcmdr[game.state.remcom].x = 0
1573             game.state.kcmdr[game.state.remcom].y = 0
1574             game.state.remcom -= 1
1575             unschedule(FTBEAM)
1576             if game.state.remcom != 0:
1577                 schedule(FTBEAM, expran(1.0*game.incom/game.state.remcom))
1578         elif type ==  IHK:
1579             game.state.remkl -= 1
1580         elif type ==  IHS:
1581             game.state.nscrem -= 1
1582             game.ishere = False
1583             game.state.kscmdr.x = game.state.kscmdr.y = game.isatb = 0
1584             game.iscate = False
1585             unschedule(FSCMOVE)
1586             unschedule(FSCDBAS)
1587         else:
1588             prout("*** Internal error, deadkl() called on %s\n" % type)
1589
1590     # For each kind of enemy, finish message to player 
1591     prout(_(" destroyed."))
1592     game.quad[w.x][w.y] = IHDOT
1593     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1594         return
1595     game.recompute()
1596     # Remove enemy ship from arrays describing local conditions 
1597     if is_scheduled(FCDBAS) and same(game.battle, game.quadrant) and type==IHC:
1598         unschedule(FCDBAS)
1599     for i in range(1, game.nenhere+1):
1600         if same(game.ks[i], w):
1601             break
1602     game.nenhere -= 1
1603     if i <= game.nenhere:
1604         for j in range(i, game.nenhere+1):
1605             game.ks[j] = game.ks[j+1]
1606             game.kpower[j] = game.kpower[j+1]
1607             game.kavgd[j] = game.kdist[j] = game.kdist[j+1]
1608     game.ks[game.nenhere+1].x = 0
1609     game.ks[game.nenhere+1].x = 0
1610     game.kdist[game.nenhere+1] = 0
1611     game.kavgd[game.nenhere+1] = 0
1612     game.kpower[game.nenhere+1] = 0
1613     return;
1614
1615 def targetcheck(x, y):
1616     # Return None if target is invalid 
1617     if not VALID_SECTOR(x, y):
1618         huh()
1619         return None
1620     deltx = 0.1*(y - game.sector.y)
1621     delty = 0.1*(x - game.sector.x)
1622     if deltx==0 and delty== 0:
1623         skip(1)
1624         prout(_("Spock-  \"Bridge to sickbay.  Dr. McCoy,"))
1625         prout(_("  I recommend an immediate review of"))
1626         prout(_("  the Captain's psychological profile.\""))
1627         chew()
1628         return None
1629     return 1.90985932*math.atan2(deltx, delty)
1630
1631 def photon():
1632     # launch photon torpedo 
1633     game.ididit = False
1634     if damaged(DPHOTON):
1635         prout(_("Photon tubes damaged."))
1636         chew()
1637         return
1638     if game.torps == 0:
1639         prout(_("No torpedoes left."))
1640         chew()
1641         return
1642     key = scan()
1643     while True:
1644         if key == IHALPHA:
1645             huh()
1646             return
1647         elif key == IHEOL:
1648             prout(_("%d torpedoes left."), game.torps)
1649             proutn(_("Number of torpedoes to fire- "))
1650             key = scan()
1651         else: # key == IHREAL  {
1652             n = aaitem + 0.5
1653             if n <= 0: # abort command 
1654                 chew()
1655                 return
1656             if n > 3:
1657                 chew()
1658                 prout(_("Maximum of 3 torpedoes per burst."))
1659                 key = IHEOL
1660                 return
1661             if n <= game.torps:
1662                 break
1663             chew()
1664             key = IHEOL
1665     for i in range(1, n+1):
1666         key = scan()
1667         if i==1 and key == IHEOL:
1668             break;      # we will try prompting 
1669         if i==2 and key == IHEOL:
1670             # direct all torpedoes at one target 
1671             while i <= n:
1672                 targ[i][1] = targ[1][1]
1673                 targ[i][2] = targ[1][2]
1674                 course[i] = course[1]
1675                 i += 1
1676             break
1677         if key != IHREAL:
1678             huh()
1679             return
1680         targ[i][1] = aaitem
1681         key = scan()
1682         if key != IHREAL:
1683             huh()
1684             return
1685         targ[i][2] = aaitem
1686         course[i] = targetcheck(targ[i][1], targ[i][2])
1687         if course[i] == None:
1688             return
1689     chew()
1690     if i == 1 and key == IHEOL:
1691         # prompt for each one 
1692         for i in range(1, n+1):
1693             proutn(_("Target sector for torpedo number %d- "), i)
1694             key = scan()
1695             if key != IHREAL:
1696                 huh()
1697                 return
1698             targ[i][1] = aaitem
1699             key = scan()
1700             if key != IHREAL:
1701                 huh()
1702                 return
1703             targ[i][2] = aaitem
1704             chew()
1705             course[i] = targetcheck(targ[i][1], targ[i][2])
1706             if course[i] == None:
1707                 return
1708     game.ididit = True
1709     # Loop for moving <n> torpedoes 
1710     for i in range(1, n+1):
1711         if game.condition != "docked":
1712             game.torps -= 1
1713         r = (Rand()+Rand())*0.5 -0.5
1714         if math.fabs(r) >= 0.47:
1715             # misfire! 
1716             r = (Rand()+1.2) * r
1717             if n>1:
1718                 prouts(_("***TORPEDO NUMBER %d MISFIRES"), i)
1719             else:
1720                 prouts(_("***TORPEDO MISFIRES."))
1721             skip(1)
1722             if i < n:
1723                 prout(_("  Remainder of burst aborted."))
1724             if Rand() <= 0.2:
1725                 prout(_("***Photon tubes damaged by misfire."))
1726                 game.damage[DPHOTON] = game.damfac*(1.0+2.0*Rand())
1727             break
1728         if game.shldup or game.condition == "docked":
1729             r *= 1.0 + 0.0001*game.shield
1730         torpedo(course[i], r, game.sector, i, n)
1731         if game.alldone or game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
1732             return
1733     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1734         finish(FWON);
1735
1736 def overheat(rpow):
1737     # check for phasers overheating 
1738     if rpow > 1500:
1739         chekbrn = (rpow-1500.)*0.00038
1740         if Rand() <= chekbrn:
1741             prout(_("Weapons officer Sulu-  \"Phasers overheated, sir.\""))
1742             game.damage[DPHASER] = game.damfac*(1.0 + Rand()) * (1.0+chekbrn)
1743
1744 def checkshctrl(rpow):
1745     # check shield control 
1746         
1747     skip(1)
1748     if Rand() < 0.998:
1749         prout(_("Shields lowered."))
1750         return False
1751     # Something bad has happened 
1752     prouts(_("***RED ALERT!  RED ALERT!"))
1753     skip(2)
1754     hit = rpow*game.shield/game.inshld
1755     game.energy -= rpow+hit*0.8
1756     game.shield -= hit*0.2
1757     if game.energy <= 0.0:
1758         prouts(_("Sulu-  \"Captain! Shield malf***********************\""))
1759         skip(1)
1760         stars()
1761         finish(FPHASER)
1762         return True
1763     prouts(_("Sulu-  \"Captain! Shield malfunction! Phaser fire contained!\""))
1764     skip(2)
1765     prout(_("Lt. Uhura-  \"Sir, all decks reporting damage.\""))
1766     icas = hit*Rand()*0.012
1767     skip(1)
1768     fry(0.8*hit)
1769     if icas:
1770         skip(1)
1771         prout(_("McCoy to bridge- \"Severe radiation burns, Jim."))
1772         prout(_("  %d casualties so far.\""), icas)
1773         game.casual += icas
1774         game.state.crew -= icas
1775     skip(1)
1776     prout(_("Phaser energy dispersed by shields."))
1777     prout(_("Enemy unaffected."))
1778     overheat(rpow)
1779     return True;
1780
1781 def hittem(doublehits):
1782     # register a phaser hit on Klingons and Romulans 
1783     nenhr2=game.nenhere; kk=1
1784     w = coord()
1785     skip(1)
1786     for k in range(1, nenhr2+1):
1787         wham = hits[k]
1788         if wham==0:
1789             continue
1790         dustfac = 0.9 + 0.01*Rand()
1791         hit = wham*math.pow(dustfac,game.kdist[kk])
1792         kpini = game.kpower[kk]
1793         kp = math.fabs(kpini)
1794         if PHASEFAC*hit < kp:
1795             kp = PHASEFAC*hit
1796         if game.kpower[kk] < 0:
1797             game.kpower[kk] -= -kp
1798         else:
1799             game.kpower[kk] -= kp
1800         kpow = game.kpower[kk]
1801         w = game.ks[kk]
1802         if hit > 0.005:
1803             if not damaged(DSRSENS):
1804                 boom(w)
1805             proutn(_("%d unit hit on ") % int(hit))
1806         else:
1807             proutn(_("Very small hit on "))
1808         ienm = game.quad[w.x][w.y]
1809         if ienm==IHQUEST:
1810             iqengry = True
1811         crmena(False, ienm, "sector", w)
1812         skip(1)
1813         if kpow == 0:
1814             deadkl(w, ienm, w)
1815             if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1816                 finish(FWON);           
1817             if game.alldone:
1818                 return
1819             kk -= 1; # don't do the increment 
1820         else: # decide whether or not to emasculate klingon 
1821             if kpow > 0 and Rand() >= 0.9 and \
1822                 kpow <= ((0.4 + 0.4*Rand())*kpini):
1823                 prout(_("***Mr. Spock-  \"Captain, the vessel at %s"),
1824                       cramlc(sector, w))
1825                 prout(_("   has just lost its firepower.\""))
1826                 game.kpower[kk] = -kpow
1827         kk += 1
1828     return;
1829
1830 def phasers():
1831     # fire phasers 
1832     hits = []; rpow=0
1833     kz = 0; k = 1; irec=0 # Cheating inhibitor 
1834     ifast = False; no = False; itarg = True; msgflag = True
1835     automode = "NOTSET"
1836     key=0
1837
1838     skip(1)
1839     # SR sensors and Computer are needed fopr automode 
1840     if damaged(DSRSENS) or damaged(DCOMPTR):
1841         itarg = False
1842     if game.condition == "docked":
1843         prout(_("Phasers can't be fired through base shields."))
1844         chew()
1845         return
1846     if damaged(DPHASER):
1847         prout(_("Phaser control damaged."))
1848         chew()
1849         return
1850     if game.shldup:
1851         if damaged(DSHCTRL):
1852             prout(_("High speed shield control damaged."))
1853             chew()
1854             return
1855         if game.energy <= 200.0:
1856             prout(_("Insufficient energy to activate high-speed shield control."))
1857             chew()
1858             return
1859         prout(_("Weapons Officer Sulu-  \"High-speed shield control enabled, sir.\""))
1860         ifast = True
1861                 
1862     # Original code so convoluted, I re-did it all 
1863     while automode=="NOTSET":
1864         key=scan()
1865         if key == IHALPHA:
1866             if isit("manual"):
1867                 if game.nenhere==0:
1868                     prout(_("There is no enemy present to select."))
1869                     chew()
1870                     key = IHEOL
1871                     automode="AUTOMATIC"
1872                 else:
1873                     automode = "MANUAL"
1874                     key = scan()
1875             elif isit("automatic"):
1876                 if (not itarg) and game.nenhere != 0:
1877                     automode = "FORCEMAN"
1878                 else:
1879                     if game.nenhere==0:
1880                         prout(_("Energy will be expended into space."))
1881                     automode = "AUTOMATIC"
1882                     key = scan()
1883             elif isit("no"):
1884                 no = True
1885             else:
1886                 huh()
1887                 return
1888         elif key == IHREAL:
1889             if game.nenhere==0:
1890                 prout(_("Energy will be expended into space."))
1891                 automode = "AUTOMATIC"
1892             elif not itarg:
1893                 automode = "FORCEMAN"
1894             else:
1895                 automode = "AUTOMATIC"
1896         else:
1897             # IHEOL 
1898             if game.nenhere==0:
1899                 prout(_("Energy will be expended into space."))
1900                 automode = "AUTOMATIC"
1901             elif not itarg:
1902                 automode = "FORCEMAN"
1903             else: 
1904                 proutn(_("Manual or automatic? "))                      
1905     avail = game.energy
1906     if ifast:
1907         avail -= 200.0
1908     if automode == "AUTOMATIC":
1909         if key == IHALPHA and isit("no"):
1910             no = True
1911             key = scan()
1912         if key != IHREAL and game.nenhere != 0:
1913             prout(_("Phasers locked on target. Energy available: %.2f"),
1914                   avail)
1915         irec=0
1916         while True:
1917             chew()
1918             if not kz:
1919                 for i in range(1, game.nenhere+1):
1920                     irec += math.fabs(game.kpower[i])/(PHASEFAC*math.pow(0.90,game.kdist[i]))*(1.01+0.05*Rand()) + 1.0
1921             kz=1
1922             proutn(_("%d units required. "), irec)
1923             chew()
1924             proutn(_("Units to fire= "))
1925             key = scan()
1926             if key!=IHREAL:
1927                 return
1928             rpow = aaitem
1929             if rpow > avail:
1930                 proutn(_("Energy available= %.2f") % avail)
1931                 skip(1)
1932                 key = IHEOL
1933             if not rpow > avail:
1934                 break
1935         if rpow<=0:
1936             # chicken out 
1937             chew()
1938             return
1939         key=scan()
1940         if key == IHALPHA and isit("no"):
1941             no = True
1942         if ifast:
1943             game.energy -= 200; # Go and do it! 
1944             if checkshctrl(rpow):
1945                 return
1946         chew()
1947         game.energy -= rpow
1948         extra = rpow
1949         if game.nenhere:
1950             extra = 0.0
1951             powrem = rpow
1952             for i in range(1, game.nenhere+1):
1953                 hits[i] = 0.0
1954                 if powrem <= 0:
1955                     continue
1956                 hits[i] = math.fabs(game.kpower[i])/(PHASEFAC*math.pow(0.90,game.kdist[i]))
1957                 over = (0.01 + 0.05*Rand())*hits[i]
1958                 temp = powrem
1959                 powrem -= hits[i] + over
1960                 if powrem <= 0 and temp < hits[i]:
1961                     hits[i] = temp
1962                 if powrem <= 0:
1963                     over = 0.0
1964                 extra += over
1965             if powrem > 0.0:
1966                 extra += powrem
1967             hittem(hits)
1968             game.ididit = True
1969         if extra > 0 and not game.alldone:
1970             if game.ithere:
1971                 proutn(_("*** Tholian web absorbs "))
1972                 if game.nenhere>0:
1973                     proutn(_("excess "))
1974                 prout(_("phaser energy."))
1975             else:
1976                 prout(_("%d expended on empty space."), int(extra))
1977     elif automode == "FORCEMAN":
1978         chew()
1979         key = IHEOL
1980         if damaged(DCOMPTR):
1981             prout(_("Battle computer damaged, manual fire only."))
1982         else:
1983             skip(1)
1984             prouts(_("---WORKING---"))
1985             skip(1)
1986             prout(_("Short-range-sensors-damaged"))
1987             prout(_("Insufficient-data-for-automatic-phaser-fire"))
1988             prout(_("Manual-fire-must-be-used"))
1989             skip(1)
1990     elif automode == "MANUAL":
1991         rpow = 0.0
1992         for k in range(1, game.nenhere+1):
1993             aim = game.ks[k]
1994             ienm = game.quad[aim.x][aim.y]
1995             if msgflag:
1996                 proutn(_("Energy available= %.2f") % avail-0.006)
1997                 skip(1)
1998                 msgflag = False
1999                 rpow = 0.0
2000             if damaged(DSRSENS) and not (abs(game.sector.x-aim.x) < 2 and abs(game.sector.y-aim.y) < 2) and \
2001                 (ienm == IHC or ienm == IHS):
2002                 cramen(ienm)
2003                 prout(_(" can't be located without short range scan."))
2004                 chew()
2005                 key = IHEOL
2006                 hits[k] = 0; # prevent overflow -- thanks to Alexei Voitenko 
2007                 k += 1
2008                 continue
2009             if key == IHEOL:
2010                 chew()
2011                 if itarg and k > kz:
2012                     irec=(abs(game.kpower[k])/(PHASEFAC*math.pow(0.9,game.kdist[k]))) * (1.01+0.05*Rand()) + 1.0
2013                 kz = k
2014                 proutn("(")
2015                 if not damaged(DCOMPTR):
2016                     proutn("%d", irec)
2017                 else:
2018                     proutn("??")
2019                 proutn(")  ")
2020                 proutn(_("units to fire at "))
2021                 crmena(False, ienm, sector, aim)
2022                 proutn("-  ")
2023                 key = scan()
2024             if key == IHALPHA and isit("no"):
2025                 no = True
2026                 key = scan()
2027                 continue
2028             if key == IHALPHA:
2029                 huh()
2030                 return
2031             if key == IHEOL:
2032                 if k==1: # Let me say I'm baffled by this 
2033                     msgflag = True
2034                 continue
2035             if aaitem < 0:
2036                 # abort out 
2037                 chew()
2038                 return
2039             hits[k] = aaitem
2040             rpow += aaitem
2041             # If total requested is too much, inform and start over 
2042             if rpow > avail:
2043                 prout(_("Available energy exceeded -- try again."))
2044                 chew()
2045                 return
2046             key = scan(); # scan for next value 
2047             k += 1
2048         if rpow == 0.0:
2049             # zero energy -- abort 
2050             chew()
2051             return
2052         if key == IHALPHA and isit("no"):
2053             no = True
2054         game.energy -= rpow
2055         chew()
2056         if ifast:
2057             game.energy -= 200.0
2058             if checkshctrl(rpow):
2059                 return
2060         hittem(hits)
2061         game.ididit = True
2062      # Say shield raised or malfunction, if necessary 
2063     if game.alldone:
2064         return
2065     if ifast:
2066         skip(1)
2067         if no == 0:
2068             if Rand() >= 0.99:
2069                 prout(_("Sulu-  \"Sir, the high-speed shield control has malfunctioned . . ."))
2070                 prouts(_("         CLICK   CLICK   POP  . . ."))
2071                 prout(_(" No response, sir!"))
2072                 game.shldup = False
2073             else:
2074                 prout(_("Shields raised."))
2075         else:
2076             game.shldup = False
2077     overheat(rpow);
2078
2079 # Code from events,c begins here.
2080
2081 # This isn't a real event queue a la BSD Trek yet -- you can only have one 
2082 # event of each type active at any given time.  Mostly these means we can 
2083 # only have one FDISTR/FENSLV/FREPRO sequence going at any given time
2084 # BSD Trek, from which we swiped the idea, can have up to 5.
2085
2086 import math
2087
2088 def unschedule(evtype):
2089     # remove an event from the schedule 
2090     game.future[evtype].date = FOREVER
2091     return game.future[evtype]
2092
2093 def is_scheduled(evtype):
2094     # is an event of specified type scheduled 
2095     return game.future[evtype].date != FOREVER
2096
2097 def scheduled(evtype):
2098     # when will this event happen? 
2099     return game.future[evtype].date
2100
2101 def schedule(evtype, offset):
2102     # schedule an event of specified type 
2103     game.future[evtype].date = game.state.date + offset
2104     return game.future[evtype]
2105
2106 def postpone(evtype, offset):
2107     # postpone a scheduled event 
2108     game.future[evtype].date += offset
2109
2110 def cancelrest():
2111     # rest period is interrupted by event 
2112     if game.resting:
2113         skip(1)
2114         proutn(_("Mr. Spock-  \"Captain, shall we cancel the rest period?\""))
2115         if ja() == True:
2116             game.resting = False
2117             game.optime = 0.0
2118             return True
2119
2120     return False
2121
2122 def events():
2123     # run through the event queue looking for things to do 
2124     i=0
2125     fintim = game.state.date + game.optime; yank=0
2126     ictbeam = False; istract = False
2127     w = coord(); hold = coord()
2128     ev = event(); ev2 = event()
2129
2130     def tractorbeam():
2131         # tractor beaming cases merge here 
2132         yank = math.sqrt(yank)
2133         announce()
2134         game.optime = (10.0/(7.5*7.5))*yank # 7.5 is yank rate (warp 7.5) 
2135         skip(1)
2136         proutn("***")
2137         crmshp()
2138         prout(_(" caught in long range tractor beam--"))
2139         # If Kirk & Co. screwing around on planet, handle 
2140         atover(True) # atover(true) is Grab 
2141         if game.alldone:
2142             return
2143         if game.icraft: # Caught in Galileo? 
2144             finish(FSTRACTOR)
2145             return
2146         # Check to see if shuttle is aboard 
2147         if game.iscraft == "offship":
2148             skip(1)
2149             if Rand() > 0.5:
2150                 prout(_("Galileo, left on the planet surface, is captured"))
2151                 prout(_("by aliens and made into a flying McDonald's."))
2152                 game.damage[DSHUTTL] = -10
2153                 game.iscraft = "removed"
2154             else:
2155                 prout(_("Galileo, left on the planet surface, is well hidden."))
2156         if evcode==0:
2157             game.quadrant = game.state.kscmdr
2158         else:
2159             game.quadrant = game.state.kcmdr[i]
2160         game.sector = randplace(QUADSIZE)
2161         crmshp()
2162         proutn(_(" is pulled to "))
2163         proutn(cramlc(quadrant, game.quadrant))
2164         proutn(", ")
2165         prout(cramlc(sector, game.sector))
2166         if game.resting:
2167             prout(_("(Remainder of rest/repair period cancelled.)"))
2168             game.resting = False
2169         if not game.shldup:
2170             if not damaged(DSHIELD) and game.shield > 0:
2171                 doshield(True) # raise shields 
2172                 game.shldchg=False
2173             else:
2174                 prout(_("(Shields not currently useable.)"))
2175         newqad(False)
2176         # Adjust finish time to time of tractor beaming 
2177         fintim = game.state.date+game.optime
2178         attack(False)
2179         if game.state.remcom <= 0:
2180             unschedule(FTBEAM)
2181         else: 
2182             schedule(FTBEAM, game.optime+expran(1.5*game.intime/game.state.remcom))
2183
2184     def destroybase():
2185         # Code merges here for any commander destroying base 
2186         # Not perfect, but will have to do 
2187         # Handle case where base is in same quadrant as starship 
2188         if same(game.battle, game.quadrant):
2189             game.state.chart[game.battle.x][game.battle.y].starbase = False
2190             game.quad[game.base.x][game.base.y] = IHDOT
2191             game.base.x=game.base.y=0
2192             newcnd()
2193             skip(1)
2194             prout(_("Spock-  \"Captain, I believe the starbase has been destroyed.\""))
2195         elif game.state.rembase != 1 and \
2196                  (not damaged(DRADIO) or game.condition == "docked"):
2197             # Get word via subspace radio 
2198             announce()
2199             skip(1)
2200             prout(_("Lt. Uhura-  \"Captain, Starfleet Command reports that"))
2201             proutn(_("   the starbase in "))
2202             proutn(cramlc(quadrant, game.battle))
2203             prout(_(" has been destroyed by"))
2204             if game.isatb == 2: 
2205                 prout(_("the Klingon Super-Commander"))
2206             else:
2207                 prout(_("a Klingon Commander"))
2208             game.state.chart[game.battle.x][game.battle.y].starbase = False
2209         # Remove Starbase from galaxy 
2210         game.state.galaxy[game.battle.x][game.battle.y].starbase = False
2211         for i in range(1, game.state.rembase+1):
2212             if same(game.state.baseq[i], game.battle):
2213                 game.state.baseq[i] = game.state.baseq[game.state.rembase]
2214         game.state.rembase -= 1
2215         if game.isatb == 2:
2216             # reinstate a commander's base attack 
2217             game.battle = hold
2218             game.isatb = 0
2219         else:
2220             invalidate(game.battle)
2221
2222     if idebug:
2223         prout("=== EVENTS from %.2f to %.2f:" % (game.state.date, fintim))
2224         for i in range(1, NEVENTS):
2225             if   i == FSNOVA:  proutn("=== Supernova       ")
2226             elif i == FTBEAM:  proutn("=== T Beam          ")
2227             elif i == FSNAP:   proutn("=== Snapshot        ")
2228             elif i == FBATTAK: proutn("=== Base Attack     ")
2229             elif i == FCDBAS:  proutn("=== Base Destroy    ")
2230             elif i == FSCMOVE: proutn("=== SC Move         ")
2231             elif i == FSCDBAS: proutn("=== SC Base Destroy ")
2232             elif i == FDSPROB: proutn("=== Probe Move      ")
2233             elif i == FDISTR:  proutn("=== Distress Call   ")
2234             elif i == FENSLV:  proutn("=== Enslavement     ")
2235             elif i == FREPRO:  proutn("=== Klingon Build   ")
2236             if is_scheduled(i):
2237                 prout("%.2f" % (scheduled(i)))
2238             else:
2239                 prout("never")
2240     radio_was_broken = damaged(DRADIO)
2241     hold.x = hold.y = 0
2242     while True:
2243         # Select earliest extraneous event, evcode==0 if no events 
2244         evcode = FSPY
2245         if game.alldone:
2246             return
2247         datemin = fintim
2248         for l in range(1, NEVENTS):
2249             if game.future[l].date < datemin:
2250                 evcode = l
2251                 if idebug:
2252                     prout("== Event %d fires" % (evcode))
2253                 datemin = game.future[l].date
2254         xtime = datemin-game.state.date
2255         game.state.date = datemin
2256         # Decrement Federation resources and recompute remaining time 
2257         game.state.remres -= (game.state.remkl+4*game.state.remcom)*xtime
2258         game.recompute()
2259         if game.state.remtime <=0:
2260             finish(FDEPLETE)
2261             return
2262         # Any crew left alive? 
2263         if game.state.crew <=0:
2264             finish(FCREW)
2265             return
2266         # Is life support adequate? 
2267         if damaged(DLIFSUP) and game.condition != "docked":
2268             if game.lsupres < xtime and game.damage[DLIFSUP] > game.lsupres:
2269                 finish(FLIFESUP)
2270                 return
2271             game.lsupres -= xtime
2272             if game.damage[DLIFSUP] <= xtime:
2273                 game.lsupres = game.inlsr
2274         # Fix devices 
2275         repair = xtime
2276         if game.condition == "docked":
2277             repair /= game.docfac
2278         # Don't fix Deathray here 
2279         for l in range(0, NDEVICES):
2280             if game.damage[l] > 0.0 and l != DDRAY:
2281                 if game.damage[l]-repair > 0.0:
2282                     game.damage[l] -= repair
2283                 else:
2284                     game.damage[l] = 0.0
2285         # If radio repaired, update star chart and attack reports 
2286         if radio_was_broken and not damaged(DRADIO):
2287             prout(_("Lt. Uhura- \"Captain, the sub-space radio is working and"))
2288             prout(_("   surveillance reports are coming in."))
2289             skip(1)
2290             if not game.iseenit:
2291                 attackreport(False)
2292                 game.iseenit = True
2293             rechart()
2294             prout(_("   The star chart is now up to date.\""))
2295             skip(1)
2296         # Cause extraneous event EVCODE to occur 
2297         game.optime -= xtime
2298         if evcode == FSNOVA: # Supernova 
2299             announce()
2300             supernova(False)
2301             schedule(FSNOVA, expran(0.5*game.intime))
2302             if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
2303                 return
2304         elif evcode == FSPY: # Check with spy to see if SC should tractor beam 
2305             if game.state.nscrem == 0 or \
2306                 ictbeam or istract or \
2307                 game.condition=="docked" or game.isatb==1 or game.iscate:
2308                 return
2309             if game.ientesc or \
2310                 (game.energy<2000 and game.torps<4 and game.shield < 1250) or \
2311                 (damaged(DPHASER) and (damaged(DPHOTON) or game.torps<4)) or \
2312                 (damaged(DSHIELD) and \
2313                  (game.energy < 2500 or damaged(DPHASER)) and \
2314                  (game.torps < 5 or damaged(DPHOTON))):
2315                 # Tractor-beam her! 
2316                 istract = True
2317                 yank = distance(game.state.kscmdr, game.quadrant)
2318                 ictbeam = True
2319                 tractorbeam()
2320             else:
2321                 return
2322         elif evcode == FTBEAM: # Tractor beam 
2323             if game.state.remcom == 0:
2324                 unschedule(FTBEAM)
2325                 continue
2326             i = Rand()*game.state.remcom+1.0
2327             yank = square(game.state.kcmdr[i].x-game.quadrant.x) + square(game.state.kcmdr[i].y-game.quadrant.y)
2328             if istract or game.condition == "docked" or yank == 0:
2329                 # Drats! Have to reschedule 
2330                 schedule(FTBEAM, 
2331                          game.optime + expran(1.5*game.intime/game.state.remcom))
2332                 continue
2333             ictbeam = True
2334             tractorbeam()
2335         elif evcode == FSNAP: # Snapshot of the universe (for time warp) 
2336             game.snapsht = game.state
2337             game.state.snap = True
2338             schedule(FSNAP, expran(0.5 * game.intime))
2339         elif evcode == FBATTAK: # Commander attacks starbase 
2340             if game.state.remcom==0 or game.state.rembase==0:
2341                 # no can do 
2342                 unschedule(FBATTAK)
2343                 unschedule(FCDBAS)
2344                 continue
2345             i = 0
2346             for j in range(1, game.state.rembase+1):
2347                 for k in range(1, game.state.remcom+1):
2348                     if same(game.state.baseq[j], game.state.kcmdr[k]) and \
2349                         not same(game.state.baseq[j], game.quadrant) and \
2350                         not same(game.state.baseq[j], game.state.kscmdr):
2351                         i = 1
2352                 if i == 1:
2353                     continue
2354             if j>game.state.rembase:
2355                 # no match found -- try later 
2356                 schedule(FBATTAK, expran(0.3*game.intime))
2357                 unschedule(FCDBAS)
2358                 continue
2359             # commander + starbase combination found -- launch attack 
2360             game.battle = game.state.baseq[j]
2361             schedule(FCDBAS, 1.0+3.0*Rand())
2362             if game.isatb: # extra time if SC already attacking 
2363                 postpone(FCDBAS, scheduled(FSCDBAS)-game.state.date)
2364             game.future[FBATTAK].date = game.future[FCDBAS].date + expran(0.3*game.intime)
2365             game.iseenit = False
2366             if damaged(DRADIO) and game.condition != "docked": 
2367                 continue # No warning :-( 
2368             game.iseenit = True
2369             announce()
2370             skip(1)
2371             proutn(_("Lt. Uhura-  \"Captain, the starbase in Quadrant %s") % game.battle)
2372             prout(_("   reports that it is under attack and that it can"))
2373             proutn(_("   hold out only until stardate %d" % (int(scheduled(FCDBAS)))))
2374             prout(".\"")
2375             if cancelrest():
2376                 return
2377         elif evcode == FSCDBAS: # Supercommander destroys base 
2378             unschedule(FSCDBAS)
2379             game.isatb = 2
2380             if not game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].starbase: 
2381                 continue # WAS RETURN! 
2382             hold = game.battle
2383             game.battle = game.state.kscmdr
2384             destroybase()
2385         elif evcode == FCDBAS: # Commander succeeds in destroying base 
2386             if evcode==FCDBAS:
2387                 unschedule(FCDBAS)
2388                 # find the lucky pair 
2389                 for i in range(1, game.state.remcom+1):
2390                     if same(game.state.kcmdr[i], game.battle): 
2391                         break
2392                 if i > game.state.remcom or game.state.rembase == 0 or \
2393                     not game.state.galaxy[game.battle.x][game.battle.y].starbase:
2394                     # No action to take after all 
2395                     invalidate(game.battle)
2396                     continue
2397             destroybase()
2398         elif evcode == FSCMOVE: # Supercommander moves 
2399             schedule(FSCMOVE, 0.2777)
2400             if not game.ientesc and not istract and game.isatb != 1 and \
2401                    (not game.iscate or not game.justin): 
2402                 supercommander()
2403         elif evcode == FDSPROB: # Move deep space probe 
2404             schedule(FDSPROB, 0.01)
2405             game.probex += game.probeinx
2406             game.probey += game.probeiny
2407             i = (int)(game.probex/QUADSIZE +0.05)
2408             j = (int)(game.probey/QUADSIZE + 0.05)
2409             if game.probec.x != i or game.probec.y != j:
2410                 game.probec.x = i
2411                 game.probec.y = j
2412                 if not VALID_QUADRANT(i, j) or \
2413                     game.state.galaxy[game.probec.x][game.probec.y].supernova:
2414                     # Left galaxy or ran into supernova
2415                     if not damaged(DRADIO) or game.condition == "docked":
2416                         announce()
2417                         skip(1)
2418                         proutn(_("Lt. Uhura-  \"The deep space probe "))
2419                         if not VALID_QUADRANT(j, i):
2420                             proutn(_("has left the galaxy"))
2421                         else:
2422                             proutn(_("is no longer transmitting"))
2423                         prout(".\"")
2424                     unschedule(FDSPROB)
2425                     continue
2426                 if not damaged(DRADIO) or game.condition == "docked":
2427                     announce()
2428                     skip(1)
2429                     proutn(_("Lt. Uhura-  \"The deep space probe is now in "))
2430                     proutn(cramlc(quadrant, game.probec))
2431                     prout(".\"")
2432             pdest = game.state.galaxy[game.probec.x][game.probec.y]
2433             # Update star chart if Radio is working or have access to radio
2434             if not damaged(DRADIO) or game.condition == "docked":
2435                 chp = game.state.chart[game.probec.x][game.probec.y]
2436                 chp.klingons = pdest.klingons
2437                 chp.starbase = pdest.starbase
2438                 chp.stars = pdest.stars
2439                 pdest.charted = True
2440             game.proben -= 1 # One less to travel
2441             if game.proben == 0 and game.isarmed and pdest.stars:
2442                 # lets blow the sucker! 
2443                 supernova(True, game.probec)
2444                 unschedule(FDSPROB)
2445                 if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova: 
2446                     return
2447         elif evcode == FDISTR: # inhabited system issues distress call 
2448             unschedule(FDISTR)
2449             # try a whole bunch of times to find something suitable 
2450             for i in range(100):
2451                 # need a quadrant which is not the current one,
2452                 # which has some stars which are inhabited and
2453                 # not already under attack, which is not
2454                 # supernova'ed, and which has some Klingons in it
2455                 w = randplace(GALSIZE)
2456                 q = game.state.galaxy[w.x][w.y]
2457                 if not (same(game.quadrant, w) or q.planet == NOPLANET or \
2458                       game.state.planets[q.planet].inhabited == UNINHABITED or \
2459                       q.supernova or q.status!=secure or q.klingons<=0):
2460                     break
2461             else:
2462                 # can't seem to find one; ignore this call 
2463                 if idebug:
2464                     prout("=== Couldn't find location for distress event.")
2465                 continue
2466             # got one!!  Schedule its enslavement 
2467             ev = schedule(FENSLV, expran(game.intime))
2468             ev.quadrant = w
2469             q.status = distressed
2470
2471             # tell the captain about it if we can 
2472             if not damaged(DRADIO) or game.condition == "docked":
2473                 prout(_("Uhura- Captain, %s in Quadrant %s reports it is under attack" \
2474                         % (systnames[q.planet], `w`)))
2475                 prout(_("by a Klingon invasion fleet."))
2476                 if cancelrest():
2477                     return
2478         elif evcode == FENSLV:          # starsystem is enslaved 
2479             ev = unschedule(FENSLV)
2480             # see if current distress call still active 
2481             q = game.state.galaxy[ev.quadrant.x][ev.quadrant.y]
2482             if q.klingons <= 0:
2483                 q.status = "secure"
2484                 continue
2485             q.status = "enslaved"
2486
2487             # play stork and schedule the first baby 
2488             ev2 = schedule(FREPRO, expran(2.0 * game.intime))
2489             ev2.quadrant = ev.quadrant
2490
2491             # report the disaster if we can 
2492             if not damaged(DRADIO) or game.condition == "docked":
2493                 prout(_("Uhura- We've lost contact with starsystem %s" % \
2494                         systnames[q.planet]))
2495                 prout(_("in Quadrant %s.\n" % ev.quadrant))
2496         elif evcode == FREPRO:          # Klingon reproduces 
2497             # If we ever switch to a real event queue, we'll need to
2498             # explicitly retrieve and restore the x and y.
2499             ev = schedule(FREPRO, expran(1.0 * game.intime))
2500             # see if current distress call still active 
2501             q = game.state.galaxy[ev.quadrant.x][ev.quadrant.y]
2502             if q.klingons <= 0:
2503                 q.status = "secure"
2504                 continue
2505             if game.state.remkl >=MAXKLGAME:
2506                 continue                # full right now 
2507             # reproduce one Klingon 
2508             w = ev.quadrant
2509             if game.klhere >= MAXKLQUAD:
2510                 try:
2511                     # this quadrant not ok, pick an adjacent one 
2512                     for i in range(w.x - 1, w.x + 2):
2513                         for j in range(w.y - 1, w.y + 2):
2514                             if not VALID_QUADRANT(i, j):
2515                                 continue
2516                             q = game.state.galaxy[w.x][w.y]
2517                             # check for this quad ok (not full & no snova) 
2518                             if q.klingons >= MAXKLQUAD or q.supernova:
2519                                 continue
2520                             raise "FOUNDIT"
2521                     else:
2522                         continue        # search for eligible quadrant failed
2523                 except "FOUNDIT":
2524                     w.x = i
2525                     w.y = j
2526             # deliver the child 
2527             game.state.remkl += 1
2528             q.klingons += 1
2529             if same(game.quadrant, w):
2530                 newkling(++game.klhere)
2531
2532             # recompute time left
2533             game.recompute()
2534             # report the disaster if we can 
2535             if not damaged(DRADIO) or game.condition == "docked":
2536                 if same(game.quadrant, w):
2537                     prout(_("Spock- sensors indicate the Klingons have"))
2538                     prout(_("launched a warship from %s." \
2539                             % systnames[q.planet]))
2540                 else:
2541                     prout(_("Uhura- Starfleet reports increased Klingon activity"))
2542                     if q.planet != NOPLANET:
2543                         proutn(_("near %s" % systnames[q.planet]))
2544                     prout(_("in %s.\n" % cramlc(quadrant, w)))
2545                                 
2546 def wait():
2547     # wait on events 
2548     game.ididit = False
2549     while True:
2550         key = scan()
2551         if key  != IHEOL:
2552             break
2553         proutn(_("How long? "))
2554     chew()
2555     if key != IHREAL:
2556         huh()
2557         return
2558     origTime = delay = aaitem
2559     if delay <= 0.0:
2560         return
2561     if delay >= game.state.remtime or game.nenhere != 0:
2562         proutn(_("Are you sure? "))
2563         if ja() == False:
2564             return
2565
2566     # Alternate resting periods (events) with attacks 
2567
2568     game.resting = True
2569     while True:
2570         if delay <= 0:
2571             game.resting = False
2572         if not game.resting:
2573             prout(_("%d stardates left." % int(game.state.remtime)))
2574             return
2575         temp = game.optime = delay
2576         if game.nenhere:
2577             rtime = 1.0 + Rand()
2578             if rtime < temp:
2579                 temp = rtime
2580             game.optime = temp
2581         if game.optime < delay:
2582             attack(False)
2583         if game.alldone:
2584             return
2585         events()
2586         game.ididit = True
2587         if game.alldone:
2588             return
2589         delay -= temp
2590         # Repair Deathray if long rest at starbase 
2591         if origTime-delay >= 9.99 and game.condition == "docked":
2592             game.damage[DDRAY] = 0.0
2593         # leave if quadrant supernovas
2594         if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
2595             break
2596     game.resting = False
2597     game.optime = 0
2598
2599 # A nova occurs.  It is the result of having a star hit with a
2600 # photon torpedo, or possibly of a probe warhead going off.
2601 # Stars that go nova cause stars which surround them to undergo
2602 # the same probabilistic process.  Klingons next to them are
2603 # destroyed.  And if the starship is next to it, it gets zapped.
2604 # If the zap is too much, it gets destroyed.
2605         
2606 def nova(nov):
2607     # star goes nova 
2608     course = (0.0, 10.5, 12.0, 1.5, 9.0, 0.0, 3.0, 7.5, 6.0, 4.5)
2609     newc = coord(); scratch = coord()
2610
2611     if Rand() < 0.05:
2612         # Wow! We've supernova'ed 
2613         supernova(False, nov)
2614         return
2615
2616     # handle initial nova 
2617     game.quad[nov.x][nov.y] = IHDOT
2618     crmena(False, IHSTAR, sector, nov)
2619     prout(_(" novas."))
2620     game.state.galaxy[game.quadrant.x][game.quadrant.y].stars -= 1
2621     game.state.starkl += 1
2622         
2623     # Set up stack to recursively trigger adjacent stars 
2624     bot = top = top2 = 1
2625     kount = 0
2626     icx = icy = 0
2627     hits[1][1] = nov.x
2628     hits[1][2] = nov.y
2629     while True:
2630         for mm in range(bot, top+1): 
2631             for nn in range(1, 3+1):  # nn,j represents coordinates around current 
2632                 for j in range(1, 3+1):
2633                     if j==2 and nn== 2:
2634                         continue
2635                     scratch.x = hits[mm][1]+nn-2
2636                     scratch.y = hits[mm][2]+j-2
2637                     if not VALID_SECTOR(scratch.y, scratch.x):
2638                         continue
2639                     iquad = game.quad[scratch.x][scratch.y]
2640                     # Empty space ends reaction
2641                     if iquad in (IHDOT, IHQUEST, IHBLANK, IHT, IHWEB):
2642                         break
2643                     elif iquad == IHSTAR: # Affect another star 
2644                         if Rand() < 0.05:
2645                             # This star supernovas 
2646                             scratch = supernova(False)
2647                             return
2648                         top2 += 1
2649                         hits[top2][1]=scratch.x
2650                         hits[top2][2]=scratch.y
2651                         game.state.galaxy[game.quadrant.x][game.quadrant.y].stars -= 1
2652                         game.state.starkl += 1
2653                         crmena(True, IHSTAR, sector, scratch)
2654                         prout(_(" novas."))
2655                         game.quad[scratch.x][scratch.y] = IHDOT
2656                     elif iquad == IHP: # Destroy planet 
2657                         game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
2658                         game.state.nplankl += 1
2659                         crmena(True, IHP, sector, scratch)
2660                         prout(_(" destroyed."))
2661                         game.state.planets[game.iplnet].pclass = destroyed
2662                         game.iplnet = 0
2663                         invalidate(game.plnet)
2664                         if game.landed:
2665                             finish(FPNOVA)
2666                             return
2667                         game.quad[scratch.x][scratch.y] = IHDOT
2668                     elif iquad == IHB: # Destroy base 
2669                         game.state.galaxy[game.quadrant.x][game.quadrant.y].starbase = False
2670                         for i in range(1, game.state.rembase+1):
2671                             if same(game.state.baseq[i], game.quadrant): 
2672                                 break
2673                         game.state.baseq[i] = game.state.baseq[game.state.rembase]
2674                         game.state.rembase -= 1
2675                         invalidate(game.base)
2676                         game.state.basekl += 1
2677                         newcnd()
2678                         crmena(True, IHB, sector, scratch)
2679                         prout(_(" destroyed."))
2680                         game.quad[scratch.x][scratch.y] = IHDOT
2681                     elif iquad in (IHE, IHF): # Buffet ship 
2682                         prout(_("***Starship buffeted by nova."))
2683                         if game.shldup:
2684                             if game.shield >= 2000.0:
2685                                 game.shield -= 2000.0
2686                             else:
2687                                 diff = 2000.0 - game.shield
2688                                 game.energy -= diff
2689                                 game.shield = 0.0
2690                                 game.shldup = False
2691                                 prout(_("***Shields knocked out."))
2692                                 game.damage[DSHIELD] += 0.005*game.damfac*Rand()*diff
2693                         else:
2694                             game.energy -= 2000.0
2695                         if game.energy <= 0:
2696                             finish(FNOVA)
2697                             return
2698                         # add in course nova contributes to kicking starship
2699                         icx += game.sector.x-hits[mm][1]
2700                         icy += game.sector.y-hits[mm][2]
2701                         kount += 1
2702                     elif iquad == IHK: # kill klingon 
2703                         deadkl(scratch,iquad, scratch)
2704                     elif iquad in (IHC,IHS,IHR): # Damage/destroy big enemies 
2705                         for ll in range(1, game.nenhere+1):
2706                             if same(game.ks[ll], scratch):
2707                                 break
2708                         game.kpower[ll] -= 800.0 # If firepower is lost, die 
2709                         if game.kpower[ll] <= 0.0:
2710                             deadkl(scratch, iquad, scratch)
2711                             break
2712                         newc.x = scratch.x + scratch.x - hits[mm][1]
2713                         newc.y = scratch.y + scratch.y - hits[mm][2]
2714                         crmena(True, iquad, sector, scratch)
2715                         proutn(_(" damaged"))
2716                         if not VALID_SECTOR(newc.x, newc.y):
2717                             # can't leave quadrant 
2718                             skip(1)
2719                             break
2720                         iquad1 = game.quad[newc.x][newc.y]
2721                         if iquad1 == IHBLANK:
2722                             proutn(_(", blasted into "))
2723                             crmena(False, IHBLANK, sector, newc)
2724                             skip(1)
2725                             deadkl(scratch, iquad, newc)
2726                             break
2727                         if iquad1 != IHDOT:
2728                             # can't move into something else 
2729                             skip(1)
2730                             break
2731                         proutn(_(", buffeted to "))
2732                         proutn(cramlc(sector, newc))
2733                         game.quad[scratch.x][scratch.y] = IHDOT
2734                         game.quad[newc.x][newc.y] = iquad
2735                         game.ks[ll] = newc
2736                         game.kdist[ll] = game.kavgd[ll] = distance(game.sector, newc)
2737                         skip(1)
2738         if top == top2: 
2739             break
2740         bot = top + 1
2741         top = top2
2742     if kount==0: 
2743         return
2744
2745     # Starship affected by nova -- kick it away. 
2746     game.dist = kount*0.1
2747     icx = sgn(icx)
2748     icy = sgn(icy)
2749     game.direc = course[3*(icx+1)+icy+2]
2750     if game.direc == 0.0:
2751         game.dist = 0.0
2752     if game.dist == 0.0:
2753         return
2754     game.optime = 10.0*game.dist/16.0
2755     skip(1)
2756     prout(_("Force of nova displaces starship."))
2757     imove(True)
2758     game.optime = 10.0*game.dist/16.0
2759     return
2760         
2761 def supernova(induced, w=None):
2762     # star goes supernova 
2763     num = 0; npdead = 0
2764     nq = coord()
2765
2766     if w != None: 
2767         nq = w
2768     else:
2769         stars = 0
2770         # Scheduled supernova -- select star 
2771         # logic changed here so that we won't favor quadrants in top
2772         # left of universe 
2773         for nq.x in range(1, GALSIZE+1):
2774             for nq.y in range(1, GALSIZE+1):
2775                 stars += game.state.galaxy[nq.x][nq.y].stars
2776         if stars == 0:
2777             return # nothing to supernova exists 
2778         num = Rand()*stars + 1
2779         for nq.x in range(1, GALSIZE+1):
2780             for nq.y in range(1, GALSIZE+1):
2781                 num -= game.state.galaxy[nq.x][nq.y].stars
2782                 if num <= 0:
2783                     break
2784             if num <=0:
2785                 break
2786         if idebug:
2787             proutn("=== Super nova here?")
2788             if ja() == True:
2789                 nq = game.quadrant
2790
2791     if not same(nq, game.quadrant) or game.justin:
2792         # it isn't here, or we just entered (treat as enroute) 
2793         if not damaged(DRADIO) or game.condition == "docked":
2794             skip(1)
2795             prout(_("Message from Starfleet Command       Stardate %.2f" % game.state.date))
2796             prout(_("     Supernova in Quadrant %s; caution advised." % nq))
2797     else:
2798         ns = coord()
2799         # we are in the quadrant! 
2800         num = Rand()* game.state.galaxy[nq.x][nq.y].stars + 1
2801         for ns.x in range(1, QUADSIZE+1):
2802             for ns.y in range(1, QUADSIZE+1):
2803                 if game.quad[ns.x][ns.y]==IHSTAR:
2804                     num -= 1
2805                     if num==0:
2806                         break
2807             if num==0:
2808                 break
2809
2810         skip(1)
2811         prouts(_("***RED ALERT!  RED ALERT!"))
2812         skip(1)
2813         prout(_("***Incipient supernova detected at Sector %s" % ns))
2814         if square(ns.x-game.sector.x) + square(ns.y-game.sector.y) <= 2.1:
2815             proutn(_("Emergency override attempts t"))
2816             prouts("***************")
2817             skip(1)
2818             stars()
2819             game.alldone = True
2820
2821     # destroy any Klingons in supernovaed quadrant 
2822     kldead = game.state.galaxy[nq.x][nq.y].klingons
2823     game.state.galaxy[nq.x][nq.y].klingons = 0
2824     if same(nq, game.state.kscmdr):
2825         # did in the Supercommander! 
2826         game.state.nscrem = game.state.kscmdr.x = game.state.kscmdr.y = game.isatb =  0
2827         game.iscate = False
2828         unschedule(FSCMOVE)
2829         unschedule(FSCDBAS)
2830     if game.state.remcom:
2831         maxloop = game.state.remcom
2832         for l in range(1, maxloop+1):
2833             if same(game.state.kcmdr[l], nq):
2834                 game.state.kcmdr[l] = game.state.kcmdr[game.state.remcom]
2835                 invalidate(game.state.kcmdr[game.state.remcom])
2836                 game.state.remcom -= 1
2837                 kldead -= 1
2838                 if game.state.remcom==0:
2839                     unschedule(FTBEAM)
2840                 break
2841     game.state.remkl -= kldead
2842     # destroy Romulans and planets in supernovaed quadrant 
2843     nrmdead = game.state.galaxy[nq.x][nq.y].romulans
2844     game.state.galaxy[nq.x][nq.y].romulans = 0
2845     game.state.nromrem -= nrmdead
2846     # Destroy planets 
2847     for loop in range(game.inplan):
2848         if same(game.state.planets[loop].w, nq):
2849             game.state.planets[loop].pclass = destroyed
2850             npdead += 1
2851     # Destroy any base in supernovaed quadrant 
2852     if game.state.rembase:
2853         maxloop = game.state.rembase
2854         for loop in range(1, maxloop+1):
2855             if same(game.state.baseq[loop], nq):
2856                 game.state.baseq[loop] = game.state.baseq[game.state.rembase]
2857                 invalidate(game.state.baseq[game.state.rembase])
2858                 game.state.rembase -= 1
2859                 break
2860     # If starship caused supernova, tally up destruction 
2861     if induced:
2862         game.state.starkl += game.state.galaxy[nq.x][nq.y].stars
2863         game.state.basekl += game.state.galaxy[nq.x][nq.y].starbase
2864         game.state.nplankl += npdead
2865     # mark supernova in galaxy and in star chart 
2866     if same(game.quadrant, nq) or not damaged(DRADIO) or game.condition == "docked":
2867         game.state.galaxy[nq.x][nq.y].supernova = True
2868     # If supernova destroys last Klingons give special message 
2869     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0 and not same(nq, game.quadrant):
2870         skip(2)
2871         if not induced:
2872             prout(_("Lucky you!"))
2873         proutn(_("A supernova in %s has just destroyed the last Klingons." % nq))
2874         finish(FWON)
2875         return
2876     # if some Klingons remain, continue or die in supernova 
2877     if game.alldone:
2878         finish(FSNOVAED)
2879     return