import re as regexp
import random
import curses
+import termios
from optparse import OptionParser
from BeautifulSoup import BeautifulSoup
if opts.debug > 0:
print >>opts.debug_file, m
-def sleep(seconds):
+def debug_flush():
if opts.debug > 0:
- opts.debug_file.flush()
+ opts.debug_file.flush()
+
+def sleep(seconds):
+ debug_flush()
time.sleep(seconds)
def format_time_interval(ti):
ages.append(age)
return ages
- def need_wait(self, now):
+ def need_wait(self, now, imaginary=[]):
ages = self._cache_scan(now)
+ ages += imaginary
ages.sort()
debug('Fetcher ages ' + `ages`)
min_age = 1
skl.msg('puzzle "%s" no standing found' % puzzle)
continue
standing = sl[0]
- for i in range(0, len(standingvals)-1):
+ for i in range(0, len(standingvals)):
if standing == standingvals[i]:
self.standings[puzzle] = i
if not puzzle in self.standings:
pa.pi = None
def pirate_info(pa):
- if not pa.pi and not fetcher.need_wait(time.time()):
- pa.pi = PirateInfo(pa.name, 3600)
+ now = time.time()
+ if pa.pi:
+ age = now - pa.pi_fetched
+ guide = random.randint(120,240)
+ if age <= guide:
+ return pa.pi
+ debug('PirateAboard refresh %d > %d %s' % (
+ age, guide, pa.name))
+ imaginary = [2,6]
+ else:
+ imaginary = [1]
+ wait = fetcher.need_wait(now, imaginary)
+ if wait:
+ debug('PirateAboard fetcher not ready %d' % wait)
+ return pa.pi
+ pa.pi = PirateInfo(pa.name, 600)
+ pa.pi_fetched = now
return pa.pi
class ChatLogTracker:
self._progress = [0, os.fstat(self._f.fileno()).st_size]
self._disembark_myself()
self._need_redisplay = False
+ self._lastvessel = None
def _disembark_myself(self):
self._v = None
if pattern is None:
pattern_check = lambda vn: True
else:
- re = '(?:.* )?%s$' % pattern.lower().replace('*','.*')
+ re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
pattern_check = regexp.compile(re, regexp.I).match
tries = []
del v[pirate]
del self._pl[pirate]
+ def disembark_me(why):
+ self._disembark_myself()
+ return d('disembark-me '+why)
+
m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
if m:
dm = ['boarding']
pn = self._myself.name
vn = m.group(1)
v = self._vessel_lookup(vn, timestamp, dm, create=True)
- self._vessel = vn
+ self._lastvessel = self._vessel = vn
self._v = v
ob_x(pn, 'we boarded')
self.expire_garbage(timestamp)
if m: return chat_metacmd('officer')
m = rm('Ye accepted the offer to job with ')
- if m:
- self._disembark_myself()
- return d('taking-job')
+ if m: return disembark_me('jobbing')
+
+ m = rm('Ye hop on the ferry and are whisked away ')
+ if m: return disembark_me('ferry')
+
+ m = rm('Whisking away to yer home on the magical winds')
+ if m: return disembark_me('home')
m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
if m:
pl = m.group(1).split(', ')
if not self._myself.name in pl:
- return d('lost boarding battle')
+ return d('lost melee')
for pn in pl:
if ' ' in pn: continue
- ob_x(pn,'won boarding battle')
- return d('won boarding battle')
+ ob_x(pn,'won melee')
+ return d('won melee')
m = rm('(\\w+) is eliminated\\!')
if m: return ob1('eliminated in fray');
+ m = rm('(\\w+) has driven \w+ from the ship\\!')
+ if m: return ob1('boarder repelled');
+
+ m = rm('\w+ has bested (\\w+), and turns'+
+ ' to the rest of the ship\\.')
+ if m: return ob1('boarder unrepelled');
+
m = rm('(\\w+) has left the vessel\.')
if m:
pirate = m.group(1)
def myname(self):
# returns our pirate name
return self._myself.name
- def vessel(self):
- # returns the vessel we're aboard or None
+ def vesselname(self):
+ # returns the vessel name we're aboard or None
return self._vessel
- def aboard(self):
- # returns a list of PirateAboard sorted by name
- if self._v is None: return []
- return [ self._v[pn]
- for pn in sorted(self._v.keys())
+ def lastvesselname(self):
+ # returns the last vessel name we were aboard or None
+ return self._lastvessel
+ def aboard(self, vesselname=True):
+ # returns a list of PirateAboard the vessel
+ # sorted by pirate name
+ # you can pass this None and you'll get []
+ # or True for the current vessel (which is the default)
+ if vesselname is True: v = self._v
+ else: v = self._vl.get(vesselname.title())
+ if v is None: return []
+ return [ v[pn]
+ for pn in sorted(v.keys())
if not pn.startswith('#') ]
#---------- implementations of actual operation modes ----------
if not match: bu('chat log filename is not in expected format')
(pirate, ocean) = match.groups()
fetcher.default_ocean(ocean)
-
- myself = PirateInfo(pirate,max_myself_age)
+
progress.show_init(pirate, fetcher.ocean)
+ myself = PirateInfo(pirate,max_myself_age)
track = ChatLogTracker(myself, logfn)
opts.debug -= 2
if opts.ship_duty is None: opts.ship_duty = True
displayer = globals()['Display_'+opts.display]()
- rotate_nya = '/-\\'
(myself, track) = prep_chat_log(args, bu, progress=displayer)
+ displayer.realstart()
+
+ if os.isatty(0): kr_create = KeystrokeReader
+ else: kr_create = DummyKeystrokeReader
+
+ try:
+ kreader = kr_create(0, 10)
+ ship_aid_core(myself, track, displayer, kreader)
+ finally:
+ kreader.stop()
+ print '\n'
+
+def ship_aid_core(myself, track, displayer, kreader):
+
+ def find_vessel():
+ vn = track.vesselname()
+ if vn: return (vn, " on board the %s" % vn)
+ vn = track.lastvesselname()
+ if vn: return (vn, " ashore from the %s" % vn)
+ return (None, " not on a vessel")
+
def timeevent(t,e):
if t is None: return ' ' * 22
return " %-4s %-16s" % (format_time_interval(now - t),e)
- displayer.realstart()
+ displayer.show(track.myname() + find_vessel()[1] + '...')
+
+ rotate_nya = '/-\\'
while True:
track.catchup()
now = time.time()
- s = "%s" % track.myname()
-
- vn = track.vessel()
- if vn is None: s += " not on a vessel"
- else: s += " on board the %s" % vn
- s += " at %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")
+ (vn, s) = find_vessel()
+ s = track.myname() + s
+ s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
+ s += kreader.info()
+ s += '\n'
tbl = StandingsTable()
tbl.headings()
- for pa in track.aboard():
+ aboard = track.aboard(vn)
+
+ for pa in aboard:
pi = pa.pirate_info()
xs = ''
tbl.pirate(pi, xs)
s += tbl.results()
-
displayer.show(s)
- sleep(1)
- rotate_nya = rotate_nya[1:3] + rotate_nya[0]
+
+ k = kreader.getch()
+ if k is None:
+ rotate_nya = rotate_nya[1:3] + rotate_nya[0]
+ continue
+
+ if k == 'q':
+ break
+
+#---------- individual keystroke input ----------
+
+class DummyKeystrokeReader:
+ def __init__(self,fd,timeout_dummy): pass
+ def stop(self): pass
+ def getch(self): sleep(1); return None
+ def info(self): return ' [noninteractive]'
+
+class KeystrokeReader(DummyKeystrokeReader):
+ def __init__(self, fd, timeout_decisec=0):
+ self._fd = fd
+ self._saved = termios.tcgetattr(fd)
+ a = termios.tcgetattr(fd)
+ a[3] &= ~(termios.ECHO | termios.ECHONL |
+ termios.ICANON | termios.IEXTEN)
+ a[6][termios.VMIN] = 0
+ a[6][termios.VTIME] = timeout_decisec
+ termios.tcsetattr(fd, termios.TCSANOW, a)
+ def stop(self):
+ termios.tcsetattr(self._fd, termios.TCSANOW, self._saved)
+ def getch(self):
+ debug_flush()
+ byte = os.read(self._fd, 1)
+ if not len(byte): return None
+ return byte
+ def info(self):
+ return ''
#---------- main program ----------