planets.c code incorporated into Python translation.
[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, time, atexit, readline
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 # How to represent features
38 IHR = 'R',
39 IHK = 'K',
40 IHC = 'C',
41 IHS = 'S',
42 IHSTAR = '*',
43 IHP = 'P',
44 IHW = '@',
45 IHB = 'B',
46 IHBLANK = ' ',
47 IHDOT = '.',
48 IHQUEST = '?',
49 IHE = 'E',
50 IHF = 'F',
51 IHT = 'T',
52 IHWEB = '#',
53 IHMATER0 = '-',
54 IHMATER1 = 'o',
55 IHMATER2 = '0'
56
57 class coord:
58     def __init(self, x=None, y=None):
59         self.x = x
60         self.y = y
61     def invalidate(self):
62         self.x = self.y = None
63     def is_valid(self):
64         return self.x != None and self.y != None
65     def __eq__(self, other):
66         return self.x == other.y and self.x == other.y
67     def __add__(self, other):
68         return coord(self.x+self.x, self.y+self.y)
69     def __sub__(self, other):
70         return coord(self.x-self.x, self.y-self.y)
71     def distance(self, other):
72         return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
73     def sgn(self):
74         return coord(self.x / abs(x), self.y / abs(y));
75     def __hash__(self):
76         return hash((x, y))
77     def __str__(self):
78         return "%d - %d" % (self.x, self.y)
79
80 class planet:
81     def __init(self):
82         self.name = None        # string-valued if inhabited
83         self.w = coord()        # quadrant located
84         self.pclass = None      # could be ""M", "N", "O", or "destroyed"
85         self.crystals = None    # could be "mined", "present", "absent"
86         self.known = None       # could be "unknown", "known", "shuttle_down"
87     def __str__(self):
88         return self.name
89
90 NOPLANET = None
91 class quadrant:
92     def __init(self):
93         self.stars = None
94         self.planet = None
95         self.starbase = None
96         self.klingons = None
97         self.romulans = None
98         self.supernova = None
99         self.charted = None
100         self.status = None      # Could be "secure", "distressed", "enslaved"
101
102 class page:
103     def __init(self):
104         self.stars = None
105         self.starbase = None
106         self.klingons = None
107
108 class snapshot:
109     def __init(self):
110         self.snap = False       # snapshot taken
111         self.crew = None        # crew complement
112         self.remkl = None       # remaining klingons
113         self.remcom = None      # remaining commanders
114         self.nscrem = None      # remaining super commanders
115         self.rembase = None     # remaining bases
116         self.starkl = None      # destroyed stars
117         self.basekl = None      # destroyed bases
118         self.nromrem = None     # Romulans remaining
119         self.nplankl = None     # destroyed uninhabited planets
120         self.nworldkl = None    # destroyed inhabited planets
121         self.planets = []       # Planet information
122         for i in range(PLNETMAX):
123             self.planets.append(planet())
124         self.date = None        # stardate
125         self.remres = None      # remaining resources
126         self.remtime = None     # remaining time
127         self.baseq = []         # Base quadrant coordinates
128         for i in range(BASEMAX+1):
129             self.baseq.append(coord())
130         self.kcmdr = []         # Commander quadrant coordinates
131         for i in range(QUADSIZE+1):
132             self.kcmdr.append(coord())
133         self.kscmdr = coord()   # Supercommander quadrant coordinates
134         self.galaxy = []        # The Galaxy (subscript 0 not used)
135         for i in range(GALSIZE+1):
136             self.chart.append([])
137             for j in range(GALSIZE+1):
138                 self.galaxy[i].append(quadrant())
139         self.chart = []         # the starchart (subscript 0 not used)
140         for i in range(GALSIZE+1):
141             self.chart.append([])
142             for j in range(GALSIZE+1):
143                 self.chart[i].append(page())
144
145 class event:
146     def __init__(self):
147         self.date = None        # A real number
148         self.quadrant = None    # A coord structure
149
150 # game options 
151 OPTION_ALL      = 0xffffffff
152 OPTION_TTY      = 0x00000001    # old interface 
153 OPTION_CURSES   = 0x00000002    # new interface 
154 OPTION_IOMODES  = 0x00000003    # cover both interfaces 
155 OPTION_PLANETS  = 0x00000004    # planets and mining 
156 OPTION_THOLIAN  = 0x00000008    # Tholians and their webs 
157 OPTION_THINGY   = 0x00000010    # Space Thingy can shoot back 
158 OPTION_PROBE    = 0x00000020    # deep-space probes 
159 OPTION_SHOWME   = 0x00000040    # bracket Enterprise in chart 
160 OPTION_RAMMING  = 0x00000080    # enemies may ram Enterprise 
161 OPTION_MVBADDY  = 0x00000100    # more enemies can move 
162 OPTION_BLKHOLE  = 0x00000200    # black hole may timewarp you 
163 OPTION_BASE     = 0x00000400    # bases have good shields 
164 OPTION_WORLDS   = 0x00000800    # logic for inhabited worlds 
165 OPTION_PLAIN    = 0x01000000    # user chose plain game 
166 OPTION_ALMY     = 0x02000000    # user chose Almy variant 
167
168 # Define devices 
169 DSRSENS = 0
170 DLRSENS = 1
171 DPHASER = 2
172 DPHOTON = 3
173 DLIFSUP = 4
174 DWARPEN = 5
175 DIMPULS = 6
176 DSHIELD = 7
177 DRADIO  = 0
178 DSHUTTL = 9
179 DCOMPTR = 10
180 DNAVSYS = 11
181 DTRANSP = 12
182 DSHCTRL = 13
183 DDRAY   = 14
184 DDSP    = 15
185 NDEVICES= 16    # Number of devices
186
187 SKILL_NONE      = 0
188 SKILL_NOVICE    = 1
189 SKILL_FAIR      = 2
190 SKILL_GOOD      = 3
191 SKILL_EXPERT    = 4
192 SKILL_EMERITUS  = 5
193
194 def damaged(dev):       return (game.damage[dev] != 0.0)
195
196 # Define future events 
197 FSPY    = 0     # Spy event happens always (no future[] entry)
198                 # can cause SC to tractor beam Enterprise
199 FSNOVA  = 1     # Supernova
200 FTBEAM  = 2     # Commander tractor beams Enterprise
201 FSNAP   = 3     # Snapshot for time warp
202 FBATTAK = 4     # Commander attacks base
203 FCDBAS  = 5     # Commander destroys base
204 FSCMOVE = 6     # Supercommander moves (might attack base)
205 FSCDBAS = 7     # Supercommander destroys base
206 FDSPROB = 8     # Move deep space probe
207 FDISTR  = 9     # Emit distress call from an inhabited world 
208 FENSLV  = 10    # Inhabited word is enslaved */
209 FREPRO  = 11    # Klingons build a ship in an enslaved system
210 NEVENTS = 12
211
212 #
213 # abstract out the event handling -- underlying data structures will change
214 # when we implement stateful events
215
216 def findevent(evtype):  return game.future[evtype]
217
218 class gamestate:
219     def __init__(self):
220         self.options = None     # Game options
221         self.state = None       # A snapshot structure
222         self.snapsht = None     # Last snapshot taken for time-travel purposes
223         self.quad = [[IHDOT * (QUADSIZE+1)] * (QUADSIZE+1)]     # contents of our quadrant
224         self.kpower = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]       # enemy energy levels
225         self.kdist = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]        # enemy distances
226         self.kavgd = [[0 * (QUADSIZE+1)] * (QUADSIZE+1)]        # average distances
227         self.damage = [0] * NDEVICES    # damage encountered
228         self.future = [0.0] * NEVENTS   # future events
229         for i in range(NEVENTS):
230             self.future.append(event())
231         self.passwd  = None;            # Self Destruct password
232         self.ks = [[None * (QUADSIZE+1)] * (QUADSIZE+1)]        # enemy sector locations
233         self.quadrant = None    # where we are in the large
234         self.sector = None      # where we are in the small
235         self.tholian = None     # coordinates of Tholian
236         self.base = None        # position of base in current quadrant
237         self.battle = None      # base coordinates being attacked
238         self.plnet = None       # location of planet in quadrant
239         self.probec = None      # current probe quadrant
240         self.gamewon = False    # Finished!
241         self.ididit = False     # action taken -- allows enemy to attack
242         self.alive = False      # we are alive (not killed)
243         self.justin = False     # just entered quadrant
244         self.shldup = False     # shields are up
245         self.shldchg = False    # shield is changing (affects efficiency)
246         self.comhere = False    # commander here
247         self.ishere = False     # super-commander in quadrant
248         self.iscate = False     # super commander is here
249         self.ientesc = False    # attempted escape from supercommander
250         self.ithere = False     # Tholian is here 
251         self.resting = False    # rest time
252         self.icraft = False     # Kirk in Galileo
253         self.landed = False     # party on planet (true), on ship (false)
254         self.alldone = False    # game is now finished
255         self.neutz = False      # Romulan Neutral Zone
256         self.isarmed = False    # probe is armed
257         self.inorbit = False    # orbiting a planet
258         self.imine = False      # mining
259         self.icrystl = False    # dilithium crystals aboard
260         self.iseenit = False    # seen base attack report
261         self.thawed = False     # thawed game
262         self.condition = None   # "green", "yellow", "red", "docked", "dead"
263         self.iscraft = None     # "onship", "offship", "removed"
264         self.skill = None       # Player skill level
265         self.inkling = 0        # initial number of klingons
266         self.inbase = 0         # initial number of bases
267         self.incom = 0          # initial number of commanders
268         self.inscom = 0         # initial number of commanders
269         self.inrom = 0          # initial number of commanders
270         self.instar = 0         # initial stars
271         self.intorps = 0        # initial/max torpedoes
272         self.torps = 0          # number of torpedoes
273         self.ship = 0           # ship type -- 'E' is Enterprise
274         self.abandoned = 0      # count of crew abandoned in space
275         self.length = 0         # length of game
276         self.klhere = 0         # klingons here
277         self.casual = 0         # causalties
278         self.nhelp = 0          # calls for help
279         self.nkinks = 0         # count of energy-barrier crossings
280         self.iplnet = 0         # planet # in quadrant
281         self.inplan = 0         # initial planets
282         self.nenhere = 0        # number of enemies in quadrant
283         self.irhere = 0         # Romulans in quadrant
284         self.isatb = 0          # =1 if super commander is attacking base
285         self.tourn = 0          # tournament number
286         self.proben = 0         # number of moves for probe
287         self.nprobes = 0        # number of probes available
288         self.inresor = 0.0      # initial resources
289         self.intime = 0.0       # initial time
290         self.inenrg = 0.0       # initial/max energy
291         self.inshld = 0.0       # initial/max shield
292         self.inlsr = 0.0        # initial life support resources
293         self.indate = 0.0       # initial date
294         self.energy = 0.0       # energy level
295         self.shield = 0.0       # shield level
296         self.warpfac = 0.0      # warp speed
297         self.wfacsq = 0.0       # squared warp factor
298         self.lsupres = 0.0      # life support reserves
299         self.dist = 0.0         # movement distance
300         self.direc = 0.0        # movement direction
301         self.optime = 0.0       # time taken by current operation
302         self.docfac = 0.0       # repair factor when docking (constant?)
303         self.damfac = 0.0       # damage factor
304         self.lastchart = 0.0    # time star chart was last updated
305         self.cryprob = 0.0      # probability that crystal will work
306         self.probex = 0.0       # location of probe
307         self.probey = 0.0       #
308         self.probeinx = 0.0     # probe x,y increment
309         self.probeiny = 0.0     #
310         self.height = 0.0       # height of orbit around planet
311     def recompute(self):
312         # Stas thinks this should be (C expression): 
313         # game.state.remkl + game.state.remcom > 0 ?
314         #       game.state.remres/(game.state.remkl + 4*game.state.remcom) : 99
315         # He says the existing expression is prone to divide-by-zero errors
316         # after killing the last klingon when score is shown -- perhaps also
317         # if the only remaining klingon is SCOM.
318         game.state.remtime = game.state.remres/(game.state.remkl + 4*game.state.remcom)
319 # From enumerated type 'feature'
320 IHR = 'R'
321 IHK = 'K'
322 IHC = 'C'
323 IHS = 'S'
324 IHSTAR = '*'
325 IHP = 'P'
326 IHW = '@'
327 IHB = 'B'
328 IHBLANK = ' '
329 IHDOT = '.'
330 IHQUEST = '?'
331 IHE = 'E'
332 IHF = 'F'
333 IHT = 'T'
334 IHWEB = '#'
335 IHMATER0 = '-'
336 IHMATER1 = 'o'
337 IHMATER2 = '0'
338
339
340 # From enumerated type 'FINTYPE'
341 FWON = 0
342 FDEPLETE = 1
343 FLIFESUP = 2
344 FNRG = 3
345 FBATTLE = 4
346 FNEG3 = 5
347 FNOVA = 6
348 FSNOVAED = 7
349 FABANDN = 8
350 FDILITHIUM = 9
351 FMATERIALIZE = 10
352 FPHASER = 11
353 FLOST = 12
354 FMINING = 13
355 FDPLANET = 14
356 FPNOVA = 15
357 FSSC = 16
358 FSTRACTOR = 17
359 FDRAY = 18
360 FTRIBBLE = 19
361 FHOLE = 20
362 FCREW = 21
363
364 # From enumerated type 'COLORS'
365 DEFAULT = 0
366 BLACK = 1
367 BLUE = 2
368 GREEN = 3
369 CYAN = 4
370 RED = 5
371 MAGENTA = 6
372 BROWN = 7
373 LIGHTGRAY = 8
374 DARKGRAY = 9
375 LIGHTBLUE = 10
376 LIGHTGREEN = 11
377 LIGHTCYAN = 12
378 LIGHTRED = 13
379 LIGHTMAGENTA = 14
380 YELLOW = 15
381 WHITE = 16
382
383 # Code from ai.c begins here
384
385 def tryexit(look, ienm, loccom, irun):
386     # a bad guy attempts to bug out 
387     iq = coord()
388     iq.x = game.quadrant.x+(look.x+(QUADSIZE-1))/QUADSIZE - 1
389     iq.y = game.quadrant.y+(look.y+(QUADSIZE-1))/QUADSIZE - 1
390     if not VALID_QUADRANT(iq.x,iq.y) or \
391         game.state.galaxy[iq.x][iq.y].supernova or \
392         game.state.galaxy[iq.x][iq.y].klingons > MAXKLQUAD-1:
393         return False; # no can do -- neg energy, supernovae, or >MAXKLQUAD-1 Klingons 
394     if ienm == IHR:
395         return False; # Romulans cannot escape! 
396     if not irun:
397         # avoid intruding on another commander's territory 
398         if ienm == IHC:
399             for n in range(1, game.state.remcom+1):
400                 if same(game.state.kcmdr[n],iq):
401                     return False
402             # refuse to leave if currently attacking starbase 
403             if same(game.battle, game.quadrant):
404                 return False
405         # don't leave if over 1000 units of energy 
406         if game.kpower[loccom] > 1000.0:
407             return False
408     # print escape message and move out of quadrant.
409     # we know this if either short or long range sensors are working
410     if not damaged(DSRSENS) or not damaged(DLRSENS) or \
411         game.condition == docked:
412         crmena(True, ienm, "sector", game.ks[loccom])
413         prout(_(" escapes to Quadrant %s (and regains strength).") % q)
414     # handle local matters related to escape 
415     game.quad[game.ks[loccom].x][game.ks[loccom].y] = IHDOT
416     game.ks[loccom] = game.ks[game.nenhere]
417     game.kavgd[loccom] = game.kavgd[game.nenhere]
418     game.kpower[loccom] = game.kpower[game.nenhere]
419     game.kdist[loccom] = game.kdist[game.nenhere]
420     game.klhere -= 1
421     game.nenhere -= 1
422     if game.condition != docked:
423         newcnd()
424     # Handle global matters related to escape 
425     game.state.galaxy[game.quadrant.x][game.quadrant.y].klingons -= 1
426     game.state.galaxy[iq.x][iq.y].klingons += 1
427     if ienm==IHS:
428         game.ishere = False
429         game.iscate = False
430         game.ientesc = False
431         game.isatb = 0
432         schedule(FSCMOVE, 0.2777)
433         unschedule(FSCDBAS)
434         game.state.kscmdr=iq
435     else:
436         for n in range(1, game.state.remcom+1):
437             if same(game.state.kcmdr[n], game.quadrant):
438                 game.state.kcmdr[n]=iq
439                 break
440         game.comhere = False
441     return True; # success 
442
443 #
444 # The bad-guy movement algorithm:
445
446 # 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
447 # If both are operating full strength, force is 1000. If both are damaged,
448 # force is -1000. Having shields down subtracts an additional 1000.
449
450 # 2. Enemy has forces equal to the energy of the attacker plus
451 # 100*(K+R) + 500*(C+S) - 400 for novice through good levels OR
452 # 346*K + 400*R + 500*(C+S) - 400 for expert and emeritus.
453
454 # Attacker Initial energy levels (nominal):
455 # Klingon   Romulan   Commander   Super-Commander
456 # Novice    400        700        1200        
457 # Fair      425        750        1250
458 # Good      450        800        1300        1750
459 # Expert    475        850        1350        1875
460 # Emeritus  500        900        1400        2000
461 # VARIANCE   75        200         200         200
462
463 # Enemy vessels only move prior to their attack. In Novice - Good games
464 # only commanders move. In Expert games, all enemy vessels move if there
465 # is a commander present. In Emeritus games all enemy vessels move.
466
467 # 3. If Enterprise is not docked, an aggressive action is taken if enemy
468 # forces are 1000 greater than Enterprise.
469
470 # Agressive action on average cuts the distance between the ship and
471 # the enemy to 1/4 the original.
472
473 # 4.  At lower energy advantage, movement units are proportional to the
474 # advantage with a 650 advantage being to hold ground, 800 to move forward
475 # 1, 950 for two, 150 for back 4, etc. Variance of 100.
476
477 # If docked, is reduced by roughly 1.75*game.skill, generally forcing a
478 # retreat, especially at high skill levels.
479
480 # 5.  Motion is limited to skill level, except for SC hi-tailing it out.
481
482
483 def movebaddy(com, loccom, ienm):
484     # tactical movement for the bad guys 
485     next = coord(); look = coord()
486     irun = False
487     # This should probably be just game.comhere + game.ishere 
488     if game.skill >= SKILL_EXPERT:
489         nbaddys = ((game.comhere*2 + game.ishere*2+game.klhere*1.23+game.irhere*1.5)/2.0)
490     else:
491         nbaddys = game.comhere + game.ishere
492
493     dist1 = game.kdist[loccom]
494     mdist = int(dist1 + 0.5); # Nearest integer distance 
495
496     # If SC, check with spy to see if should hi-tail it 
497     if ienm==IHS and \
498         (game.kpower[loccom] <= 500.0 or (game.condition=="docked" and not damaged(DPHOTON))):
499         irun = True
500         motion = -QUADSIZE
501     else:
502         # decide whether to advance, retreat, or hold position 
503         forces = game.kpower[loccom]+100.0*game.nenhere+400*(nbaddys-1)
504         if not game.shldup:
505             forces += 1000; # Good for enemy if shield is down! 
506         if not damaged(DPHASER) or not damaged(DPHOTON):
507             if damaged(DPHASER): # phasers damaged 
508                 forces += 300.0
509             else:
510                 forces -= 0.2*(game.energy - 2500.0)
511             if damaged(DPHOTON): # photon torpedoes damaged 
512                 forces += 300.0
513             else:
514                 forces -= 50.0*game.torps
515         else:
516             # phasers and photon tubes both out! 
517             forces += 1000.0
518         motion = 0
519         if forces <= 1000.0 and game.condition != "docked": # Typical situation 
520             motion = ((forces+200.0*Rand())/150.0) - 5.0
521         else:
522             if forces > 1000.0: # Very strong -- move in for kill 
523                 motion = (1.0-square(Rand()))*dist1 + 1.0
524             if game.condition=="docked" and (game.options & OPTION_BASE): # protected by base -- back off ! 
525                 motion -= game.skill*(2.0-square(Rand()))
526         if idebug:
527             proutn("=== MOTION = %d, FORCES = %1.2f, " % (motion, forces))
528         # don't move if no motion 
529         if motion==0:
530             return
531         # Limit motion according to skill 
532         if abs(motion) > game.skill:
533             if motion < 0:
534                 motion = -game.skill
535             else:
536                 motion = game.skill
537     # calculate preferred number of steps 
538     if motion < 0:
539         msteps = -motion
540     else:
541         msteps = motion
542     if motion > 0 and nsteps > mdist:
543         nsteps = mdist; # don't overshoot 
544     if nsteps > QUADSIZE:
545         nsteps = QUADSIZE; # This shouldn't be necessary 
546     if nsteps < 1:
547         nsteps = 1; # This shouldn't be necessary 
548     if idebug:
549         proutn("NSTEPS = %d:" % nsteps)
550     # Compute preferred values of delta X and Y 
551     mx = game.sector.x - com.x
552     my = game.sector.y - com.y
553     if 2.0 * abs(mx) < abs(my):
554         mx = 0
555     if 2.0 * abs(my) < abs(game.sector.x-com.x):
556         my = 0
557     if mx != 0:
558         if mx*motion < 0:
559             mx = -1
560         else:
561             mx = 1
562     if my != 0:
563         if my*motion < 0:
564             my = -1
565         else:
566             my = 1
567     next = com
568     # main move loop 
569     for ll in range(nsteps):
570         if idebug:
571             proutn(" %d" % (ll+1))
572         # Check if preferred position available 
573         look.x = next.x + mx
574         look.y = next.y + my
575         if mx < 0:
576             krawlx = 1
577         else:
578             krawlx = -1
579         if my < 0:
580             krawly = 1
581         else:
582             krawly = -1
583         success = False
584         attempts = 0; # Settle mysterious hang problem 
585         while attempts < 20 and not success:
586             attempts += 1
587             if look.x < 1 or look.x > QUADSIZE:
588                 if motion < 0 and tryexit(look, ienm, loccom, irun):
589                     return
590                 if krawlx == mx or my == 0:
591                     break
592                 look.x = next.x + krawlx
593                 krawlx = -krawlx
594             elif look.y < 1 or look.y > QUADSIZE:
595                 if motion < 0 and tryexit(look, ienm, loccom, irun):
596                     return
597                 if krawly == my or mx == 0:
598                     break
599                 look.y = next.y + krawly
600                 krawly = -krawly
601             elif (game.options & OPTION_RAMMING) and game.quad[look.x][look.y] != IHDOT:
602                 # See if we should ram ship 
603                 if game.quad[look.x][look.y] == game.ship and \
604                     (ienm == IHC or ienm == IHS):
605                     ram(True, ienm, com)
606                     return
607                 if krawlx != mx and my != 0:
608                     look.x = next.x + krawlx
609                     krawlx = -krawlx
610                 elif krawly != my and mx != 0:
611                     look.y = next.y + krawly
612                     krawly = -krawly
613                 else:
614                     break; # we have failed 
615             else:
616                 success = True
617         if success:
618             next = look
619             if idebug:
620                 proutn(`next`)
621         else:
622             break; # done early 
623         
624     if idebug:
625         skip(1)
626     # Put commander in place within same quadrant 
627     game.quad[com.x][com.y] = IHDOT
628     game.quad[next.x][next.y] = ienm
629     if not same(next, com):
630         # it moved 
631         game.ks[loccom] = next
632         game.kdist[loccom] = game.kavgd[loccom] = distance(game.sector, next)
633         if not damaged(DSRSENS) or game.condition == docked:
634             proutn("***")
635             cramen(ienm)
636             proutn(_(" from Sector %s") % com)
637             if game.kdist[loccom] < dist1:
638                 proutn(_(" advances to "))
639             else:
640                 proutn(_(" retreats to "))
641             prout("Sector %s." % next)
642
643 def moveklings():
644     # Klingon tactical movement 
645     if idebug:
646         prout("== MOVCOM")
647     # Figure out which Klingon is the commander (or Supercommander)
648     # and do move
649     if game.comhere:
650         for i in range(1, game.nenhere+1):
651             w = game.ks[i]
652             if game.quad[w.x][w.y] == IHC:
653                 movebaddy(w, i, IHC)
654                 break
655     if game.ishere:
656         for i in range(1, game.nenhere+1):
657             w = game.ks[i]
658             if game.quad[w.x][w.y] == IHS:
659                 movebaddy(w, i, IHS)
660                 break
661     # If skill level is high, move other Klingons and Romulans too!
662     # Move these last so they can base their actions on what the
663     # commander(s) do.
664     if game.skill >= SKILL_EXPERT and (game.options & OPTION_MVBADDY):
665         for i in range(1, game.nenhere+1):
666             w = game.ks[i]
667             if game.quad[w.x][w.y] == IHK or game.quad[w.x][w.y] == IHR:
668                 movebaddy(w, i, game.quad[w.x][w.y])
669     sortklings();
670
671 def movescom(iq, avoid):
672     # commander movement helper 
673     if same(iq, game.quadrant) or not VALID_QUADRANT(iq.x, iq.y) or \
674         game.state.galaxy[iq.x][iq.y].supernova or \
675         game.state.galaxy[iq.x][iq.y].klingons > MAXKLQUAD-1:
676         return 1
677     if avoid:
678         # Avoid quadrants with bases if we want to avoid Enterprise 
679         for i in range(1, game.state.rembase+1):
680             if same(game.state.baseq[i], iq):
681                 return True
682     if game.justin and not game.iscate:
683         return True
684     # do the move 
685     game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].klingons -= 1
686     game.state.kscmdr = iq
687     game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].klingons += 1
688     if game.ishere:
689         # SC has scooted, Remove him from current quadrant 
690         game.iscate=False
691         game.isatb=0
692         game.ishere = False
693         game.ientesc = False
694         unschedule(FSCDBAS)
695         for i in range(1, game.nenhere+1):
696             if game.quad[game.ks[i].x][game.ks[i].y] == IHS:
697                 break
698         game.quad[game.ks[i].x][game.ks[i].y] = IHDOT
699         game.ks[i] = game.ks[game.nenhere]
700         game.kdist[i] = game.kdist[game.nenhere]
701         game.kavgd[i] = game.kavgd[game.nenhere]
702         game.kpower[i] = game.kpower[game.nenhere]
703         game.klhere -= 1
704         game.nenhere -= 1
705         if game.condition!=docked:
706             newcnd()
707         sortklings()
708     # check for a helpful planet 
709     for i in range(game.inplan):
710         if same(game.state.planets[i].w, game.state.kscmdr) and \
711             game.state.planets[i].crystals == present:
712             # destroy the planet 
713             game.state.planets[i].pclass = destroyed
714             game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].planet = NOPLANET
715             if not damaged(DRADIO) or game.condition == docked:
716                 announce()
717                 prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
718                 proutn(_("   a planet in Quadrant %s has been destroyed") % game.state.kscmdr)
719                 prout(_("   by the Super-commander.\""))
720             break
721     return False; # looks good! 
722                         
723 def supercommander():
724     # move the Super Commander 
725     iq = coord(); sc = coord(); ibq = coord(); idelta = coord()
726     basetbl = []
727     if idebug:
728         prout("== SUPERCOMMANDER")
729     # Decide on being active or passive 
730     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 \
731             (game.state.date-game.indate) < 3.0)
732     if not game.iscate and avoid:
733         # compute move away from Enterprise 
734         idelta = game.state.kscmdr-game.quadrant
735         if math.sqrt(idelta.x*idelta.x+idelta.y*idelta.y) > 2.0:
736             # circulate in space 
737             idelta.x = game.state.kscmdr.y-game.quadrant.y
738             idelta.y = game.quadrant.x-game.state.kscmdr.x
739     else:
740         # compute distances to starbases 
741         if game.state.rembase <= 0:
742             # nothing left to do 
743             unschedule(FSCMOVE)
744             return
745         sc = game.state.kscmdr
746         for i in range(1, game.state.rembase+1):
747             basetbl.append((i, distance(game.state.baseq[i], sc)))
748         if game.state.rembase > 1:
749             basetbl.sort(lambda x, y: cmp(x[1]. y[1]))
750         # look for nearest base without a commander, no Enterprise, and
751         # without too many Klingons, and not already under attack. 
752         ifindit = iwhichb = 0
753         for i2 in range(1, game.state.rembase+1):
754             i = basetbl[i2][0]; # bug in original had it not finding nearest
755             ibq = game.state.baseq[i]
756             if same(ibq, game.quadrant) or same(ibq, game.battle) or \
757                 game.state.galaxy[ibq.x][ibq.y].supernova or \
758                 game.state.galaxy[ibq.x][ibq.y].klingons > MAXKLQUAD-1:
759                 continue
760             # if there is a commander, and no other base is appropriate,
761             #   we will take the one with the commander
762             for j in range(1, game.state.remcom+1):
763                 if same(ibq, game.state.kcmdr[j]) and ifindit!= 2:
764                     ifindit = 2
765                     iwhichb = i
766                     break
767             if j > game.state.remcom: # no commander -- use this one 
768                 ifindit = 1
769                 iwhichb = i
770                 break
771         if ifindit==0:
772             return; # Nothing suitable -- wait until next time
773         ibq = game.state.baseq[iwhichb]
774         # decide how to move toward base 
775         idelta = ibq - game.state.kscmdr
776     # Maximum movement is 1 quadrant in either or both axes 
777     idelta = idelta.sgn()
778     # try moving in both x and y directions
779     # there was what looked like a bug in the Almy C code here,
780     # but it might be this translation is just wrong.
781     iq = game.state.kscmdr + idelta
782     if movescom(iq, avoid):
783         # failed -- try some other maneuvers 
784         if idelta.x==0 or idelta.y==0:
785             # attempt angle move 
786             if idelta.x != 0:
787                 iq.y = game.state.kscmdr.y + 1
788                 if movescom(iq, avoid):
789                     iq.y = game.state.kscmdr.y - 1
790                     movescom(iq, avoid)
791             else:
792                 iq.x = game.state.kscmdr.x + 1
793                 if movescom(iq, avoid):
794                     iq.x = game.state.kscmdr.x - 1
795                     movescom(iq, avoid)
796         else:
797             # try moving just in x or y 
798             iq.y = game.state.kscmdr.y
799             if movescom(iq, avoid):
800                 iq.y = game.state.kscmdr.y + idelta.y
801                 iq.x = game.state.kscmdr.x
802                 movescom(iq, avoid)
803     # check for a base 
804     if game.state.rembase == 0:
805         unschedule(FSCMOVE)
806     else:
807         for i in range(1, game.state.rembase+1):
808             ibq = game.state.baseq[i]
809             if same(ibq, game.state.kscmdr) and same(game.state.kscmdr, game.battle):
810                 # attack the base 
811                 if avoid:
812                     return; # no, don't attack base! 
813                 game.iseenit = False
814                 game.isatb = 1
815                 schedule(FSCDBAS, 1.0 +2.0*Rand())
816                 if is_scheduled(FCDBAS):
817                     postpone(FSCDBAS, scheduled(FCDBAS)-game.state.date)
818                 if damaged(DRADIO) and game.condition != docked:
819                     return; # no warning 
820                 game.iseenit = True
821                 announce()
822                 prout(_("Lt. Uhura-  \"Captain, the starbase in Quadrant %s") \
823                       % game.state.kscmdr)
824                 prout(_("   reports that it is under attack from the Klingon Super-commander."))
825                 proutn(_("   It can survive until stardate %d.\"") \
826                        % int(scheduled(FSCDBAS)))
827                 if not game.resting:
828                     return
829                 prout(_("Mr. Spock-  \"Captain, shall we cancel the rest period?\""))
830                 if ja() == False:
831                     return
832                 game.resting = False
833                 game.optime = 0.0; # actually finished 
834                 return
835     # Check for intelligence report 
836     if not idebug and \
837         (Rand() > 0.2 or \
838          (damaged(DRADIO) and game.condition != docked) or \
839          not game.state.galaxy[game.state.kscmdr.x][game.state.kscmdr.y].charted):
840         return
841     announce()
842     prout(_("Lt. Uhura-  \"Captain, Starfleet Intelligence reports"))
843     proutn(_("   the Super-commander is in Quadrant %s,") % game.state.kscmdr)
844     return;
845
846 def movetholian():
847     # move the Tholian 
848     if not game.ithere or game.justin:
849         return
850
851     if game.tholian.x == 1 and game.tholian.y == 1:
852         idx = 1; idy = QUADSIZE
853     elif game.tholian.x == 1 and game.tholian.y == QUADSIZE:
854         idx = QUADSIZE; idy = QUADSIZE
855     elif game.tholian.x == QUADSIZE and game.tholian.y == QUADSIZE:
856         idx = QUADSIZE; idy = 1
857     elif game.tholian.x == QUADSIZE and game.tholian.y == 1:
858         idx = 1; idy = 1
859     else:
860         # something is wrong! 
861         game.ithere = False
862         return
863
864     # do nothing if we are blocked 
865     if game.quad[idx][idy]!= IHDOT and game.quad[idx][idy]!= IHWEB:
866         return
867     game.quad[game.tholian.x][game.tholian.y] = IHWEB
868
869     if game.tholian.x != idx:
870         # move in x axis 
871         im = math.fabs(idx - game.tholian.x)*1.0/(idx - game.tholian.x)
872         while game.tholian.x != idx:
873             game.tholian.x += im
874             if game.quad[game.tholian.x][game.tholian.y]==IHDOT:
875                 game.quad[game.tholian.x][game.tholian.y] = IHWEB
876     elif game.tholian.y != idy:
877         # move in y axis 
878         im = math.fabs(idy - game.tholian.y)*1.0/(idy - game.tholian.y)
879         while game.tholian.y != idy:
880             game.tholian.y += im
881             if game.quad[game.tholian.x][game.tholian.y]==IHDOT:
882                 game.quad[game.tholian.x][game.tholian.y] = IHWEB
883     game.quad[game.tholian.x][game.tholian.y] = IHT
884     game.ks[game.nenhere] = game.tholian
885
886     # check to see if all holes plugged 
887     for i in range(1, QUADSIZE+1):
888         if game.quad[1][i]!=IHWEB and game.quad[1][i]!=IHT:
889             return
890         if game.quad[QUADSIZE][i]!=IHWEB and game.quad[QUADSIZE][i]!=IHT:
891             return
892         if game.quad[i][1]!=IHWEB and game.quad[i][1]!=IHT:
893             return
894         if game.quad[i][QUADSIZE]!=IHWEB and game.quad[i][QUADSIZE]!=IHT:
895             return
896     # All plugged up -- Tholian splits 
897     game.quad[game.tholian.x][game.tholian.y]=IHWEB
898     dropin(IHBLANK)
899     crmena(True, IHT, "sector", game.tholian)
900     prout(_(" completes web."))
901     game.ithere = False
902     game.nenhere -= 1
903     return
904
905 # Code from battle.c begins here
906
907 def doshield(shraise):
908     # change shield status 
909     action = "NONE"
910     game.ididit = False
911     if shraise:
912         action = "SHUP"
913     else:
914         key = scan()
915         if key == IHALPHA:
916             if isit("transfer"):
917                 action = "NRG"
918             else:
919                 chew()
920                 if damaged(DSHIELD):
921                     prout(_("Shields damaged and down."))
922                     return
923                 if isit("up"):
924                     action = "SHUP"
925                 elif isit("down"):
926                     action = "SHDN"
927         if action=="NONE":
928             proutn(_("Do you wish to change shield energy? "))
929             if ja() == True:
930                 proutn(_("Energy to transfer to shields- "))
931                 action = "NRG"
932             elif damaged(DSHIELD):
933                 prout(_("Shields damaged and down."))
934                 return
935             elif game.shldup:
936                 proutn(_("Shields are up. Do you want them down? "))
937                 if ja() == True:
938                     action = "SHDN"
939                 else:
940                     chew()
941                     return
942             else:
943                 proutn(_("Shields are down. Do you want them up? "))
944                 if ja() == True:
945                     action = "SHUP"
946                 else:
947                     chew()
948                     return    
949     if action == "SHUP": # raise shields 
950         if game.shldup:
951             prout(_("Shields already up."))
952             return
953         game.shldup = True
954         game.shldchg = True
955         if game.condition != "docked":
956             game.energy -= 50.0
957         prout(_("Shields raised."))
958         if game.energy <= 0:
959             skip(1)
960             prout(_("Shields raising uses up last of energy."))
961             finish(FNRG)
962             return
963         game.ididit=True
964         return
965     elif action == "SHDN":
966         if not game.shldup:
967             prout(_("Shields already down."))
968             return
969         game.shldup=False
970         game.shldchg=True
971         prout(_("Shields lowered."))
972         game.ididit = True
973         return
974     elif action == "NRG":
975         while scan() != IHREAL:
976             chew()
977             proutn(_("Energy to transfer to shields- "))
978         chew()
979         if aaitem==0:
980             return
981         if aaitem > game.energy:
982             prout(_("Insufficient ship energy."))
983             return
984         game.ididit = True
985         if game.shield+aaitem >= game.inshld:
986             prout(_("Shield energy maximized."))
987             if game.shield+aaitem > game.inshld:
988                 prout(_("Excess energy requested returned to ship energy"))
989             game.energy -= game.inshld-game.shield
990             game.shield = game.inshld
991             return
992         if aaitem < 0.0 and game.energy-aaitem > game.inenrg:
993             # Prevent shield drain loophole 
994             skip(1)
995             prout(_("Engineering to bridge--"))
996             prout(_("  Scott here. Power circuit problem, Captain."))
997             prout(_("  I can't drain the shields."))
998             game.ididit = False
999             return
1000         if game.shield+aaitem < 0:
1001             prout(_("All shield energy transferred to ship."))
1002             game.energy += game.shield
1003             game.shield = 0.0
1004             return
1005         proutn(_("Scotty- \""))
1006         if aaitem > 0:
1007             prout(_("Transferring energy to shields.\""))
1008         else:
1009             prout(_("Draining energy from shields.\""))
1010         game.shield += aaitem
1011         game.energy -= aaitem
1012         return
1013
1014 def randdevice():
1015     # choose a device to damage, at random. 
1016     #
1017     # Quoth Eric Allman in the code of BSD-Trek:
1018     # "Under certain conditions you can get a critical hit.  This
1019     # sort of hit damages devices.  The probability that a given
1020     # device is damaged depends on the device.  Well protected
1021     # devices (such as the computer, which is in the core of the
1022     # ship and has considerable redundancy) almost never get
1023     # damaged, whereas devices which are exposed (such as the
1024     # warp engines) or which are particularly delicate (such as
1025     # the transporter) have a much higher probability of being
1026     # damaged."
1027     # 
1028     # This is one place where OPTION_PLAIN does not restore the
1029     # original behavior, which was equiprobable damage across
1030     # all devices.  If we wanted that, we'd return NDEVICES*Rand()
1031     # and have done with it.  Also, in the original game, DNAVYS
1032     # and DCOMPTR were the same device. 
1033     # 
1034     # Instead, we use a table of weights similar to the one from BSD Trek.
1035     # BSD doesn't have the shuttle, shield controller, death ray, or probes. 
1036     # We don't have a cloaking device.  The shuttle got the allocation
1037     # for the cloaking device, then we shaved a half-percent off
1038     # everything to have some weight to give DSHCTRL/DDRAY/DDSP.
1039     # 
1040     weights = (
1041         105,    # DSRSENS: short range scanners 10.5% 
1042         105,    # DLRSENS: long range scanners          10.5% 
1043         120,    # DPHASER: phasers                      12.0% 
1044         120,    # DPHOTON: photon torpedoes             12.0% 
1045         25,     # DLIFSUP: life support          2.5% 
1046         65,     # DWARPEN: warp drive                    6.5% 
1047         70,     # DIMPULS: impulse engines               6.5% 
1048         145,    # DSHIELD: deflector shields            14.5% 
1049         30,     # DRADIO:  subspace radio                3.0% 
1050         45,     # DSHUTTL: shuttle                       4.5% 
1051         15,     # DCOMPTR: computer                      1.5% 
1052         20,     # NAVCOMP: navigation system             2.0% 
1053         75,     # DTRANSP: transporter                   7.5% 
1054         20,     # DSHCTRL: high-speed shield controller 2.0% 
1055         10,     # DDRAY: death ray                       1.0% 
1056         30,     # DDSP: deep-space probes                3.0% 
1057     )
1058     idx = Rand() * 1000.0       # weights must sum to 1000 
1059     sum = 0
1060     for (i, w) in enumerate(weights):
1061         sum += w
1062         if idx < sum:
1063             return i
1064     return None;        # we should never get here
1065
1066 def ram(ibumpd, ienm, w):
1067     # make our ship ram something 
1068     prouts(_("***RED ALERT!  RED ALERT!"))
1069     skip(1)
1070     prout(_("***COLLISION IMMINENT."))
1071     skip(2)
1072     proutn("***")
1073     crmshp()
1074     hardness = {IHR:1.5, IHC:2.0, IHS:2.5, IHT:0.5, IHQUEST:4.0}.get(ienm, 1.0)
1075     if ibumpd:
1076         proutn(_(" rammed by "))
1077     else:
1078         proutn(_(" rams "))
1079     crmena(False, ienm, sector, w)
1080     if ibumpd:
1081         proutn(_(" (original position)"))
1082     skip(1)
1083     deadkl(w, ienm, game.sector)
1084     proutn("***")
1085     crmshp()
1086     prout(_(" heavily damaged."))
1087     icas = 10.0+20.0*Rand()
1088     prout(_("***Sickbay reports %d casualties"), icas)
1089     game.casual += icas
1090     game.state.crew -= icas
1091     #
1092     # In the pre-SST2K version, all devices got equiprobably damaged,
1093     # which was silly.  Instead, pick up to half the devices at
1094     # random according to our weighting table,
1095     # 
1096     ncrits = Rand() * (NDEVICES/2)
1097     for m in range(ncrits):
1098         dev = randdevice()
1099         if game.damage[dev] < 0:
1100             continue
1101         extradm = (10.0*hardness*Rand()+1.0)*game.damfac
1102         # Damage for at least time of travel! 
1103         game.damage[dev] += game.optime + extradm
1104     game.shldup = False
1105     prout(_("***Shields are down."))
1106     if game.state.remkl + game.state.remcom + game.state.nscrem:
1107         announce()
1108         damagereport()
1109     else:
1110         finish(FWON)
1111     return;
1112
1113 def torpedo(course, r, incoming, i, n):
1114     # let a photon torpedo fly 
1115     iquad = 0
1116     shoved = False
1117     ac = course + 0.25*r
1118     angle = (15.0-ac)*0.5235988
1119     bullseye = (15.0 - course)*0.5235988
1120     deltax = -math.sin(angle);
1121     deltay = math.cos(angle);
1122     x = incoming.x; y = incoming.y
1123     w = coord(); jw = coord()
1124     w.x = w.y = jw.x = jw.y = 0
1125     bigger = max(math.fabs(deltax), math.fabs(deltay))
1126     deltax /= bigger
1127     deltay /= bigger
1128     if not damaged(DSRSENS) or game.condition=="docked":
1129         setwnd(srscan_window)
1130     else: 
1131         setwnd(message_window)
1132     # Loop to move a single torpedo 
1133     for l in range(1, 15+1):
1134         x += deltax
1135         w.x = x + 0.5
1136         y += deltay
1137         w.y = y + 0.5
1138         if not VALID_SECTOR(w.x, w.y):
1139             break
1140         iquad=game.quad[w.x][w.y]
1141         tracktorpedo(w, l, i, n, iquad)
1142         if iquad==IHDOT:
1143             continue
1144         # hit something 
1145         setwnd(message_window)
1146         if damaged(DSRSENS) and not game.condition=="docked":
1147             skip(1);    # start new line after text track 
1148         if iquad in (IHE, IHF): # Hit our ship 
1149             skip(1)
1150             proutn(_("Torpedo hits "))
1151             crmshp()
1152             prout(".")
1153             hit = 700.0 + 100.0*Rand() - \
1154                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1155             newcnd(); # we're blown out of dock 
1156             # We may be displaced. 
1157             if game.landed or game.condition=="docked":
1158                 return hit # Cheat if on a planet 
1159             ang = angle + 2.5*(Rand()-0.5)
1160             temp = math.fabs(math.sin(ang))
1161             if math.fabs(math.cos(ang)) > temp:
1162                 temp = math.fabs(math.cos(ang))
1163             xx = -math.sin(ang)/temp
1164             yy = math.cos(ang)/temp
1165             jw.x=w.x+xx+0.5
1166             jw.y=w.y+yy+0.5
1167             if not VALID_SECTOR(jw.x, jw.y):
1168                 return hit
1169             if game.quad[jw.x][jw.y]==IHBLANK:
1170                 finish(FHOLE)
1171                 return hit
1172             if game.quad[jw.x][jw.y]!=IHDOT:
1173                 # can't move into object 
1174                 return hit
1175             game.sector = jw
1176             crmshp()
1177             shoved = True
1178         elif iquad in (IHC, IHS): # Hit a commander 
1179             if Rand() <= 0.05:
1180                 crmena(True, iquad, sector, w)
1181                 prout(_(" uses anti-photon device;"))
1182                 prout(_("   torpedo neutralized."))
1183                 return None
1184         elif iquad in (IHR, IHK): # Hit a regular enemy 
1185             # find the enemy 
1186             for ll in range(1, game.nenhere+1):
1187                 if same(w, game.ks[ll]):
1188                     break
1189             kp = math.fabs(game.kpower[ll])
1190             h1 = 700.0 + 100.0*Rand() - \
1191                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1192             h1 = math.fabs(h1)
1193             if kp < h1:
1194                 h1 = kp
1195             if game.kpower[ll] < 0:
1196                 game.kpower[ll] -= -h1
1197             else:
1198                 game.kpower[ll] -= h1
1199             if game.kpower[ll] == 0:
1200                 deadkl(w, iquad, w)
1201                 return None
1202             crmena(True, iquad, "sector", w)
1203             # If enemy damaged but not destroyed, try to displace 
1204             ang = angle + 2.5*(Rand()-0.5)
1205             temp = math.fabs(math.sin(ang))
1206             if math.fabs(math.cos(ang)) > temp:
1207                 temp = math.fabs(math.cos(ang))
1208             xx = -math.sin(ang)/temp
1209             yy = math.cos(ang)/temp
1210             jw.x=w.x+xx+0.5
1211             jw.y=w.y+yy+0.5
1212             if not VALID_SECTOR(jw.x, jw.y):
1213                 prout(_(" damaged but not destroyed."))
1214                 return
1215             if game.quad[jw.x][jw.y]==IHBLANK:
1216                 prout(_(" buffeted into black hole."))
1217                 deadkl(w, iquad, jw)
1218                 return None
1219             if game.quad[jw.x][jw.y]!=IHDOT:
1220                 # can't move into object 
1221                 prout(_(" damaged but not destroyed."))
1222                 return None
1223             proutn(_(" damaged--"))
1224             game.ks[ll] = jw
1225             shoved = True
1226             break
1227         elif iquad == IHB: # Hit a base 
1228             skip(1)
1229             prout(_("***STARBASE DESTROYED.."))
1230             for ll in range(1, game.state.rembase+1):
1231                 if same(game.state.baseq[ll], game.quadrant):
1232                     game.state.baseq[ll]=game.state.baseq[game.state.rembase]
1233                     break
1234             game.quad[w.x][w.y]=IHDOT
1235             game.state.rembase -= 1
1236             game.base.x=game.base.y=0
1237             game.state.galaxy[game.quadrant.x][game.quadrant.y].starbase -= 1
1238             game.state.chart[game.quadrant.x][game.quadrant.y].starbase -= 1
1239             game.state.basekl += 1
1240             newcnd()
1241             return None
1242         elif iquad == IHP: # Hit a planet 
1243             crmena(True, iquad, sector, w)
1244             prout(_(" destroyed."))
1245             game.state.nplankl += 1
1246             game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
1247             game.state.planets[game.iplnet].pclass = destroyed
1248             game.iplnet = 0
1249             invalidate(game.plnet)
1250             game.quad[w.x][w.y] = IHDOT
1251             if game.landed:
1252                 # captain perishes on planet 
1253                 finish(FDPLANET)
1254             return None
1255         elif iquad == IHW: # Hit an inhabited world -- very bad! 
1256             crmena(True, iquad, sector, w)
1257             prout(_(" destroyed."))
1258             game.state.nworldkl += 1
1259             game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
1260             game.state.planets[game.iplnet].pclass = destroyed
1261             game.iplnet = 0
1262             invalidate(game.plnet)
1263             game.quad[w.x][w.y] = IHDOT
1264             if game.landed:
1265                 # captain perishes on planet 
1266                 finish(FDPLANET)
1267             prout(_("You have just destroyed an inhabited planet."))
1268             prout(_("Celebratory rallies are being held on the Klingon homeworld."))
1269             return None
1270         elif iquad == IHSTAR: # Hit a star 
1271             if Rand() > 0.10:
1272                 nova(w)
1273                 return None
1274             crmena(True, IHSTAR, sector, w)
1275             prout(_(" unaffected by photon blast."))
1276             return None
1277         elif iquad == IHQUEST: # Hit a thingy 
1278             if not (game.options & OPTION_THINGY) or Rand()>0.7:
1279                 skip(1)
1280                 prouts(_("AAAAIIIIEEEEEEEEAAAAAAAAUUUUUGGGGGHHHHHHHHHHHH!!!"))
1281                 skip(1)
1282                 prouts(_("    HACK!     HACK!    HACK!        *CHOKE!*  "))
1283                 skip(1)
1284                 proutn(_("Mr. Spock-"))
1285                 prouts(_("  \"Fascinating!\""))
1286                 skip(1)
1287                 deadkl(w, iquad, w)
1288             else:
1289                 #
1290                 # Stas Sergeev added the possibility that
1291                 # you can shove the Thingy and piss it off.
1292                 # It then becomes an enemy and may fire at you.
1293                 # 
1294                 iqengry = True
1295                 shoved = True
1296             return None
1297         elif iquad == IHBLANK: # Black hole 
1298             skip(1)
1299             crmena(True, IHBLANK, sector, w)
1300             prout(_(" swallows torpedo."))
1301             return None
1302         elif iquad == IHWEB: # hit the web 
1303             skip(1)
1304             prout(_("***Torpedo absorbed by Tholian web."))
1305             return None
1306         elif iquad == IHT:  # Hit a Tholian 
1307             h1 = 700.0 + 100.0*Rand() - \
1308                 1000.0 * distance(w, incoming) * math.fabs(math.sin(bullseye-angle))
1309             h1 = math.fabs(h1)
1310             if h1 >= 600:
1311                 game.quad[w.x][w.y] = IHDOT
1312                 game.ithere = False
1313                 deadkl(w, iquad, w)
1314                 return None
1315             skip(1)
1316             crmena(True, IHT, sector, w)
1317             if Rand() > 0.05:
1318                 prout(_(" survives photon blast."))
1319                 return None
1320             prout(_(" disappears."))
1321             game.quad[w.x][w.y] = IHWEB
1322             game.ithere = False
1323             game.nenhere -= 1
1324             dropin(IHBLANK)
1325             return None
1326         else: # Problem!
1327             skip(1)
1328             proutn("Don't know how to handle torpedo collision with ")
1329             crmena(True, iquad, sector, w)
1330             skip(1)
1331             return None
1332         break
1333     if curwnd!=message_window:
1334         setwnd(message_window)
1335     if shoved:
1336         game.quad[w.x][w.y]=IHDOT
1337         game.quad[jw.x][jw.y]=iquad
1338         prout(_(" displaced by blast to Sector %s ") % jw)
1339         for ll in range(1, game.nenhere+1):
1340             game.kdist[ll] = game.kavgd[ll] = distance(game.sector,game.ks[ll])
1341         sortklings()
1342         return None
1343     skip(1)
1344     prout(_("Torpedo missed."))
1345     return None;
1346
1347 def fry(hit):
1348     # critical-hit resolution 
1349     ktr=1
1350     # a critical hit occured 
1351     if hit < (275.0-25.0*game.skill)*(1.0+0.5*Rand()):
1352         return
1353
1354     ncrit = 1.0 + hit/(500.0+100.0*Rand())
1355     proutn(_("***CRITICAL HIT--"))
1356     # Select devices and cause damage
1357     cdam = []
1358     for loop1 in range(ncrit):
1359         while True:
1360             j = randdevice()
1361             # Cheat to prevent shuttle damage unless on ship 
1362             if not (game.damage[j]<0.0 or (j==DSHUTTL and game.iscraft != "onship")):
1363                 break
1364         cdam.append(j)
1365         extradm = (hit*game.damfac)/(ncrit*(75.0+25.0*Rand()))
1366         game.damage[j] += extradm
1367         if loop1 > 0:
1368             for loop2 in range(loop1):
1369                 if j == cdam[loop2]:
1370                     break
1371             if loop2 < loop1:
1372                 continue
1373             ktr += 1
1374             if ktr==3:
1375                 skip(1)
1376             proutn(_(" and "))
1377         proutn(device[j])
1378     prout(_(" damaged."))
1379     if damaged(DSHIELD) and game.shldup:
1380         prout(_("***Shields knocked down."))
1381         game.shldup=False
1382
1383 def attack(torps_ok):
1384     # bad guy attacks us 
1385     # torps_ok == false forces use of phasers in an attack 
1386     atackd = False; attempt = False; ihurt = False;
1387     hitmax=0.0; hittot=0.0; chgfac=1.0
1388     jay = coord()
1389     where = "neither"
1390
1391     # game could be over at this point, check 
1392     if game.alldone:
1393         return
1394
1395     if idebug:
1396         prout("=== ATTACK!")
1397
1398     # Tholian gewts to move before attacking 
1399     if game.ithere:
1400         movetholian()
1401
1402     # if you have just entered the RNZ, you'll get a warning 
1403     if game.neutz: # The one chance not to be attacked 
1404         game.neutz = False
1405         return
1406
1407     # commanders get a chance to tac-move towards you 
1408     if (((game.comhere or game.ishere) and not game.justin) or game.skill == SKILL_EMERITUS) and torps_ok:
1409         moveklings()
1410
1411     # if no enemies remain after movement, we're done 
1412     if game.nenhere==0 or (game.nenhere==1 and iqhere and not iqengry):
1413         return
1414
1415     # set up partial hits if attack happens during shield status change 
1416     pfac = 1.0/game.inshld
1417     if game.shldchg:
1418         chgfac = 0.25+0.5*Rand()
1419
1420     skip(1)
1421
1422     # message verbosity control 
1423     if game.skill <= SKILL_FAIR:
1424         where = "sector"
1425
1426     for loop in range(1, game.nenhere+1):
1427         if game.kpower[loop] < 0:
1428             continue;   # too weak to attack 
1429         # compute hit strength and diminish shield power 
1430         r = Rand()
1431         # Increase chance of photon torpedos if docked or enemy energy low 
1432         if game.condition == "docked":
1433             r *= 0.25
1434         if game.kpower[loop] < 500:
1435             r *= 0.25; 
1436         jay = game.ks[loop]
1437         iquad = game.quad[jay.x][jay.y]
1438         if iquad==IHT or (iquad==IHQUEST and not iqengry):
1439             continue
1440         # different enemies have different probabilities of throwing a torp 
1441         usephasers = not torps_ok or \
1442             (iquad == IHK and r > 0.0005) or \
1443             (iquad==IHC and r > 0.015) or \
1444             (iquad==IHR and r > 0.3) or \
1445             (iquad==IHS and r > 0.07) or \
1446             (iquad==IHQUEST and r > 0.05)
1447         if usephasers:      # Enemy uses phasers 
1448             if game.condition == "docked":
1449                 continue; # Don't waste the effort! 
1450             attempt = True; # Attempt to attack 
1451             dustfac = 0.8+0.05*Rand()
1452             hit = game.kpower[loop]*math.pow(dustfac,game.kavgd[loop])
1453             game.kpower[loop] *= 0.75
1454         else: # Enemy uses photon torpedo 
1455             course = 1.90985*math.atan2(game.sector.y-jay.y, jay.x-game.sector.x)
1456             hit = 0
1457             proutn(_("***TORPEDO INCOMING"))
1458             if not damaged(DSRSENS):
1459                 proutn(_(" From "))
1460                 crmena(False, iquad, where, jay)
1461             attempt = True
1462             prout("  ")
1463             r = (Rand()+Rand())*0.5 -0.5
1464             r += 0.002*game.kpower[loop]*r
1465             hit = torpedo(course, r, jay, 1, 1)
1466             if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1467                 finish(FWON); # Klingons did themselves in! 
1468             if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova or game.alldone:
1469                 return; # Supernova or finished 
1470             if hit == None:
1471                 continue
1472         # incoming phaser or torpedo, shields may dissipate it 
1473         if game.shldup or game.shldchg or game.condition=="docked":
1474             # shields will take hits 
1475             propor = pfac * game.shield
1476             if game.condition =="docked":
1477                 propr *= 2.1
1478             if propor < 0.1:
1479                 propor = 0.1
1480             hitsh = propor*chgfac*hit+1.0
1481             absorb = 0.8*hitsh
1482             if absorb > game.shield:
1483                 absorb = game.shield
1484             game.shield -= absorb
1485             hit -= hitsh
1486             # taking a hit blasts us out of a starbase dock 
1487             if game.condition == "docked":
1488                 dock(False)
1489             # but the shields may take care of it 
1490             if propor > 0.1 and hit < 0.005*game.energy:
1491                 continue
1492         # hit from this opponent got through shields, so take damage 
1493         ihurt = True
1494         proutn(_("%d unit hit") % int(hit))
1495         if (damaged(DSRSENS) and usephasers) or game.skill<=SKILL_FAIR:
1496             proutn(_(" on the "))
1497             crmshp()
1498         if not damaged(DSRSENS) and usephasers:
1499             proutn(_(" from "))
1500             crmena(False, iquad, where, jay)
1501         skip(1)
1502         # Decide if hit is critical 
1503         if hit > hitmax:
1504             hitmax = hit
1505         hittot += hit
1506         fry(hit)
1507         game.energy -= hit
1508     if game.energy <= 0:
1509         # Returning home upon your shield, not with it... 
1510         finish(FBATTLE)
1511         return
1512     if not attempt and game.condition == "docked":
1513         prout(_("***Enemies decide against attacking your ship."))
1514     if not atackd:
1515         return
1516     percent = 100.0*pfac*game.shield+0.5
1517     if not ihurt:
1518         # Shields fully protect ship 
1519         proutn(_("Enemy attack reduces shield strength to "))
1520     else:
1521         # Print message if starship suffered hit(s) 
1522         skip(1)
1523         proutn(_("Energy left %2d    shields ") % int(game.energy))
1524         if game.shldup:
1525             proutn(_("up "))
1526         elif not damaged(DSHIELD):
1527             proutn(_("down "))
1528         else:
1529             proutn(_("damaged, "))
1530     prout(_("%d%%,   torpedoes left %d") % (percent, game.torps))
1531     # Check if anyone was hurt 
1532     if hitmax >= 200 or hittot >= 500:
1533         icas= hittot*Rand()*0.015
1534         if icas >= 2:
1535             skip(1)
1536             prout(_("Mc Coy-  \"Sickbay to bridge.  We suffered %d casualties") % icas)
1537             prout(_("   in that last attack.\""))
1538             game.casual += icas
1539             game.state.crew -= icas
1540     # After attack, reset average distance to enemies 
1541     for loop in range(1, game.nenhere+1):
1542         game.kavgd[loop] = game.kdist[loop]
1543     sortklings()
1544     return;
1545                 
1546 def deadkl(w, type, mv):
1547     # kill a Klingon, Tholian, Romulan, or Thingy 
1548     # Added mv to allow enemy to "move" before dying 
1549
1550     crmena(True, type, sector, mv)
1551     # Decide what kind of enemy it is and update appropriately 
1552     if type == IHR:
1553         # chalk up a Romulan 
1554         game.state.galaxy[game.quadrant.x][game.quadrant.y].romulans -= 1
1555         game.irhere -= 1
1556         game.state.nromrem -= 1
1557     elif type == IHT:
1558         # Killed a Tholian 
1559         game.ithere = False
1560     elif type == IHQUEST:
1561         # Killed a Thingy 
1562         iqhere = iqengry = False
1563         invalidate(thing)
1564     else:
1565         # Some type of a Klingon 
1566         game.state.galaxy[game.quadrant.x][game.quadrant.y].klingons -= 1
1567         game.klhere -= 1
1568         if type == IHC:
1569             game.comhere = False
1570             for i in range(1, game.state.remcom+1):
1571                 if same(game.state.kcmdr[i], game.quadrant):
1572                     break
1573             game.state.kcmdr[i] = game.state.kcmdr[game.state.remcom]
1574             game.state.kcmdr[game.state.remcom].x = 0
1575             game.state.kcmdr[game.state.remcom].y = 0
1576             game.state.remcom -= 1
1577             unschedule(FTBEAM)
1578             if game.state.remcom != 0:
1579                 schedule(FTBEAM, expran(1.0*game.incom/game.state.remcom))
1580         elif type ==  IHK:
1581             game.state.remkl -= 1
1582         elif type ==  IHS:
1583             game.state.nscrem -= 1
1584             game.ishere = False
1585             game.state.kscmdr.x = game.state.kscmdr.y = game.isatb = 0
1586             game.iscate = False
1587             unschedule(FSCMOVE)
1588             unschedule(FSCDBAS)
1589         else:
1590             prout("*** Internal error, deadkl() called on %s\n" % type)
1591
1592     # For each kind of enemy, finish message to player 
1593     prout(_(" destroyed."))
1594     game.quad[w.x][w.y] = IHDOT
1595     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1596         return
1597     game.recompute()
1598     # Remove enemy ship from arrays describing local conditions 
1599     if is_scheduled(FCDBAS) and same(game.battle, game.quadrant) and type==IHC:
1600         unschedule(FCDBAS)
1601     for i in range(1, game.nenhere+1):
1602         if same(game.ks[i], w):
1603             break
1604     game.nenhere -= 1
1605     if i <= game.nenhere:
1606         for j in range(i, game.nenhere+1):
1607             game.ks[j] = game.ks[j+1]
1608             game.kpower[j] = game.kpower[j+1]
1609             game.kavgd[j] = game.kdist[j] = game.kdist[j+1]
1610     game.ks[game.nenhere+1].x = 0
1611     game.ks[game.nenhere+1].x = 0
1612     game.kdist[game.nenhere+1] = 0
1613     game.kavgd[game.nenhere+1] = 0
1614     game.kpower[game.nenhere+1] = 0
1615     return;
1616
1617 def targetcheck(x, y):
1618     # Return None if target is invalid 
1619     if not VALID_SECTOR(x, y):
1620         huh()
1621         return None
1622     deltx = 0.1*(y - game.sector.y)
1623     delty = 0.1*(x - game.sector.x)
1624     if deltx==0 and delty== 0:
1625         skip(1)
1626         prout(_("Spock-  \"Bridge to sickbay.  Dr. McCoy,"))
1627         prout(_("  I recommend an immediate review of"))
1628         prout(_("  the Captain's psychological profile.\""))
1629         chew()
1630         return None
1631     return 1.90985932*math.atan2(deltx, delty)
1632
1633 def photon():
1634     # launch photon torpedo 
1635     game.ididit = False
1636     if damaged(DPHOTON):
1637         prout(_("Photon tubes damaged."))
1638         chew()
1639         return
1640     if game.torps == 0:
1641         prout(_("No torpedoes left."))
1642         chew()
1643         return
1644     key = scan()
1645     while True:
1646         if key == IHALPHA:
1647             huh()
1648             return
1649         elif key == IHEOL:
1650             prout(_("%d torpedoes left.") % game.torps)
1651             proutn(_("Number of torpedoes to fire- "))
1652             key = scan()
1653         else: # key == IHREAL  {
1654             n = aaitem + 0.5
1655             if n <= 0: # abort command 
1656                 chew()
1657                 return
1658             if n > 3:
1659                 chew()
1660                 prout(_("Maximum of 3 torpedoes per burst."))
1661                 key = IHEOL
1662                 return
1663             if n <= game.torps:
1664                 break
1665             chew()
1666             key = IHEOL
1667     for i in range(1, n+1):
1668         key = scan()
1669         if i==1 and key == IHEOL:
1670             break;      # we will try prompting 
1671         if i==2 and key == IHEOL:
1672             # direct all torpedoes at one target 
1673             while i <= n:
1674                 targ[i][1] = targ[1][1]
1675                 targ[i][2] = targ[1][2]
1676                 course[i] = course[1]
1677                 i += 1
1678             break
1679         if key != IHREAL:
1680             huh()
1681             return
1682         targ[i][1] = aaitem
1683         key = scan()
1684         if key != IHREAL:
1685             huh()
1686             return
1687         targ[i][2] = aaitem
1688         course[i] = targetcheck(targ[i][1], targ[i][2])
1689         if course[i] == None:
1690             return
1691     chew()
1692     if i == 1 and key == IHEOL:
1693         # prompt for each one 
1694         for i in range(1, n+1):
1695             proutn(_("Target sector for torpedo number %d- ") % i)
1696             key = scan()
1697             if key != IHREAL:
1698                 huh()
1699                 return
1700             targ[i][1] = aaitem
1701             key = scan()
1702             if key != IHREAL:
1703                 huh()
1704                 return
1705             targ[i][2] = aaitem
1706             chew()
1707             course[i] = targetcheck(targ[i][1], targ[i][2])
1708             if course[i] == None:
1709                 return
1710     game.ididit = True
1711     # Loop for moving <n> torpedoes 
1712     for i in range(1, n+1):
1713         if game.condition != "docked":
1714             game.torps -= 1
1715         r = (Rand()+Rand())*0.5 -0.5
1716         if math.fabs(r) >= 0.47:
1717             # misfire! 
1718             r = (Rand()+1.2) * r
1719             if n>1:
1720                 prouts(_("***TORPEDO NUMBER %d MISFIRES") % i)
1721             else:
1722                 prouts(_("***TORPEDO MISFIRES."))
1723             skip(1)
1724             if i < n:
1725                 prout(_("  Remainder of burst aborted."))
1726             if Rand() <= 0.2:
1727                 prout(_("***Photon tubes damaged by misfire."))
1728                 game.damage[DPHOTON] = game.damfac*(1.0+2.0*Rand())
1729             break
1730         if game.shldup or game.condition == "docked":
1731             r *= 1.0 + 0.0001*game.shield
1732         torpedo(course[i], r, game.sector, i, n)
1733         if game.alldone or game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
1734             return
1735     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1736         finish(FWON);
1737
1738 def overheat(rpow):
1739     # check for phasers overheating 
1740     if rpow > 1500:
1741         chekbrn = (rpow-1500.)*0.00038
1742         if Rand() <= chekbrn:
1743             prout(_("Weapons officer Sulu-  \"Phasers overheated, sir.\""))
1744             game.damage[DPHASER] = game.damfac*(1.0 + Rand()) * (1.0+chekbrn)
1745
1746 def checkshctrl(rpow):
1747     # check shield control 
1748         
1749     skip(1)
1750     if Rand() < 0.998:
1751         prout(_("Shields lowered."))
1752         return False
1753     # Something bad has happened 
1754     prouts(_("***RED ALERT!  RED ALERT!"))
1755     skip(2)
1756     hit = rpow*game.shield/game.inshld
1757     game.energy -= rpow+hit*0.8
1758     game.shield -= hit*0.2
1759     if game.energy <= 0.0:
1760         prouts(_("Sulu-  \"Captain! Shield malf***********************\""))
1761         skip(1)
1762         stars()
1763         finish(FPHASER)
1764         return True
1765     prouts(_("Sulu-  \"Captain! Shield malfunction! Phaser fire contained!\""))
1766     skip(2)
1767     prout(_("Lt. Uhura-  \"Sir, all decks reporting damage.\""))
1768     icas = hit*Rand()*0.012
1769     skip(1)
1770     fry(0.8*hit)
1771     if icas:
1772         skip(1)
1773         prout(_("McCoy to bridge- \"Severe radiation burns, Jim."))
1774         prout(_("  %d casualties so far.\"") % icas)
1775         game.casual += icas
1776         game.state.crew -= icas
1777     skip(1)
1778     prout(_("Phaser energy dispersed by shields."))
1779     prout(_("Enemy unaffected."))
1780     overheat(rpow)
1781     return True;
1782
1783 def hittem(doublehits):
1784     # register a phaser hit on Klingons and Romulans 
1785     nenhr2=game.nenhere; kk=1
1786     w = coord()
1787     skip(1)
1788     for k in range(1, nenhr2+1):
1789         wham = hits[k]
1790         if wham==0:
1791             continue
1792         dustfac = 0.9 + 0.01*Rand()
1793         hit = wham*math.pow(dustfac,game.kdist[kk])
1794         kpini = game.kpower[kk]
1795         kp = math.fabs(kpini)
1796         if PHASEFAC*hit < kp:
1797             kp = PHASEFAC*hit
1798         if game.kpower[kk] < 0:
1799             game.kpower[kk] -= -kp
1800         else:
1801             game.kpower[kk] -= kp
1802         kpow = game.kpower[kk]
1803         w = game.ks[kk]
1804         if hit > 0.005:
1805             if not damaged(DSRSENS):
1806                 boom(w)
1807             proutn(_("%d unit hit on ") % int(hit))
1808         else:
1809             proutn(_("Very small hit on "))
1810         ienm = game.quad[w.x][w.y]
1811         if ienm==IHQUEST:
1812             iqengry = True
1813         crmena(False, ienm, "sector", w)
1814         skip(1)
1815         if kpow == 0:
1816             deadkl(w, ienm, w)
1817             if (game.state.remkl + game.state.remcom + game.state.nscrem)==0:
1818                 finish(FWON);           
1819             if game.alldone:
1820                 return
1821             kk -= 1; # don't do the increment 
1822         else: # decide whether or not to emasculate klingon 
1823             if kpow > 0 and Rand() >= 0.9 and \
1824                 kpow <= ((0.4 + 0.4*Rand())*kpini):
1825                 prout(_("***Mr. Spock-  \"Captain, the vessel at Sector %s"), w)
1826                 prout(_("   has just lost its firepower.\""))
1827                 game.kpower[kk] = -kpow
1828         kk += 1
1829     return;
1830
1831 def phasers():
1832     # fire phasers 
1833     hits = []; rpow=0
1834     kz = 0; k = 1; irec=0 # Cheating inhibitor 
1835     ifast = False; no = False; itarg = True; msgflag = True
1836     automode = "NOTSET"
1837     key=0
1838
1839     skip(1)
1840     # SR sensors and Computer are needed fopr automode 
1841     if damaged(DSRSENS) or damaged(DCOMPTR):
1842         itarg = False
1843     if game.condition == "docked":
1844         prout(_("Phasers can't be fired through base shields."))
1845         chew()
1846         return
1847     if damaged(DPHASER):
1848         prout(_("Phaser control damaged."))
1849         chew()
1850         return
1851     if game.shldup:
1852         if damaged(DSHCTRL):
1853             prout(_("High speed shield control damaged."))
1854             chew()
1855             return
1856         if game.energy <= 200.0:
1857             prout(_("Insufficient energy to activate high-speed shield control."))
1858             chew()
1859             return
1860         prout(_("Weapons Officer Sulu-  \"High-speed shield control enabled, sir.\""))
1861         ifast = True
1862                 
1863     # Original code so convoluted, I re-did it all 
1864     while automode=="NOTSET":
1865         key=scan()
1866         if key == IHALPHA:
1867             if isit("manual"):
1868                 if game.nenhere==0:
1869                     prout(_("There is no enemy present to select."))
1870                     chew()
1871                     key = IHEOL
1872                     automode="AUTOMATIC"
1873                 else:
1874                     automode = "MANUAL"
1875                     key = scan()
1876             elif isit("automatic"):
1877                 if (not itarg) and game.nenhere != 0:
1878                     automode = "FORCEMAN"
1879                 else:
1880                     if game.nenhere==0:
1881                         prout(_("Energy will be expended into space."))
1882                     automode = "AUTOMATIC"
1883                     key = scan()
1884             elif isit("no"):
1885                 no = True
1886             else:
1887                 huh()
1888                 return
1889         elif key == IHREAL:
1890             if game.nenhere==0:
1891                 prout(_("Energy will be expended into space."))
1892                 automode = "AUTOMATIC"
1893             elif not itarg:
1894                 automode = "FORCEMAN"
1895             else:
1896                 automode = "AUTOMATIC"
1897         else:
1898             # IHEOL 
1899             if game.nenhere==0:
1900                 prout(_("Energy will be expended into space."))
1901                 automode = "AUTOMATIC"
1902             elif not itarg:
1903                 automode = "FORCEMAN"
1904             else: 
1905                 proutn(_("Manual or automatic? "))                      
1906     avail = game.energy
1907     if ifast:
1908         avail -= 200.0
1909     if automode == "AUTOMATIC":
1910         if key == IHALPHA and isit("no"):
1911             no = True
1912             key = scan()
1913         if key != IHREAL and game.nenhere != 0:
1914             prout(_("Phasers locked on target. Energy available: %.2f")%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                         % (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                         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.") % q.planet)
2539                 else:
2540                     prout(_("Uhura- Starfleet reports increased Klingon activity"))
2541                     if q.planet != NOPLANET:
2542                         proutn(_("near %s") % q.planet)
2543                     prout(_("in Quadrant %s.") % w)
2544                                 
2545 def wait():
2546     # wait on events 
2547     game.ididit = False
2548     while True:
2549         key = scan()
2550         if key  != IHEOL:
2551             break
2552         proutn(_("How long? "))
2553     chew()
2554     if key != IHREAL:
2555         huh()
2556         return
2557     origTime = delay = aaitem
2558     if delay <= 0.0:
2559         return
2560     if delay >= game.state.remtime or game.nenhere != 0:
2561         proutn(_("Are you sure? "))
2562         if ja() == False:
2563             return
2564
2565     # Alternate resting periods (events) with attacks 
2566
2567     game.resting = True
2568     while True:
2569         if delay <= 0:
2570             game.resting = False
2571         if not game.resting:
2572             prout(_("%d stardates left.") % int(game.state.remtime))
2573             return
2574         temp = game.optime = delay
2575         if game.nenhere:
2576             rtime = 1.0 + Rand()
2577             if rtime < temp:
2578                 temp = rtime
2579             game.optime = temp
2580         if game.optime < delay:
2581             attack(False)
2582         if game.alldone:
2583             return
2584         events()
2585         game.ididit = True
2586         if game.alldone:
2587             return
2588         delay -= temp
2589         # Repair Deathray if long rest at starbase 
2590         if origTime-delay >= 9.99 and game.condition == "docked":
2591             game.damage[DDRAY] = 0.0
2592         # leave if quadrant supernovas
2593         if game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
2594             break
2595     game.resting = False
2596     game.optime = 0
2597
2598 # A nova occurs.  It is the result of having a star hit with a
2599 # photon torpedo, or possibly of a probe warhead going off.
2600 # Stars that go nova cause stars which surround them to undergo
2601 # the same probabilistic process.  Klingons next to them are
2602 # destroyed.  And if the starship is next to it, it gets zapped.
2603 # If the zap is too much, it gets destroyed.
2604         
2605 def nova(nov):
2606     # star goes nova 
2607     course = (0.0, 10.5, 12.0, 1.5, 9.0, 0.0, 3.0, 7.5, 6.0, 4.5)
2608     newc = coord(); scratch = coord()
2609
2610     if Rand() < 0.05:
2611         # Wow! We've supernova'ed 
2612         supernova(False, nov)
2613         return
2614
2615     # handle initial nova 
2616     game.quad[nov.x][nov.y] = IHDOT
2617     crmena(False, IHSTAR, sector, nov)
2618     prout(_(" novas."))
2619     game.state.galaxy[game.quadrant.x][game.quadrant.y].stars -= 1
2620     game.state.starkl += 1
2621         
2622     # Set up stack to recursively trigger adjacent stars 
2623     bot = top = top2 = 1
2624     kount = 0
2625     icx = icy = 0
2626     hits[1][1] = nov.x
2627     hits[1][2] = nov.y
2628     while True:
2629         for mm in range(bot, top+1): 
2630             for nn in range(1, 3+1):  # nn,j represents coordinates around current 
2631                 for j in range(1, 3+1):
2632                     if j==2 and nn== 2:
2633                         continue
2634                     scratch.x = hits[mm][1]+nn-2
2635                     scratch.y = hits[mm][2]+j-2
2636                     if not VALID_SECTOR(scratch.y, scratch.x):
2637                         continue
2638                     iquad = game.quad[scratch.x][scratch.y]
2639                     # Empty space ends reaction
2640                     if iquad in (IHDOT, IHQUEST, IHBLANK, IHT, IHWEB):
2641                         break
2642                     elif iquad == IHSTAR: # Affect another star 
2643                         if Rand() < 0.05:
2644                             # This star supernovas 
2645                             scratch = supernova(False)
2646                             return
2647                         top2 += 1
2648                         hits[top2][1]=scratch.x
2649                         hits[top2][2]=scratch.y
2650                         game.state.galaxy[game.quadrant.x][game.quadrant.y].stars -= 1
2651                         game.state.starkl += 1
2652                         crmena(True, IHSTAR, sector, scratch)
2653                         prout(_(" novas."))
2654                         game.quad[scratch.x][scratch.y] = IHDOT
2655                     elif iquad == IHP: # Destroy planet 
2656                         game.state.galaxy[game.quadrant.x][game.quadrant.y].planet = NOPLANET
2657                         game.state.nplankl += 1
2658                         crmena(True, IHP, sector, scratch)
2659                         prout(_(" destroyed."))
2660                         game.state.planets[game.iplnet].pclass = destroyed
2661                         game.iplnet = 0
2662                         invalidate(game.plnet)
2663                         if game.landed:
2664                             finish(FPNOVA)
2665                             return
2666                         game.quad[scratch.x][scratch.y] = IHDOT
2667                     elif iquad == IHB: # Destroy base 
2668                         game.state.galaxy[game.quadrant.x][game.quadrant.y].starbase = False
2669                         for i in range(1, game.state.rembase+1):
2670                             if same(game.state.baseq[i], game.quadrant): 
2671                                 break
2672                         game.state.baseq[i] = game.state.baseq[game.state.rembase]
2673                         game.state.rembase -= 1
2674                         invalidate(game.base)
2675                         game.state.basekl += 1
2676                         newcnd()
2677                         crmena(True, IHB, sector, scratch)
2678                         prout(_(" destroyed."))
2679                         game.quad[scratch.x][scratch.y] = IHDOT
2680                     elif iquad in (IHE, IHF): # Buffet ship 
2681                         prout(_("***Starship buffeted by nova."))
2682                         if game.shldup:
2683                             if game.shield >= 2000.0:
2684                                 game.shield -= 2000.0
2685                             else:
2686                                 diff = 2000.0 - game.shield
2687                                 game.energy -= diff
2688                                 game.shield = 0.0
2689                                 game.shldup = False
2690                                 prout(_("***Shields knocked out."))
2691                                 game.damage[DSHIELD] += 0.005*game.damfac*Rand()*diff
2692                         else:
2693                             game.energy -= 2000.0
2694                         if game.energy <= 0:
2695                             finish(FNOVA)
2696                             return
2697                         # add in course nova contributes to kicking starship
2698                         icx += game.sector.x-hits[mm][1]
2699                         icy += game.sector.y-hits[mm][2]
2700                         kount += 1
2701                     elif iquad == IHK: # kill klingon 
2702                         deadkl(scratch,iquad, scratch)
2703                     elif iquad in (IHC,IHS,IHR): # Damage/destroy big enemies 
2704                         for ll in range(1, game.nenhere+1):
2705                             if same(game.ks[ll], scratch):
2706                                 break
2707                         game.kpower[ll] -= 800.0 # If firepower is lost, die 
2708                         if game.kpower[ll] <= 0.0:
2709                             deadkl(scratch, iquad, scratch)
2710                             break
2711                         newc.x = scratch.x + scratch.x - hits[mm][1]
2712                         newc.y = scratch.y + scratch.y - hits[mm][2]
2713                         crmena(True, iquad, sector, scratch)
2714                         proutn(_(" damaged"))
2715                         if not VALID_SECTOR(newc.x, newc.y):
2716                             # can't leave quadrant 
2717                             skip(1)
2718                             break
2719                         iquad1 = game.quad[newc.x][newc.y]
2720                         if iquad1 == IHBLANK:
2721                             proutn(_(", blasted into "))
2722                             crmena(False, IHBLANK, sector, newc)
2723                             skip(1)
2724                             deadkl(scratch, iquad, newc)
2725                             break
2726                         if iquad1 != IHDOT:
2727                             # can't move into something else 
2728                             skip(1)
2729                             break
2730                         proutn(_(", buffeted to "))
2731                         proutn(cramlc(sector, newc))
2732                         game.quad[scratch.x][scratch.y] = IHDOT
2733                         game.quad[newc.x][newc.y] = iquad
2734                         game.ks[ll] = newc
2735                         game.kdist[ll] = game.kavgd[ll] = distance(game.sector, newc)
2736                         skip(1)
2737         if top == top2: 
2738             break
2739         bot = top + 1
2740         top = top2
2741     if kount==0: 
2742         return
2743
2744     # Starship affected by nova -- kick it away. 
2745     game.dist = kount*0.1
2746     icx = sgn(icx)
2747     icy = sgn(icy)
2748     game.direc = course[3*(icx+1)+icy+2]
2749     if game.direc == 0.0:
2750         game.dist = 0.0
2751     if game.dist == 0.0:
2752         return
2753     game.optime = 10.0*game.dist/16.0
2754     skip(1)
2755     prout(_("Force of nova displaces starship."))
2756     imove(True)
2757     game.optime = 10.0*game.dist/16.0
2758     return
2759         
2760 def supernova(induced, w=None):
2761     # star goes supernova 
2762     num = 0; npdead = 0
2763     nq = coord()
2764
2765     if w != None: 
2766         nq = w
2767     else:
2768         stars = 0
2769         # Scheduled supernova -- select star 
2770         # logic changed here so that we won't favor quadrants in top
2771         # left of universe 
2772         for nq.x in range(1, GALSIZE+1):
2773             for nq.y in range(1, GALSIZE+1):
2774                 stars += game.state.galaxy[nq.x][nq.y].stars
2775         if stars == 0:
2776             return # nothing to supernova exists 
2777         num = Rand()*stars + 1
2778         for nq.x in range(1, GALSIZE+1):
2779             for nq.y in range(1, GALSIZE+1):
2780                 num -= game.state.galaxy[nq.x][nq.y].stars
2781                 if num <= 0:
2782                     break
2783             if num <=0:
2784                 break
2785         if idebug:
2786             proutn("=== Super nova here?")
2787             if ja() == True:
2788                 nq = game.quadrant
2789
2790     if not same(nq, game.quadrant) or game.justin:
2791         # it isn't here, or we just entered (treat as enroute) 
2792         if not damaged(DRADIO) or game.condition == "docked":
2793             skip(1)
2794             prout(_("Message from Starfleet Command       Stardate %.2f") % game.state.date)
2795             prout(_("     Supernova in Quadrant %s; caution advised.") % nq)
2796     else:
2797         ns = coord()
2798         # we are in the quadrant! 
2799         num = Rand()* game.state.galaxy[nq.x][nq.y].stars + 1
2800         for ns.x in range(1, QUADSIZE+1):
2801             for ns.y in range(1, QUADSIZE+1):
2802                 if game.quad[ns.x][ns.y]==IHSTAR:
2803                     num -= 1
2804                     if num==0:
2805                         break
2806             if num==0:
2807                 break
2808
2809         skip(1)
2810         prouts(_("***RED ALERT!  RED ALERT!"))
2811         skip(1)
2812         prout(_("***Incipient supernova detected at Sector %s") % ns)
2813         if square(ns.x-game.sector.x) + square(ns.y-game.sector.y) <= 2.1:
2814             proutn(_("Emergency override attempts t"))
2815             prouts("***************")
2816             skip(1)
2817             stars()
2818             game.alldone = True
2819
2820     # destroy any Klingons in supernovaed quadrant 
2821     kldead = game.state.galaxy[nq.x][nq.y].klingons
2822     game.state.galaxy[nq.x][nq.y].klingons = 0
2823     if same(nq, game.state.kscmdr):
2824         # did in the Supercommander! 
2825         game.state.nscrem = game.state.kscmdr.x = game.state.kscmdr.y = game.isatb =  0
2826         game.iscate = False
2827         unschedule(FSCMOVE)
2828         unschedule(FSCDBAS)
2829     if game.state.remcom:
2830         maxloop = game.state.remcom
2831         for l in range(1, maxloop+1):
2832             if same(game.state.kcmdr[l], nq):
2833                 game.state.kcmdr[l] = game.state.kcmdr[game.state.remcom]
2834                 invalidate(game.state.kcmdr[game.state.remcom])
2835                 game.state.remcom -= 1
2836                 kldead -= 1
2837                 if game.state.remcom==0:
2838                     unschedule(FTBEAM)
2839                 break
2840     game.state.remkl -= kldead
2841     # destroy Romulans and planets in supernovaed quadrant 
2842     nrmdead = game.state.galaxy[nq.x][nq.y].romulans
2843     game.state.galaxy[nq.x][nq.y].romulans = 0
2844     game.state.nromrem -= nrmdead
2845     # Destroy planets 
2846     for loop in range(game.inplan):
2847         if same(game.state.planets[loop].w, nq):
2848             game.state.planets[loop].pclass = destroyed
2849             npdead += 1
2850     # Destroy any base in supernovaed quadrant 
2851     if game.state.rembase:
2852         maxloop = game.state.rembase
2853         for loop in range(1, maxloop+1):
2854             if same(game.state.baseq[loop], nq):
2855                 game.state.baseq[loop] = game.state.baseq[game.state.rembase]
2856                 invalidate(game.state.baseq[game.state.rembase])
2857                 game.state.rembase -= 1
2858                 break
2859     # If starship caused supernova, tally up destruction 
2860     if induced:
2861         game.state.starkl += game.state.galaxy[nq.x][nq.y].stars
2862         game.state.basekl += game.state.galaxy[nq.x][nq.y].starbase
2863         game.state.nplankl += npdead
2864     # mark supernova in galaxy and in star chart 
2865     if same(game.quadrant, nq) or not damaged(DRADIO) or game.condition == "docked":
2866         game.state.galaxy[nq.x][nq.y].supernova = True
2867     # If supernova destroys last Klingons give special message 
2868     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0 and not same(nq, game.quadrant):
2869         skip(2)
2870         if not induced:
2871             prout(_("Lucky you!"))
2872         proutn(_("A supernova in %s has just destroyed the last Klingons.") % nq)
2873         finish(FWON)
2874         return
2875     # if some Klingons remain, continue or die in supernova 
2876     if game.alldone:
2877         finish(FSNOVAED)
2878     return
2879
2880 # Code from finish.c ends here.
2881
2882 def selfdestruct():
2883     # self-destruct maneuver 
2884     # Finish with a BANG! 
2885     chew()
2886     if damaged(DCOMPTR):
2887         prout(_("Computer damaged; cannot execute destruct sequence."))
2888         return
2889     prouts(_("---WORKING---")); skip(1)
2890     prouts(_("SELF-DESTRUCT-SEQUENCE-ACTIVATED")); skip(1)
2891     prouts("   10"); skip(1)
2892     prouts("       9"); skip(1)
2893     prouts("          8"); skip(1)
2894     prouts("             7"); skip(1)
2895     prouts("                6"); skip(1)
2896     skip(1)
2897     prout(_("ENTER-CORRECT-PASSWORD-TO-CONTINUE-"))
2898     skip(1)
2899     prout(_("SELF-DESTRUCT-SEQUENCE-OTHERWISE-"))
2900     skip(1)
2901     prout(_("SELF-DESTRUCT-SEQUENCE-WILL-BE-ABORTED"))
2902     skip(1)
2903     scan()
2904     chew()
2905     if game.passwd != citem:
2906         prouts(_("PASSWORD-REJECTED;"))
2907         skip(1)
2908         prouts(_("CONTINUITY-EFFECTED"))
2909         skip(2)
2910         return
2911     prouts(_("PASSWORD-ACCEPTED")); skip(1)
2912     prouts("                   5"); skip(1)
2913     prouts("                      4"); skip(1)
2914     prouts("                         3"); skip(1)
2915     prouts("                            2"); skip(1)
2916     prouts("                              1"); skip(1)
2917     if Rand() < 0.15:
2918         prouts(_("GOODBYE-CRUEL-WORLD"))
2919         skip(1)
2920     kaboom()
2921
2922 def kaboom():
2923     stars()
2924     if game.ship==IHE:
2925         prouts("***")
2926     prouts(_("********* Entropy of "))
2927     crmshp()
2928     prouts(_(" maximized *********"))
2929     skip(1)
2930     stars()
2931     skip(1)
2932     if game.nenhere != 0:
2933         whammo = 25.0 * game.energy
2934         l=1
2935         while l <= game.nenhere:
2936             if game.kpower[l]*game.kdist[l] <= whammo: 
2937                 deadkl(game.ks[l], game.quad[game.ks[l].x][game.ks[l].y], game.ks[l])
2938             l += 1
2939     finish(FDILITHIUM)
2940                                 
2941 def killrate():
2942     "Compute our rate of kils over time."
2943     return ((game.inkling + game.incom + game.inscom) - (game.state.remkl + game.state.remcom + game.state.nscrem))/(game.state.date-game.indate)
2944
2945 def badpoints():
2946     "Compute demerits."
2947     badpt = 5.0*game.state.starkl + \
2948             game.casual + \
2949             10.0*game.state.nplankl + \
2950             300*game.state.nworldkl + \
2951             45.0*game.nhelp +\
2952             100.0*game.state.basekl +\
2953             3.0*game.abandoned
2954     if game.ship == IHF:
2955         badpt += 100.0
2956     elif game.ship == None:
2957         badpt += 200.0
2958     return badpt
2959
2960
2961 def finish(ifin):
2962     # end the game, with appropriate notfications 
2963     igotit = False
2964     game.alldone = True
2965     skip(3)
2966     prout(_("It is stardate %.1f.") % game.state.date)
2967     skip(1)
2968     if ifin == FWON: # Game has been won
2969         if game.state.nromrem != 0:
2970             prout(_("The remaining %d Romulans surrender to Starfleet Command.") %
2971                   game.state.nromrem)
2972
2973         prout(_("You have smashed the Klingon invasion fleet and saved"))
2974         prout(_("the Federation."))
2975         game.gamewon = True
2976         if game.alive:
2977             badpt = badpoints()
2978             if badpt < 100.0:
2979                 badpt = 0.0     # Close enough!
2980             # killsPerDate >= RateMax
2981             if game.state.date-game.indate < 5.0 or \
2982                 killrate() >= 0.1*game.skill*(game.skill+1.0) + 0.1 + 0.008*badpt:
2983                 skip(1)
2984                 prout(_("In fact, you have done so well that Starfleet Command"))
2985                 if game.skill == SKILL_NOVICE:
2986                     prout(_("promotes you one step in rank from \"Novice\" to \"Fair\"."))
2987                 elif game.skill == SKILL_FAIR:
2988                     prout(_("promotes you one step in rank from \"Fair\" to \"Good\"."))
2989                 elif game.skill == SKILL_GOOD:
2990                     prout(_("promotes you one step in rank from \"Good\" to \"Expert\"."))
2991                 elif game.skill == SKILL_EXPERT:
2992                     prout(_("promotes you to Commodore Emeritus."))
2993                     skip(1)
2994                     prout(_("Now that you think you're really good, try playing"))
2995                     prout(_("the \"Emeritus\" game. It will splatter your ego."))
2996                 elif game.skill == SKILL_EMERITUS:
2997                     skip(1)
2998                     proutn(_("Computer-  "))
2999                     prouts(_("ERROR-ERROR-ERROR-ERROR"))
3000                     skip(2)
3001                     prouts(_("  YOUR-SKILL-HAS-EXCEEDED-THE-CAPACITY-OF-THIS-PROGRAM"))
3002                     skip(1)
3003                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3004                     skip(1)
3005                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3006                     skip(1)
3007                     prouts(_("  THIS-PROGRAM-MUST-SURVIVE"))
3008                     skip(1)
3009                     prouts(_("  THIS-PROGRAM-MUST?- MUST ? - SUR? ? -?  VI"))
3010                     skip(2)
3011                     prout(_("Now you can retire and write your own Star Trek game!"))
3012                     skip(1)
3013                 elif game.skill >= SKILL_EXPERT:
3014                     if game.thawed and not idebug:
3015                         prout(_("You cannot get a citation, so..."))
3016                     else:
3017                         proutn(_("Do you want your Commodore Emeritus Citation printed? "))
3018                         chew()
3019                         if ja() == True:
3020                             igotit = True
3021             # Only grant long life if alive (original didn't!)
3022             skip(1)
3023             prout(_("LIVE LONG AND PROSPER."))
3024         score()
3025         if igotit:
3026             plaque()        
3027         return
3028     elif ifin == FDEPLETE: # Federation Resources Depleted
3029         prout(_("Your time has run out and the Federation has been"))
3030         prout(_("conquered.  Your starship is now Klingon property,"))
3031         prout(_("and you are put on trial as a war criminal.  On the"))
3032         proutn(_("basis of your record, you are "))
3033         if (game.state.remkl + game.state.remcom + game.state.nscrem)*3.0 > (game.inkling + game.incom + game.inscom):
3034             prout(_("acquitted."))
3035             skip(1)
3036             prout(_("LIVE LONG AND PROSPER."))
3037         else:
3038             prout(_("found guilty and"))
3039             prout(_("sentenced to death by slow torture."))
3040             game.alive = False
3041         score()
3042         return
3043     elif ifin == FLIFESUP:
3044         prout(_("Your life support reserves have run out, and"))
3045         prout(_("you die of thirst, starvation, and asphyxiation."))
3046         prout(_("Your starship is a derelict in space."))
3047     elif ifin == FNRG:
3048         prout(_("Your energy supply is exhausted."))
3049         skip(1)
3050         prout(_("Your starship is a derelict in space."))
3051     elif ifin == FBATTLE:
3052         proutn(_("The "))
3053         crmshp()
3054         prout(_("has been destroyed in battle."))
3055         skip(1)
3056         prout(_("Dulce et decorum est pro patria mori."))
3057     elif ifin == FNEG3:
3058         prout(_("You have made three attempts to cross the negative energy"))
3059         prout(_("barrier which surrounds the galaxy."))
3060         skip(1)
3061         prout(_("Your navigation is abominable."))
3062         score()
3063     elif ifin == FNOVA:
3064         prout(_("Your starship has been destroyed by a nova."))
3065         prout(_("That was a great shot."))
3066         skip(1)
3067     elif ifin == FSNOVAED:
3068         proutn(_("The "))
3069         crmshp()
3070         prout(_(" has been fried by a supernova."))
3071         prout(_("...Not even cinders remain..."))
3072     elif ifin == FABANDN:
3073         prout(_("You have been captured by the Klingons. If you still"))
3074         prout(_("had a starbase to be returned to, you would have been"))
3075         prout(_("repatriated and given another chance. Since you have"))
3076         prout(_("no starbases, you will be mercilessly tortured to death."))
3077     elif ifin == FDILITHIUM:
3078         prout(_("Your starship is now an expanding cloud of subatomic particles"))
3079     elif ifin == FMATERIALIZE:
3080         prout(_("Starbase was unable to re-materialize your starship."))
3081         prout(_("Sic transit gloria mundi"))
3082     elif ifin == FPHASER:
3083         proutn(_("The "))
3084         crmshp()
3085         prout(_(" has been cremated by its own phasers."))
3086     elif ifin == FLOST:
3087         prout(_("You and your landing party have been"))
3088         prout(_("converted to energy, disipating through space."))
3089     elif ifin == FMINING:
3090         prout(_("You are left with your landing party on"))
3091         prout(_("a wild jungle planet inhabited by primitive cannibals."))
3092         skip(1)
3093         prout(_("They are very fond of \"Captain Kirk\" soup."))
3094         skip(1)
3095         proutn(_("Without your leadership, the "))
3096         crmshp()
3097         prout(_(" is destroyed."))
3098     elif ifin == FDPLANET:
3099         prout(_("You and your mining party perish."))
3100         skip(1)
3101         prout(_("That was a great shot."))
3102         skip(1)
3103     elif ifin == FSSC:
3104         prout(_("The Galileo is instantly annihilated by the supernova."))
3105         prout(_("You and your mining party are atomized."))
3106         skip(1)
3107         proutn(_("Mr. Spock takes command of the "))
3108         crmshp()
3109         prout(_(" and"))
3110         prout(_("joins the Romulans, reigning terror on the Federation."))
3111     elif ifin == FPNOVA:
3112         prout(_("You and your mining party are atomized."))
3113         skip(1)
3114         proutn(_("Mr. Spock takes command of the "))
3115         crmshp()
3116         prout(_(" and"))
3117         prout(_("joins the Romulans, reigning terror on the Federation."))
3118     elif ifin == FSTRACTOR:
3119         prout(_("The shuttle craft Galileo is also caught,"))
3120         prout(_("and breaks up under the strain."))
3121         skip(1)
3122         prout(_("Your debris is scattered for millions of miles."))
3123         proutn(_("Without your leadership, the "))
3124         crmshp()
3125         prout(_(" is destroyed."))
3126     elif ifin == FDRAY:
3127         prout(_("The mutants attack and kill Spock."))
3128         prout(_("Your ship is captured by Klingons, and"))
3129         prout(_("your crew is put on display in a Klingon zoo."))
3130     elif ifin == FTRIBBLE:
3131         prout(_("Tribbles consume all remaining water,"))
3132         prout(_("food, and oxygen on your ship."))
3133         skip(1)
3134         prout(_("You die of thirst, starvation, and asphyxiation."))
3135         prout(_("Your starship is a derelict in space."))
3136     elif ifin == FHOLE:
3137         prout(_("Your ship is drawn to the center of the black hole."))
3138         prout(_("You are crushed into extremely dense matter."))
3139     elif ifin == FCREW:
3140         prout(_("Your last crew member has died."))
3141     if game.ship == IHF:
3142         game.ship = None
3143     elif game.ship == IHE:
3144         game.ship = IHF
3145     game.alive = False
3146     if (game.state.remkl + game.state.remcom + game.state.nscrem) != 0:
3147         goodies = game.state.remres/game.inresor
3148         baddies = (game.state.remkl + 2.0*game.state.remcom)/(game.inkling+2.0*game.incom)
3149         if goodies/baddies >= 1.0+0.5*Rand():
3150             prout(_("As a result of your actions, a treaty with the Klingon"))
3151             prout(_("Empire has been signed. The terms of the treaty are"))
3152             if goodies/baddies >= 3.0+Rand():
3153                 prout(_("favorable to the Federation."))
3154                 skip(1)
3155                 prout(_("Congratulations!"))
3156             else:
3157                 prout(_("highly unfavorable to the Federation."))
3158         else:
3159             prout(_("The Federation will be destroyed."))
3160     else:
3161         prout(_("Since you took the last Klingon with you, you are a"))
3162         prout(_("martyr and a hero. Someday maybe they'll erect a"))
3163         prout(_("statue in your memory. Rest in peace, and try not"))
3164         prout(_("to think about pigeons."))
3165         game.gamewon = True
3166     score()
3167
3168 def score():
3169     # compute player's score 
3170     timused = game.state.date - game.indate
3171
3172     iskill = game.skill
3173     if (timused == 0 or (game.state.remkl + game.state.remcom + game.state.nscrem) != 0) and timused < 5.0:
3174         timused = 5.0
3175     perdate = killrate()
3176     ithperd = 500*perdate + 0.5
3177     iwon = 0
3178     if game.gamewon:
3179         iwon = 100*game.skill
3180     if game.ship == IHE: 
3181         klship = 0
3182     elif game.ship == IHF: 
3183         klship = 1
3184     else:
3185         klship = 2
3186     if not game.gamewon:
3187         game.state.nromrem = 0 # None captured if no win
3188     iscore = 10*(game.inkling - game.state.remkl) \
3189              + 50*(game.incom - game.state.remcom) \
3190              + ithperd + iwon \
3191              + 20*(game.inrom - game.state.nromrem) \
3192              + 200*(game.inscom - game.state.nscrem) \
3193              - game.state.nromrem \
3194              - badpoints()
3195     if not game.alive:
3196         iscore -= 200
3197     skip(2)
3198     prout(_("Your score --"))
3199     if game.inrom - game.state.nromrem:
3200         prout(_("%6d Romulans destroyed                 %5d") %
3201               (game.inrom - game.state.nromrem, 20*(game.inrom - game.state.nromrem)))
3202     if game.state.nromrem:
3203         prout(_("%6d Romulans captured                  %5d") %
3204               (game.state.nromrem, game.state.nromrem))
3205     if game.inkling - game.state.remkl:
3206         prout(_("%6d ordinary Klingons destroyed        %5d") %
3207               (game.inkling - game.state.remkl, 10*(game.inkling - game.state.remkl)))
3208     if game.incom - game.state.remcom:
3209         prout(_("%6d Klingon commanders destroyed       %5d") %
3210               (game.incom - game.state.remcom, 50*(game.incom - game.state.remcom)))
3211     if game.inscom - game.state.nscrem:
3212         prout(_("%6d Super-Commander destroyed          %5d") %
3213               (game.inscom - game.state.nscrem, 200*(game.inscom - game.state.nscrem)))
3214     if ithperd:
3215         prout(_("%6.2f Klingons per stardate              %5d") %
3216               (perdate, ithperd))
3217     if game.state.starkl:
3218         prout(_("%6d stars destroyed by your action     %5d") %
3219               (game.state.starkl, -5*game.state.starkl))
3220     if game.state.nplankl:
3221         prout(_("%6d planets destroyed by your action   %5d") %
3222               (game.state.nplankl, -10*game.state.nplankl))
3223     if (game.options & OPTION_WORLDS) and game.state.nworldkl:
3224         prout(_("%6d inhabited planets destroyed by your action   %5d") %
3225               (game.state.nplankl, -300*game.state.nworldkl))
3226     if game.state.basekl:
3227         prout(_("%6d bases destroyed by your action     %5d") %
3228               (game.state.basekl, -100*game.state.basekl))
3229     if game.nhelp:
3230         prout(_("%6d calls for help from starbase       %5d") %
3231               (game.nhelp, -45*game.nhelp))
3232     if game.casual:
3233         prout(_("%6d casualties incurred                %5d") %
3234               (game.casual, -game.casual))
3235     if game.abandoned:
3236         prout(_("%6d crew abandoned in space            %5d") %
3237               (game.abandoned, -3*game.abandoned))
3238     if klship:
3239         prout(_("%6d ship(s) lost or destroyed          %5d") %
3240               (klship, -100*klship))
3241     if not game.alive:
3242         prout(_("Penalty for getting yourself killed        -200"))
3243     if game.gamewon:
3244         proutn(_("Bonus for winning "))
3245         if game.skill   == SKILL_NOVICE:        proutn(_("Novice game  "))
3246         elif game.skill == SKILL_FAIR:          proutn(_("Fair game    "))
3247         elif game.skill ==  SKILL_GOOD:         proutn(_("Good game    "))
3248         elif game.skill ==  SKILL_EXPERT:       proutn(_("Expert game  "))
3249         elif game.skill ==  SKILL_EMERITUS:     proutn(_("Emeritus game"))
3250         prout("           %5d" % iwon)
3251     skip(1)
3252     prout(_("TOTAL SCORE                               %5d") % iscore)
3253
3254 def plaque():
3255     # emit winner's commemmorative plaque 
3256     skip(2)
3257     while True:
3258         proutn(_("File or device name for your plaque: "))
3259         cgetline(winner, sizeof(winner))
3260         try:
3261             fp = open(winner, "w")
3262             break
3263         except IOError:
3264             prout(_("Invalid name."))
3265
3266     proutn(_("Enter name to go on plaque (up to 30 characters): "))
3267     cgetline(winner, sizeof(winner))
3268     # The 38 below must be 64 for 132-column paper 
3269     nskip = 38 - len(winner)/2
3270
3271     fp.write("\n\n\n\n")
3272     # --------DRAW ENTERPRISE PICTURE. 
3273     fp.write("                                       EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" )
3274     fp.write("                                      EEE                      E  : :                                         :  E\n" )
3275     fp.write("                                    EE   EEE                   E  : :                   NCC-1701              :  E\n")
3276     fp.write("EEEEEEEEEEEEEEEE        EEEEEEEEEEEEEEE  : :                              : E\n")
3277     fp.write(" E                                     EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n")
3278     fp.write("                      EEEEEEEEE               EEEEEEEEEEEEE                 E  E\n")
3279     fp.write("                               EEEEEEE   EEEEE    E          E              E  E\n")
3280     fp.write("                                      EEE           E          E            E  E\n")
3281     fp.write("                                                       E         E          E  E\n")
3282     fp.write("                                                         EEEEEEEEEEEEE      E  E\n")
3283     fp.write("                                                      EEE :           EEEEEEE  EEEEEEEE\n")
3284     fp.write("                                                    :E    :                 EEEE       E\n")
3285     fp.write("                                                   .-E   -:-----                       E\n")
3286     fp.write("                                                    :E    :                            E\n")
3287     fp.write("                                                      EE  :                    EEEEEEEE\n")
3288     fp.write("                                                       EEEEEEEEEEEEEEEEEEEEEEE\n")
3289     fp.write("\n\n\n")
3290     fp.write(_("                                                       U. S. S. ENTERPRISE\n"))
3291     fp.write("\n\n\n\n")
3292     fp.write(_("                                  For demonstrating outstanding ability as a starship captain\n"))
3293     fp.write("\n")
3294     fp.write(_("                                                Starfleet Command bestows to you\n"))
3295     fp.write("\n")
3296     fp.write("%*s%s\n\n" % (nskip, "", winner))
3297     fp.write(_("                                                           the rank of\n\n"))
3298     fp.write(_("                                                       \"Commodore Emeritus\"\n\n"))
3299     fp.write("                                                          ")
3300     if game.skill ==  SKILL_EXPERT:
3301         fp.write(_(" Expert level\n\n"))
3302     elif game.skill == SKILL_EMERITUS:
3303         fp.write(_("Emeritus level\n\n"))
3304     else:
3305         fp.write(_(" Cheat level\n\n"))
3306     timestring = ctime()
3307     fp.write(_("                                                 This day of %.6s %.4s, %.8s\n\n") %
3308                     (timestring+4, timestring+20, timestring+11))
3309     fp.write(_("                                                        Your score:  %d\n\n") % iscore)
3310     fp.write(_("                                                    Klingons per stardate:  %.2f\n") % perdate)
3311     fp.close()
3312
3313 # Code from io.c begins here
3314
3315 rows = linecount = 0    # for paging 
3316 stdscr = None
3317 fullscreen_window = None
3318 srscan_window     = None
3319 report_window     = None
3320 status_window     = None
3321 lrscan_window     = None
3322 message_window    = None
3323 prompt_window     = None
3324
3325 def outro():
3326     "wrap up, either normally or due to signal"
3327     if game.options & OPTION_CURSES:
3328         #clear()
3329         #curs_set(1)
3330         #refresh()
3331         #resetterm()
3332         #echo()
3333         curses.endwin()
3334         stdout.write('\n')
3335     if logfp:
3336         logfp.close()
3337
3338 def iostart():
3339     global stdscr
3340     #setlocale(LC_ALL, "")
3341     #bindtextdomain(PACKAGE, LOCALEDIR)
3342     #textdomain(PACKAGE)
3343     if atexit.register(outro):
3344         sys.stderr.write("Unable to register outro(), exiting...\n")
3345         os.exit(1)
3346     if not (game.options & OPTION_CURSES):
3347         ln_env = os.getenv("LINES")
3348         if ln_env:
3349             rows = ln_env
3350         else:
3351             rows = 25
3352     else:
3353         stdscr = curses.initscr()
3354         stdscr.keypad(True)
3355         #saveterm()
3356         curses.nonl()
3357         curses.cbreak()
3358         curses.start_color()
3359         curses.init_pair(curses.COLOR_BLACK, curses.COLOR_BLACK, curses.COLOR_BLACK)
3360         curses.init_pair(curses.COLOR_GREEN, curses.COLOR_GREEN, curses.COLOR_BLACK)
3361         curses.init_pair(curses.COLOR_RED, curses.COLOR_RED, curses.COLOR_BLACK)
3362         curses.init_pair(curses.COLOR_CYAN, curses.COLOR_CYAN, curses.COLOR_BLACK)
3363         curses.init_pair(curses.COLOR_WHITE, curses.COLOR_WHITE, curses.COLOR_BLACK)
3364         curses.init_pair(curses.COLOR_MAGENTA, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
3365         curses.init_pair(curses.COLOR_BLUE, curses.COLOR_BLUE, curses.COLOR_BLACK)
3366         curses.init_pair(curses.COLOR_YELLOW, curses.COLOR_YELLOW, curses.COLOR_BLACK)
3367         #noecho()
3368         global fullscreen_window, srscan_window, report_window, status_window
3369         global lrscan_window, message_window, prompt_window
3370         fullscreen_window = stdscr
3371         srscan_window     = curses.newwin(12, 25, 0,       0)
3372         report_window     = curses.newwin(11, 0,  1,       25)
3373         status_window     = curses.newwin(10, 0,  1,       39)
3374         lrscan_window     = curses.newwin(5,  0,  0,       64) 
3375         message_window    = curses.newwin(0,  0,  12,      0)
3376         prompt_window     = curses.newwin(1,  0,  rows-2,  0) 
3377         message_window.scrollok(True)
3378         setwnd(fullscreen_window)
3379         textcolor(DEFAULT)
3380
3381
3382 def waitfor():
3383     "wait for user action -- OK to do nothing if on a TTY"
3384     if game.options & OPTION_CURSES:
3385         stsdcr.getch()
3386
3387 def announce():
3388     skip(1)
3389     if game.skill > SKILL_FAIR:
3390         prouts(_("[ANOUNCEMENT ARRIVING...]"))
3391     else:
3392         prouts(_("[IMPORTANT ANNOUNCEMENT ARRIVING -- PRESS ENTER TO CONTINUE]"))
3393     skip(1)
3394
3395 def pause_game():
3396     if game.skill > SKILL_FAIR:
3397         prompt = _("[CONTINUE?]")
3398     else:
3399         prompt = _("[PRESS ENTER TO CONTINUE]")
3400
3401     if game.options & OPTION_CURSES:
3402         drawmaps(0)
3403         setwnd(prompt_window)
3404         prompt_window.wclear()
3405         prompt_window.addstr(prompt)
3406         prompt_window.getstr()
3407         prompt_window.clear()
3408         prompt_window.refresh()
3409         setwnd(message_window)
3410     else:
3411         global linecount
3412         stdout.write('\n')
3413         proutn(prompt)
3414         raw_input()
3415         for j in range(0, rows):
3416             stdout.write('\n')
3417         linecount = 0
3418
3419 def skip(i):
3420     "Skip i lines.  Pause game if this would cause a scrolling event."
3421     while dummy in range(i):
3422         if game.options & OPTION_CURSES:
3423             (y, x) = curwnd.getyx()
3424             (my, mx) = curwnd.getmaxyx()
3425             if curwnd == message_window and y >= my - 3:
3426                 pause_game()
3427                 clrscr()
3428             else:
3429                 proutn("\n")
3430         else:
3431             global linecount
3432             linecount += 1
3433             if linecount >= rows:
3434                 pause_game()
3435             else:
3436                 stdout.write('\n')
3437
3438 def proutn(line):
3439     "Utter a line with no following line feed."
3440     if game.options & OPTION_CURSES:
3441         curwnd.addstr(line)
3442         curwnd.refresh()
3443     else:
3444         stdout.write(line)
3445
3446 def prout(line):
3447     proutn(line)
3448     skip(1)
3449
3450 def prouts(line):
3451     "print slowly!" 
3452     for c in line:
3453         curses.delay_output(30)
3454         proutn(c)
3455         if game.options & OPTION_CURSES:
3456             wrefresh(curwnd)
3457         else:
3458             sys.stdout.flush()
3459     curses.delay_output(300)
3460
3461 def cgetline(line, max):
3462     "Get a line of input."
3463     if game.options & OPTION_CURSES:
3464         line = curwnd.getstr() + "\n"
3465         curwnd.refresh()
3466     else:
3467         if replayfp and not replayfp.closed:
3468             line = replayfp.readline()
3469         else:
3470             sys.stdin.readline()
3471     if logfp:
3472         logfp.write(line)
3473
3474 def setwnd(wnd):
3475     "Change windows -- OK for this to be a no-op in tty mode." 
3476     if game.options & OPTION_CURSES:
3477         curwnd = wnd
3478         curses.curs_set(wnd == fullscreen_window or wnd == message_window or wnd == prompt_window)
3479
3480 def clreol():
3481     "Clear to end of line -- can be a no-op in tty mode" 
3482     if game.options & OPTION_CURSES:
3483         wclrtoeol(curwnd)
3484         wrefresh(curwnd)
3485
3486 def clrscr():
3487     "Clear screen -- can be a no-op in tty mode."
3488     global linecount
3489     if game.options & OPTION_CURSES:
3490        curwnd.clear()
3491        curwnd.move(0, 0)
3492        curwnd.refresh()
3493     linecount = 0
3494
3495 def textcolor(color):
3496     "Set the current text color"
3497     if game.options & OPTION_CURSES:
3498         if color == DEFAULT: 
3499             curwnd.attrset(0)
3500         elif color == BLACK: 
3501             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_BLACK))
3502         elif color == BLUE: 
3503             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_BLUE))
3504         elif color == GREEN: 
3505             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_GREEN))
3506         elif color == CYAN: 
3507             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_CYAN))
3508         elif color == RED: 
3509             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_RED))
3510         elif color == MAGENTA: 
3511             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_MAGENTA))
3512         elif color == BROWN: 
3513             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_YELLOW))
3514         elif color == LIGHTGRAY: 
3515             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_WHITE))
3516         elif color == DARKGRAY: 
3517             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_BLACK) | curses.A_BOLD)
3518         elif color == LIGHTBLUE: 
3519             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_BLUE) | curses.A_BOLD)
3520         elif color == LIGHTGREEN: 
3521             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_GREEN) | curses.A_BOLD)
3522         elif color == LIGHTCYAN: 
3523             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_CYAN) | curses.A_BOLD)
3524         elif color == LIGHTRED: 
3525             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_RED) | curses.A_BOLD)
3526         elif color == LIGHTMAGENTA: 
3527             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_MAGENTA) | curses.A_BOLD)
3528         elif color == YELLOW: 
3529             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_YELLOW) | curses.A_BOLD)
3530         elif color == WHITE:
3531             curwnd.attron(curses.COLOR_PAIR(curses.COLOR_WHITE) | curses.A_BOLD)
3532
3533 def highvideo():
3534     "Set highlight video, if this is reasonable."
3535     if game.options & OPTION_CURSES:
3536         curwnd.attron(curses.A_REVERSE)
3537  
3538 def commandhook(cmd, before):
3539     pass
3540
3541 #
3542 # Things past this point have policy implications.
3543
3544
3545 def drawmaps(mode):
3546     "Hook to be called after moving to redraw maps."
3547     if game.options & OPTION_CURSES:
3548         if mode == 1:
3549             sensor()
3550         setwnd(srscan_window)
3551         curwnd.move(0, 0)
3552         srscan()
3553         if mode != 2:
3554             setwnd(status_window)
3555             status_window.clear()
3556             status_window.move(0, 0)
3557             setwnd(report_window)
3558             report_window.clear()
3559             report_window.move(0, 0)
3560             status(0)
3561             setwnd(lrscan_window)
3562             lrscan_window.clear()
3563             lrscan_window.move(0, 0)
3564             lrscan()
3565
3566 def put_srscan_sym(w, sym):
3567     "Emit symbol for short-range scan."
3568     srscan_window.move(w.x+1, w.y*2+2)
3569     srscan_window.addch(sym)
3570     srscan_window.refresh()
3571
3572 def boom(w):
3573     "Enemy fall down, go boom."  
3574     if game.options & OPTION_CURSES:
3575         drawmaps(2)
3576         setwnd(srscan_window)
3577         srscan_window.attron(curses.A_REVERSE)
3578         put_srscan_sym(w, game.quad[w.x][w.y])
3579         #sound(500)
3580         #delay(1000)
3581         #nosound()
3582         srscan_window.attroff(curses.A_REVERSE)
3583         put_srscan_sym(w, game.quad[w.x][w.y])
3584         curses.delay_output(500)
3585         setwnd(message_window) 
3586
3587 def warble():
3588     "Sound and visual effects for teleportation."
3589     if game.options & OPTION_CURSES:
3590         drawmaps(2)
3591         setwnd(message_window)
3592         #sound(50)
3593     prouts("     . . . . .     ")
3594     if game.options & OPTION_CURSES:
3595         #curses.delay_output(1000)
3596         #nosound()
3597         pass
3598
3599 def tracktorpedo(w, l, i, n, iquad):
3600     "Torpedo-track animation." 
3601     if not game.options & OPTION_CURSES:
3602         if l == 1:
3603             if n != 1:
3604                 skip(1)
3605                 proutn(_("Track for torpedo number %d-  ") % i)
3606             else:
3607                 skip(1)
3608                 proutn(_("Torpedo track- "))
3609         elif l==4 or l==9: 
3610             skip(1)
3611         proutn("%d - %d   " % (w.x, w.y))
3612     else:
3613         if not damaged(DSRSENS) or game.condition=="docked":
3614             if i != 1 and l == 1:
3615                 drawmaps(2)
3616                 curses.delay_output(400)
3617             if (iquad==IHDOT) or (iquad==IHBLANK):
3618                 put_srscan_sym(w, '+')
3619                 #sound(l*10)
3620                 #curses.delay_output(100)
3621                 #nosound()
3622                 put_srscan_sym(w, iquad)
3623             else:
3624                 curwnd.attron(curses.A_REVERSE)
3625                 put_srscan_sym(w, iquad)
3626                 #sound(500)
3627                 #curses.delay_output(1000)
3628                 #nosound()
3629                 curwnd.attroff(curses.A_REVERSE)
3630                 put_srscan_sym(w, iquad)
3631         else:
3632             proutn("%d - %d   " % (w.x, w.y))
3633
3634 def makechart():
3635     "Display the current galaxy chart."
3636     if game.options & OPTION_CURSES:
3637         setwnd(message_window)
3638         message_window.clear()
3639     chart()
3640     if game.options & OPTION_TTY:
3641         skip(1)
3642
3643 NSYM    = 14
3644
3645 def prstat(txt, data):
3646     proutn(txt)
3647     if game.options & OPTION_CURSES:
3648         skip(1)
3649         setwnd(status_window)
3650     else:
3651         proutn(" " * NSYM - len(tx))
3652     vproutn(data)
3653     skip(1)
3654     if game.options & OPTION_CURSES:
3655         setwnd(report_window)
3656
3657 # Code from moving.c begins here
3658
3659 def imove(novapush):
3660     # movement execution for warp, impulse, supernova, and tractor-beam events 
3661     w = coord(); final = coord()
3662     trbeam = False
3663
3664     def no_quad_change():
3665         # No quadrant change -- compute new avg enemy distances 
3666         game.quad[game.sector.x][game.sector.y] = game.ship
3667         if game.nenhere:
3668             for m in range(1, game.nenhere+1):
3669                 finald = distance(w, game.ks[m])
3670                 game.kavgd[m] = 0.5 * (finald+game.kdist[m])
3671                 game.kdist[m] = finald
3672             sortklings()
3673             if not game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
3674                 attack(False)
3675             for m in range(1, game.nenhere+1):
3676                 game.kavgd[m] = game.kdist[m]
3677         newcnd()
3678         drawmaps(0)
3679         setwnd(message_window)
3680
3681     w.x = w.y = 0
3682     if game.inorbit:
3683         prout(_("Helmsman Sulu- \"Leaving standard orbit.\""))
3684         game.inorbit = False
3685
3686     angle = ((15.0 - game.direc) * 0.5235988)
3687     deltax = -math.sin(angle)
3688     deltay = math.cos(angle)
3689     if math.fabs(deltax) > math.fabs(deltay):
3690         bigger = math.fabs(deltax)
3691     else:
3692         bigger = math.fabs(deltay)
3693                 
3694     deltay /= bigger
3695     deltax /= bigger
3696
3697     # If tractor beam is to occur, don't move full distance 
3698     if game.state.date+game.optime >= scheduled(FTBEAM):
3699         trbeam = True
3700         game.condition = "red"
3701         game.dist = game.dist*(scheduled(FTBEAM)-game.state.date)/game.optime + 0.1
3702         game.optime = scheduled(FTBEAM) - game.state.date + 1e-5
3703     # Move within the quadrant 
3704     game.quad[game.sector.x][game.sector.y] = IHDOT
3705     x = game.sector.x
3706     y = game.sector.y
3707     n = 10.0*game.dist*bigger+0.5
3708
3709     if n > 0:
3710         for m in range(1, n+1):
3711             x += deltax
3712             y += deltay
3713             w.x = x + 0.5
3714             w.y = y + 0.5
3715             if not VALID_SECTOR(w.x, w.y):
3716                 # Leaving quadrant -- allow final enemy attack 
3717                 # Don't do it if being pushed by Nova 
3718                 if game.nenhere != 0 and not novapush:
3719                     newcnd()
3720                     for m in range(1, game.nenhere+1):
3721                         finald = distance(w, game.ks[m])
3722                         game.kavgd[m] = 0.5 * (finald + game.kdist[m])
3723                     #
3724                     # Stas Sergeev added the condition
3725                     # that attacks only happen if Klingons
3726                     # are present and your skill is good.
3727                     # 
3728                     if game.skill > SKILL_GOOD and game.klhere > 0 and not game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
3729                         attack(False)
3730                     if game.alldone:
3731                         return
3732                 # compute final position -- new quadrant and sector 
3733                 x = QUADSIZE*(game.quadrant.x-1)+game.sector.x
3734                 y = QUADSIZE*(game.quadrant.y-1)+game.sector.y
3735                 w.x = x+10.0*game.dist*bigger*deltax+0.5
3736                 w.y = y+10.0*game.dist*bigger*deltay+0.5
3737                 # check for edge of galaxy 
3738                 kinks = 0
3739                 while True:
3740                     kink = 0
3741                     if w.x <= 0:
3742                         w.x = -w.x + 1
3743                         kink = 1
3744                     if w.y <= 0:
3745                         w.y = -w.y + 1
3746                         kink = 1
3747                     if w.x > GALSIZE*QUADSIZE:
3748                         w.x = (GALSIZE*QUADSIZE*2)+1 - w.x
3749                         kink = 1
3750                     if w.y > GALSIZE*QUADSIZE:
3751                         w.y = (GALSIZE*QUADSIZE*2)+1 - w.y
3752                         kink = 1
3753                     if kink:
3754                         kinks = 1
3755                 if not kink:
3756                     break
3757
3758                 if kinks:
3759                     game.nkinks += 1
3760                     if game.nkinks == 3:
3761                         # Three strikes -- you're out! 
3762                         finish(FNEG3)
3763                         return
3764                     skip(1)
3765                     prout(_("YOU HAVE ATTEMPTED TO CROSS THE NEGATIVE ENERGY BARRIER"))
3766                     prout(_("AT THE EDGE OF THE GALAXY.  THE THIRD TIME YOU TRY THIS,"))
3767                     prout(_("YOU WILL BE DESTROYED."))
3768                 # Compute final position in new quadrant 
3769                 if trbeam: # Don't bother if we are to be beamed 
3770                     return
3771                 game.quadrant.x = (w.x+(QUADSIZE-1))/QUADSIZE
3772                 game.quadrant.y = (w.y+(QUADSIZE-1))/QUADSIZE
3773                 game.sector.x = w.x - QUADSIZE*(game.quadrant.x-1)
3774                 game.sector.y = w.y - QUADSIZE*(game.quadrant.y-1)
3775                 skip(1)
3776                 prout(_("Entering Quadrant %s.") % game.quadrant)
3777                 game.quad[game.sector.x][game.sector.y] = game.ship
3778                 newqad(False)
3779                 if game.skill>SKILL_NOVICE:
3780                     attack(False)  
3781                 return
3782             iquad = game.quad[w.x][w.y]
3783             if iquad != IHDOT:
3784                 # object encountered in flight path 
3785                 stopegy = 50.0*game.dist/game.optime
3786                 game.dist = distance(game.sector, w) / (QUADSIZE * 1.0)
3787                 if iquad in (IHT. IHK, OHC, IHS, IHR, IHQUEST):
3788                     game.sector = w
3789                     ram(False, iquad, game.sector)
3790                     final = game.sector
3791                 elif iquad == IHBLANK:
3792                     skip(1)
3793                     prouts(_("***RED ALERT!  RED ALERT!"))
3794                     skip(1)
3795                     proutn("***")
3796                     crmshp()
3797                     proutn(_(" pulled into black hole at Sector %s") % w)
3798                     #
3799                     # Getting pulled into a black hole was certain
3800                     # death in Almy's original.  Stas Sergeev added a
3801                     # possibility that you'll get timewarped instead.
3802                     # 
3803                     n=0
3804                     for m in range(0, NDEVICES):
3805                         if game.damage[m]>0: 
3806                             n += 1
3807                     probf=math.pow(1.4,(game.energy+game.shield)/5000.0-1.0)*math.pow(1.3,1.0/(n+1)-1.0)
3808                     if (game.options & OPTION_BLKHOLE) and Rand()>probf: 
3809                         timwrp()
3810                     else: 
3811                         finish(FHOLE)
3812                     return
3813                 else:
3814                     # something else 
3815                     skip(1)
3816                     crmshp()
3817                     if iquad == IHWEB:
3818                         proutn(_(" encounters Tholian web at %s;") % w)
3819                     else:
3820                         proutn(_(" blocked by object at %s;") % w)
3821                     proutn(_("Emergency stop required "))
3822                     prout(_("%2d units of energy.") % int(stopegy))
3823                     game.energy -= stopegy
3824                     final.x = x-deltax+0.5
3825                     final.y = y-deltay+0.5
3826                     game.sector = final
3827                     if game.energy <= 0:
3828                         finish(FNRG)
3829                         return
3830                 # We're here!
3831                 no_quad_change()
3832                 return
3833         game.dist = distance(game.sector, w) / (QUADSIZE * 1.0)
3834         game.sector = w
3835     final = game.sector
3836     no_quad_change()
3837     return
3838
3839 def dock(verbose):
3840     # dock our ship at a starbase 
3841     chew()
3842     if game.condition == "docked" and verbose:
3843         prout(_("Already docked."))
3844         return
3845     if game.inorbit:
3846         prout(_("You must first leave standard orbit."))
3847         return
3848     if not is_valid(game.base) or abs(game.sector.x-game.base.x) > 1 or abs(game.sector.y-game.base.y) > 1:
3849         crmshp()
3850         prout(_(" not adjacent to base."))
3851         return
3852     game.condition = "docked"
3853     if "verbose":
3854         prout(_("Docked."))
3855     game.ididit = True
3856     if game.energy < game.inenrg:
3857         game.energy = game.inenrg
3858     game.shield = game.inshld
3859     game.torps = game.intorps
3860     game.lsupres = game.inlsr
3861     game.state.crew = FULLCREW
3862     if not damaged(DRADIO) and \
3863         ((is_scheduled(FCDBAS) or game.isatb == 1) and not game.iseenit):
3864         # get attack report from base 
3865         prout(_("Lt. Uhura- \"Captain, an important message from the starbase:\""))
3866         attackreport(False)
3867         game.iseenit = True
3868
3869
3870 # This program originally required input in terms of a (clock)
3871 # direction and distance. Somewhere in history, it was changed to
3872 # cartesian coordinates. So we need to convert.  Probably
3873 # "manual" input should still be done this way -- it's a real
3874 # pain if the computer isn't working! Manual mode is still confusing
3875 # because it involves giving x and y motions, yet the coordinates
3876 # are always displayed y - x, where +y is downward!
3877
3878
3879 def getcd(isprobe, akey):
3880     # get course and distance 
3881     irowq=game.quadrant.x; icolq=game.quadrant.y; key=0
3882     navmode = "unspecified"
3883     itemp = "curt"
3884     incr = coord()
3885     iprompt = False
3886
3887     # Get course direction and distance. If user types bad values, return
3888     # with DIREC = -1.0.
3889     game.direc = -1.0
3890         
3891     if game.landed and not isprobe:
3892         prout(_("Dummy! You can't leave standard orbit until you"))
3893         proutn(_("are back aboard the ship."))
3894         chew()
3895         return
3896     while navmode == "unspecified":
3897         if damaged(DNAVSYS):
3898             if isprobe:
3899                 prout(_("Computer damaged; manual navigation only"))
3900             else:
3901                 prout(_("Computer damaged; manual movement only"))
3902             chew()
3903             navmode = "manual"
3904             key = IHEOL
3905             break
3906         if isprobe and akey != -1:
3907             # For probe launch, use pre-scanned value first time 
3908             key = akey
3909             akey = -1
3910         else: 
3911             key = scan()
3912
3913         if key == IHEOL:
3914             proutn(_("Manual or automatic- "))
3915             iprompt = True
3916             chew()
3917         elif key == IHALPHA:
3918             if isit("manual"):
3919                 navmode = "manual"
3920                 key = scan()
3921                 break
3922             elif isit("automatic"):
3923                 navmode = "automatic"
3924                 key = scan()
3925                 break
3926             else:
3927                 huh()
3928                 chew()
3929                 return
3930         else: # numeric 
3931             if isprobe:
3932                 prout(_("(Manual navigation assumed.)"))
3933             else:
3934                 prout(_("(Manual movement assumed.)"))
3935             navmode = "manual"
3936             break
3937
3938     if navmode == "automatic":
3939         while key == IHEOL:
3940             if isprobe:
3941                 proutn(_("Target quadrant or quadrant&sector- "))
3942             else:
3943                 proutn(_("Destination sector or quadrant&sector- "))
3944             chew()
3945             iprompt = True
3946             key = scan()
3947
3948         if key != IHREAL:
3949             huh()
3950             return
3951         xi = aaitem
3952         key = scan()
3953         if key != IHREAL:
3954             huh()
3955             return
3956         xj = aaitem
3957         key = scan()
3958         if key == IHREAL:
3959             # both quadrant and sector specified 
3960             xk = aaitem
3961             key = scan()
3962             if key != IHREAL:
3963                 huh()
3964                 return
3965             xl = aaitem
3966
3967             irowq = xi + 0.5
3968             icolq = xj + 0.5
3969             incr.y = xk + 0.5
3970             incr.x = xl + 0.5
3971         else:
3972             if isprobe:
3973                 # only quadrant specified -- go to center of dest quad 
3974                 irowq = xi + 0.5
3975                 icolq = xj + 0.5
3976                 incr.y = incr.x = 5
3977             else:
3978                 incr.y = xi + 0.5
3979                 incr.x = xj + 0.5
3980             itemp = "normal"
3981         if not VALID_QUADRANT(icolq,irowq) or not VALID_SECTOR(incr.x,incr.y):
3982             huh()
3983             return
3984         skip(1)
3985         if not isprobe:
3986             if itemp > "curt":
3987                 if iprompt:
3988                     prout(_("Helmsman Sulu- \"Course locked in for Sector %s.\"") % incr)
3989             else:
3990                 prout(_("Ensign Chekov- \"Course laid in, Captain.\""))
3991         deltax = icolq - game.quadrant.y + 0.1*(incr.x-game.sector.y)
3992         deltay = game.quadrant.x - irowq + 0.1*(game.sector.x-incr.y)
3993     else: # manual 
3994         while key == IHEOL:
3995             proutn(_("X and Y displacements- "))
3996             chew()
3997             iprompt = True
3998             key = scan()
3999         itemp = "verbose"
4000         if key != IHREAL:
4001             huh()
4002             return
4003         deltax = aaitem
4004         key = scan()
4005         if key != IHREAL:
4006             huh()
4007             return
4008         deltay = aaitem
4009     # Check for zero movement 
4010     if deltax == 0 and deltay == 0:
4011         chew()
4012         return
4013     if itemp == "verbose" and not isprobe:
4014         skip(1)
4015         prout(_("Helmsman Sulu- \"Aye, Sir.\""))
4016     game.dist = math.sqrt(deltax*deltax + deltay*deltay)
4017     game.direc = math.atan2(deltax, deltay)*1.90985932
4018     if game.direc < 0.0:
4019         game.direc += 12.0
4020     chew()
4021     return
4022
4023 def impulse():
4024     # move under impulse power 
4025     game.ididit = False
4026     if damaged(DIMPULS):
4027         chew()
4028         skip(1)
4029         prout(_("Engineer Scott- \"The impulse engines are damaged, Sir.\""))
4030         return
4031     if game.energy > 30.0:
4032         getcd(False, 0)
4033         if game.direc == -1.0:
4034             return
4035         power = 20.0 + 100.0*game.dist
4036     else:
4037         power = 30.0
4038
4039     if power >= game.energy:
4040         # Insufficient power for trip 
4041         skip(1)
4042         prout(_("First Officer Spock- \"Captain, the impulse engines"))
4043         prout(_("require 20.0 units to engage, plus 100.0 units per"))
4044         if game.energy > 30:
4045             proutn(_("quadrant.  We can go, therefore, a maximum of %d") %
4046                      int(0.01 * (game.energy-20.0)-0.05))
4047             prout(_(" quadrants.\""))
4048         else:
4049             prout(_("quadrant.  They are, therefore, useless.\""))
4050         chew()
4051         return
4052     # Make sure enough time is left for the trip 
4053     game.optime = game.dist/0.095
4054     if game.optime >= game.state.remtime:
4055         prout(_("First Officer Spock- \"Captain, our speed under impulse"))
4056         prout(_("power is only 0.95 sectors per stardate. Are you sure"))
4057         proutn(_("we dare spend the time?\" "))
4058         if ja() == False:
4059             return
4060     # Activate impulse engines and pay the cost 
4061     imove(False)
4062     game.ididit = True
4063     if game.alldone:
4064         return
4065     power = 20.0 + 100.0*game.dist
4066     game.energy -= power
4067     game.optime = game.dist/0.095
4068     if game.energy <= 0:
4069         finish(FNRG)
4070     return
4071
4072 def warp(timewarp):
4073     # move under warp drive 
4074     blooey = False; twarp = False
4075     if not timewarp: # Not WARPX entry 
4076         game.ididit = False
4077         if game.damage[DWARPEN] > 10.0:
4078             chew()
4079             skip(1)
4080             prout(_("Engineer Scott- \"The impulse engines are damaged, Sir.\""))
4081             return
4082         if damaged(DWARPEN) and game.warpfac > 4.0:
4083             chew()
4084             skip(1)
4085             prout(_("Engineer Scott- \"Sorry, Captain. Until this damage"))
4086             prout(_("  is repaired, I can only give you warp 4.\""))
4087             return
4088                         
4089         # Read in course and distance 
4090         getcd(False, 0)
4091         if game.direc == -1.0:
4092             return
4093
4094         # Make sure starship has enough energy for the trip 
4095         power = (game.dist+0.05)*game.warpfac*game.warpfac*game.warpfac*(game.shldup+1)
4096         if power >= game.energy:
4097             # Insufficient power for trip 
4098             game.ididit = False
4099             skip(1)
4100             prout(_("Engineering to bridge--"))
4101             if not game.shldup or 0.5*power > game.energy:
4102                 iwarp = math.pow((game.energy/(game.dist+0.05)), 0.333333333)
4103                 if iwarp <= 0:
4104                     prout(_("We can't do it, Captain. We don't have enough energy."))
4105                 else:
4106                     proutn(_("We don't have enough energy, but we could do it at warp %d") % iwarp)
4107                     if game.shldup:
4108                         prout(",")
4109                         prout(_("if you'll lower the shields."))
4110                     else:
4111                         prout(".")
4112             else:
4113                 prout(_("We haven't the energy to go that far with the shields up."))
4114             return
4115                                                 
4116         # Make sure enough time is left for the trip 
4117         game.optime = 10.0*game.dist/game.wfacsq
4118         if game.optime >= 0.8*game.state.remtime:
4119             skip(1)
4120             prout(_("First Officer Spock- \"Captain, I compute that such"))
4121             proutn(_("  a trip would require approximately %2.0f") %
4122                    (100.0*game.optime/game.state.remtime))
4123             prout(_(" percent of our"))
4124             proutn(_("  remaining time.  Are you sure this is wise?\" "))
4125             if ja() == False:
4126                 game.ididit = False
4127                 game.optime=0 
4128                 return
4129     # Entry WARPX 
4130     if game.warpfac > 6.0:
4131         # Decide if engine damage will occur 
4132         prob = game.dist*(6.0-game.warpfac)*(6.0-game.warpfac)/66.666666666
4133         if prob > Rand():
4134             blooey = True
4135             game.dist = Rand()*game.dist
4136         # Decide if time warp will occur 
4137         if 0.5*game.dist*math.pow(7.0,game.warpfac-10.0) > Rand():
4138             twarp = True
4139         if idebug and game.warpfac==10 and not twarp:
4140             blooey = False
4141             proutn("=== Force time warp? ")
4142             if ja() == True:
4143                 twarp = True
4144         if blooey or twarp:
4145             # If time warp or engine damage, check path 
4146             # If it is obstructed, don't do warp or damage 
4147             angle = ((15.0-game.direc)*0.5235998)
4148             deltax = -math.sin(angle)
4149             deltay = math.cos(angle)
4150             if math.fabs(deltax) > math.fabs(deltay):
4151                 bigger = math.fabs(deltax)
4152             else:
4153                 bigger = math.fabs(deltay)
4154                         
4155             deltax /= bigger
4156             deltay /= bigger
4157             n = 10.0 * game.dist * bigger +0.5
4158             x = game.sector.x
4159             y = game.sector.y
4160             for l in range(1, n+1):
4161                 x += deltax
4162                 ix = x + 0.5
4163                 y += deltay
4164                 iy = y +0.5
4165                 if not VALID_SECTOR(ix, iy):
4166                     break
4167                 if game.quad[ix][iy] != IHDOT:
4168                     blooey = False
4169                     twarp = False
4170                                 
4171
4172     # Activate Warp Engines and pay the cost 
4173     imove(False)
4174     if game.alldone:
4175         return
4176     game.energy -= game.dist*game.warpfac*game.warpfac*game.warpfac*(game.shldup+1)
4177     if game.energy <= 0:
4178         finish(FNRG)
4179     game.optime = 10.0*game.dist/game.wfacsq
4180     if twarp:
4181         timwrp()
4182     if blooey:
4183         game.damage[DWARPEN] = game.damfac*(3.0*Rand()+1.0)
4184         skip(1)
4185         prout(_("Engineering to bridge--"))
4186         prout(_("  Scott here.  The warp engines are damaged."))
4187         prout(_("  We'll have to reduce speed to warp 4."))
4188     game.ididit = True
4189     return
4190
4191 def setwarp():
4192     # change the warp factor    
4193     while True:
4194         key=scan()
4195         if key != IHEOL:
4196             break
4197         chew()
4198         proutn(_("Warp factor- "))
4199     chew()
4200     if key != IHREAL:
4201         huh()
4202         return
4203     if game.damage[DWARPEN] > 10.0:
4204         prout(_("Warp engines inoperative."))
4205         return
4206     if damaged(DWARPEN) and aaitem > 4.0:
4207         prout(_("Engineer Scott- \"I'm doing my best, Captain,"))
4208         prout(_("  but right now we can only go warp 4.\""))
4209         return
4210     if aaitem > 10.0:
4211         prout(_("Helmsman Sulu- \"Our top speed is warp 10, Captain.\""))
4212         return
4213     if aaitem < 1.0:
4214         prout(_("Helmsman Sulu- \"We can't go below warp 1, Captain.\""))
4215         return
4216     oldfac = game.warpfac
4217     game.warpfac = aaitem
4218     game.wfacsq=game.warpfac*game.warpfac
4219     if game.warpfac <= oldfac or game.warpfac <= 6.0:
4220         prout(_("Helmsman Sulu- \"Warp factor %d, Captain.\"") %
4221                int(game.warpfac))
4222         return
4223     if game.warpfac < 8.00:
4224         prout(_("Engineer Scott- \"Aye, but our maximum safe speed is warp 6.\""))
4225         return
4226     if game.warpfac == 10.0:
4227         prout(_("Engineer Scott- \"Aye, Captain, we'll try it.\""))
4228         return
4229     prout(_("Engineer Scott- \"Aye, Captain, but our engines may not take it.\""))
4230     return
4231
4232 def atover(igrab):
4233     # cope with being tossed out of quadrant by supernova or yanked by beam 
4234
4235     chew()
4236     # is captain on planet? 
4237     if game.landed:
4238         if damaged(DTRANSP):
4239             finish(FPNOVA)
4240             return
4241         prout(_("Scotty rushes to the transporter controls."))
4242         if game.shldup:
4243             prout(_("But with the shields up it's hopeless."))
4244             finish(FPNOVA)
4245         prouts(_("His desperate attempt to rescue you . . ."))
4246         if Rand() <= 0.5:
4247             prout(_("fails."))
4248             finish(FPNOVA)
4249             return
4250         prout(_("SUCCEEDS!"))
4251         if game.imine:
4252             game.imine = False
4253             proutn(_("The crystals mined were "))
4254             if Rand() <= 0.25:
4255                 prout(_("lost."))
4256             else:
4257                 prout(_("saved."))
4258                 game.icrystl = True
4259     if igrab:
4260         return
4261
4262     # Check to see if captain in shuttle craft 
4263     if game.icraft:
4264         finish(FSTRACTOR)
4265     if game.alldone:
4266         return
4267
4268     # Inform captain of attempt to reach safety 
4269     skip(1)
4270     while True:
4271         if game.justin:
4272             prouts(_("***RED ALERT!  RED ALERT!"))
4273             skip(1)
4274             proutn(_("The "))
4275             crmshp()
4276             prout(_(" has stopped in a quadrant containing"))
4277             prouts(_("   a supernova."))
4278             skip(2)
4279         proutn(_("***Emergency automatic override attempts to hurl "))
4280         crmshp()
4281         skip(1)
4282         prout(_("safely out of quadrant."))
4283         if not damaged(DRADIO):
4284             game.state.galaxy[game.quadrant.x][game.quadrant.y].charted = True
4285         # Try to use warp engines 
4286         if damaged(DWARPEN):
4287             skip(1)
4288             prout(_("Warp engines damaged."))
4289             finish(FSNOVAED)
4290             return
4291         game.warpfac = 6.0+2.0*Rand()
4292         game.wfacsq = game.warpfac * game.warpfac
4293         prout(_("Warp factor set to %d") % int(game.warpfac))
4294         power = 0.75*game.energy
4295         game.dist = power/(game.warpfac*game.warpfac*game.warpfac*(game.shldup+1))
4296         distreq = 1.4142+Rand()
4297         if distreq < game.dist:
4298             game.dist = distreq
4299         game.optime = 10.0*game.dist/game.wfacsq
4300         game.direc = 12.0*Rand()        # How dumb! 
4301         game.justin = False
4302         game.inorbit = False
4303         warp(True)
4304         if not game.justin:
4305             # This is bad news, we didn't leave quadrant. 
4306             if game.alldone:
4307                 return
4308             skip(1)
4309             prout(_("Insufficient energy to leave quadrant."))
4310             finish(FSNOVAED)
4311             return
4312         # Repeat if another snova
4313         if not game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova:
4314             break
4315     if (game.state.remkl + game.state.remcom + game.state.nscrem)==0: 
4316         finish(FWON) # Snova killed remaining enemy. 
4317
4318 def timwrp():
4319     # let's do the time warp again 
4320     prout(_("***TIME WARP ENTERED."))
4321     if game.state.snap and Rand() < 0.5:
4322         # Go back in time 
4323         prout(_("You are traveling backwards in time %d stardates.") %
4324               int(game.state.date-game.snapsht.date))
4325         game.state = game.snapsht
4326         game.state.snap = False
4327         if game.state.remcom:
4328             schedule(FTBEAM, expran(game.intime/game.state.remcom))
4329             schedule(FBATTAK, expran(0.3*game.intime))
4330         schedule(FSNOVA, expran(0.5*game.intime))
4331         # next snapshot will be sooner 
4332         schedule(FSNAP, expran(0.25*game.state.remtime))
4333                                 
4334         if game.state.nscrem:
4335             schedule(FSCMOVE, 0.2777)       
4336         game.isatb = 0
4337         unschedule(FCDBAS)
4338         unschedule(FSCDBAS)
4339         invalidate(game.battle)
4340
4341         # Make sure Galileo is consistant -- Snapshot may have been taken
4342         # when on planet, which would give us two Galileos! 
4343         gotit = False
4344         for l in range(game.inplan):
4345             if game.state.planets[l].known == "shuttle_down":
4346                 gotit = True
4347                 if game.iscraft == "onship" and game.ship==IHE:
4348                     prout(_("Chekov-  \"Security reports the Galileo has disappeared, Sir!"))
4349                     game.iscraft = "offship"
4350         # Likewise, if in the original time the Galileo was abandoned, but
4351         # was on ship earlier, it would have vanished -- let's restore it.
4352         if game.iscraft == "offship" and not gotit and game.damage[DSHUTTL] >= 0.0:
4353             prout(_("Checkov-  \"Security reports the Galileo has reappeared in the dock!\""))
4354             game.iscraft = "onship"
4355         # 
4356 #        * There used to be code to do the actual reconstrction here,
4357 #        * but the starchart is now part of the snapshotted galaxy state.
4358 #        
4359         prout(_("Spock has reconstructed a correct star chart from memory"))
4360     else:
4361         # Go forward in time 
4362         game.optime = -0.5*game.intime*math.log(Rand())
4363         prout(_("You are traveling forward in time %d stardates.") % int(game.optime))
4364         # cheat to make sure no tractor beams occur during time warp 
4365         postpone(FTBEAM, game.optime)
4366         game.damage[DRADIO] += game.optime
4367     newqad(False)
4368     events()    # Stas Sergeev added this -- do pending events 
4369
4370 def probe():
4371     # launch deep-space probe 
4372     # New code to launch a deep space probe 
4373     if game.nprobes == 0:
4374         chew()
4375         skip(1)
4376         if game.ship == IHE: 
4377             prout(_("Engineer Scott- \"We have no more deep space probes, Sir.\""))
4378         else:
4379             prout(_("Ye Faerie Queene has no deep space probes."))
4380         return
4381     if damaged(DDSP):
4382         chew()
4383         skip(1)
4384         prout(_("Engineer Scott- \"The probe launcher is damaged, Sir.\""))
4385         return
4386     if is_scheduled(FDSPROB):
4387         chew()
4388         skip(1)
4389         if damaged(DRADIO) and game.condition != "docked":
4390             prout(_("Spock-  \"Records show the previous probe has not yet"))
4391             prout(_("   reached its destination.\""))
4392         else:
4393             prout(_("Uhura- \"The previous probe is still reporting data, Sir.\""))
4394         return
4395     key = scan()
4396
4397     if key == IHEOL:
4398         # slow mode, so let Kirk know how many probes there are left
4399         if game.nprobes == 1:
4400             prout(_("1 probe left."))
4401         else:
4402             prout(_("%d probes left") % game.nprobes)
4403         proutn(_("Are you sure you want to fire a probe? "))
4404         if ja() == False:
4405             return
4406
4407     game.isarmed = False
4408     if key == IHALPHA and citem == "armed":
4409         game.isarmed = True
4410         key = scan()
4411     elif key == IHEOL:
4412         proutn(_("Arm NOVAMAX warhead? "))
4413         game.isarmed = ja()
4414     getcd(True, key)
4415     if game.direc == -1.0:
4416         return
4417     game.nprobes -= 1
4418     angle = ((15.0 - game.direc) * 0.5235988)
4419     game.probeinx = -math.sin(angle)
4420     game.probeiny = math.cos(angle)
4421     if math.fabs(game.probeinx) > math.fabs(game.probeiny):
4422         bigger = math.fabs(game.probeinx)
4423     else:
4424         bigger = math.fabs(game.probeiny)
4425                 
4426     game.probeiny /= bigger
4427     game.probeinx /= bigger
4428     game.proben = 10.0*game.dist*bigger +0.5
4429     game.probex = game.quadrant.x*QUADSIZE + game.sector.x - 1  # We will use better packing than original
4430     game.probey = game.quadrant.y*QUADSIZE + game.sector.y - 1
4431     game.probec = game.quadrant
4432     schedule(FDSPROB, 0.01) # Time to move one sector
4433     prout(_("Ensign Chekov-  \"The deep space probe is launched, Captain.\""))
4434     game.ididit = True
4435     return
4436
4437 # Here's how the mayday code works:
4438
4439 # First, the closest starbase is selected.  If there is a a starbase
4440 # in your own quadrant, you are in good shape.  This distance takes
4441 # quadrant distances into account only.
4442 #
4443 # A magic number is computed based on the distance which acts as the
4444 # probability that you will be rematerialized.  You get three tries.
4445 #
4446 # When it is determined that you should be able to be rematerialized
4447 # (i.e., when the probability thing mentioned above comes up
4448 # positive), you are put into that quadrant (anywhere).  Then, we try
4449 # to see if there is a spot adjacent to the star- base.  If not, you
4450 # can't be rematerialized!!!  Otherwise, it drops you there.  It only
4451 # tries five times to find a spot to drop you.  After that, it's your
4452 # problem.
4453
4454 def mayday():
4455     # yell for help from nearest starbase 
4456     # There's more than one way to move in this game! 
4457     line = 0
4458
4459     chew()
4460     # Test for conditions which prevent calling for help 
4461     if game.condition == "docked":
4462         prout(_("Lt. Uhura-  \"But Captain, we're already docked.\""))
4463         return
4464     if damaged(DRADIO):
4465         prout(_("Subspace radio damaged."))
4466         return
4467     if game.state.rembase==0:
4468         prout(_("Lt. Uhura-  \"Captain, I'm not getting any response from Starbase.\""))
4469         return
4470     if game.landed:
4471         proutn(_("You must be aboard the "))
4472         crmshp()
4473         prout(".")
4474         return
4475     # OK -- call for help from nearest starbase 
4476     game.nhelp += 1
4477     if game.base.x!=0:
4478         # There's one in this quadrant 
4479         ddist = distance(game.base, game.sector)
4480     else:
4481         ddist = FOREVER
4482         for m in range(1, game.state.rembase+1):
4483             xdist = QUADSIZE * distance(game.state.baseq[m], game.quadrant)
4484             if xdist < ddist:
4485                 ddist = xdist
4486                 line = m
4487         # Since starbase not in quadrant, set up new quadrant 
4488         game.quadrant = game.state.baseq[line]
4489         newqad(True)
4490     # dematerialize starship 
4491     game.quad[game.sector.x][game.sector.y]=IHDOT
4492     proutn(_("Starbase in Quadrant %s responds--") % game.quadrant)
4493     crmshp()
4494     prout(_(" dematerializes."))
4495     game.sector.x=0
4496     for m in range(1, 5+1):
4497         ix = game.base.x+3.0*Rand()-1
4498         iy = game.base.y+3.0*Rand()-1
4499         if VALID_SECTOR(ix,iy) and game.quad[ix][iy]==IHDOT:
4500             # found one -- finish up 
4501             game.sector.x=ix
4502             game.sector.y=iy
4503             break
4504     if not is_valid(game.sector):
4505         prout(_("You have been lost in space..."))
4506         finish(FMATERIALIZE)
4507         return
4508     # Give starbase three chances to rematerialize starship 
4509     probf = math.pow((1.0 - math.pow(0.98,ddist)), 0.33333333)
4510     for m in range(1, 3+1):
4511         if m == 1: proutn(_("1st"))
4512         elif m == 2: proutn(_("2nd"))
4513         elif m == 3: proutn(_("3rd"))
4514         proutn(_(" attempt to re-materialize "))
4515         crmshp()
4516         game.quad[ix][iy]=(IHMATER0,IHMATER1,IHMATER2)[m-1]
4517         textcolor(RED)
4518         warble()
4519         if Rand() > probf:
4520             break
4521         prout(_("fails."))
4522         curses.delay_output(500)
4523         textcolor(DEFAULT)
4524     if m > 3:
4525         game.quad[ix][iy]=IHQUEST
4526         game.alive = False
4527         drawmaps(1)
4528         setwnd(message_window)
4529         finish(FMATERIALIZE)
4530         return
4531     game.quad[ix][iy]=game.ship
4532     textcolor(GREEN)
4533     prout(_("succeeds."))
4534     textcolor(DEFAULT)
4535     dock(False)
4536     skip(1)
4537     prout(_("Lt. Uhura-  \"Captain, we made it!\""))
4538
4539 # Abandon Ship (the BSD-Trek description)
4540
4541 # The ship is abandoned.  If your current ship is the Faire
4542 # Queene, or if your shuttlecraft is dead, you're out of
4543 # luck.  You need the shuttlecraft in order for the captain
4544 # (that's you!!) to escape.
4545
4546 # Your crew can beam to an inhabited starsystem in the
4547 # quadrant, if there is one and if the transporter is working.
4548 # If there is no inhabited starsystem, or if the transporter
4549 # is out, they are left to die in outer space.
4550
4551 # If there are no starbases left, you are captured by the
4552 # Klingons, who torture you mercilessly.  However, if there
4553 # is at least one starbase, you are returned to the
4554 # Federation in a prisoner of war exchange.  Of course, this
4555 # can't happen unless you have taken some prisoners.
4556
4557 def abandon():
4558     # abandon ship 
4559     chew()
4560     if game.condition=="docked":
4561         if game.ship!=IHE:
4562             prout(_("You cannot abandon Ye Faerie Queene."))
4563             return
4564     else:
4565         # Must take shuttle craft to exit 
4566         if game.damage[DSHUTTL]==-1:
4567             prout(_("Ye Faerie Queene has no shuttle craft."))
4568             return
4569         if game.damage[DSHUTTL]<0:
4570             prout(_("Shuttle craft now serving Big Macs."))
4571             return
4572         if game.damage[DSHUTTL]>0:
4573             prout(_("Shuttle craft damaged."))
4574             return
4575         if game.landed:
4576             prout(_("You must be aboard the ship."))
4577             return
4578         if game.iscraft != "onship":
4579             prout(_("Shuttle craft not currently available."))
4580             return
4581         # Print abandon ship messages 
4582         skip(1)
4583         prouts(_("***ABANDON SHIP!  ABANDON SHIP!"))
4584         skip(1)
4585         prouts(_("***ALL HANDS ABANDON SHIP!"))
4586         skip(2)
4587         prout(_("Captain and crew escape in shuttle craft."))
4588         if game.state.rembase==0:
4589             # Oops! no place to go... 
4590             finish(FABANDN)
4591             return
4592         q = game.state.galaxy[game.quadrant.x][game.quadrant.y]
4593         # Dispose of crew 
4594         if not (game.options & OPTION_WORLDS) and not damaged(DTRANSP):
4595             prout(_("Remainder of ship's complement beam down"))
4596             prout(_("to nearest habitable planet."))
4597         elif q.planet != NOPLANET and not damaged(DTRANSP):
4598             prout(_("Remainder of ship's complement beam down to %s.") %
4599                     q.planet)
4600         else:
4601             prout(_("Entire crew of %d left to die in outer space.") %
4602                     game.state.crew)
4603             game.casual += game.state.crew
4604             game.abandoned += game.state.crew
4605
4606         # If at least one base left, give 'em the Faerie Queene 
4607         skip(1)
4608         game.icrystl = False # crystals are lost 
4609         game.nprobes = 0 # No probes 
4610         prout(_("You are captured by Klingons and released to"))
4611         prout(_("the Federation in a prisoner-of-war exchange."))
4612         nb = Rand()*game.state.rembase+1
4613         # Set up quadrant and position FQ adjacient to base 
4614         if not same(game.quadrant, game.state.baseq[nb]):
4615             game.quadrant = game.state.baseq[nb]
4616             game.sector.x = game.sector.y = 5
4617             newqad(True)
4618         while True:
4619             # position next to base by trial and error 
4620             game.quad[game.sector.x][game.sector.y] = IHDOT
4621             for l in range(1, QUADSIZE+1):
4622                 game.sector.x = 3.0*Rand() - 1.0 + game.base.x
4623                 game.sector.y = 3.0*Rand() - 1.0 + game.base.y
4624                 if VALID_SECTOR(game.sector.x, game.sector.y) and \
4625                        game.quad[game.sector.x][game.sector.y] == IHDOT:
4626                     break
4627             if l < QUADSIZE+1:
4628                 break # found a spot 
4629             game.sector.x=QUADSIZE/2
4630             game.sector.y=QUADSIZE/2
4631             newqad(True)
4632     # Get new commission 
4633     game.quad[game.sector.x][game.sector.y] = game.ship = IHF
4634     game.state.crew = FULLCREW
4635     prout(_("Starfleet puts you in command of another ship,"))
4636     prout(_("the Faerie Queene, which is antiquated but,"))
4637     prout(_("still useable."))
4638     if game.icrystl:
4639         prout(_("The dilithium crystals have been moved."))
4640     game.imine = False
4641     game.iscraft = "offship" # Galileo disappears 
4642     # Resupply ship 
4643     game.condition="docked"
4644     for l in range(0, NDEVICES): 
4645         game.damage[l] = 0.0
4646     game.damage[DSHUTTL] = -1
4647     game.energy = game.inenrg = 3000.0
4648     game.shield = game.inshld = 1250.0
4649     game.torps = game.intorps = 6
4650     game.lsupres=game.inlsr=3.0
4651     game.shldup=False
4652     game.warpfac=5.0
4653     game.wfacsq=25.0
4654     return
4655
4656 # Code from planets.c begins here.
4657
4658 def consumeTime():
4659     # abort a lengthy operation if an event interrupts it 
4660     game.ididit = True
4661     events()
4662     if game.alldone or game.state.galaxy[game.quadrant.x][game.quadrant.y].supernova or game.justin: 
4663         return True
4664     return False
4665
4666 def survey():
4667     # report on (uninhabited) planets in the galaxy 
4668     iknow = False
4669     skip(1)
4670     chew()
4671     prout(_("Spock-  \"Planet report follows, Captain.\""))
4672     skip(1)
4673     for i in range(game.inplan):
4674         if game.state.planets[i].pclass == destroyed:
4675             continue
4676         if (game.state.planets[i].known != "unknown" \
4677             and game.state.planets[i].inhabited == UNINHABITED) \
4678             or idebug:
4679             iknow = True
4680             if idebug and game.state.planets[i].known=="unknown":
4681                 proutn("(Unknown) ")
4682             proutn(cramlc(quadrant, game.state.planets[i].w))
4683             proutn(_("   class "))
4684             proutn(game.state.planets[i].pclass)
4685             proutn("   ")
4686             if game.state.planets[i].crystals != present:
4687                 proutn(_("no "))
4688             prout(_("dilithium crystals present."))
4689             if game.state.planets[i].known=="shuttle_down": 
4690                 prout(_("    Shuttle Craft Galileo on surface."))
4691     if not iknow:
4692         prout(_("No information available."))
4693
4694 def orbit():
4695     # enter standard orbit 
4696     skip(1)
4697     chew()
4698     if game.inorbit:
4699         prout(_("Already in standard orbit."))
4700         return
4701     if damaged(DWARPEN) and damaged(DIMPULS):
4702         prout(_("Both warp and impulse engines damaged."))
4703         return
4704     if not is_valid(game.plnet) or abs(game.sector.x-game.plnet.x) > 1 or abs(game.sector.y-game.plnet.y) > 1:
4705         crmshp()
4706         prout(_(" not adjacent to planet."))
4707         skip(1)
4708         return
4709     game.optime = 0.02+0.03*Rand()
4710     prout(_("Helmsman Sulu-  \"Entering standard orbit, Sir.\""))
4711     newcnd()
4712     if consumeTime():
4713         return
4714     game.height = (1400.0+7200.0*Rand())
4715     prout(_("Sulu-  \"Entered orbit at altitude %.2f kilometers.\"") % game.height)
4716     game.inorbit = True
4717     game.ididit = True
4718
4719 def sensor():
4720     # examine planets in this quadrant 
4721     if damaged(DSRSENS):
4722         if game.options & OPTION_TTY:
4723             prout(_("Short range sensors damaged."))
4724         return
4725     if not is_valid(game.plnet):
4726         if game.options & OPTION_TTY:
4727             prout(_("Spock- \"No planet in this quadrant, Captain.\""))
4728         return
4729     if game.state.planets[game.iplnet].known == "unknown":
4730         prout(_("Spock-  \"Sensor scan for Quadrant %s-") % game.quadrant)
4731         skip(1)
4732         prout(_("         Planet at Sector %s is of class %s.") %
4733               (sector,game.plnet, game.state.planets[game.iplnet]))
4734         if game.state.planets[game.iplnet].known=="shuttle_down": 
4735             prout(_("         Sensors show Galileo still on surface."))
4736         proutn(_("         Readings indicate"))
4737         if game.state.planets[game.iplnet].crystals != present:
4738             proutn(_(" no"))
4739         prout(_(" dilithium crystals present.\""))
4740         if game.state.planets[game.iplnet].known == "unknown":
4741             game.state.planets[game.iplnet].known = "known"
4742
4743 def beam():
4744     # use the transporter 
4745     nrgneed = 0
4746     chew()
4747     skip(1)
4748     if damaged(DTRANSP):
4749         prout(_("Transporter damaged."))
4750         if not damaged(DSHUTTL) and (game.state.planets[game.iplnet].known=="shuttle_down" or game.iscraft == "onship"):
4751             skip(1)
4752             proutn(_("Spock-  \"May I suggest the shuttle craft, Sir?\" "))
4753             if ja() == True:
4754                 shuttle()
4755         return
4756     if not game.inorbit:
4757         crmshp()
4758         prout(_(" not in standard orbit."))
4759         return
4760     if game.shldup:
4761         prout(_("Impossible to transport through shields."))
4762         return
4763     if game.state.planets[game.iplnet].known=="unknown":
4764         prout(_("Spock-  \"Captain, we have no information on this planet"))
4765         prout(_("  and Starfleet Regulations clearly state that in this situation"))
4766         prout(_("  you may not go down.\""))
4767         return
4768     if not game.landed and game.state.planets[game.iplnet].crystals==absent:
4769         prout(_("Spock-  \"Captain, I fail to see the logic in"))
4770         prout(_("  exploring a planet with no dilithium crystals."))
4771         proutn(_("  Are you sure this is wise?\" "))
4772         if ja() == False:
4773             chew()
4774             return
4775     if not (game.options & OPTION_PLAIN):
4776         nrgneed = 50 * game.skill + game.height / 100.0
4777         if nrgneed > game.energy:
4778             prout(_("Engineering to bridge--"))
4779             prout(_("  Captain, we don't have enough energy for transportation."))
4780             return
4781         if not game.landed and nrgneed * 2 > game.energy:
4782             prout(_("Engineering to bridge--"))
4783             prout(_("  Captain, we have enough energy only to transport you down to"))
4784             prout(_("  the planet, but there wouldn't be an energy for the trip back."))
4785             if game.state.planets[game.iplnet].known == "shuttle_down":
4786                 prout(_("  Although the Galileo shuttle craft may still be on a surface."))
4787             proutn(_("  Are you sure this is wise?\" "))
4788             if ja() == False:
4789                 chew()
4790                 return
4791     if game.landed:
4792         # Coming from planet 
4793         if game.state.planets[game.iplnet].known=="shuttle_down":
4794             proutn(_("Spock-  \"Wouldn't you rather take the Galileo?\" "))
4795             if ja() == True:
4796                 chew()
4797                 return
4798             prout(_("Your crew hides the Galileo to prevent capture by aliens."))
4799         prout(_("Landing party assembled, ready to beam up."))
4800         skip(1)
4801         prout(_("Kirk whips out communicator..."))
4802         prouts(_("BEEP  BEEP  BEEP"))
4803         skip(2)
4804         prout(_("\"Kirk to enterprise-  Lock on coordinates...energize.\""))
4805     else:
4806         # Going to planet 
4807         prout(_("Scotty-  \"Transporter room ready, Sir.\""))
4808         skip(1)
4809         prout(_("Kirk and landing party prepare to beam down to planet surface."))
4810         skip(1)
4811         prout(_("Kirk-  \"Energize.\""))
4812     game.ididit = True
4813     skip(1)
4814     prouts("WWHOOOIIIIIRRRRREEEE.E.E.  .  .  .  .   .    .")
4815     skip(2)
4816     if Rand() > 0.98:
4817         prouts("BOOOIIIOOOIIOOOOIIIOIING . . .")
4818         skip(2)
4819         prout(_("Scotty-  \"Oh my God!  I've lost them.\""))
4820         finish(FLOST)
4821         return
4822     prouts(".    .   .  .  .  .  .E.E.EEEERRRRRIIIIIOOOHWW")
4823     game.landed = not game.landed
4824     game.energy -= nrgneed
4825     skip(2)
4826     prout(_("Transport complete."))
4827     if game.landed and game.state.planets[game.iplnet].known=="shuttle_down":
4828         prout(_("The shuttle craft Galileo is here!"))
4829     if not game.landed and game.imine:
4830         game.icrystl = True
4831         game.cryprob = 0.05
4832     game.imine = False
4833     return
4834
4835 def mine():
4836     # strip-mine a world for dilithium 
4837     skip(1)
4838     chew()
4839     if not game.landed:
4840         prout(_("Mining party not on planet."))
4841         return
4842     if game.state.planets[game.iplnet].crystals == mined:
4843         prout(_("This planet has already been strip-mined for dilithium."))
4844         return
4845     elif game.state.planets[game.iplnet].crystals == absent:
4846         prout(_("No dilithium crystals on this planet."))
4847         return
4848     if game.imine:
4849         prout(_("You've already mined enough crystals for this trip."))
4850         return
4851     if game.icrystl and game.cryprob == 0.05:
4852         proutn(_("With all those fresh crystals aboard the "))
4853         crmshp()
4854         skip(1)
4855         prout(_("there's no reason to mine more at this time."))
4856         return
4857     game.optime = (0.1+0.2*Rand())*game.state.planets[game.iplnet].pclass
4858     if consumeTime():
4859         return
4860     prout(_("Mining operation complete."))
4861     game.state.planets[game.iplnet].crystals = mined
4862     game.imine = game.ididit = True
4863
4864 def usecrystals():
4865     # use dilithium crystals 
4866     game.ididit = False
4867     skip(1)
4868     chew()
4869     if not game.icrystl:
4870         prout(_("No dilithium crystals available."))
4871         return
4872     if game.energy >= 1000:
4873         prout(_("Spock-  \"Captain, Starfleet Regulations prohibit such an operation"))
4874         prout(_("  except when Condition Yellow exists."))
4875         return
4876     prout(_("Spock- \"Captain, I must warn you that loading"))
4877     prout(_("  raw dilithium crystals into the ship's power"))
4878     prout(_("  system may risk a severe explosion."))
4879     proutn(_("  Are you sure this is wise?\" "))
4880     if ja() == False:
4881         chew()
4882         return
4883     skip(1)
4884     prout(_("Engineering Officer Scott-  \"(GULP) Aye Sir."))
4885     prout(_("  Mr. Spock and I will try it.\""))
4886     skip(1)
4887     prout(_("Spock-  \"Crystals in place, Sir."))
4888     prout(_("  Ready to activate circuit.\""))
4889     skip(1)
4890     prouts(_("Scotty-  \"Keep your fingers crossed, Sir!\""))
4891     skip(1)
4892     if Rand() <= game.cryprob:
4893         prouts(_("  \"Activating now! - - No good!  It's***"))
4894         skip(2)
4895         prouts(_("***RED ALERT!  RED A*L********************************"))
4896         skip(1)
4897         stars()
4898         prouts(_("******************   KA-BOOM!!!!   *******************"))
4899         skip(1)
4900         kaboom()
4901         return
4902     game.energy += 5000.0*(1.0 + 0.9*Rand())
4903     prouts(_("  \"Activating now! - - "))
4904     prout(_("The instruments"))
4905     prout(_("   are going crazy, but I think it's"))
4906     prout(_("   going to work!!  Congratulations, Sir!\""))
4907     game.cryprob *= 2.0
4908     game.ididit = True
4909
4910 def shuttle():
4911     # use shuttlecraft for planetary jaunt 
4912     chew()
4913     skip(1)
4914     if damaged(DSHUTTL):
4915         if game.damage[DSHUTTL] == -1.0:
4916             if game.inorbit and game.state.planets[game.iplnet].known == "shuttle_down":
4917                 prout(_("Ye Faerie Queene has no shuttle craft bay to dock it at."))
4918             else:
4919                 prout(_("Ye Faerie Queene had no shuttle craft."))
4920         elif game.damage[DSHUTTL] > 0:
4921             prout(_("The Galileo is damaged."))
4922         else: # game.damage[DSHUTTL] < 0  
4923             prout(_("Shuttle craft is now serving Big Macs."))
4924         return
4925     if not game.inorbit:
4926         crmshp()
4927         prout(_(" not in standard orbit."))
4928         return
4929     if (game.state.planets[game.iplnet].known != "shuttle_down") and game.iscraft != "onship":
4930         prout(_("Shuttle craft not currently available."))
4931         return
4932     if not game.landed and game.state.planets[game.iplnet].known=="shuttle_down":
4933         prout(_("You will have to beam down to retrieve the shuttle craft."))
4934         return
4935     if game.shldup or game.condition == "docked":
4936         prout(_("Shuttle craft cannot pass through shields."))
4937         return
4938     if game.state.planets[game.iplnet].known=="unknown":
4939         prout(_("Spock-  \"Captain, we have no information on this planet"))
4940         prout(_("  and Starfleet Regulations clearly state that in this situation"))
4941         prout(_("  you may not fly down.\""))
4942         return
4943     game.optime = 3.0e-5*game.height
4944     if game.optime >= 0.8*game.state.remtime:
4945         prout(_("First Officer Spock-  \"Captain, I compute that such"))
4946         proutn(_("  a maneuver would require approximately %2d%% of our") % \
4947                int(100*game.optime/game.state.remtime))
4948         prout(_("remaining time."))
4949         proutn(_("Are you sure this is wise?\" "))
4950         if ja() == False:
4951             game.optime = 0.0
4952             return
4953     if game.landed:
4954         # Kirk on planet 
4955         if game.iscraft == "onship":
4956             # Galileo on ship! 
4957             if not damaged(DTRANSP):
4958                 proutn(_("Spock-  \"Would you rather use the transporter?\" "))
4959                 if ja() == True:
4960                     beam()
4961                     return
4962                 proutn(_("Shuttle crew"))
4963             else:
4964                 proutn(_("Rescue party"))
4965             prout(_(" boards Galileo and swoops toward planet surface."))
4966             game.iscraft = "offship"
4967             skip(1)
4968             if consumeTime():
4969                 return
4970             game.state.planets[game.iplnet].known="shuttle_down"
4971             prout(_("Trip complete."))
4972             return
4973         else:
4974             # Ready to go back to ship 
4975             prout(_("You and your mining party board the"))
4976             prout(_("shuttle craft for the trip back to the Enterprise."))
4977             skip(1)
4978             prouts(_("The short hop begins . . ."))
4979             skip(1)
4980             game.state.planets[game.iplnet].known="known"
4981             game.icraft = True
4982             skip(1)
4983             game.landed = False
4984             if consumeTime():
4985                 return
4986             game.iscraft = "onship"
4987             game.icraft = False
4988             if game.imine:
4989                 game.icrystl = True
4990                 game.cryprob = 0.05
4991             game.imine = False
4992             prout(_("Trip complete."))
4993             return
4994     else:
4995         # Kirk on ship 
4996         # and so is Galileo 
4997         prout(_("Mining party assembles in the hangar deck,"))
4998         prout(_("ready to board the shuttle craft \"Galileo\"."))
4999         skip(1)
5000         prouts(_("The hangar doors open; the trip begins."))
5001         skip(1)
5002         game.icraft = True
5003         game.iscraft = "offship"
5004         if consumeTime():
5005             return
5006         game.state.planets[game.iplnet].known = "shuttle_down"
5007         game.landed = True
5008         game.icraft = False
5009         prout(_("Trip complete."))
5010         return
5011
5012 def deathray():
5013     # use the big zapper 
5014     r = Rand()
5015         
5016     game.ididit = False
5017     skip(1)
5018     chew()
5019     if game.ship != IHE:
5020         prout(_("Ye Faerie Queene has no death ray."))
5021         return
5022     if game.nenhere==0:
5023         prout(_("Sulu-  \"But Sir, there are no enemies in this quadrant.\""))
5024         return
5025     if damaged(DDRAY):
5026         prout(_("Death Ray is damaged."))
5027         return
5028     prout(_("Spock-  \"Captain, the 'Experimental Death Ray'"))
5029     prout(_("  is highly unpredictible.  Considering the alternatives,"))
5030     proutn(_("  are you sure this is wise?\" "))
5031     if ja() == False:
5032         return
5033     prout(_("Spock-  \"Acknowledged.\""))
5034     skip(1)
5035     game.ididit = True
5036     prouts(_("WHOOEE ... WHOOEE ... WHOOEE ... WHOOEE"))
5037     skip(1)
5038     prout(_("Crew scrambles in emergency preparation."))
5039     prout(_("Spock and Scotty ready the death ray and"))
5040     prout(_("prepare to channel all ship's power to the device."))
5041     skip(1)
5042     prout(_("Spock-  \"Preparations complete, sir.\""))
5043     prout(_("Kirk-  \"Engage!\""))
5044     skip(1)
5045     prouts(_("WHIRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"))
5046     skip(1)
5047     dprob = .30
5048     if game.options & OPTION_PLAIN:
5049         dprob = .5
5050     if r > dprob:
5051         prouts(_("Sulu- \"Captain!  It's working!\""))
5052         skip(2)
5053         while game.nenhere > 0:
5054             deadkl(game.ks[1], game.quad[game.ks[1].x][game.ks[1].y],game.ks[1])
5055         prout(_("Ensign Chekov-  \"Congratulations, Captain!\""))
5056         if (game.state.remkl + game.state.remcom + game.state.nscrem) == 0:
5057             finish(FWON)    
5058         if (game.options & OPTION_PLAIN) == 0:
5059             prout(_("Spock-  \"Captain, I believe the `Experimental Death Ray'"))
5060             if Rand() <= 0.05:
5061                 prout(_("   is still operational.\""))
5062             else:
5063                 prout(_("   has been rendered nonfunctional.\""))
5064                 game.damage[DDRAY] = 39.95
5065         return
5066     r = Rand()  # Pick failure method 
5067     if r <= .30:
5068         prouts(_("Sulu- \"Captain!  It's working!\""))
5069         skip(1)
5070         prouts(_("***RED ALERT!  RED ALERT!"))
5071         skip(1)
5072         prout(_("***MATTER-ANTIMATTER IMPLOSION IMMINENT!"))
5073         skip(1)
5074         prouts(_("***RED ALERT!  RED A*L********************************"))
5075         skip(1)
5076         stars()
5077         prouts(_("******************   KA-BOOM!!!!   *******************"))
5078         skip(1)
5079         kaboom()
5080         return
5081     if r <= .55:
5082         prouts(_("Sulu- \"Captain!  Yagabandaghangrapl, brachriigringlanbla!\""))
5083         skip(1)
5084         prout(_("Lt. Uhura-  \"Graaeek!  Graaeek!\""))
5085         skip(1)
5086         prout(_("Spock-  \"Fascinating!  . . . All humans aboard"))
5087         prout(_("  have apparently been transformed into strange mutations."))
5088         prout(_("  Vulcans do not seem to be affected."))
5089         skip(1)
5090         prout(_("Kirk-  \"Raauch!  Raauch!\""))
5091         finish(FDRAY)
5092         return
5093     if r <= 0.75:
5094         intj
5095         prouts(_("Sulu- \"Captain!  It's   --WHAT?!?!\""))
5096         skip(2)
5097         proutn(_("Spock-  \"I believe the word is"))
5098         prouts(_(" *ASTONISHING*"))
5099         prout(_(" Mr. Sulu."))
5100         for i in range(1, QUADSIZE+1):
5101             for j in range(1, QUADSIZE+1):
5102                 if game.quad[i][j] == IHDOT:
5103                     game.quad[i][j] = IHQUEST
5104         prout(_("  Captain, our quadrant is now infested with"))
5105         prouts(_(" - - - - - -  *THINGS*."))
5106         skip(1)
5107         prout(_("  I have no logical explanation.\""))
5108         return
5109     prouts(_("Sulu- \"Captain!  The Death Ray is creating tribbles!\""))
5110     skip(1)
5111     prout(_("Scotty-  \"There are so many tribbles down here"))
5112     prout(_("  in Engineering, we can't move for 'em, Captain.\""))
5113     finish(FTRIBBLE)
5114     return