3 sst.py -- Super Star Trek 2K
5 SST2K is a Python translation of a C translation of a FORTRAN
6 original dating back to 1973. Beautiful Python it is not, but it
7 works. Translation by Eric S. Raymond; original game by David Matuszek
8 and Paul Reynolds, with modifications by Don Smith, Tom Almy,
9 Stas Sergeev, and Eric S. Raymond.
11 See the doc/HACKING file in the distribution for designers notes and advice
12 on how to modify (and how not to modify!) this code.
14 import os, sys, math, curses, time, readline, cPickle, random, copy, gettext, getpass
18 docpath = (".", "../doc", "/usr/share/doc/sst")
20 def _(str): return gettext.gettext(str)
22 GALSIZE = 8 # Galaxy size in quadrants
23 NINHAB = (GALSIZE * GALSIZE / 2) # Number of inhabited worlds
24 MAXUNINHAB = 10 # Maximum uninhabited worlds
25 QUADSIZE = 10 # Quadrant size in sectors
26 BASEMIN = 2 # Minimum starbases
27 BASEMAX = (GALSIZE * GALSIZE / 12) # Maximum starbases
28 MAXKLGAME = 127 # Maximum Klingons per game
29 MAXKLQUAD = 9 # Maximum Klingons per quadrant
30 FULLCREW = 428 # Crew size. BSD Trek was 387, that's wrong
31 FOREVER = 1e30 # Time for the indefinite future
32 MAXBURST = 3 # Max # of torps you can launch in one turn
33 MINCMDR = 10 # Minimum number of Klingon commanders
34 DOCKFAC = 0.25 # Repair faster when docked
35 PHASEFAC = 2.0 # Unclear what this is, it was in the C version
59 def __init__(self, x=None, y=None):
62 def valid_quadrant(self):
63 return self.i>=0 and self.i<GALSIZE and self.j>=0 and self.j<GALSIZE
64 def valid_sector(self):
65 return self.i>=0 and self.i<QUADSIZE and self.j>=0 and self.j<QUADSIZE
67 self.i = self.j = None
69 return self.i != None and self.j != None
70 def __eq__(self, other):
71 return other != None and self.i == other.i and self.j == other.j
72 def __ne__(self, other):
73 return other == None or self.i != other.i or self.j != other.j
74 def __add__(self, other):
75 return coord(self.i+other.i, self.j+other.j)
76 def __sub__(self, other):
77 return coord(self.i-other.i, self.j-other.j)
78 def __mul__(self, other):
79 return coord(self.i*other, self.j*other)
80 def __rmul__(self, other):
81 return coord(self.i*other, self.j*other)
82 def __div__(self, other):
83 return coord(self.i/other, self.j/other)
84 def __mod__(self, other):
85 return coord(self.i % other, self.j % other)
86 def __rdiv__(self, other):
87 return coord(self.i/other, self.j/other)
88 def roundtogrid(self):
89 return coord(int(round(self.i)), int(round(self.j)))
90 def distance(self, other=None):
91 if not other: other = coord(0, 0)
92 return math.sqrt((self.i - other.i)**2 + (self.j - other.j)**2)
94 return 1.90985*math.atan2(self.j, self.i)
100 s.i = self.i / abs(self.i)
104 s.j = self.j / abs(self.j)
107 #print "Location %s -> %s" % (self, (self / QUADSIZE).roundtogrid())
108 return self.roundtogrid() / QUADSIZE
110 return self.roundtogrid() % QUADSIZE
113 s.i = self.i + randrange(-1, 2)
114 s.j = self.j + randrange(-1, 2)
117 if self.i == None or self.j == None:
119 return "%s - %s" % (self.i+1, self.j+1)
124 self.name = None # string-valued if inhabited
125 self.quadrant = coord() # quadrant located
126 self.pclass = None # could be ""M", "N", "O", or "destroyed"
127 self.crystals = "absent"# could be "mined", "present", "absent"
128 self.known = "unknown" # could be "unknown", "known", "shuttle_down"
129 self.inhabited = False # is it inhabites?
137 self.starbase = False
140 self.supernova = False
142 self.status = "secure" # Could be "secure", "distressed", "enslaved"
150 def fill2d(size, fillfun):
151 "Fill an empty list in 2D."
153 for i in range(size):
155 for j in range(size):
156 lst[i].append(fillfun(i, j))
161 self.snap = False # snapshot taken
162 self.crew = 0 # crew complement
163 self.remkl = 0 # remaining klingons
164 self.nscrem = 0 # remaining super commanders
165 self.starkl = 0 # destroyed stars
166 self.basekl = 0 # destroyed bases
167 self.nromrem = 0 # Romulans remaining
168 self.nplankl = 0 # destroyed uninhabited planets
169 self.nworldkl = 0 # destroyed inhabited planets
170 self.planets = [] # Planet information
171 self.date = 0.0 # stardate
172 self.remres = 0 # remaining resources
173 self.remtime = 0 # remaining time
174 self.baseq = [] # Base quadrant coordinates
175 self.kcmdr = [] # Commander quadrant coordinates
176 self.kscmdr = coord() # Supercommander quadrant coordinates
178 self.galaxy = fill2d(GALSIZE, lambda i, j: quadrant())
180 self.chart = fill2d(GALSIZE, lambda i, j: page())
184 self.date = None # A real number
185 self.quadrant = None # A coord structure
188 OPTION_ALL = 0xffffffff
189 OPTION_TTY = 0x00000001 # old interface
190 OPTION_CURSES = 0x00000002 # new interface
191 OPTION_IOMODES = 0x00000003 # cover both interfaces
192 OPTION_PLANETS = 0x00000004 # planets and mining
193 OPTION_THOLIAN = 0x00000008 # Tholians and their webs (UT 1979 version)
194 OPTION_THINGY = 0x00000010 # Space Thingy can shoot back (Stas, 2005)
195 OPTION_PROBE = 0x00000020 # deep-space probes (DECUS version, 1980)
196 OPTION_SHOWME = 0x00000040 # bracket Enterprise in chart
197 OPTION_RAMMING = 0x00000080 # enemies may ram Enterprise (Almy)
198 OPTION_MVBADDY = 0x00000100 # more enemies can move (Almy)
199 OPTION_BLKHOLE = 0x00000200 # black hole may timewarp you (Stas, 2005)
200 OPTION_BASE = 0x00000400 # bases have good shields (Stas, 2005)
201 OPTION_WORLDS = 0x00000800 # logic for inhabited worlds (ESR, 2006)
202 OPTION_AUTOSCAN = 0x00001000 # automatic LRSCAN before CHART (ESR, 2006)
203 OPTION_PLAIN = 0x01000000 # user chose plain game
204 OPTION_ALMY = 0x02000000 # user chose Almy variant
205 OPTION_COLOR = 0x04000000 # enable color display (experimental, ESR, 2010)
224 NDEVICES= 16 # Number of devices
233 def damaged(dev): return (game.damage[dev] != 0.0)
234 def communicating(): return not damaged(DRADIO) or game.condition=="docked"
236 # Define future events
237 FSPY = 0 # Spy event happens always (no future[] entry)
238 # can cause SC to tractor beam Enterprise
239 FSNOVA = 1 # Supernova
240 FTBEAM = 2 # Commander tractor beams Enterprise
241 FSNAP = 3 # Snapshot for time warp
242 FBATTAK = 4 # Commander attacks base
243 FCDBAS = 5 # Commander destroys base
244 FSCMOVE = 6 # Supercommander moves (might attack base)
245 FSCDBAS = 7 # Supercommander destroys base
246 FDSPROB = 8 # Move deep space probe
247 FDISTR = 9 # Emit distress call from an inhabited world
248 FENSLV = 10 # Inhabited word is enslaved */
249 FREPRO = 11 # Klingons build a ship in an enslaved system
252 # Abstract out the event handling -- underlying data structures will change
253 # when we implement stateful events
254 def findevent(evtype): return game.future[evtype]
257 def __init__(self, type=None, loc=None, power=None):
259 self.location = coord()
262 self.power = power # enemy energy level
263 game.enemies.append(self)
265 motion = (loc != self.location)
266 if self.location.i is not None and self.location.j is not None:
269 game.quad[self.location.i][self.location.j] = '#'
271 game.quad[self.location.i][self.location.j] = '.'
273 self.location = copy.copy(loc)
274 game.quad[self.location.i][self.location.j] = self.type
275 self.kdist = self.kavgd = (game.sector - loc).distance()
277 self.location = coord()
278 self.kdist = self.kavgd = None
279 game.enemies.remove(self)
282 return "<%s,%s.%f>" % (self.type, self.location, self.power) # For debugging
286 self.options = None # Game options
287 self.state = snapshot() # A snapshot structure
288 self.snapsht = snapshot() # Last snapshot taken for time-travel purposes
289 self.quad = None # contents of our quadrant
290 self.damage = [0.0] * NDEVICES # damage encountered
291 self.future = [] # future events
292 for i in range(NEVENTS):
293 self.future.append(event())
294 self.passwd = None; # Self Destruct password
296 self.quadrant = None # where we are in the large
297 self.sector = None # where we are in the small
298 self.tholian = None # Tholian enemy object
299 self.base = None # position of base in current quadrant
300 self.battle = None # base coordinates being attacked
301 self.plnet = None # location of planet in quadrant
302 self.gamewon = False # Finished!
303 self.ididit = False # action taken -- allows enemy to attack
304 self.alive = False # we are alive (not killed)
305 self.justin = False # just entered quadrant
306 self.shldup = False # shields are up
307 self.shldchg = False # shield is changing (affects efficiency)
308 self.iscate = False # super commander is here
309 self.ientesc = False # attempted escape from supercommander
310 self.resting = False # rest time
311 self.icraft = False # Kirk in Galileo
312 self.landed = False # party on planet (true), on ship (false)
313 self.alldone = False # game is now finished
314 self.neutz = False # Romulan Neutral Zone
315 self.isarmed = False # probe is armed
316 self.inorbit = False # orbiting a planet
317 self.imine = False # mining
318 self.icrystl = False # dilithium crystals aboard
319 self.iseenit = False # seen base attack report
320 self.thawed = False # thawed game
321 self.condition = None # "green", "yellow", "red", "docked", "dead"
322 self.iscraft = None # "onship", "offship", "removed"
323 self.skill = None # Player skill level
324 self.inkling = 0 # initial number of klingons
325 self.inbase = 0 # initial number of bases
326 self.incom = 0 # initial number of commanders
327 self.inscom = 0 # initial number of commanders
328 self.inrom = 0 # initial number of commanders
329 self.instar = 0 # initial stars
330 self.intorps = 0 # initial/max torpedoes
331 self.torps = 0 # number of torpedoes
332 self.ship = 0 # ship type -- 'E' is Enterprise
333 self.abandoned = 0 # count of crew abandoned in space
334 self.length = 0 # length of game
335 self.klhere = 0 # klingons here
336 self.casual = 0 # causalties
337 self.nhelp = 0 # calls for help
338 self.nkinks = 0 # count of energy-barrier crossings
339 self.iplnet = None # planet # in quadrant
340 self.inplan = 0 # initial planets
341 self.irhere = 0 # Romulans in quadrant
342 self.isatb = 0 # =2 if super commander is attacking base
343 self.tourn = None # tournament number
344 self.nprobes = 0 # number of probes available
345 self.inresor = 0.0 # initial resources
346 self.intime = 0.0 # initial time
347 self.inenrg = 0.0 # initial/max energy
348 self.inshld = 0.0 # initial/max shield
349 self.inlsr = 0.0 # initial life support resources
350 self.indate = 0.0 # initial date
351 self.energy = 0.0 # energy level
352 self.shield = 0.0 # shield level
353 self.warpfac = 0.0 # warp speed
354 self.lsupres = 0.0 # life support reserves
355 self.optime = 0.0 # time taken by current operation
356 self.damfac = 0.0 # damage factor
357 self.lastchart = 0.0 # time star chart was last updated
358 self.cryprob = 0.0 # probability that crystal will work
359 self.probe = None # object holding probe course info
360 self.height = 0.0 # height of orbit around planet
362 # Stas thinks this should be (C expression):
363 # game.state.remkl + len(game.state.kcmdr) > 0 ?
364 # game.state.remres/(game.state.remkl + 4*len(game.state.kcmdr)) : 99
365 # He says the existing expression is prone to divide-by-zero errors
366 # after killing the last klingon when score is shown -- perhaps also
367 # if the only remaining klingon is SCOM.
368 game.state.remtime = game.state.remres/(game.state.remkl + 4*len(game.state.kcmdr))
394 return random.random() < p
396 def randrange(*args):
397 return random.randrange(*args)
402 v *= args[0] # from [0, args[0])
404 v = args[0] + v*(args[1]-args[0]) # from [args[0], args[1])
407 # Code from ai.c begins here
410 "Would this quadrant welcome another Klingon?"
411 return iq.valid_quadrant() and \
412 not game.state.galaxy[iq.i][iq.j].supernova and \
413 game.state.galaxy[iq.i][iq.j].klingons < MAXKLQUAD
415 def tryexit(enemy, look, irun):
416 "A bad guy attempts to bug out."
418 iq.i = game.quadrant.i+(look.i+(QUADSIZE-1))/QUADSIZE - 1
419 iq.j = game.quadrant.j+(look.j+(QUADSIZE-1))/QUADSIZE - 1
420 if not welcoming(iq):
422 if enemy.type == 'R':
423 return False; # Romulans cannot escape!
425 # avoid intruding on another commander's territory
426 if enemy.type == 'C':
427 if iq in game.state.kcmdr:
429 # refuse to leave if currently attacking starbase
430 if game.battle == game.quadrant:
432 # don't leave if over 1000 units of energy
433 if enemy.power > 1000.0:
435 # emit escape message and move out of quadrant.
436 # we know this if either short or long range sensors are working
437 if not damaged(DSRSENS) or not damaged(DLRSENS) or \
438 game.condition == "docked":
439 prout(crmena(True, enemy.type, "sector", enemy.location) + \
440 (_(" escapes to Quadrant %s (and regains strength).") % q))
441 # handle local matters related to escape
444 if game.condition != "docked":
446 # Handle global matters related to escape
447 game.state.galaxy[game.quadrant.i][game.quadrant.j].klingons -= 1
448 game.state.galaxy[iq.i][iq.j].klingons += 1
453 schedule(FSCMOVE, 0.2777)
457 for cmdr in game.state.kcmdr:
458 if cmdr == game.quadrant:
459 game.state.kcmdr[n] = iq
461 return True; # success
463 # The bad-guy movement algorithm:
465 # 1. Enterprise has "force" based on condition of phaser and photon torpedoes.
466 # If both are operating full strength, force is 1000. If both are damaged,
467 # force is -1000. Having shields down subtracts an additional 1000.
469 # 2. Enemy has forces equal to the energy of the attacker plus
470 # 100*(K+R) + 500*(C+S) - 400 for novice through good levels OR
471 # 346*K + 400*R + 500*(C+S) - 400 for expert and emeritus.
473 # Attacker Initial energy levels (nominal):
474 # Klingon Romulan Commander Super-Commander
475 # Novice 400 700 1200
477 # Good 450 800 1300 1750
478 # Expert 475 850 1350 1875
479 # Emeritus 500 900 1400 2000
480 # VARIANCE 75 200 200 200
482 # Enemy vessels only move prior to their attack. In Novice - Good games
483 # only commanders move. In Expert games, all enemy vessels move if there
484 # is a commander present. In Emeritus games all enemy vessels move.
486 # 3. If Enterprise is not docked, an aggressive action is taken if enemy
487 # forces are 1000 greater than Enterprise.
489 # Agressive action on average cuts the distance between the ship and
490 # the enemy to 1/4 the original.
492 # 4. At lower energy advantage, movement units are proportional to the
493 # advantage with a 650 advantage being to hold ground, 800 to move forward
494 # 1, 950 for two, 150 for back 4, etc. Variance of 100.
496 # If docked, is reduced by roughly 1.75*game.skill, generally forcing a
497 # retreat, especially at high skill levels.
499 # 5. Motion is limited to skill level, except for SC hi-tailing it out.
501 def movebaddy(enemy):
502 "Tactical movement for the bad guys."
503 next = coord(); look = coord()
505 # This should probably be just (game.quadrant in game.state.kcmdr) + (game.state.kscmdr==game.quadrant)
506 if game.skill >= SKILL_EXPERT:
507 nbaddys = (((game.quadrant in game.state.kcmdr)*2 + (game.state.kscmdr==game.quadrant)*2+game.klhere*1.23+game.irhere*1.5)/2.0)
509 nbaddys = (game.quadrant in game.state.kcmdr) + (game.state.kscmdr==game.quadrant)
511 mdist = int(dist1 + 0.5); # Nearest integer distance
512 # If SC, check with spy to see if should hi-tail it
513 if enemy.type=='S' and \
514 (enemy.power <= 500.0 or (game.condition=="docked" and not damaged(DPHOTON))):
518 # decide whether to advance, retreat, or hold position
519 forces = enemy.power+100.0*len(game.enemies)+400*(nbaddys-1)
521 forces += 1000; # Good for enemy if shield is down!
522 if not damaged(DPHASER) or not damaged(DPHOTON):
523 if damaged(DPHASER): # phasers damaged
526 forces -= 0.2*(game.energy - 2500.0)
527 if damaged(DPHOTON): # photon torpedoes damaged
530 forces -= 50.0*game.torps
532 # phasers and photon tubes both out!
535 if forces <= 1000.0 and game.condition != "docked": # Typical situation
536 motion = ((forces + randreal(200))/150.0) - 5.0
538 if forces > 1000.0: # Very strong -- move in for kill
539 motion = (1.0 - randreal())**2 * dist1 + 1.0
540 if game.condition=="docked" and (game.options & OPTION_BASE): # protected by base -- back off !
541 motion -= game.skill*(2.0-randreal()**2)
543 proutn("=== MOTION = %d, FORCES = %1.2f, " % (motion, forces))
544 # don't move if no motion
547 # Limit motion according to skill
548 if abs(motion) > game.skill:
553 # calculate preferred number of steps
554 nsteps = abs(int(motion))
555 if motion > 0 and nsteps > mdist:
556 nsteps = mdist; # don't overshoot
557 if nsteps > QUADSIZE:
558 nsteps = QUADSIZE; # This shouldn't be necessary
560 nsteps = 1; # This shouldn't be necessary
562 proutn("NSTEPS = %d:" % nsteps)
563 # Compute preferred values of delta X and Y
564 m = game.sector - enemy.location
565 if 2.0 * abs(m.i) < abs(m.j):
567 if 2.0 * abs(m.j) < abs(game.sector.i-enemy.location.i):
569 m = (motion * m).sgn()
570 next = enemy.location
572 for ll in range(nsteps):
574 proutn(" %d" % (ll+1))
575 # Check if preferred position available
586 attempts = 0; # Settle mysterious hang problem
587 while attempts < 20 and not success:
589 if look.i < 0 or look.i >= QUADSIZE:
590 if motion < 0 and tryexit(enemy, look, irun):
592 if krawli == m.i or m.j == 0:
594 look.i = next.i + krawli
596 elif look.j < 0 or look.j >= QUADSIZE:
597 if motion < 0 and tryexit(enemy, look, irun):
599 if krawlj == m.j or m.i == 0:
601 look.j = next.j + krawlj
603 elif (game.options & OPTION_RAMMING) and game.quad[look.i][look.j] != '.':
604 # See if enemy should ram ship
605 if game.quad[look.i][look.j] == game.ship and \
606 (enemy.type == 'C' or enemy.type == 'S'):
607 collision(rammed=True, enemy=enemy)
609 if krawli != m.i and m.j != 0:
610 look.i = next.i + krawli
612 elif krawlj != m.j and m.i != 0:
613 look.j = next.j + krawlj
616 break; # we have failed
628 if not damaged(DSRSENS) or game.condition == "docked":
629 proutn(_("*** %s from Sector %s") % (cramen(enemy.type), enemy.location))
630 if enemy.kdist < dist1:
631 proutn(_(" advances to "))
633 proutn(_(" retreats to "))
634 prout("Sector %s." % next)
637 "Sequence Klingon tactical movement."
640 # Figure out which Klingon is the commander (or Supercommander)
642 if game.quadrant in game.state.kcmdr:
643 for enemy in game.enemies:
644 if enemy.type == 'C':
646 if game.state.kscmdr==game.quadrant:
647 for enemy in game.enemies:
648 if enemy.type == 'S':
651 # If skill level is high, move other Klingons and Romulans too!
652 # Move these last so they can base their actions on what the
654 if game.skill >= SKILL_EXPERT and (game.options & OPTION_MVBADDY):
655 for enemy in game.enemies:
656 if enemy.type in ('K', 'R'):
658 game.enemies.sort(lambda x, y: cmp(x.kdist, y.kdist))
660 def movescom(iq, avoid):
661 "Commander movement helper."
662 # Avoid quadrants with bases if we want to avoid Enterprise
663 if not welcoming(iq) or (avoid and iq in game.state.baseq):
665 if game.justin and not game.iscate:
668 game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].klingons -= 1
669 game.state.kscmdr = iq
670 game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].klingons += 1
671 if game.state.kscmdr==game.quadrant:
672 # SC has scooted, remove him from current quadrant
677 for enemy in game.enemies:
678 if enemy.type == 'S':
682 if game.condition != "docked":
684 game.enemies.sort(lambda x, y: cmp(x.kdist, y.kdist))
685 # check for a helpful planet
686 for i in range(game.inplan):
687 if game.state.planets[i].quadrant == game.state.kscmdr and \
688 game.state.planets[i].crystals == "present":
690 game.state.planets[i].pclass = "destroyed"
691 game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].planet = None
694 prout(_("Lt. Uhura- \"Captain, Starfleet Intelligence reports"))
695 proutn(_(" a planet in Quadrant %s has been destroyed") % game.state.kscmdr)
696 prout(_(" by the Super-commander.\""))
698 return True; # looks good!
700 def supercommander():
701 "Move the Super Commander."
702 iq = coord(); sc = coord(); ibq = coord(); idelta = coord()
705 prout("== SUPERCOMMANDER")
706 # Decide on being active or passive
707 avoid = ((game.incom - len(game.state.kcmdr) + game.inkling - game.state.remkl)/(game.state.date+0.01-game.indate) < 0.1*game.skill*(game.skill+1.0) or \
708 (game.state.date-game.indate) < 3.0)
709 if not game.iscate and avoid:
710 # compute move away from Enterprise
711 idelta = game.state.kscmdr-game.quadrant
712 if idelta.distance() > 2.0:
714 idelta.i = game.state.kscmdr.j-game.quadrant.j
715 idelta.j = game.quadrant.i-game.state.kscmdr.i
717 # compute distances to starbases
718 if not game.state.baseq:
722 sc = game.state.kscmdr
723 for base in game.state.baseq:
724 basetbl.append((i, (base - sc).distance()))
725 if game.state.baseq > 1:
726 basetbl.sort(lambda x, y: cmp(x[1]. y[1]))
727 # look for nearest base without a commander, no Enterprise, and
728 # without too many Klingons, and not already under attack.
729 ifindit = iwhichb = 0
730 for (i2, base) in enumerate(game.state.baseq):
731 i = basetbl[i2][0]; # bug in original had it not finding nearest
732 if base==game.quadrant or base==game.battle or not welcoming(base):
734 # if there is a commander, and no other base is appropriate,
735 # we will take the one with the commander
736 for cmdr in game.state.kcmdr:
737 if base == cmdr and ifindit != 2:
741 else: # no commander -- use this one
746 return # Nothing suitable -- wait until next time
747 ibq = game.state.baseq[iwhichb]
748 # decide how to move toward base
749 idelta = ibq - game.state.kscmdr
750 # Maximum movement is 1 quadrant in either or both axes
751 idelta = idelta.sgn()
752 # try moving in both x and y directions
753 # there was what looked like a bug in the Almy C code here,
754 # but it might be this translation is just wrong.
755 iq = game.state.kscmdr + idelta
756 if not movescom(iq, avoid):
757 # failed -- try some other maneuvers
758 if idelta.i==0 or idelta.j==0:
761 iq.j = game.state.kscmdr.j + 1
762 if not movescom(iq, avoid):
763 iq.j = game.state.kscmdr.j - 1
766 iq.i = game.state.kscmdr.i + 1
767 if not movescom(iq, avoid):
768 iq.i = game.state.kscmdr.i - 1
771 # try moving just in x or y
772 iq.j = game.state.kscmdr.j
773 if not movescom(iq, avoid):
774 iq.j = game.state.kscmdr.j + idelta.j
775 iq.i = game.state.kscmdr.i
778 if len(game.state.baseq) == 0:
781 for ibq in game.state.baseq:
782 if ibq == game.state.kscmdr and game.state.kscmdr == game.battle:
785 return # no, don't attack base!
788 schedule(FSCDBAS, randreal(1.0, 3.0))
789 if is_scheduled(FCDBAS):
790 postpone(FSCDBAS, scheduled(FCDBAS)-game.state.date)
791 if not communicating():
795 prout(_("Lt. Uhura- \"Captain, the starbase in Quadrant %s") \
797 prout(_(" reports that it is under attack from the Klingon Super-commander."))
798 proutn(_(" It can survive until stardate %d.\"") \
799 % int(scheduled(FSCDBAS)))
802 prout(_("Mr. Spock- \"Captain, shall we cancel the rest period?\""))
806 game.optime = 0.0; # actually finished
808 # Check for intelligence report
811 (not communicating()) or \
812 not game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].charted):
815 prout(_("Lt. Uhura- \"Captain, Starfleet Intelligence reports"))
816 proutn(_(" the Super-commander is in Quadrant %s,") % game.state.kscmdr)
821 if not game.tholian or game.justin:
824 if game.tholian.location.i == 0 and game.tholian.location.j == 0:
825 id.i = 0; id.j = QUADSIZE-1
826 elif game.tholian.location.i == 0 and game.tholian.location.j == QUADSIZE-1:
827 id.i = QUADSIZE-1; id.j = QUADSIZE-1
828 elif game.tholian.location.i == QUADSIZE-1 and game.tholian.location.j == QUADSIZE-1:
829 id.i = QUADSIZE-1; id.j = 0
830 elif game.tholian.location.i == QUADSIZE-1 and game.tholian.location.j == 0:
833 # something is wrong!
834 game.tholian.move(None)
835 prout("***Internal error: Tholian in a bad spot.")
837 # do nothing if we are blocked
838 if game.quad[id.i][id.j] not in ('.', '#'):
840 here = copy.copy(game.tholian.location)
841 delta = (id - game.tholian.location).sgn()
843 while here.i != id.i:
845 if game.quad[here.i][here.j]=='.':
846 game.tholian.move(here)
848 while here.j != id.j:
850 if game.quad[here.i][here.j]=='.':
851 game.tholian.move(here)
852 # check to see if all holes plugged
853 for i in range(QUADSIZE):
854 if game.quad[0][i]!='#' and game.quad[0][i]!='T':
856 if game.quad[QUADSIZE-1][i]!='#' and game.quad[QUADSIZE-1][i]!='T':
858 if game.quad[i][0]!='#' and game.quad[i][0]!='T':
860 if game.quad[i][QUADSIZE-1]!='#' and game.quad[i][QUADSIZE-1]!='T':
862 # All plugged up -- Tholian splits
863 game.quad[game.tholian.location.i][game.tholian.location.j]='#'
865 prout(crmena(True, 'T', "sector", game.tholian) + _(" completes web."))
866 game.tholian.move(None)
869 # Code from battle.c begins here
871 def doshield(shraise):
872 "Change shield status."
880 if scanner.sees("transfer"):
884 prout(_("Shields damaged and down."))
886 if scanner.sees("up"):
888 elif scanner.sees("down"):
891 proutn(_("Do you wish to change shield energy? "))
894 elif damaged(DSHIELD):
895 prout(_("Shields damaged and down."))
898 proutn(_("Shields are up. Do you want them down? "))
905 proutn(_("Shields are down. Do you want them up? "))
911 if action == "SHUP": # raise shields
913 prout(_("Shields already up."))
917 if game.condition != "docked":
919 prout(_("Shields raised."))
922 prout(_("Shields raising uses up last of energy."))
927 elif action == "SHDN":
929 prout(_("Shields already down."))
933 prout(_("Shields lowered."))
936 elif action == "NRG":
937 while scanner.next() != "IHREAL":
939 proutn(_("Energy to transfer to shields- "))
944 if nrg > game.energy:
945 prout(_("Insufficient ship energy."))
948 if game.shield+nrg >= game.inshld:
949 prout(_("Shield energy maximized."))
950 if game.shield+nrg > game.inshld:
951 prout(_("Excess energy requested returned to ship energy"))
952 game.energy -= game.inshld-game.shield
953 game.shield = game.inshld
955 if nrg < 0.0 and game.energy-nrg > game.inenrg:
956 # Prevent shield drain loophole
958 prout(_("Engineering to bridge--"))
959 prout(_(" Scott here. Power circuit problem, Captain."))
960 prout(_(" I can't drain the shields."))
963 if game.shield+nrg < 0:
964 prout(_("All shield energy transferred to ship."))
965 game.energy += game.shield
968 proutn(_("Scotty- \""))
970 prout(_("Transferring energy to shields.\""))
972 prout(_("Draining energy from shields.\""))
978 "Choose a device to damage, at random."
980 105, # DSRSENS: short range scanners 10.5%
981 105, # DLRSENS: long range scanners 10.5%
982 120, # DPHASER: phasers 12.0%
983 120, # DPHOTON: photon torpedoes 12.0%
984 25, # DLIFSUP: life support 2.5%
985 65, # DWARPEN: warp drive 6.5%
986 70, # DIMPULS: impulse engines 6.5%
987 145, # DSHIELD: deflector shields 14.5%
988 30, # DRADIO: subspace radio 3.0%
989 45, # DSHUTTL: shuttle 4.5%
990 15, # DCOMPTR: computer 1.5%
991 20, # NAVCOMP: navigation system 2.0%
992 75, # DTRANSP: transporter 7.5%
993 20, # DSHCTRL: high-speed shield controller 2.0%
994 10, # DDRAY: death ray 1.0%
995 30, # DDSP: deep-space probes 3.0%
997 assert(sum(weights) == 1000)
998 idx = randrange(1000)
1000 for (i, w) in enumerate(weights):
1004 return None; # we should never get here
1006 def collision(rammed, enemy):
1007 "Collision handling fot rammong events."
1008 prouts(_("***RED ALERT! RED ALERT!"))
1010 prout(_("***COLLISION IMMINENT."))
1014 hardness = {'R':1.5, 'C':2.0, 'S':2.5, 'T':0.5, '?':4.0}.get(enemy.type, 1.0)
1016 proutn(_(" rammed by "))
1019 proutn(crmena(False, enemy.type, "sector", enemy.location))
1021 proutn(_(" (original position)"))
1023 deadkl(enemy.location, enemy.type, game.sector)
1024 proutn("***" + crmship() + " heavily damaged.")
1025 icas = randrange(10, 30)
1026 prout(_("***Sickbay reports %d casualties"), icas)
1028 game.state.crew -= icas
1029 # In the pre-SST2K version, all devices got equiprobably damaged,
1030 # which was silly. Instead, pick up to half the devices at
1031 # random according to our weighting table,
1032 ncrits = randrange(NDEVICES/2)
1033 for m in range(ncrits):
1035 if game.damage[dev] < 0:
1037 extradm = (10.0*hardness*randreal()+1.0)*game.damfac
1038 # Damage for at least time of travel!
1039 game.damage[dev] += game.optime + extradm
1041 prout(_("***Shields are down."))
1042 if game.state.remkl + len(game.state.kcmdr) + game.state.nscrem:
1049 def torpedo(origin, bearing, dispersion, number, nburst):
1050 "Let a photon torpedo fly"
1051 if not damaged(DSRSENS) or game.condition=="docked":
1052 setwnd(srscan_window)
1054 setwnd(message_window)
1055 ac = bearing + 0.25*dispersion # dispersion is a random variable
1056 bullseye = (15.0 - bearing)*0.5235988
1057 track = course(bearing=ac, distance=QUADSIZE, origin=cartesian(origin))
1058 bumpto = coord(0, 0)
1059 # Loop to move a single torpedo
1060 setwnd(message_window)
1061 for step in range(1, QUADSIZE*2):
1062 if not track.next(): break
1064 if not w.valid_sector():
1066 iquad=game.quad[w.i][w.j]
1067 tracktorpedo(origin, w, step, number, nburst, iquad)
1071 if not damaged(DSRSENS) or game.condition == "docked":
1072 skip(1); # start new line after text track
1073 if iquad in ('E', 'F'): # Hit our ship
1075 prout(_("Torpedo hits %s.") % crmshp())
1076 hit = 700.0 + randreal(100) - \
1077 1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-track.angle))
1078 newcnd(); # we're blown out of dock
1079 if game.landed or game.condition=="docked":
1080 return hit # Cheat if on a planet
1081 # In the C/FORTRAN version, dispersion was 2.5 radians, which
1082 # is 143 degrees, which is almost exactly 4.8 clockface units
1083 displacement = course(track.bearing+randreal(-2.4,2.4), distance=2**0.5)
1085 bumpto = displacement.sector()
1086 if not bumpto.valid_sector():
1088 if game.quad[bumpto.i][bumpto.j]==' ':
1091 if game.quad[bumpto.i][bumpto.j]!='.':
1092 # can't move into object
1094 game.sector = bumpto
1096 game.quad[w.i][w.j]='.'
1097 game.quad[bumpto.i][bumpto.j]=iquad
1098 prout(_(" displaced by blast to Sector %s ") % bumpto)
1099 for enemy in game.enemies:
1100 enemy.kdist = enemy.kavgd = (game.sector-enemy.location).distance()
1101 game.enemies.sort(lambda x, y: cmp(x.kdist, y.kdist))
1103 elif iquad in ('C', 'S', 'R', 'K'): # Hit a regular enemy
1105 if iquad in ('C', 'S') and withprob(0.05):
1106 prout(crmena(True, iquad, "sector", w) + _(" uses anti-photon device;"))
1107 prout(_(" torpedo neutralized."))
1109 for enemy in game.enemies:
1110 if w == enemy.location:
1112 kp = math.fabs(enemy.power)
1113 h1 = 700.0 + randrange(100) - \
1114 1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-track.angle))
1122 if enemy.power == 0:
1125 proutn(crmena(True, iquad, "sector", w))
1126 displacement = course(track.bearing+randreal(-2.4,2.4), distance=2**0.5)
1128 bumpto = displacement.sector()
1129 if not bumpto.valid_sector():
1130 prout(_(" damaged but not destroyed."))
1132 if game.quad[bumpto.i][bumpto.j] == ' ':
1133 prout(_(" buffeted into black hole."))
1134 deadkl(w, iquad, bumpto)
1135 if game.quad[bumpto.i][bumpto.j] != '.':
1136 prout(_(" damaged but not destroyed."))
1138 prout(_(" damaged-- displaced by blast to Sector %s ")%bumpto)
1139 enemy.location = bumpto
1140 game.quad[w.i][w.j]='.'
1141 game.quad[bumpto.i][bumpto.j]=iquad
1142 for enemy in game.enemies:
1143 enemy.kdist = enemy.kavgd = (game.sector-enemy.location).distance()
1144 game.enemies.sort(lambda x, y: cmp(x.kdist, y.kdist))
1146 elif iquad == 'B': # Hit a base
1148 prout(_("***STARBASE DESTROYED.."))
1149 game.state.baseq = filter(lambda x: x != game.quadrant, game.state.baseq)
1150 game.quad[w.i][w.j]='.'
1151 game.base.invalidate()
1152 game.state.galaxy[game.quadrant.i][game.quadrant.j].starbase -= 1
1153 game.state.chart[game.quadrant.i][game.quadrant.j].starbase -= 1
1154 game.state.basekl += 1
1157 elif iquad == 'P': # Hit a planet
1158 prout(crmena(True, iquad, "sector", w) + _(" destroyed."))
1159 game.state.nplankl += 1
1160 game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
1161 game.iplnet.pclass = "destroyed"
1163 game.plnet.invalidate()
1164 game.quad[w.i][w.j] = '.'
1166 # captain perishes on planet
1169 elif iquad == '@': # Hit an inhabited world -- very bad!
1170 prout(crmena(True, iquad, "sector", w) + _(" destroyed."))
1171 game.state.nworldkl += 1
1172 game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
1173 game.iplnet.pclass = "destroyed"
1175 game.plnet.invalidate()
1176 game.quad[w.i][w.j] = '.'
1178 # captain perishes on planet
1180 prout(_("The torpedo destroyed an inhabited planet."))
1182 elif iquad == '*': # Hit a star
1186 prout(crmena(True, '*', "sector", w) + _(" unaffected by photon blast."))
1188 elif iquad == '?': # Hit a thingy
1189 if not (game.options & OPTION_THINGY) or withprob(0.3):
1191 prouts(_("AAAAIIIIEEEEEEEEAAAAAAAAUUUUUGGGGGHHHHHHHHHHHH!!!"))
1193 prouts(_(" HACK! HACK! HACK! *CHOKE!* "))
1195 proutn(_("Mr. Spock-"))
1196 prouts(_(" \"Fascinating!\""))
1200 # Stas Sergeev added the possibility that
1201 # you can shove the Thingy and piss it off.
1202 # It then becomes an enemy and may fire at you.
1206 elif iquad == ' ': # Black hole
1208 prout(crmena(True, ' ', "sector", w) + _(" swallows torpedo."))
1210 elif iquad == '#': # hit the web
1212 prout(_("***Torpedo absorbed by Tholian web."))
1214 elif iquad == 'T': # Hit a Tholian
1215 h1 = 700.0 + randrange(100) - \
1216 1000.0 * (w-origin).distance() * math.fabs(math.sin(bullseye-angle))
1219 game.quad[w.i][w.j] = '.'
1224 proutn(crmena(True, 'T', "sector", w))
1226 prout(_(" survives photon blast."))
1228 prout(_(" disappears."))
1229 game.tholian.move(None)
1230 game.quad[w.i][w.j] = '#'
1235 proutn("Don't know how to handle torpedo collision with ")
1236 proutn(crmena(True, iquad, "sector", w))
1241 prout(_("Torpedo missed."))
1245 "Critical-hit resolution."
1246 if hit < (275.0-25.0*game.skill)*randreal(1.0, 1.5):
1248 ncrit = int(1.0 + hit/(500.0+randreal(100)))
1249 proutn(_("***CRITICAL HIT--"))
1250 # Select devices and cause damage
1252 for loop1 in range(ncrit):
1255 # Cheat to prevent shuttle damage unless on ship
1256 if not (game.damage[j]<0.0 or (j==DSHUTTL and game.iscraft != "onship")):
1259 extradm = (hit*game.damfac)/(ncrit*randreal(75, 100))
1260 game.damage[j] += extradm
1262 for (i, j) in enumerate(cdam):
1264 if skipcount % 3 == 2 and i < len(cdam)-1:
1269 prout(_(" damaged."))
1270 if damaged(DSHIELD) and game.shldup:
1271 prout(_("***Shields knocked down."))
1274 def attack(torps_ok):
1275 # bad guy attacks us
1276 # torps_ok == False forces use of phasers in an attack
1277 # game could be over at this point, check
1280 attempt = False; ihurt = False;
1281 hitmax=0.0; hittot=0.0; chgfac=1.0
1284 prout("=== ATTACK!")
1285 # Tholian gets to move before attacking
1288 # if you have just entered the RNZ, you'll get a warning
1289 if game.neutz: # The one chance not to be attacked
1292 # commanders get a chance to tac-move towards you
1293 if (((game.quadrant in game.state.kcmdr or game.state.kscmdr==game.quadrant) and not game.justin) or game.skill == SKILL_EMERITUS) and torps_ok:
1295 # if no enemies remain after movement, we're done
1296 if len(game.enemies)==0 or (len(game.enemies)==1 and thing == game.quadrant and not thing.angry):
1298 # set up partial hits if attack happens during shield status change
1299 pfac = 1.0/game.inshld
1301 chgfac = 0.25 + randreal(0.5)
1303 # message verbosity control
1304 if game.skill <= SKILL_FAIR:
1306 for enemy in game.enemies:
1308 continue; # too weak to attack
1309 # compute hit strength and diminish shield power
1311 # Increase chance of photon torpedos if docked or enemy energy is low
1312 if game.condition == "docked":
1314 if enemy.power < 500:
1316 if enemy.type=='T' or (enemy.type=='?' and not thing.angry):
1318 # different enemies have different probabilities of throwing a torp
1319 usephasers = not torps_ok or \
1320 (enemy.type == 'K' and r > 0.0005) or \
1321 (enemy.type=='C' and r > 0.015) or \
1322 (enemy.type=='R' and r > 0.3) or \
1323 (enemy.type=='S' and r > 0.07) or \
1324 (enemy.type=='?' and r > 0.05)
1325 if usephasers: # Enemy uses phasers
1326 if game.condition == "docked":
1327 continue; # Don't waste the effort!
1328 attempt = True; # Attempt to attack
1329 dustfac = randreal(0.8, 0.85)
1330 hit = enemy.power*math.pow(dustfac,enemy.kavgd)
1332 else: # Enemy uses photon torpedo
1333 # We should be able to make the bearing() method work here
1334 course = 1.90985*math.atan2(game.sector.j-enemy.location.j, enemy.location.i-game.sector.i)
1336 proutn(_("***TORPEDO INCOMING"))
1337 if not damaged(DSRSENS):
1338 proutn(_(" From ") + crmena(False, enemy.type, where, enemy.location))
1341 dispersion = (randreal()+randreal())*0.5 - 0.5
1342 dispersion += 0.002*enemy.power*dispersion
1343 hit = torpedo(enemy.location, course, dispersion, number=1, nburst=1)
1344 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)==0:
1345 finish(FWON); # Klingons did themselves in!
1346 if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova or game.alldone:
1347 return # Supernova or finished
1350 # incoming phaser or torpedo, shields may dissipate it
1351 if game.shldup or game.shldchg or game.condition=="docked":
1352 # shields will take hits
1353 propor = pfac * game.shield
1354 if game.condition =="docked":
1358 hitsh = propor*chgfac*hit+1.0
1360 if absorb > game.shield:
1361 absorb = game.shield
1362 game.shield -= absorb
1364 # taking a hit blasts us out of a starbase dock
1365 if game.condition == "docked":
1367 # but the shields may take care of it
1368 if propor > 0.1 and hit < 0.005*game.energy:
1370 # hit from this opponent got through shields, so take damage
1372 proutn(_("%d unit hit") % int(hit))
1373 if (damaged(DSRSENS) and usephasers) or game.skill<=SKILL_FAIR:
1374 proutn(_(" on the ") + crmshp())
1375 if not damaged(DSRSENS) and usephasers:
1376 prout(_(" from ") + crmena(False, enemy.type, where, enemy.location))
1378 # Decide if hit is critical
1384 if game.energy <= 0:
1385 # Returning home upon your shield, not with it...
1388 if not attempt and game.condition == "docked":
1389 prout(_("***Enemies decide against attacking your ship."))
1390 percent = 100.0*pfac*game.shield+0.5
1392 # Shields fully protect ship
1393 proutn(_("Enemy attack reduces shield strength to "))
1395 # Emit message if starship suffered hit(s)
1397 proutn(_("Energy left %2d shields ") % int(game.energy))
1400 elif not damaged(DSHIELD):
1403 proutn(_("damaged, "))
1404 prout(_("%d%%, torpedoes left %d") % (percent, game.torps))
1405 # Check if anyone was hurt
1406 if hitmax >= 200 or hittot >= 500:
1407 icas = randrange(int(hittot * 0.015))
1410 prout(_("Mc Coy- \"Sickbay to bridge. We suffered %d casualties") % icas)
1411 prout(_(" in that last attack.\""))
1413 game.state.crew -= icas
1414 # After attack, reset average distance to enemies
1415 for enemy in game.enemies:
1416 enemy.kavgd = enemy.kdist
1417 game.enemies.sort(lambda x, y: cmp(x.kdist, y.kdist))
1420 def deadkl(w, type, mv):
1421 "Kill a Klingon, Tholian, Romulan, or Thingy."
1422 # Added mv to allow enemy to "move" before dying
1423 proutn(crmena(True, type, "sector", mv))
1424 # Decide what kind of enemy it is and update appropriately
1426 # Chalk up a Romulan
1427 game.state.galaxy[game.quadrant.i][game.quadrant.j].romulans -= 1
1429 game.state.nromrem -= 1
1438 # Killed some type of Klingon
1439 game.state.galaxy[game.quadrant.i][game.quadrant.j].klingons -= 1
1442 game.state.kcmdr.remove(game.quadrant)
1444 if game.state.kcmdr:
1445 schedule(FTBEAM, expran(1.0*game.incom/len(game.state.kcmdr)))
1446 if is_scheduled(FCDBAS) and game.battle == game.quadrant:
1449 game.state.remkl -= 1
1451 game.state.nscrem -= 1
1452 game.state.kscmdr.invalidate()
1457 # For each kind of enemy, finish message to player
1458 prout(_(" destroyed."))
1459 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)==0:
1462 # Remove enemy ship from arrays describing local conditions
1463 for e in game.enemies:
1470 "Return None if target is invalid, otherwise return a course angle."
1471 if not w.valid_sector():
1475 # FIXME: C code this was translated from is wacky -- why the sign reversal?
1476 delta.j = (w.j - game.sector.j);
1477 delta.i = (game.sector.i - w.i);
1478 if delta == coord(0, 0):
1480 prout(_("Spock- \"Bridge to sickbay. Dr. McCoy,"))
1481 prout(_(" I recommend an immediate review of"))
1482 prout(_(" the Captain's psychological profile.\""))
1485 return delta.bearing()
1488 "Launch photon torpedo salvo."
1491 if damaged(DPHOTON):
1492 prout(_("Photon tubes damaged."))
1496 prout(_("No torpedoes left."))
1499 # First, get torpedo count
1502 if scanner.token == "IHALPHA":
1505 elif scanner.token == "IHEOL" or not scanner.waiting():
1506 prout(_("%d torpedoes left.") % game.torps)
1508 proutn(_("Number of torpedoes to fire- "))
1509 continue # Go back around to get a number
1510 else: # key == "IHREAL"
1512 if n <= 0: # abort command
1517 prout(_("Maximum of %d torpedoes per burst.") % MAXBURST)
1520 scanner.chew() # User requested more torps than available
1521 continue # Go back around
1522 break # All is good, go to next stage
1526 key = scanner.next()
1527 if i==0 and key == "IHEOL":
1528 break; # no coordinate waiting, we will try prompting
1529 if i==1 and key == "IHEOL":
1530 # direct all torpedoes at one target
1532 target.append(target[0])
1533 course.append(course[0])
1536 scanner.push(scanner.token)
1537 target.append(scanner.getcoord())
1538 if target[-1] == None:
1540 course.append(targetcheck(target[-1]))
1541 if course[-1] == None:
1544 if len(target) == 0:
1545 # prompt for each one
1547 proutn(_("Target sector for torpedo number %d- ") % (i+1))
1549 target.append(scanner.getcoord())
1550 if target[-1] == None:
1552 course.append(targetcheck(target[-1]))
1553 if course[-1] == None:
1556 # Loop for moving <n> torpedoes
1558 if game.condition != "docked":
1560 dispersion = (randreal()+randreal())*0.5 -0.5
1561 if math.fabs(dispersion) >= 0.47:
1563 dispersion *= randreal(1.2, 2.2)
1565 prouts(_("***TORPEDO NUMBER %d MISFIRES") % (i+1))
1567 prouts(_("***TORPEDO MISFIRES."))
1570 prout(_(" Remainder of burst aborted."))
1572 prout(_("***Photon tubes damaged by misfire."))
1573 game.damage[DPHOTON] = game.damfac * randreal(1.0, 3.0)
1575 if game.shldup or game.condition == "docked":
1576 dispersion *= 1.0 + 0.0001*game.shield
1577 torpedo(game.sector, course[i], dispersion, number=i, nburst=n)
1578 if game.alldone or game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
1580 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)<=0:
1584 "Check for phasers overheating."
1586 checkburn = (rpow-1500.0)*0.00038
1587 if withprob(checkburn):
1588 prout(_("Weapons officer Sulu- \"Phasers overheated, sir.\""))
1589 game.damage[DPHASER] = game.damfac* randreal(1.0, 2.0) * (1.0+checkburn)
1591 def checkshctrl(rpow):
1592 "Check shield control."
1595 prout(_("Shields lowered."))
1597 # Something bad has happened
1598 prouts(_("***RED ALERT! RED ALERT!"))
1600 hit = rpow*game.shield/game.inshld
1601 game.energy -= rpow+hit*0.8
1602 game.shield -= hit*0.2
1603 if game.energy <= 0.0:
1604 prouts(_("Sulu- \"Captain! Shield malf***********************\""))
1609 prouts(_("Sulu- \"Captain! Shield malfunction! Phaser fire contained!\""))
1611 prout(_("Lt. Uhura- \"Sir, all decks reporting damage.\""))
1612 icas = randrange(int(hit*0.012))
1617 prout(_("McCoy to bridge- \"Severe radiation burns, Jim."))
1618 prout(_(" %d casualties so far.\"") % icas)
1620 game.state.crew -= icas
1622 prout(_("Phaser energy dispersed by shields."))
1623 prout(_("Enemy unaffected."))
1628 "Register a phaser hit on Klingons and Romulans."
1629 nenhr2 = len(game.enemies); kk=0
1632 for (k, wham) in enumerate(hits):
1635 dustfac = randreal(0.9, 1.0)
1636 hit = wham*math.pow(dustfac,game.enemies[kk].kdist)
1637 kpini = game.enemies[kk].power
1638 kp = math.fabs(kpini)
1639 if PHASEFAC*hit < kp:
1641 if game.enemies[kk].power < 0:
1642 game.enemies[kk].power -= -kp
1644 game.enemies[kk].power -= kp
1645 kpow = game.enemies[kk].power
1646 w = game.enemies[kk].location
1648 if not damaged(DSRSENS):
1650 proutn(_("%d unit hit on ") % int(hit))
1652 proutn(_("Very small hit on "))
1653 ienm = game.quad[w.i][w.j]
1656 proutn(crmena(False, ienm, "sector", w))
1660 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)==0:
1664 kk -= 1 # don't do the increment
1666 else: # decide whether or not to emasculate klingon
1667 if kpow>0 and withprob(0.9) and kpow <= randreal(0.4, 0.8)*kpini:
1668 prout(_("***Mr. Spock- \"Captain, the vessel at Sector %s")%w)
1669 prout(_(" has just lost its firepower.\""))
1670 game.enemies[kk].power = -kpow
1675 "Fire phasers at bad guys."
1677 kz = 0; k = 1; irec=0 # Cheating inhibitor
1678 ifast = False; no = False; itarg = True; msgflag = True; rpow=0
1682 # SR sensors and Computer are needed for automode
1683 if damaged(DSRSENS) or damaged(DCOMPTR):
1685 if game.condition == "docked":
1686 prout(_("Phasers can't be fired through base shields."))
1689 if damaged(DPHASER):
1690 prout(_("Phaser control damaged."))
1694 if damaged(DSHCTRL):
1695 prout(_("High speed shield control damaged."))
1698 if game.energy <= 200.0:
1699 prout(_("Insufficient energy to activate high-speed shield control."))
1702 prout(_("Weapons Officer Sulu- \"High-speed shield control enabled, sir.\""))
1704 # Original code so convoluted, I re-did it all
1705 # (That was Tom Almy talking about the C code, I think -- ESR)
1706 while automode=="NOTSET":
1708 if key == "IHALPHA":
1709 if scanner.sees("manual"):
1710 if len(game.enemies)==0:
1711 prout(_("There is no enemy present to select."))
1714 automode="AUTOMATIC"
1717 key = scanner.next()
1718 elif scanner.sees("automatic"):
1719 if (not itarg) and len(game.enemies) != 0:
1720 automode = "FORCEMAN"
1722 if len(game.enemies)==0:
1723 prout(_("Energy will be expended into space."))
1724 automode = "AUTOMATIC"
1725 key = scanner.next()
1726 elif scanner.sees("no"):
1731 elif key == "IHREAL":
1732 if len(game.enemies)==0:
1733 prout(_("Energy will be expended into space."))
1734 automode = "AUTOMATIC"
1736 automode = "FORCEMAN"
1738 automode = "AUTOMATIC"
1741 if len(game.enemies)==0:
1742 prout(_("Energy will be expended into space."))
1743 automode = "AUTOMATIC"
1745 automode = "FORCEMAN"
1747 proutn(_("Manual or automatic? "))
1752 if automode == "AUTOMATIC":
1753 if key == "IHALPHA" and scanner.sees("no"):
1755 key = scanner.next()
1756 if key != "IHREAL" and len(game.enemies) != 0:
1757 prout(_("Phasers locked on target. Energy available: %.2f")%avail)
1762 for i in range(len(game.enemies)):
1763 irec += math.fabs(game.enemies[i].power)/(PHASEFAC*math.pow(0.90,game.enemies[i].kdist))*randreal(1.01, 1.06) + 1.0
1765 proutn(_("%d units required. ") % irec)
1767 proutn(_("Units to fire= "))
1768 key = scanner.next()
1773 proutn(_("Energy available= %.2f") % avail)
1776 if not rpow > avail:
1783 if key == "IHALPHA" and scanner.sees("no"):
1786 game.energy -= 200; # Go and do it!
1787 if checkshctrl(rpow):
1792 if len(game.enemies):
1795 for i in range(len(game.enemies)):
1799 hits[i] = math.fabs(game.enemies[i].power)/(PHASEFAC*math.pow(0.90,game.enemies[i].kdist))
1800 over = randreal(1.01, 1.06) * hits[i]
1802 powrem -= hits[i] + over
1803 if powrem <= 0 and temp < hits[i]:
1812 if extra > 0 and not game.alldone:
1814 proutn(_("*** Tholian web absorbs "))
1815 if len(game.enemies)>0:
1816 proutn(_("excess "))
1817 prout(_("phaser energy."))
1819 prout(_("%d expended on empty space.") % int(extra))
1820 elif automode == "FORCEMAN":
1823 if damaged(DCOMPTR):
1824 prout(_("Battle computer damaged, manual fire only."))
1827 prouts(_("---WORKING---"))
1829 prout(_("Short-range-sensors-damaged"))
1830 prout(_("Insufficient-data-for-automatic-phaser-fire"))
1831 prout(_("Manual-fire-must-be-used"))
1833 elif automode == "MANUAL":
1835 for k in range(len(game.enemies)):
1836 aim = game.enemies[k].location
1837 ienm = game.quad[aim.i][aim.j]
1839 proutn(_("Energy available= %.2f") % (avail-0.006))
1843 if damaged(DSRSENS) and \
1844 not game.sector.distance(aim)<2**0.5 and ienm in ('C', 'S'):
1845 prout(cramen(ienm) + _(" can't be located without short range scan."))
1848 hits[k] = 0; # prevent overflow -- thanks to Alexei Voitenko
1853 if itarg and k > kz:
1854 irec=(abs(game.enemies[k].power)/(PHASEFAC*math.pow(0.9,game.enemies[k].kdist))) * randreal(1.01, 1.06) + 1.0
1857 if not damaged(DCOMPTR):
1862 proutn(_("units to fire at %s- ") % crmena(False, ienm, "sector", aim))
1863 key = scanner.next()
1864 if key == "IHALPHA" and scanner.sees("no"):
1866 key = scanner.next()
1868 if key == "IHALPHA":
1872 if k==1: # Let me say I'm baffled by this
1875 if scanner.real < 0:
1879 hits[k] = scanner.real
1880 rpow += scanner.real
1881 # If total requested is too much, inform and start over
1883 prout(_("Available energy exceeded -- try again."))
1886 key = scanner.next(); # scan for next value
1889 # zero energy -- abort
1892 if key == "IHALPHA" and scanner.sees("no"):
1897 game.energy -= 200.0
1898 if checkshctrl(rpow):
1902 # Say shield raised or malfunction, if necessary
1909 prout(_("Sulu- \"Sir, the high-speed shield control has malfunctioned . . ."))
1910 prouts(_(" CLICK CLICK POP . . ."))
1911 prout(_(" No response, sir!"))
1914 prout(_("Shields raised."))
1919 # Code from events,c begins here.
1921 # This isn't a real event queue a la BSD Trek yet -- you can only have one
1922 # event of each type active at any given time. Mostly these means we can
1923 # only have one FDISTR/FENSLV/FREPRO sequence going at any given time
1924 # BSD Trek, from which we swiped the idea, can have up to 5.
1926 def unschedule(evtype):
1927 "Remove an event from the schedule."
1928 game.future[evtype].date = FOREVER
1929 return game.future[evtype]
1931 def is_scheduled(evtype):
1932 "Is an event of specified type scheduled."
1933 return game.future[evtype].date != FOREVER
1935 def scheduled(evtype):
1936 "When will this event happen?"
1937 return game.future[evtype].date
1939 def schedule(evtype, offset):
1940 "Schedule an event of specified type."
1941 game.future[evtype].date = game.state.date + offset
1942 return game.future[evtype]
1944 def postpone(evtype, offset):
1945 "Postpone a scheduled event."
1946 game.future[evtype].date += offset
1949 "Rest period is interrupted by event."
1952 proutn(_("Mr. Spock- \"Captain, shall we cancel the rest period?\""))
1954 game.resting = False
1960 "Run through the event queue looking for things to do."
1962 fintim = game.state.date + game.optime; yank=0
1963 ictbeam = False; istract = False
1964 w = coord(); hold = coord()
1965 ev = event(); ev2 = event()
1967 def tractorbeam(yank):
1968 "Tractor-beaming cases merge here."
1970 game.optime = (10.0/(7.5*7.5))*yank # 7.5 is yank rate (warp 7.5)
1972 prout("***" + crmshp() + _(" caught in long range tractor beam--"))
1973 # If Kirk & Co. screwing around on planet, handle
1974 atover(True) # atover(true) is Grab
1977 if game.icraft: # Caught in Galileo?
1980 # Check to see if shuttle is aboard
1981 if game.iscraft == "offship":
1984 prout(_("Galileo, left on the planet surface, is captured"))
1985 prout(_("by aliens and made into a flying McDonald's."))
1986 game.damage[DSHUTTL] = -10
1987 game.iscraft = "removed"
1989 prout(_("Galileo, left on the planet surface, is well hidden."))
1991 game.quadrant = game.state.kscmdr
1993 game.quadrant = game.state.kcmdr[i]
1994 game.sector = randplace(QUADSIZE)
1995 prout(crmshp() + _(" is pulled to Quadrant %s, Sector %s") \
1996 % (game.quadrant, game.sector))
1998 prout(_("(Remainder of rest/repair period cancelled.)"))
1999 game.resting = False
2001 if not damaged(DSHIELD) and game.shield > 0:
2002 doshield(shraise=True) # raise shields
2003 game.shldchg = False
2005 prout(_("(Shields not currently useable.)"))
2007 # Adjust finish time to time of tractor beaming
2008 fintim = game.state.date+game.optime
2009 attack(torps_ok=False)
2010 if not game.state.kcmdr:
2013 schedule(FTBEAM, game.optime+expran(1.5*game.intime/len(game.state.kcmdr)))
2016 "Code merges here for any commander destroying a starbase."
2017 # Not perfect, but will have to do
2018 # Handle case where base is in same quadrant as starship
2019 if game.battle == game.quadrant:
2020 game.state.chart[game.battle.i][game.battle.j].starbase = False
2021 game.quad[game.base.i][game.base.j] = '.'
2022 game.base.invalidate()
2025 prout(_("Spock- \"Captain, I believe the starbase has been destroyed.\""))
2026 elif game.state.baseq and communicating():
2027 # Get word via subspace radio
2030 prout(_("Lt. Uhura- \"Captain, Starfleet Command reports that"))
2031 proutn(_(" the starbase in Quadrant %s has been destroyed by") % game.battle)
2033 prout(_("the Klingon Super-Commander"))
2035 prout(_("a Klingon Commander"))
2036 game.state.chart[game.battle.i][game.battle.j].starbase = False
2037 # Remove Starbase from galaxy
2038 game.state.galaxy[game.battle.i][game.battle.j].starbase = False
2039 game.state.baseq = filter(lambda x: x != game.battle, game.state.baseq)
2041 # reinstate a commander's base attack
2045 game.battle.invalidate()
2047 prout("=== EVENTS from %.2f to %.2f:" % (game.state.date, fintim))
2048 for i in range(1, NEVENTS):
2049 if i == FSNOVA: proutn("=== Supernova ")
2050 elif i == FTBEAM: proutn("=== T Beam ")
2051 elif i == FSNAP: proutn("=== Snapshot ")
2052 elif i == FBATTAK: proutn("=== Base Attack ")
2053 elif i == FCDBAS: proutn("=== Base Destroy ")
2054 elif i == FSCMOVE: proutn("=== SC Move ")
2055 elif i == FSCDBAS: proutn("=== SC Base Destroy ")
2056 elif i == FDSPROB: proutn("=== Probe Move ")
2057 elif i == FDISTR: proutn("=== Distress Call ")
2058 elif i == FENSLV: proutn("=== Enslavement ")
2059 elif i == FREPRO: proutn("=== Klingon Build ")
2061 prout("%.2f" % (scheduled(i)))
2064 radio_was_broken = damaged(DRADIO)
2067 # Select earliest extraneous event, evcode==0 if no events
2072 for l in range(1, NEVENTS):
2073 if game.future[l].date < datemin:
2076 prout("== Event %d fires" % evcode)
2077 datemin = game.future[l].date
2078 xtime = datemin-game.state.date
2079 game.state.date = datemin
2080 # Decrement Federation resources and recompute remaining time
2081 game.state.remres -= (game.state.remkl+4*len(game.state.kcmdr))*xtime
2083 if game.state.remtime <=0:
2086 # Any crew left alive?
2087 if game.state.crew <=0:
2090 # Is life support adequate?
2091 if damaged(DLIFSUP) and game.condition != "docked":
2092 if game.lsupres < xtime and game.damage[DLIFSUP] > game.lsupres:
2095 game.lsupres -= xtime
2096 if game.damage[DLIFSUP] <= xtime:
2097 game.lsupres = game.inlsr
2100 if game.condition == "docked":
2102 # Don't fix Deathray here
2103 for l in range(NDEVICES):
2104 if game.damage[l] > 0.0 and l != DDRAY:
2105 if game.damage[l]-repair > 0.0:
2106 game.damage[l] -= repair
2108 game.damage[l] = 0.0
2109 # If radio repaired, update star chart and attack reports
2110 if radio_was_broken and not damaged(DRADIO):
2111 prout(_("Lt. Uhura- \"Captain, the sub-space radio is working and"))
2112 prout(_(" surveillance reports are coming in."))
2114 if not game.iseenit:
2118 prout(_(" The star chart is now up to date.\""))
2120 # Cause extraneous event EVCODE to occur
2121 game.optime -= xtime
2122 if evcode == FSNOVA: # Supernova
2125 schedule(FSNOVA, expran(0.5*game.intime))
2126 if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
2128 elif evcode == FSPY: # Check with spy to see if SC should tractor beam
2129 if game.state.nscrem == 0 or \
2130 ictbeam or istract or \
2131 game.condition=="docked" or game.isatb==1 or game.iscate:
2133 if game.ientesc or \
2134 (game.energy<2000 and game.torps<4 and game.shield < 1250) or \
2135 (damaged(DPHASER) and (damaged(DPHOTON) or game.torps<4)) or \
2136 (damaged(DSHIELD) and \
2137 (game.energy < 2500 or damaged(DPHASER)) and \
2138 (game.torps < 5 or damaged(DPHOTON))):
2140 istract = ictbeam = True
2141 tractorbeam((game.state.kscmdr-game.quadrant).distance())
2144 elif evcode == FTBEAM: # Tractor beam
2145 if not game.state.kcmdr:
2148 i = randrange(len(game.state.kcmdr))
2149 yank = (game.state.kcmdr[i]-game.quadrant).distance()
2150 if istract or game.condition == "docked" or yank == 0:
2151 # Drats! Have to reschedule
2153 game.optime + expran(1.5*game.intime/len(game.state.kcmdr)))
2157 elif evcode == FSNAP: # Snapshot of the universe (for time warp)
2158 game.snapsht = copy.deepcopy(game.state)
2159 game.state.snap = True
2160 schedule(FSNAP, expran(0.5 * game.intime))
2161 elif evcode == FBATTAK: # Commander attacks starbase
2162 if not game.state.kcmdr or not game.state.baseq:
2168 for ibq in game.state.baseq:
2169 for cmdr in game.state.kcmdr:
2170 if ibq == cmdr and ibq != game.quadrant and ibq != game.state.kscmdr:
2173 # no match found -- try later
2174 schedule(FBATTAK, expran(0.3*game.intime))
2179 # commander + starbase combination found -- launch attack
2181 schedule(FCDBAS, randreal(1.0, 4.0))
2182 if game.isatb: # extra time if SC already attacking
2183 postpone(FCDBAS, scheduled(FSCDBAS)-game.state.date)
2184 game.future[FBATTAK].date = game.future[FCDBAS].date + expran(0.3*game.intime)
2185 game.iseenit = False
2186 if not communicating():
2187 continue # No warning :-(
2191 prout(_("Lt. Uhura- \"Captain, the starbase in Quadrant %s") % game.battle)
2192 prout(_(" reports that it is under attack and that it can"))
2193 prout(_(" hold out only until stardate %d.\"") % (int(scheduled(FCDBAS))))
2196 elif evcode == FSCDBAS: # Supercommander destroys base
2199 if not game.state.galaxy[game.state.kscmdr.i][game.state.kscmdr.j].starbase:
2200 continue # WAS RETURN!
2202 game.battle = game.state.kscmdr
2204 elif evcode == FCDBAS: # Commander succeeds in destroying base
2207 if not game.state.baseq() \
2208 or not game.state.galaxy[game.battle.i][game.battle.j].starbase:
2209 game.battle.invalidate()
2211 # find the lucky pair
2212 for cmdr in game.state.kcmdr:
2213 if cmdr == game.battle:
2216 # No action to take after all
2219 elif evcode == FSCMOVE: # Supercommander moves
2220 schedule(FSCMOVE, 0.2777)
2221 if not game.ientesc and not istract and game.isatb != 1 and \
2222 (not game.iscate or not game.justin):
2224 elif evcode == FDSPROB: # Move deep space probe
2225 schedule(FDSPROB, 0.01)
2226 if not game.probe.next():
2227 if not game.probe.quadrant().valid_quadrant() or \
2228 game.state.galaxy[game.probe.quadrant().i][game.probe.quadrant().j].supernova:
2229 # Left galaxy or ran into supernova
2233 proutn(_("Lt. Uhura- \"The deep space probe "))
2234 if not game.probe.quadrant().valid_quadrant():
2235 prout(_("has left the galaxy.\""))
2237 prout(_("is no longer transmitting.\""))
2243 prout(_("Lt. Uhura- \"The deep space probe is now in Quadrant %s.\"") % game.probe.quadrant())
2244 pdest = game.state.galaxy[game.probe.quadrant().i][game.probe.quadrant().j]
2246 chp = game.state.chart[game.probe.quadrant().i][game.probe.quadrant().j]
2247 chp.klingons = pdest.klingons
2248 chp.starbase = pdest.starbase
2249 chp.stars = pdest.stars
2250 pdest.charted = True
2251 game.probe.moves -= 1 # One less to travel
2252 if game.probe.arrived() and game.isarmed and pdest.stars:
2253 supernova(game.probe) # fire in the hole!
2255 if game.state.galaxy[game.quadrant().i][game.quadrant().j].supernova:
2257 elif evcode == FDISTR: # inhabited system issues distress call
2259 # try a whole bunch of times to find something suitable
2260 for i in range(100):
2261 # need a quadrant which is not the current one,
2262 # which has some stars which are inhabited and
2263 # not already under attack, which is not
2264 # supernova'ed, and which has some Klingons in it
2265 w = randplace(GALSIZE)
2266 q = game.state.galaxy[w.i][w.j]
2267 if not (game.quadrant == w or q.planet == None or \
2268 not q.planet.inhabited or \
2269 q.supernova or q.status!="secure" or q.klingons<=0):
2272 # can't seem to find one; ignore this call
2274 prout("=== Couldn't find location for distress event.")
2276 # got one!! Schedule its enslavement
2277 ev = schedule(FENSLV, expran(game.intime))
2279 q.status = "distressed"
2280 # tell the captain about it if we can
2282 prout(_("Uhura- Captain, %s in Quadrant %s reports it is under attack") \
2284 prout(_("by a Klingon invasion fleet."))
2287 elif evcode == FENSLV: # starsystem is enslaved
2288 ev = unschedule(FENSLV)
2289 # see if current distress call still active
2290 q = game.state.galaxy[ev.quadrant.i][ev.quadrant.j]
2294 q.status = "enslaved"
2296 # play stork and schedule the first baby
2297 ev2 = schedule(FREPRO, expran(2.0 * game.intime))
2298 ev2.quadrant = ev.quadrant
2300 # report the disaster if we can
2302 prout(_("Uhura- We've lost contact with starsystem %s") % \
2304 prout(_("in Quadrant %s.\n") % ev.quadrant)
2305 elif evcode == FREPRO: # Klingon reproduces
2306 # If we ever switch to a real event queue, we'll need to
2307 # explicitly retrieve and restore the x and y.
2308 ev = schedule(FREPRO, expran(1.0 * game.intime))
2309 # see if current distress call still active
2310 q = game.state.galaxy[ev.quadrant.i][ev.quadrant.j]
2314 if game.state.remkl >=MAXKLGAME:
2315 continue # full right now
2316 # reproduce one Klingon
2319 if game.klhere >= MAXKLQUAD:
2321 # this quadrant not ok, pick an adjacent one
2322 for m.i in range(w.i - 1, w.i + 2):
2323 for m.j in range(w.j - 1, w.j + 2):
2324 if not m.valid_quadrant():
2326 q = game.state.galaxy[m.i][m.j]
2327 # check for this quad ok (not full & no snova)
2328 if q.klingons >= MAXKLQUAD or q.supernova:
2332 continue # search for eligible quadrant failed
2336 game.state.remkl += 1
2338 if game.quadrant == w:
2340 game.enemies.append(newkling())
2341 # recompute time left
2344 if game.quadrant == w:
2345 prout(_("Spock- sensors indicate the Klingons have"))
2346 prout(_("launched a warship from %s.") % q.planet)
2348 prout(_("Uhura- Starfleet reports increased Klingon activity"))
2349 if q.planet != None:
2350 proutn(_("near %s ") % q.planet)
2351 prout(_("in Quadrant %s.") % w)
2357 key = scanner.next()
2360 proutn(_("How long? "))
2365 origTime = delay = scanner.real
2368 if delay >= game.state.remtime or len(game.enemies) != 0:
2369 proutn(_("Are you sure? "))
2372 # Alternate resting periods (events) with attacks
2376 game.resting = False
2377 if not game.resting:
2378 prout(_("%d stardates left.") % int(game.state.remtime))
2380 temp = game.optime = delay
2381 if len(game.enemies):
2382 rtime = randreal(1.0, 2.0)
2386 if game.optime < delay:
2387 attack(torps_ok=False)
2395 # Repair Deathray if long rest at starbase
2396 if origTime-delay >= 9.99 and game.condition == "docked":
2397 game.damage[DDRAY] = 0.0
2398 # leave if quadrant supernovas
2399 if game.state.galaxy[game.quadrant.i][game.quadrant.j].supernova:
2401 game.resting = False
2406 course = (0.0, 10.5, 12.0, 1.5, 9.0, 0.0, 3.0, 7.5, 6.0, 4.5)
2407 newc = coord(); neighbor = coord(); bump = coord(0, 0)
2409 # Wow! We've supernova'ed
2410 supernova(game.quadrant)
2412 # handle initial nova
2413 game.quad[nov.i][nov.j] = '.'
2414 prout(crmena(False, '*', "sector", nov) + _(" novas."))
2415 game.state.galaxy[game.quadrant.i][game.quadrant.j].stars -= 1
2416 game.state.starkl += 1
2417 # Set up queue to recursively trigger adjacent stars
2423 for offset.i in range(-1, 1+1):
2424 for offset.j in range(-1, 1+1):
2425 if offset.j==0 and offset.i==0:
2427 neighbor = start + offset
2428 if not neighbor.valid_sector():
2430 iquad = game.quad[neighbor.i][neighbor.j]
2431 # Empty space ends reaction
2432 if iquad in ('.', '?', ' ', 'T', '#'):
2434 elif iquad == '*': # Affect another star
2436 # This star supernovas
2437 supernova(game.quadrant)
2440 hits.append(neighbor)
2441 game.state.galaxy[game.quadrant.i][game.quadrant.j].stars -= 1
2442 game.state.starkl += 1
2443 proutn(crmena(True, '*', "sector", neighbor))
2445 game.quad[neighbor.i][neighbor.j] = '.'
2447 elif iquad in ('P', '@'): # Destroy planet
2448 game.state.galaxy[game.quadrant.i][game.quadrant.j].planet = None
2450 game.state.nplankl += 1
2452 game.state.worldkl += 1
2453 prout(crmena(True, 'B', "sector", neighbor) + _(" destroyed."))
2454 game.iplnet.pclass = "destroyed"
2456 game.plnet.invalidate()
2460 game.quad[neighbor.i][neighbor.j] = '.'
2461 elif iquad == 'B': # Destroy base
2462 game.state.galaxy[game.quadrant.i][game.quadrant.j].starbase = False
2463 game.state.baseq = filter(lambda x: x!= game.quadrant, game.state.baseq)
2464 game.base.invalidate()
2465 game.state.basekl += 1
2467 prout(crmena(True, 'B', "sector", neighbor) + _(" destroyed."))
2468 game.quad[neighbor.i][neighbor.j] = '.'
2469 elif iquad in ('E', 'F'): # Buffet ship
2470 prout(_("***Starship buffeted by nova."))
2472 if game.shield >= 2000.0:
2473 game.shield -= 2000.0
2475 diff = 2000.0 - game.shield
2479 prout(_("***Shields knocked out."))
2480 game.damage[DSHIELD] += 0.005*game.damfac*randreal()*diff
2482 game.energy -= 2000.0
2483 if game.energy <= 0:
2486 # add in course nova contributes to kicking starship
2487 bump += (game.sector-hits[mm]).sgn()
2488 elif iquad == 'K': # kill klingon
2489 deadkl(neighbor, iquad, neighbor)
2490 elif iquad in ('C','S','R'): # Damage/destroy big enemies
2491 for ll in range(len(game.enemies)):
2492 if game.enemies[ll].location == neighbor:
2494 game.enemies[ll].power -= 800.0 # If firepower is lost, die
2495 if game.enemies[ll].power <= 0.0:
2496 deadkl(neighbor, iquad, neighbor)
2498 newc = neighbor + neighbor - hits[mm]
2499 proutn(crmena(True, iquad, "sector", neighbor) + _(" damaged"))
2500 if not newc.valid_sector():
2501 # can't leave quadrant
2504 iquad1 = game.quad[newc.i][newc.j]
2506 proutn(_(", blasted into ") + crmena(False, ' ', "sector", newc))
2508 deadkl(neighbor, iquad, newc)
2511 # can't move into something else
2514 proutn(_(", buffeted to Sector %s") % newc)
2515 game.quad[neighbor.i][neighbor.j] = '.'
2516 game.quad[newc.i][newc.j] = iquad
2517 game.enemies[ll].move(newc)
2518 # Starship affected by nova -- kick it away.
2520 direc = course[3*(bump.i+1)+bump.j+2]
2525 course = course(bearing=direc, distance=dist)
2526 game.optime = course.time(warp=4)
2528 prout(_("Force of nova displaces starship."))
2529 imove(course, noattack=True)
2530 game.optime = course.time(warp=4)
2534 "Star goes supernova."
2539 # Scheduled supernova -- select star at random.
2542 for nq.i in range(GALSIZE):
2543 for nq.j in range(GALSIZE):
2544 stars += game.state.galaxy[nq.i][nq.j].stars
2546 return # nothing to supernova exists
2547 num = randrange(stars) + 1
2548 for nq.i in range(GALSIZE):
2549 for nq.j in range(GALSIZE):
2550 num -= game.state.galaxy[nq.i][nq.j].stars
2556 proutn("=== Super nova here?")
2559 if not nq == game.quadrant or game.justin:
2560 # it isn't here, or we just entered (treat as enroute)
2563 prout(_("Message from Starfleet Command Stardate %.2f") % game.state.date)
2564 prout(_(" Supernova in Quadrant %s; caution advised.") % nq)
2567 # we are in the quadrant!
2568 num = randrange(game.state.galaxy[nq.i][nq.j].stars) + 1
2569 for ns.i in range(QUADSIZE):
2570 for ns.j in range(QUADSIZE):
2571 if game.quad[ns.i][ns.j]=='*':
2578 prouts(_("***RED ALERT! RED ALERT!"))
2580 prout(_("***Incipient supernova detected at Sector %s") % ns)
2581 if (ns.i-game.sector.i)**2 + (ns.j-game.sector.j)**2 <= 2.1:
2582 proutn(_("Emergency override attempts t"))
2583 prouts("***************")
2587 # destroy any Klingons in supernovaed quadrant
2588 kldead = game.state.galaxy[nq.i][nq.j].klingons
2589 game.state.galaxy[nq.i][nq.j].klingons = 0
2590 if nq == game.state.kscmdr:
2591 # did in the Supercommander!
2592 game.state.nscrem = game.state.kscmdr.i = game.state.kscmdr.j = game.isatb = 0
2596 survivors = filter(lambda w: w != nq, game.state.kcmdr)
2597 comkills = len(game.state.kcmdr) - len(survivors)
2598 game.state.kcmdr = survivors
2600 if not game.state.kcmdr:
2602 game.state.remkl -= kldead
2603 # destroy Romulans and planets in supernovaed quadrant
2604 nrmdead = game.state.galaxy[nq.i][nq.j].romulans
2605 game.state.galaxy[nq.i][nq.j].romulans = 0
2606 game.state.nromrem -= nrmdead
2608 for loop in range(game.inplan):
2609 if game.state.planets[loop].quadrant == nq:
2610 game.state.planets[loop].pclass = "destroyed"
2612 # Destroy any base in supernovaed quadrant
2613 game.state.baseq = filter(lambda x: x != nq, game.state.baseq)
2614 # If starship caused supernova, tally up destruction
2616 game.state.starkl += game.state.galaxy[nq.i][nq.j].stars
2617 game.state.basekl += game.state.galaxy[nq.i][nq.j].starbase
2618 game.state.nplankl += npdead
2619 # mark supernova in galaxy and in star chart
2620 if game.quadrant == nq or communicating():
2621 game.state.galaxy[nq.i][nq.j].supernova = True
2622 # If supernova destroys last Klingons give special message
2623 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)==0 and not nq == game.quadrant:
2626 prout(_("Lucky you!"))
2627 proutn(_("A supernova in %s has just destroyed the last Klingons.") % nq)
2630 # if some Klingons remain, continue or die in supernova
2635 # Code from finish.c ends here.
2638 "Self-destruct maneuver. Finish with a BANG!"
2640 if damaged(DCOMPTR):
2641 prout(_("Computer damaged; cannot execute destruct sequence."))
2643 prouts(_("---WORKING---")); skip(1)
2644 prouts(_("SELF-DESTRUCT-SEQUENCE-ACTIVATED")); skip(1)
2645 prouts(" 10"); skip(1)
2646 prouts(" 9"); skip(1)
2647 prouts(" 8"); skip(1)
2648 prouts(" 7"); skip(1)
2649 prouts(" 6"); skip(1)
2651 prout(_("ENTER-CORRECT-PASSWORD-TO-CONTINUE-"))
2653 prout(_("SELF-DESTRUCT-SEQUENCE-OTHERWISE-"))
2655 prout(_("SELF-DESTRUCT-SEQUENCE-WILL-BE-ABORTED"))
2659 if game.passwd != scanner.token:
2660 prouts(_("PASSWORD-REJECTED;"))
2662 prouts(_("CONTINUITY-EFFECTED"))
2665 prouts(_("PASSWORD-ACCEPTED")); skip(1)
2666 prouts(" 5"); skip(1)
2667 prouts(" 4"); skip(1)
2668 prouts(" 3"); skip(1)
2669 prouts(" 2"); skip(1)
2670 prouts(" 1"); skip(1)
2672 prouts(_("GOODBYE-CRUEL-WORLD"))
2680 prouts(_("********* Entropy of %s maximized *********") % crmshp())
2684 if len(game.enemies) != 0:
2685 whammo = 25.0 * game.energy
2687 while l <= len(game.enemies):
2688 if game.enemies[l].power*game.enemies[l].kdist <= whammo:
2689 deadkl(game.enemies[l].location, game.quad[game.enemies[l].location.i][game.enemies[l].location.j], game.enemies[l].location)
2694 "Compute our rate of kils over time."
2695 elapsed = game.state.date - game.indate
2696 if elapsed == 0: # Avoid divide-by-zero error if calculated on turn 0
2699 starting = (game.inkling + game.incom + game.inscom)
2700 remaining = (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)
2701 return (starting - remaining)/elapsed
2705 badpt = 5.0*game.state.starkl + \
2707 10.0*game.state.nplankl + \
2708 300*game.state.nworldkl + \
2710 100.0*game.state.basekl +\
2712 if game.ship == 'F':
2714 elif game.ship == None:
2719 # end the game, with appropriate notfications
2723 prout(_("It is stardate %.1f.") % game.state.date)
2725 if ifin == FWON: # Game has been won
2726 if game.state.nromrem != 0:
2727 prout(_("The remaining %d Romulans surrender to Starfleet Command.") %
2730 prout(_("You have smashed the Klingon invasion fleet and saved"))
2731 prout(_("the Federation."))
2736 badpt = 0.0 # Close enough!
2737 # killsPerDate >= RateMax
2738 if game.state.date-game.indate < 5.0 or \
2739 killrate() >= 0.1*game.skill*(game.skill+1.0) + 0.1 + 0.008*badpt:
2741 prout(_("In fact, you have done so well that Starfleet Command"))
2742 if game.skill == SKILL_NOVICE:
2743 prout(_("promotes you one step in rank from \"Novice\" to \"Fair\"."))
2744 elif game.skill == SKILL_FAIR:
2745 prout(_("promotes you one step in rank from \"Fair\" to \"Good\"."))
2746 elif game.skill == SKILL_GOOD:
2747 prout(_("promotes you one step in rank from \"Good\" to \"Expert\"."))
2748 elif game.skill == SKILL_EXPERT:
2749 prout(_("promotes you to Commodore Emeritus."))
2751 prout(_("Now that you think you're really good, try playing"))
2752 prout(_("the \"Emeritus\" game. It will splatter your ego."))
2753 elif game.skill == SKILL_EMERITUS:
2755 proutn(_("Computer- "))
2756 prouts(_("ERROR-ERROR-ERROR-ERROR"))
2758 prouts(_(" YOUR-SKILL-HAS-EXCEEDED-THE-CAPACITY-OF-THIS-PROGRAM"))
2760 prouts(_(" THIS-PROGRAM-MUST-SURVIVE"))
2762 prouts(_(" THIS-PROGRAM-MUST-SURVIVE"))
2764 prouts(_(" THIS-PROGRAM-MUST-SURVIVE"))
2766 prouts(_(" THIS-PROGRAM-MUST?- MUST ? - SUR? ? -? VI"))
2768 prout(_("Now you can retire and write your own Star Trek game!"))
2770 elif game.skill >= SKILL_EXPERT:
2771 if game.thawed and not idebug:
2772 prout(_("You cannot get a citation, so..."))
2774 proutn(_("Do you want your Commodore Emeritus Citation printed? "))
2778 # Only grant long life if alive (original didn't!)
2780 prout(_("LIVE LONG AND PROSPER."))
2785 elif ifin == FDEPLETE: # Federation Resources Depleted
2786 prout(_("Your time has run out and the Federation has been"))
2787 prout(_("conquered. Your starship is now Klingon property,"))
2788 prout(_("and you are put on trial as a war criminal. On the"))
2789 proutn(_("basis of your record, you are "))
2790 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem)*3.0 > (game.inkling + game.incom + game.inscom):
2791 prout(_("acquitted."))
2793 prout(_("LIVE LONG AND PROSPER."))
2795 prout(_("found guilty and"))
2796 prout(_("sentenced to death by slow torture."))
2800 elif ifin == FLIFESUP:
2801 prout(_("Your life support reserves have run out, and"))
2802 prout(_("you die of thirst, starvation, and asphyxiation."))
2803 prout(_("Your starship is a derelict in space."))
2805 prout(_("Your energy supply is exhausted."))
2807 prout(_("Your starship is a derelict in space."))
2808 elif ifin == FBATTLE:
2809 prout(_("The %s has been destroyed in battle.") % crmshp())
2811 prout(_("Dulce et decorum est pro patria mori."))
2813 prout(_("You have made three attempts to cross the negative energy"))
2814 prout(_("barrier which surrounds the galaxy."))
2816 prout(_("Your navigation is abominable."))
2819 prout(_("Your starship has been destroyed by a nova."))
2820 prout(_("That was a great shot."))
2822 elif ifin == FSNOVAED:
2823 prout(_("The %s has been fried by a supernova.") % crmshp())
2824 prout(_("...Not even cinders remain..."))
2825 elif ifin == FABANDN:
2826 prout(_("You have been captured by the Klingons. If you still"))
2827 prout(_("had a starbase to be returned to, you would have been"))
2828 prout(_("repatriated and given another chance. Since you have"))
2829 prout(_("no starbases, you will be mercilessly tortured to death."))
2830 elif ifin == FDILITHIUM:
2831 prout(_("Your starship is now an expanding cloud of subatomic particles"))
2832 elif ifin == FMATERIALIZE:
2833 prout(_("Starbase was unable to re-materialize your starship."))
2834 prout(_("Sic transit gloria mundi"))
2835 elif ifin == FPHASER:
2836 prout(_("The %s has been cremated by its own phasers.") % crmshp())
2838 prout(_("You and your landing party have been"))
2839 prout(_("converted to energy, disipating through space."))
2840 elif ifin == FMINING:
2841 prout(_("You are left with your landing party on"))
2842 prout(_("a wild jungle planet inhabited by primitive cannibals."))
2844 prout(_("They are very fond of \"Captain Kirk\" soup."))
2846 prout(_("Without your leadership, the %s is destroyed.") % crmshp())
2847 elif ifin == FDPLANET:
2848 prout(_("You and your mining party perish."))
2850 prout(_("That was a great shot."))
2853 prout(_("The Galileo is instantly annihilated by the supernova."))
2854 prout(_("You and your mining party are atomized."))
2856 prout(_("Mr. Spock takes command of the %s and") % crmshp())
2857 prout(_("joins the Romulans, wreaking terror on the Federation."))
2858 elif ifin == FPNOVA:
2859 prout(_("You and your mining party are atomized."))
2861 prout(_("Mr. Spock takes command of the %s and") % crmshp())
2862 prout(_("joins the Romulans, wreaking terror on the Federation."))
2863 elif ifin == FSTRACTOR:
2864 prout(_("The shuttle craft Galileo is also caught,"))
2865 prout(_("and breaks up under the strain."))
2867 prout(_("Your debris is scattered for millions of miles."))
2868 prout(_("Without your leadership, the %s is destroyed.") % crmshp())
2870 prout(_("The mutants attack and kill Spock."))
2871 prout(_("Your ship is captured by Klingons, and"))
2872 prout(_("your crew is put on display in a Klingon zoo."))
2873 elif ifin == FTRIBBLE:
2874 prout(_("Tribbles consume all remaining water,"))
2875 prout(_("food, and oxygen on your ship."))
2877 prout(_("You die of thirst, starvation, and asphyxiation."))
2878 prout(_("Your starship is a derelict in space."))
2880 prout(_("Your ship is drawn to the center of the black hole."))
2881 prout(_("You are crushed into extremely dense matter."))
2883 prout(_("Your last crew member has died."))
2884 if game.ship == 'F':
2886 elif game.ship == 'E':
2889 if (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem) != 0:
2890 goodies = game.state.remres/game.inresor
2891 baddies = (game.state.remkl + 2.0*len(game.state.kcmdr))/(game.inkling+2.0*game.incom)
2892 if goodies/baddies >= randreal(1.0, 1.5):
2893 prout(_("As a result of your actions, a treaty with the Klingon"))
2894 prout(_("Empire has been signed. The terms of the treaty are"))
2895 if goodies/baddies >= randreal(3.0):
2896 prout(_("favorable to the Federation."))
2898 prout(_("Congratulations!"))
2900 prout(_("highly unfavorable to the Federation."))
2902 prout(_("The Federation will be destroyed."))
2904 prout(_("Since you took the last Klingon with you, you are a"))
2905 prout(_("martyr and a hero. Someday maybe they'll erect a"))
2906 prout(_("statue in your memory. Rest in peace, and try not"))
2907 prout(_("to think about pigeons."))
2912 "Compute player's score."
2913 timused = game.state.date - game.indate
2915 if (timused == 0 or (game.state.remkl + len(game.state.kcmdr) + game.state.nscrem) != 0) and timused < 5.0:
2917 perdate = killrate()
2918 ithperd = 500*perdate + 0.5
2921 iwon = 100*game.skill
2922 if game.ship == 'E':
2924 elif game.ship == 'F':
2928 iscore = 10*(game.inkling - game.state.remkl) \
2929 + 50*(game.incom - len(game.state.kcmdr)) \
2931 + 20*(game.inrom - game.state.nromrem) \
2932 + 200*(game.inscom - game.state.nscrem) \
2933 - game.state.nromrem \
2938 prout(_("Your score --"))
2939 if game.inrom - game.state.nromrem:
2940 prout(_("%6d Romulans destroyed %5d") %
2941 (game.inrom - game.state.nromrem, 20*(game.inrom - game.state.nromrem)))
2942 if game.state.nromrem and game.gamewon:
2943 prout(_("%6d Romulans captured %5d") %
2944 (game.state.nromrem, game.state.nromrem))
2945 if game.inkling - game.state.remkl:
2946 prout(_("%6d ordinary Klingons destroyed %5d") %
2947 (game.inkling - game.state.remkl, 10*(game.inkling - game.state.remkl)))
2948 if game.incom - len(game.state.kcmdr):
2949 prout(_("%6d Klingon commanders destroyed %5d") %
2950 (game.incom - len(game.state.kcmdr), 50*(game.incom - len(game.state.kcmdr))))
2951 if game.inscom - game.state.nscrem:
2952 prout(_("%6d Super-Commander destroyed %5d") %
2953 (game.inscom - game.state.nscrem, 200*(game.inscom - game.state.nscrem)))
2955 prout(_("%6.2f Klingons per stardate %5d") %
2957 if game.state.starkl:
2958 prout(_("%6d stars destroyed by your action %5d") %
2959 (game.state.starkl, -5*game.state.starkl))
2960 if game.state.nplankl:
2961 prout(_("%6d planets destroyed by your action %5d") %
2962 (game.state.nplankl, -10*game.state.nplankl))
2963 if (game.options & OPTION_WORLDS) and game.state.nworldkl:
2964 prout(_("%6d inhabited planets destroyed by your action %5d") %
2965 (game.state.nworldkl, -300*game.state.nworldkl))
2966 if game.state.basekl:
2967 prout(_("%6d bases destroyed by your action %5d") %
2968 (game.state.basekl, -100*game.state.basekl))
2970 prout(_("%6d calls for help from starbase %5d") %
2971 (game.nhelp, -45*game.nhelp))
2973 prout(_("%6d casualties incurred %5d") %
2974 (game.casual, -game.casual))
2976 prout(_("%6d crew abandoned in space %5d") %
2977 (game.abandoned, -3*game.abandoned))
2979 prout(_("%6d ship(s) lost or destroyed %5d") %
2980 (klship, -100*klship))
2982 prout(_("Penalty for getting yourself killed -200"))
2984 proutn(_("Bonus for winning "))
2985 if game.skill == SKILL_NOVICE: proutn(_("Novice game "))
2986 elif game.skill == SKILL_FAIR: proutn(_("Fair game "))
2987 elif game.skill == SKILL_GOOD: proutn(_("Good game "))
2988 elif game.skill == SKILL_EXPERT: proutn(_("Expert game "))
2989 elif game.skill == SKILL_EMERITUS: proutn(_("Emeritus game"))
2990 prout(" %5d" % iwon)
2992 prout(_("TOTAL SCORE %5d") % iscore)
2995 "Emit winner's commemmorative plaque."
2998 proutn(_("File or device name for your plaque: "))
3001 fp = open(winner, "w")
3004 prout(_("Invalid name."))
3006 proutn(_("Enter name to go on plaque (up to 30 characters): "))
3008 # The 38 below must be 64 for 132-column paper
3009 nskip = 38 - len(winner)/2
3010 fp.write("\n\n\n\n")
3011 # --------DRAW ENTERPRISE PICTURE.
3012 fp.write(" EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" )
3013 fp.write(" EEE E : : : E\n" )
3014 fp.write(" EE EEE E : : NCC-1701 : E\n")
3015 fp.write("EEEEEEEEEEEEEEEE EEEEEEEEEEEEEEE : : : E\n")
3016 fp.write(" E EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n")
3017 fp.write(" EEEEEEEEE EEEEEEEEEEEEE E E\n")
3018 fp.write(" EEEEEEE EEEEE E E E E\n")
3019 fp.write(" EEE E E E E\n")
3020 fp.write(" E E E E\n")
3021 fp.write(" EEEEEEEEEEEEE E E\n")
3022 fp.write(" EEE : EEEEEEE EEEEEEEE\n")
3023 fp.write(" :E : EEEE E\n")
3024 fp.write(" .-E -:----- E\n")
3025 fp.write(" :E : E\n")
3026 fp.write(" EE : EEEEEEEE\n")
3027 fp.write(" EEEEEEEEEEEEEEEEEEEEEEE\n")
3029 fp.write(_(" U. S. S. ENTERPRISE\n"))
3030 fp.write("\n\n\n\n")
3031 fp.write(_(" For demonstrating outstanding ability as a starship captain\n"))
3033 fp.write(_(" Starfleet Command bestows to you\n"))
3035 fp.write("%*s%s\n\n" % (nskip, "", winner))
3036 fp.write(_(" the rank of\n\n"))
3037 fp.write(_(" \"Commodore Emeritus\"\n\n"))
3039 if game.skill == SKILL_EXPERT:
3040 fp.write(_(" Expert level\n\n"))
3041 elif game.skill == SKILL_EMERITUS:
3042 fp.write(_("Emeritus level\n\n"))
3044 fp.write(_(" Cheat level\n\n"))
3045 timestring = time.ctime()
3046 fp.write(_(" This day of %.6s %.4s, %.8s\n\n") %
3047 (timestring+4, timestring+20, timestring+11))
3048 fp.write(_(" Your score: %d\n\n") % iscore)
3049 fp.write(_(" Klingons per stardate: %.2f\n") % perdate)
3052 # Code from io.c begins here
3054 rows = linecount = 0 # for paging
3057 fullscreen_window = None
3058 srscan_window = None
3059 report_window = None
3060 status_window = None
3061 lrscan_window = None
3062 message_window = None
3063 prompt_window = None
3068 "for some recent versions of python2, the following enables UTF8"
3069 "for the older ones we probably need to set C locale, and the python3"
3070 "has no problems at all"
3071 if sys.version_info[0] < 3:
3073 locale.setlocale(locale.LC_ALL, "")
3074 gettext.bindtextdomain("sst", "/usr/local/share/locale")
3075 gettext.textdomain("sst")
3076 if not (game.options & OPTION_CURSES):
3077 ln_env = os.getenv("LINES")
3083 stdscr = curses.initscr()
3087 if game.options & OPTION_COLOR:
3088 curses.start_color();
3089 curses.use_default_colors()
3090 curses.init_pair(curses.COLOR_BLACK, curses.COLOR_BLACK, -1);
3091 curses.init_pair(curses.COLOR_GREEN, curses.COLOR_GREEN, -1);
3092 curses.init_pair(curses.COLOR_RED, curses.COLOR_RED, -1);
3093 curses.init_pair(curses.COLOR_CYAN, curses.COLOR_CYAN, -1);
3094 curses.init_pair(curses.COLOR_WHITE, curses.COLOR_WHITE, -1);
3095 curses.init_pair(curses.COLOR_MAGENTA, curses.COLOR_MAGENTA, -1);
3096 curses.init_pair(curses.COLOR_BLUE, curses.COLOR_BLUE, -1);
3097 curses.init_pair(curses.COLOR_YELLOW, curses.COLOR_YELLOW, -1);
3098 global fullscreen_window, srscan_window, report_window, status_window
3099 global lrscan_window, message_window, prompt_window
3100 (rows, columns) = stdscr.getmaxyx()
3101 fullscreen_window = stdscr
3102 srscan_window = curses.newwin(12, 25, 0, 0)
3103 report_window = curses.newwin(11, 0, 1, 25)
3104 status_window = curses.newwin(10, 0, 1, 39)
3105 lrscan_window = curses.newwin(5, 0, 0, 64)
3106 message_window = curses.newwin(0, 0, 12, 0)
3107 prompt_window = curses.newwin(1, 0, rows-2, 0)
3108 message_window.scrollok(True)
3109 setwnd(fullscreen_window)
3113 if game.options & OPTION_CURSES:
3114 stdscr.keypad(False)
3120 "Wait for user action -- OK to do nothing if on a TTY"
3121 if game.options & OPTION_CURSES:
3126 prouts(_("[ANNOUNCEMENT ARRIVING...]"))
3130 if game.skill > SKILL_FAIR:
3131 prompt = _("[CONTINUE?]")
3133 prompt = _("[PRESS ENTER TO CONTINUE]")
3135 if game.options & OPTION_CURSES:
3137 setwnd(prompt_window)
3138 prompt_window.clear()
3139 prompt_window.addstr(prompt)
3140 prompt_window.getstr()
3141 prompt_window.clear()
3142 prompt_window.refresh()
3143 setwnd(message_window)
3146 sys.stdout.write('\n')
3149 for j in range(rows):
3150 sys.stdout.write('\n')
3154 "Skip i lines. Pause game if this would cause a scrolling event."
3155 for dummy in range(i):
3156 if game.options & OPTION_CURSES:
3157 (y, x) = curwnd.getyx()
3158 (my, mx) = curwnd.getmaxyx()
3159 if curwnd == message_window and y >= my - 2:
3165 except curses.error:
3170 if rows and linecount >= rows:
3173 sys.stdout.write('\n')
3176 "Utter a line with no following line feed."
3177 if game.options & OPTION_CURSES:
3181 sys.stdout.write(line)
3191 if not replayfp or replayfp.closed: # Don't slow down replays
3194 if game.options & OPTION_CURSES:
3198 if not replayfp or replayfp.closed:
3202 "Get a line of input."
3203 if game.options & OPTION_CURSES:
3204 line = curwnd.getstr() + "\n"
3207 if replayfp and not replayfp.closed:
3209 line = replayfp.readline()
3212 prout("*** Replay finished")
3215 elif line[0] != "#":
3218 line = raw_input() + "\n"
3224 "Change windows -- OK for this to be a no-op in tty mode."
3226 if game.options & OPTION_CURSES:
3228 curses.curs_set(wnd == fullscreen_window or wnd == message_window or wnd == prompt_window)
3231 "Clear to end of line -- can be a no-op in tty mode"
3232 if game.options & OPTION_CURSES:
3237 "Clear screen -- can be a no-op in tty mode."
3239 if game.options & OPTION_CURSES:
3245 def textcolor(color=DEFAULT):
3246 if game.options & OPTION_COLOR:
3247 if color == DEFAULT:
3249 elif color == BLACK:
3250 curwnd.attron(curses.color_pair(curses.COLOR_BLACK));
3252 curwnd.attron(curses.color_pair(curses.COLOR_BLUE));
3253 elif color == GREEN:
3254 curwnd.attron(curses.color_pair(curses.COLOR_GREEN));
3256 curwnd.attron(curses.color_pair(curses.COLOR_CYAN));
3258 curwnd.attron(curses.color_pair(curses.COLOR_RED));
3259 elif color == MAGENTA:
3260 curwnd.attron(curses.color_pair(curses.COLOR_MAGENTA));
3261 elif color == BROWN:
3262 curwnd.attron(curses.color_pair(curses.COLOR_YELLOW));
3263 elif color == LIGHTGRAY:
3264 curwnd.attron(curses.color_pair(curses.COLOR_WHITE));
3265 elif color == DARKGRAY:
3266 curwnd.attron(curses.color_pair(curses.COLOR_BLACK) | curses.A_BOLD);
3267 elif color == LIGHTBLUE:
3268 curwnd.attron(curses.color_pair(curses.COLOR_BLUE) | curses.A_BOLD);
3269 elif color == LIGHTGREEN:
3270 curwnd.attron(curses.color_pair(curses.COLOR_GREEN) | curses.A_BOLD);
3271 elif color == LIGHTCYAN:
3272 curwnd.attron(curses.color_pair(curses.COLOR_CYAN) | curses.A_BOLD);
3273 elif color == LIGHTRED:
3274 curwnd.attron(curses.color_pair(curses.COLOR_RED) | curses.A_BOLD);
3275 elif color == LIGHTMAGENTA:
3276 curwnd.attron(curses.color_pair(curses.COLOR_MAGENTA) | curses.A_BOLD);
3277 elif color == YELLOW:
3278 curwnd.attron(curses.color_pair(curses.COLOR_YELLOW) | curses.A_BOLD);
3279 elif color == WHITE:
3280 curwnd.attron(curses.color_pair(curses.COLOR_WHITE) | curses.A_BOLD);
3283 if game.options & OPTION_COLOR:
3284 curwnd.attron(curses.A_REVERSE)
3287 # Things past this point have policy implications.
3291 "Hook to be called after moving to redraw maps."
3292 if game.options & OPTION_CURSES:
3295 setwnd(srscan_window)
3299 setwnd(status_window)
3300 status_window.clear()
3301 status_window.move(0, 0)
3302 setwnd(report_window)
3303 report_window.clear()
3304 report_window.move(0, 0)
3306 setwnd(lrscan_window)
3307 lrscan_window.clear()
3308 lrscan_window.move(0, 0)
3309 lrscan(silent=False)
3311 def put_srscan_sym(w, sym):
3312 "Emit symbol for short-range scan."
3313 srscan_window.move(w.i+1, w.j*2+2)
3314 srscan_window.addch(sym)
3315 srscan_window.refresh()
3318 "Enemy fall down, go boom."
3319 if game.options & OPTION_CURSES:
3321 setwnd(srscan_window)
3322 srscan_window.attron(curses.A_REVERSE)
3323 put_srscan_sym(w, game.quad[w.i][w.j])
3327 srscan_window.attroff(curses.A_REVERSE)
3328 put_srscan_sym(w, game.quad[w.i][w.j])
3329 curses.delay_output(500)
3330 setwnd(message_window)