+ pi = PirateInfo(p, random.randint(900,1800))
+ tab.pirate(pi)
+
+def do_ocean(args, bu):
+ if (len(args)): bu('ocean takes no further arguments')
+ fetcher.default_ocean()
+ oi = OceanInfo(IslandFlagInfo)
+ print oi
+ for islename in sorted(oi.islands.keys()):
+ isle = oi.islands[islename]
+ print isle
+
+def do_embargoes(args, bu):
+ if (len(args)): bu('ocean takes no further arguments')
+ fetcher.default_ocean()
+ oi = OceanInfo(IslandFlagInfo)
+ wr = sys.stdout.write
+ print ('EMBARGOES: Island | Owning flag'+
+ ' | Embargoed flags')
+
+ def getflname(isle):
+ if isle.islandid is None: return 'uncolonisable'
+ if isle.flag is None: return 'uncolonised'
+ return isle.flag.name
+
+ progressreporter.stop()
+
+ for archname in sorted(oi.arches.keys()):
+ print 'ARCHIPELAGO: ',archname
+ for islename in sorted(oi.arches[archname].keys()):
+ isle = oi.islands[islename]
+ wr(' %-20s | ' % isle.name)
+ flname = getflname(isle)
+ wr('%-30s | ' % flname)
+ flag = isle.flag
+ if flag is None: print ''; continue
+ delim = ''
+ for rel in flag.relations:
+ if rel.this_declaring >= 0: continue
+ wr(delim)
+ wr(rel.other_flagname)
+ delim = '; '
+ print ''
+
+def do_embargoes_flag_of(args, bu):
+ progressreporter.doing('fetching flag info')
+ fi = prep_flag_of(args, bu)
+ if fi is None:
+ progressreporter.stop()
+ print 'Pirate is not in a flag.'
+ return
+
+ oi = OceanInfo(IslandFlagInfo)
+
+ progressreporter.stop()
+ print ''
+
+ any = False
+ for islename in sorted(oi.islands.keys()):
+ isle = oi.islands[islename]
+ flag = isle.flag
+ if flag is None: continue
+ for rel in flag.relations:
+ if rel.this_declaring >= 0: continue
+ if rel.other_flagid != fi.flagid: continue
+ if not any: print 'EMBARGOED:'
+ any = True
+ print " %-30s (%s)" % (islename, flag.name)
+ if not any:
+ print 'No embargoes.'
+ print ''
+
+ war_flag(fi)
+ print ''
+
+def do_war_flag_of(args, bu):
+ fi = prep_flag_of(args, bu)
+ war_flag(fi)
+
+def war_flag(fi):
+ any = False
+ for certain in [True, False]:
+ anythis = False
+ for rel in fi.relations:
+ if rel.this_declaring >= 0: continue
+ if (rel.other_declaring_max < 0) != certain: continue
+ if not anythis:
+ if certain: m = 'SINKING PvP'
+ else: m = 'RISK OF SINKING PvP'
+ print '%s (%s):' % (m, rel.yoweb_heading)
+ anythis = True
+ any = True
+ print " ", rel.other_flagname
+ if not any:
+ print 'No sinking PvP.'
+
+#----- modes which use the chat log parser are quite complex -----
+
+class ProgressPrintPercentage:
+ def __init__(self, f=sys.stdout):
+ self._f = f
+ def progress_string(self,done,total):
+ return "scan chat logs %3d%%\r" % ((done*100) / total)
+ def progress(self,*a):
+ self._f.write(self.progress_string(*a))
+ self._f.flush()
+ def show_init(self, pirate, ocean):
+ print >>self._f, 'Starting up, %s on the %s ocean' % (
+ pirate, ocean)
+ def caughtup(self):
+ self._f.write(' \r')
+ self._f.flush()
+
+def prep_chat_log(args, bu,
+ progress=ProgressPrintPercentage(),
+ max_myself_age=3600):
+ if len(args) != 1: bu('this action takes only chat log filename')
+ logfn = args[0]
+ logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
+ match = regexp.match(logfn_re, logfn)
+ if not match: bu('chat log filename is not in expected format')
+ (pirate, ocean) = match.groups()
+ fetcher.default_ocean(ocean)
+
+ progress.show_init(pirate, fetcher.ocean)
+ myself = PirateInfo(pirate,max_myself_age)
+ track = ChatLogTracker(myself, logfn)
+
+ opts.debug -= 2
+ track.catchup(progress)
+ opts.debug += 2
+
+ track.force_redisplay()
+
+ return (myself, track)
+
+def do_track_chat_log(args, bu):
+ (myself, track) = prep_chat_log(args, bu)
+ while True:
+ track.catchup()
+ if track.changed():
+ print track
+ sleep(0.5 + 0.5 * random.random())
+
+#----- ship management aid -----
+
+class Display_dumb(ProgressPrintPercentage):
+ def __init__(self):
+ ProgressPrintPercentage.__init__(self)
+ def show(self, s):
+ print '\n\n', s;
+ def realstart(self):
+ pass
+
+class Display_overwrite(ProgressPrintPercentage):
+ def __init__(self):
+ ProgressPrintPercentage.__init__(self)
+
+ null = file('/dev/null','w')
+ curses.setupterm(fd=null.fileno())
+
+ self._clear = curses.tigetstr('clear')
+ if not self._clear:
+ self._debug('missing clear!')
+ self.show = Display_dumb.show
+ return
+
+ self._t = {'el':'', 'ed':''}
+ if not self._init_sophisticated():
+ for k in self._t.keys(): self._t[k] = ''
+ self._t['ho'] = self._clear
+
+ def _debug(self,m): debug('display overwrite: '+m)
+
+ def _init_sophisticated(self):
+ for k in self._t.keys():
+ s = curses.tigetstr(k)
+ self._t[k] = s
+ self._t['ho'] = curses.tigetstr('ho')
+ if not self._t['ho']:
+ cup = curses.tigetstr('cup')
+ self._t['ho'] = curses.tparm(cup,0,0)
+ missing = [k for k in self._t.keys() if not self._t[k]]
+ if missing:
+ self.debug('missing '+(' '.join(missing)))
+ return 0
+ return 1
+
+ def show(self, s):
+ w = sys.stdout.write
+ def wti(k): w(self._t[k])
+
+ wti('ho')
+ nl = ''
+ for l in s.rstrip().split('\n'):
+ w(nl)
+ w(l)
+ wti('el')
+ nl = '\r\n'
+ wti('ed')
+ w(' ')
+ sys.stdout.flush()
+
+ def realstart(self):
+ sys.stdout.write(self._clear)
+ sys.stdout.flush()
+
+
+def do_ship_aid(args, bu):
+ if opts.ship_duty is None: opts.ship_duty = True
+
+ displayer = globals()['Display_'+opts.display]()
+
+ (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'
+
+class KeyBasedSorter:
+ def compar_key_pa(self, pa):
+ pi = pa.pirate_info()
+ if pi is None: return None
+ return self.compar_key(pi)
+ def lsort_pa(self, l):
+ l.sort(key = self.compar_key_pa)
+
+class NameSorter(KeyBasedSorter):
+ def compar_key(self, pi): return pi.name
+ def desc(self): return 'name'
+
+class SkillSorter(NameSorter):
+ def __init__(self, relevant):
+ self._want = frozenset(relevant.split('/'))
+ self._avoid = set()
+ for p in core_duty_puzzles:
+ if isinstance(p,basestring): self._avoid.add(p)
+ else: self._avoid |= set(p)
+ self._avoid -= self._want
+ self._desc = '%s' % relevant
+
+ def desc(self): return self._desc
+
+ def compar_key(self, pi):
+ best_want = max([
+ pi.standings.get(puz,-1)
+ for puz in self._want
+ ])
+ best_avoid = [
+ -pi.standings.get(puz,standing_limit)
+ for puz in self._avoid
+ ]
+ best_avoid.sort()
+ def negate(x): return -x
+ debug('compar_key %s bw=%s ba=%s' % (pi.name, `best_want`,
+ `best_avoid`))
+ return (-best_want, map(negate, best_avoid), pi.name)
+
+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.show(track.myname() + find_vessel()[1] + '...')
+
+ rotate_nya = '/-\\'
+
+ sort = NameSorter()
+ clicmd = None
+ clierr = None
+ cliexec = None
+
+ while True:
+ track.catchup()
+ now = time.time()
+
+ (vn, vs) = find_vessel()
+
+ s = ''
+ if cliexec is not None:
+ s += '...'
+ elif clierr is not None:
+ s += 'Error: '+clierr
+ elif clicmd is not None:
+ s += '/' + clicmd
+ else:
+ s = track.myname() + vs
+ s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
+ s += kreader.info()
+ s += '\n'
+
+ tbl_s = StringIO()
+ tbl = StandingsTable(tbl_s)
+
+ aboard = track.aboard(vn)
+ sort.lsort_pa(aboard)
+
+ jobbers = track.jobbers()
+
+ if track.vesselname(): howmany = 'aboard: %2d' % len(aboard)
+ else: howmany = ''
+
+ tbl.headings(howmany, ' sorted by '+sort.desc())
+
+ last_jobber = None
+
+ for pa in aboard + jobbers:
+ if pa.jobber != last_jobber:
+ last_jobber = pa.jobber
+ tbl.literalline('')
+ tbl.literalline('jobbers '+last_jobber)
+
+ pi = pa.pirate_info()
+
+ xs = ''
+ if pa.gunner: xs += 'G '
+ else: xs += ' '
+ xs += timeevent(pa.last_time, pa.last_event)
+ xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
+
+ if pi is None:
+ tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
+ else:
+ tbl.pirate(pi, xs)
+
+ s += tbl_s.getvalue()
+ displayer.show(s)
+ tbl_s.close()
+
+ if cliexec is not None:
+ clierr = track.local_command("/"+cliexec.strip())
+ cliexec = None
+ continue
+
+ k = kreader.getch()
+ if k is None:
+ rotate_nya = rotate_nya[1:3] + rotate_nya[0]
+ continue
+
+ if clierr is not None:
+ clierr = None
+ continue
+
+ if clicmd is not None:
+ if k == '\r' or k == '\n':
+ cliexec = clicmd
+ clicmd = clicmdbase
+ elif k == '\e' and clicmd != "":
+ clicmd = clicmdbase
+ elif k == '\33':
+ clicmd = None
+ elif k == '\b' or k == '\177':
+ clicmd = clicmd[ 0 : len(clicmd)-1 ]
+ else:
+ clicmd += k
+ continue
+
+ if k == 'q': break
+ elif k == 'g': sort = SkillSorter('Gunning')
+ elif k == 'c': sort = SkillSorter('Carpentry')
+ elif k == 's': sort = SkillSorter('Sailing/Rigging')
+ elif k == 'b': sort = SkillSorter('Bilging')
+ elif k == 'n': sort = SkillSorter('Navigating')
+ elif k == 'd': sort = SkillSorter('Battle Navigation')
+ elif k == 't': sort = SkillSorter('Treasure Haul')
+ elif k == 'a': sort = NameSorter()
+ elif k == '/': clicmdbase = ""; clicmd = clicmdbase
+ elif k == '+': clicmdbase = "a "; clicmd = clicmdbase
+ else: pass # unknown key command
+
+#---------- 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 ----------