Files
pfQuest_xpGuide/tools/build_vanillaguide.py
pfQuest xpGuideandClaude Sonnet 5.5 ef2f4f34b3 pfQuest xpGuide 1.0.0
A leveling guide for WoW 1.12 players of pfQuest, based on Easy Route by stealthzi (MIT).
See README.md and CHANGES.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XfR1apt9f3R7SxBKB2FF2D
2026-11-16 14:47:43 +08:00

584 lines
30 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Converts VanillaGuide's guides (Joana's and Brian Kopps' guides, in VanillaGuide's English GuideTables) into
pfQuest xpGuide's guide format.
Usage: python3 build_vanillaguide.py <VanillaGuide/en folder> <pfQuest_xpGuide folder> <output Data/VanillaGuide.lua>
Each guide item ({ str = "...", x =, y =, zone = }) becomes one step, in the guide's own words. Its tags:
#GETname# accept (A) #INname# hand in (T) #DOname# do the quest (C)
#NPCname# a person #ITEMname# an item #COORD[x,y]# a place in the words
#VIDEOname# a quest the guide says to skip (words only)
The item's x, y and zone are the step's place (the arrow). Quests are named, not numbered, in the guides: each name is
matched against the addon's own quest data (Data/Zones.lua, Data/Guides.lua): same faction, then the part ("pt.2" is the
second quest of that name in its chain), then the zone the step is in, then the level nearest the guide's. A name that
matches nothing stays in the words only.
"""
import difflib
import os
import re
import sys
ALLIANCE_RACES, HORDE_RACES = 1 | 4 | 8 | 64 | 512, 2 | 16 | 32 | 128 | 256
START = {"002_Teldrassil": "NightElf", "002_ElwynnForest": "Human", "002_DunMorogh": "Dwarf/Gnome",
"002_Durotar": "Orc/Troll", "002_Mulgore": "Tauren", "002_TirisfalGlades": "Scourge"}
def norm(s):
s = s.replace("\u2019", "'").replace("`", "'").lower()
s = re.sub(r"[^a-z0-9' ]+", " ", s)
return re.sub(r"\s+", " ", s).strip()
def load_quests(addon):
"""id -> { n, l, p, r, zone } from the addon's own data."""
quests = {}
z = open(os.path.join(addon, "Data", "Zones.lua"), encoding="utf-8").read()
for zm in re.finditer(r'\[\d+\] = \{ name = "([^"]+)", q = \{(.*?)\n \} ?\},?', z, re.S):
zone = zm.group(1)
for qm in re.finditer(r"\{ id = (\d+), n = \"((?:[^\"\\]|\\.)*)\"([^\n]*)", zm.group(2)):
qid, name, rest = int(qm.group(1)), qm.group(2).replace('\\"', '"'), qm.group(3)
def num(k):
m = re.search(r"\b%s = (-?\d+)" % k, rest)
return int(m.group(1)) if m else None
def flt(k):
m = re.search(r"\b%s = (-?[\d.]+)" % k, rest)
return float(m.group(1)) if m else None
quests[qid] = {"n": name, "l": num("l") or 0, "p": num("p"), "r": num("r"), "c": num("c"), "zone": zone,
"x": flt("x"), "y": flt("y")}
g = open(os.path.join(addon, "Data", "Guides.lua"), encoding="utf-8").read()
i = g.find("pfQuest_xpGuide_GuideQuests")
for m in re.finditer(r'\[(\d+)\] = "((?:[^"\\]|\\.)*)"', g[i:] if i >= 0 else ""):
qid = int(m.group(1))
if qid not in quests:
quests[qid] = {"n": m.group(2).replace('\\"', '"'), "l": 0, "p": None, "r": None, "zone": ""}
return quests
class Resolver:
def __init__(self, quests):
self.quests = quests
self.byname = {}
for qid, q in quests.items():
self.byname.setdefault(norm(q["n"]), []).append(qid)
self.hits = self.misses = 0
self.missed = {}
def faction_ok(self, qid, faction):
r = self.quests[qid]["r"]
if not r:
return True
return bool(r & (ALLIANCE_RACES if faction == "Alliance" else HORDE_RACES))
def depth(self, qid):
d, seen = 0, set()
while self.quests.get(qid, {}).get("p") and qid not in seen and d < 30:
seen.add(qid)
qid = self.quests[qid]["p"]
d += 1
return d
def find(self, raw, faction, zone, lo, hi):
name = raw.strip()
# the guides' own extras: "(escort)", "(complete)", " elite", a trailing full stop, a stray "QUEAT"
name = re.sub(r"^QUEAT", "", name)
name = re.sub(r"\s*\((?:escort|complete|completed|elite|group)\)\s*$", "", name, flags=re.I)
name = re.sub(r"\s+elite$", "", name, flags=re.I)
name = name.rstrip(" .")
part = None
m = re.match(r"^(.*?)\s*\(?\s*(?:pt\.?|part)\s*(\d+)\s*\)?$", name, re.I)
if m:
name, part = m.group(1).strip(), int(m.group(2))
cands = self.byname.get(norm(name), [])
if not cands and norm(name).startswith("the "):
cands = self.byname.get(norm(name)[4:], [])
if not cands:
cands = self.byname.get("the " + norm(name), [])
cands = [c for c in cands if self.faction_ok(c, faction)]
if not cands and norm(name):
# a close name ("Fuel for Zapping" / "Fuel for the Zapping"), or the data's name going on ("Reclaimers' Business"
# / "Reclaimers' Business in Desolace"); only among quests of this faction
names = [k for k, ids in self.byname.items() if any(self.faction_ok(c, faction) for c in ids)]
want = norm(name)
longer = [k for k in names if k.startswith(want + " ") and len(want) >= 12]
close = longer or difflib.get_close_matches(want, names, n=1, cutoff=0.88)
if close:
cands = [c for c in self.byname[close[0]] if self.faction_ok(c, faction)]
if not cands:
self.misses += 1
self.missed[raw] = self.missed.get(raw, 0) + 1
return None
self.hits += 1
if len(cands) == 1:
return cands[0]
if part:
# the parts of a chain: quests of this name linked to each other (one's prerequisite is another), in chain order;
# a same-named quest outside the chain comes after them
cs = set(cands)
def linked(c):
q = self.quests[c]
return (q["p"] in cs) or any(self.quests[o]["p"] == c for o in cs)
ordered = sorted(cands, key=lambda c: (0 if linked(c) else 1, self.depth(c), self.quests[c]["l"], c))
# one quest per part: the same chain's quests in order (drop exact duplicates of a part)
return ordered[min(part, len(ordered)) - 1]
mid = (lo + hi) / 2.0
def score(c):
q = self.quests[c]
return (0 if zone and q["zone"] == zone else 1, abs((q["l"] or mid) - mid), c)
return sorted(cands, key=score)[0]
CLASS_BITS = [(1, "Warrior"), (2, "Paladin"), (4, "Hunter"), (8, "Rogue"), (16, "Priest"), (64, "Shaman"),
(128, "Mage"), (256, "Warlock"), (1024, "Druid")]
def class_cond(quests, qid):
"""A class quest ("Etched Sigil" is the Hunter's): the element is only for those classes ("Hunter/Druid")."""
c = quests.get(qid, {}).get("c")
if not c:
return ""
names = [n for bit, n in CLASS_BITS if c & bit]
return "/".join(names) if 0 < len(names) < len(CLASS_BITS) else ""
def lua_str(s):
return s.replace("\\'", "'")
def esc(s):
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t")
TURN_IN = re.compile(r"\b(turn|hand)\s+(it|them|both|these|those|all|that|em)\s+in\b", re.I)
LATER = re.compile(r"when you get the chance|next time|later|\\byet\\b", re.I)
COORD = re.compile(r"#COORD\[\s*([\d.]+)\s*,\s*([\d.]+)\s*\]#")
TAG = re.compile(r"#(GET|IN|DO)([^#]*)#")
# "... accept A at (58,42), then run up the ramp and hand it in at (59,39). Accept B": the line is two stops, not one
MOVE = re.compile(r"(?:[,.;]\s*|\s+)(?:and\s+)?then\s+(?=(?:go|run|head|walk|fly|ride|travel|return|hearth|take)\b)", re.I)
IT_IN = re.compile(r"\b(?:turn|hand)\s+it\s+in\b", re.I)
def split_stops_moves(s):
"""One line of the guide that holds several stops (the quests are handed in and taken at one place, then "then run ... and
hand it in" somewhere else) becomes one step per stop. Only when the first stop is plain turning in / accepting (a "do X, then
run back and turn it in" line stays whole: its hand-in step is made further down) and the next stop has quests of its own.
"hand it in" there is the quest accepted just before, so it is written out by name."""
out, rest = [], s
while True:
cut = None
for m in MOVE.finditer(rest):
before, after = rest[:m.start()], rest[m.end():]
bt = TAG.findall(before)
if not bt or any(k == "DO" for k, _ in bt):
continue
gets = [n for k, n in bt if k == "GET"]
if IT_IN.search(after) and gets and not any(k == "IN" and n == gets[-1] for k, n in TAG.findall(after)):
after = IT_IN.sub("turn in #IN%s#" % gets[-1], after, 1)
if not TAG.search(after):
continue
cut = (before, after)
break
if not cut:
out.append(rest)
return out
out.append(cut[0].rstrip(" ,;"))
rest = cut[1][:1].upper() + cut[1][1:]
ACCEPT_NEXT = re.compile(r"[.,;]?\s*(?:and\s+)?(?=accept\s+(?:the\s+)?#GET)", re.I)
def split_stops(s):
"""Then, at a later stop, what is taken after a hand-in is a step of its own (it can only be taken once the hand-in is done):
each part is (text, same_place) - same_place when it stands where the part before it does."""
parts = split_stops_moves(s)
out = []
for i, p in enumerate(parts):
out.append((p, False))
if i:
m = next((m for m in ACCEPT_NEXT.finditer(p) if m.start() > 0 and any(k == "IN" for k, _ in TAG.findall(p[:m.start()]))), None)
if m:
head, tail = p[:m.start()].rstrip(" ,;"), p[m.end():]
out[-1] = (head, False)
out.append((tail[:1].upper() + tail[1:], True))
return out
# ---- a step as a short action line and a tip ------------------------------------------------------------------------------
# The list shows the step's first quest line ("Accept X", "Hand in Y", "Finish Z"); the guide's own sentence under it is a tip.
# A clause that only says what those lines already say ("Turn in X at (59, 44) and accept Y") is dropped from the tip, so what is
# left is advice. A step with no quest of its own gets a short title made from the first clause of its words.
NPC_TAG = re.compile(r"#NPC([^#]*)#")
ANY_TAG = re.compile(r"#(?:GET|IN|DO|COORD\[[^\]]*\]|NPC[^#]*|ITEM[^#]*|VIDEO[^#]*)#")
PLAIN = set("""accept accepted get pick up grab take turn hand in it them the and then from at to go run back head over quest quests
next part do finish complete now also new your on with talk speak see near by just there here both for of a an you will can
should please first again again also all these those that this is are""".split())
CLAUSE = re.compile(r"(?<=[.!;])\s+|,?\s+then\s+", re.I)
FILL = PLAIN | set("""go run head walk travel west east north south nw ne sw se northwest northeast southwest southeast up down into
inside outside towards toward around over there here now out off is are will be ready done etc when once after before""".split())
# "turn in <quest> and <quest> at <npc>", "accept <quest>", "do <quest>": what the step's own quest lines already say
ACT = re.compile(r"\b(?:turn(?:\s+it)?\s+in|hand(?:\s+it)?\s+in|turn|accept(?:\s+the\s+quest)?|get|pick\s+up|grab|take)\b[:\s]*"
r"(?:(?:#(?:GET|IN)[^#]*#|\s|,|and|&)+)(?:\s*(?:at|from|to|with)\s*(?:#NPC[^#]*#|#COORD[^#]*#))?", re.I)
def strip_clause(c, spot):
"""(what is left of a clause once its quest actions and its spot are taken out, the npcs it named)"""
npcs = []
def act(m):
npcs.extend(NPC_TAG.findall(m.group(0)))
return " "
c2 = ACT.sub(act, c)
# further quests in the same clause ("... and <B> at (61, 42)")
c2 = re.sub(r"#(?:GET|IN)[^#]*#(?:\s*(?:at|from|to)\s*(?:#NPC[^#]*#|#COORD[^#]*#))?", lambda m: act(m) or " ", c2)
def near(m):
if spot is None:
return m.group(0)
return " " if abs(float(m.group(1)) - spot[0]) <= 1.5 and abs(float(m.group(2)) - spot[1]) <= 1.5 else m.group(0)
c2 = re.sub(r"#COORD\[\s*([\d.]+)\s*,\s*([\d.]+)\s*\]#", near, c2)
c2 = re.sub(r"\(\s*\)", " ", c2)
c2 = re.sub(r"\s+(?:at|to|from|in|and|then|,)\s*(?=[,.]|$)", " ", re.sub(r"\s+", " ", c2)).strip(" ,.;")
c2 = re.sub(r"^(?:and|then|,)\s+", "", c2, flags=re.I)
return c2, npcs
def tidy_tip(s, spot):
"""The step's words without what its quest lines already say; "" when nothing is left."""
if re.search(r"#DO", s):
return s # a quest to do: the words say where and how, and the arrow takes its spot from them
clauses, pos, keep, talk = [], 0, [], []
has_tag = bool(re.search(r"#(?:GET|IN)", s))
for m in CLAUSE.finditer(s):
clauses.append(s[pos:m.start()])
pos = m.end()
clauses.append(s[pos:])
for c in clauses:
if has_tag and not re.search(r"#", c) and len(re.findall(r"[A-Za-z']+", c)) < 2:
continue # "I" of "I then go turn in ...", cut at "then"
rest, npcs = strip_clause(c, spot)
plain = ANY_TAG.sub(" ", rest)
toks = re.findall(r"[A-Za-z']+", plain.lower())
if (re.search(r"#(?:GET|IN)", c) or (has_tag and not re.search(r"#", c))) and (not rest or (all(w in FILL for w in toks) and not re.search(r"#COORD", rest))):
talk.extend(npcs)
continue
# a clause with advice in it stays as the guide wrote it
keep.append(c.strip())
if talk and not keep:
keep.append("Talk to " + " and ".join("#NPC%s#" % n for n in dict.fromkeys(talk)) + ".")
out = " ".join(keep)
return out[:1].upper() + out[1:] if out else ""
def short_title(s):
"""A step with nothing to accept, do or hand in: its first clause, plain and short."""
def plain(x):
x = re.sub(r"\s*(?:\b(?:at|around|near|to|in)\b)?\s*#COORD\[[^\]]*\]#", " ", x)
x = re.sub(r"#(?:GET|IN|DO|NPC|ITEM|VIDEO)([^#]*)#", lambda m: m.group(1).strip("[]"), x)
x = re.sub(r"\s+", " ", x.replace("#", "")).strip(" ,.:")
x = re.sub(r"^(?:then|and)\s+", "", x, flags=re.I)
x = re.sub(r"\s+(?:at|around|near|to|for|and)\s*$", "", x).strip(" ,.:")
return x.replace(";", ",").replace("=", "-")
first = plain(re.split(r"(?<=[.!;])\s+|,?\s+then\s+", s.strip())[0])
if len(first.split()) < 3:
first = plain(s)
if len(first) > 64:
first = first[:64].rsplit(" ", 1)[0].rstrip(" ,.:") + "..."
return first[:1].upper() + first[1:]
def clean(s):
return s.replace("\t", " ").strip()
NPC, ITEM, QUEST, SKIPQ, PLACE = "|cff00ff25", "|cfffca742", "|cffffd100", "|cffff6060", "|cffbbbbbb"
def words(text):
text = re.sub(r"#COORD\[\s*([\d.]+)\s*,\s*([\d.]+)\s*\]#", lambda m: PLACE + "(" + m.group(1) + ", " + m.group(2) + ")|r", text)
text = re.sub(r"#NPC([^#]*)#", lambda m: NPC + m.group(1) + "|r", text)
text = re.sub(r"#ITEM([^#]*)#", lambda m: ITEM + m.group(1) + "|r", text)
text = re.sub(r"#VIDEO([^#]*)#", lambda m: SKIPQ + m.group(1) + "|r", text)
text = re.sub(r"#(?:GET|IN|DO)([^#]*)#", lambda m: QUEST + m.group(1) + "|r", text)
text = text.replace("#", "")
return clean(re.sub(r"\s+", " ", text))
def parse_file(path):
t = open(path, encoding="utf-8", errors="replace").read()
out = []
for sm in re.finditer(r"\[(\d+)\] = \{\s*title = \"([^\"]*)\",(.*?)\n\t\},", t, re.S):
key, title, body = int(sm.group(1)), sm.group(2), sm.group(3)
items = []
for im in re.finditer(r"^[ \t]*\[(\d+)\] = \{ str = \"((?:[^\"\\]|\\.)*)\"(.*?)\},?\s*$", body, re.M):
s, rest = lua_str(im.group(2)), im.group(3)
x = re.search(r"\bx = ([\d.]+)", rest)
y = re.search(r"\by = ([\d.]+)", rest)
z = re.search(r'zone = "([^"]*)"', rest)
items.append((int(im.group(1)), s, float(x.group(1)) if x else None, float(y.group(1)) if y else None,
z.group(1) if z else None))
items.sort()
out.append((key, title, items))
out.sort()
return out
ZONE_ALIAS = {"iron forge": "Ironforge", "stormwind": "Stormwind City", "undercity": "Undercity",
"thunderbluff": "Thunder Bluff", "orgrimar": "Orgrimmar", "stranglethorn": "Stranglethorn Vale",
"hillsbrad": "Hillsbrad Foothills", "the hinterlands": "The Hinterlands", "hinterlands": "The Hinterlands",
"un'goro": "Un'Goro Crater", "ungoro": "Un'Goro Crater", "tarren mill": "Hillsbrad Foothills"}
def zone_names(addon):
"""The game's zone names, as the addon knows them (Data/ZoneSizes.lua)."""
t = open(os.path.join(addon, "Data", "ZoneSizes.lua"), encoding="utf-8").read()
return {norm(n): n for n in re.findall(r'\["([^"]+)"\]\s*=', t)}
def fix_zone(z, names):
""""Iron Forge" -> "Ironforge", "darnassus" -> "Darnassus", "Un’Goro Crater" -> "Un'Goro Crater"."""
if not z:
return z
k = norm(z)
if k in names:
return names[k]
if k in ZONE_ALIAS:
return ZONE_ALIAS[k]
close = difflib.get_close_matches(k, list(names), n=1, cutoff=0.85)
return names[close[0]] if close else z
def objective_places(addon):
"""quest id -> (zone, x, y): RestedXP's place for its objectives (the last place before its first C line)."""
g = open(os.path.join(addon, "Data", "Guides.lua"), encoding="utf-8").read()
out = {}
for m in re.finditer(r'steps = "((?:[^"\\]|\\.)*)"', g):
last = None
for line in m.group(1).split("\\n"):
f = line.split("\\t")
if f[0] == "S":
last = None
elif f[0] == "G" and len(f) > 4:
try:
last = (f[2], float(f[3]), float(f[4]))
except ValueError:
pass
elif f[0] == "C" and last and len(f) > 2 and f[2].isdigit():
out.setdefault(int(f[2]), last)
return out
def main():
src, addon, dest = sys.argv[1], sys.argv[2], sys.argv[3]
quests = load_quests(addon)
objplace = objective_places(addon)
added = {"objective steps": 0, "hand-ins": 0}
split_count = [0]
tidied = {"tips": 0, "dropped": 0, "titles": 0}
res = Resolver(quests)
names = zone_names(addon)
fixes = {"zone names": 0, "zone labels": 0}
guides = []
for faction in ("Alliance", "Horde"):
folder = os.path.join(src, "GuideTables", faction)
files = sorted(os.listdir(folder))
chain = [] # sections in play order: each starting zone, then the shared 12-60 route
starts, shared = [], []
for f in files:
base = f[:-4]
for key, title, items in parse_file(os.path.join(folder, f)):
entry = (base, key, title, items)
(starts if base in START else shared).append(entry)
# what the guide has done with each quest so far (each starting zone on its own; the shared route as one)
tracks = {}
for base, key, title, items in starts + shared:
track = tracks.setdefault(base if base in START else "shared", {"accepted": {}, "did_c": set(), "did_t": set()})
m = re.match(r"(\d+)-(\d+)\s+(.+)$", title.strip())
lo, hi, zone = (int(m.group(1)), int(m.group(2)), m.group(3)) if m else (1, 60, title)
body, count, zone_now = [], 0, None
stops = []
for n, s, x, y, z in items:
# a placeholder ("." or one letter) is not a step
if not re.search(r"#(?:GET|IN|DO)", s) and len(re.sub(r"[^A-Za-z]", "", s)) < 3:
continue
parts = split_stops(s) if s.strip() != title.strip() else [(s, False)]
for k, (part, same) in enumerate(parts):
if k:
# a later stop stands where its own text says, if it says; what is taken after a hand-in stays put
cm = COORD.search(part)
if same:
stops.append((n, part, stops[-1][2], stops[-1][3], z))
else:
stops.append((n, part, float(cm.group(1)) if cm else None, float(cm.group(2)) if cm else None, z))
split_count[0] += 1
else:
stops.append((n, part, x, y, z))
for n, s, x, y, z in stops:
if s.strip() == title.strip():
continue
fz = fix_zone(z, names)
if fz != z:
fixes["zone names"] += 1
z = fz
ids, at, raw = [], [], {}
for tm in re.finditer(r"#(GET|IN|DO)([^#]*)#", s):
qid = res.find(tm.group(2), faction, z or zone_now, lo, hi)
ids.append((tm.group(1), qid))
at.append(tm.start())
if qid:
raw.setdefault(qid, tm.group(2).strip())
# "Do X ... then run back and turn it in (at 57,45)": X's hand-in is a step of its own after this one (the
# line only tags X as "do"), unless the line hands it in by name or leaves it for later
tin = TURN_IN.search(s)
handin, later_get = [], set()
if tin and not LATER.search(s[tin.start():]) and not re.search(r"\b(don.?t|do not|not)\s*$", s[:tin.start()], re.I):
for k, (tag, qid) in enumerate(ids):
if tag == "DO" and qid and at[k] < tin.start() and qid not in handin \
and not any(t2 == "IN" and q2 == qid for t2, q2 in ids):
handin.append(qid)
if len(handin) > 1:
# "go do A, B, C ... turn them in": several quests, hand-ins not one place; left as the guide has it
handin = []
if handin:
later_get = {k for k, (tag, qid) in enumerate(ids) if tag == "GET" and at[k] > tin.start()}
# a spot labelled with the wrong zone: its coordinates are where one of the step's quest givers stands,
# in another zone ("Desolace 62,36" for Gazlowe in Ratchet, The Barrens 62.7,36.2)
if z and x is not None and y is not None:
for kind, qid in ids:
q = quests.get(qid) if qid else None
if q and q.get("zone") and q["zone"] != z and q.get("x") is not None:
if abs(q["x"] - x) <= 1.5 and abs(q["y"] - y) <= 1.5:
z = q["zone"]
fixes["zone labels"] += 1
break
if z:
zone_now = z
body.append("S\t\t\tvg=1")
if x is not None and y is not None and z:
body.append("G\t\t%s\t%s\t%s\t\t\t" % (z, x, y))
# what the quest lines below already say is left out of the words; what is left is the tip
spot = (x, y) if x is not None and y is not None else None
tip = tidy_tip(s, spot) if not any(tag == "DO" for tag, _ in ids) and all(qid for _, qid in ids) else s
if tip != s:
tidied["tips"] += 1
if tip:
body.append("I\t\t%s" % words(tip))
else:
tidied["dropped"] += 1
# a quest whose follow-up this line picks up, but which the guide never had you do or hand in (the line before
# said "go do it" with no tag): a "Finish" step for it first, and its hand-in on this line, before the follow-up
pre_steps, pre_elems = [], []
for tag, qid in ids:
if tag != "GET" or not qid:
continue
prev = quests.get(qid, {}).get("p")
if not prev or prev not in track["accepted"] or prev in track["did_t"] or prev in handin:
continue
if any(t2 == "IN" and q2 == prev for t2, q2 in ids):
continue
if prev not in track["did_c"] and not any(t2 == "DO" and q2 == prev for t2, q2 in ids):
op = objplace.get(prev)
az, ax, ay = track["accepted"][prev]
if op and (not az or norm(op[0]) == norm(az)):
place = (fix_zone(op[0], names), op[1], op[2])
else:
place = (az, ax, ay) if az and ax is not None else None
pre_steps.append("S\t\t\tvg=1")
if place:
pre_steps.append("G\t\t%s\t%s\t%s\t\t\t" % place)
pre_steps.append("C\t%s\t%d\t\t" % (class_cond(quests, prev), prev))
track["did_c"].add(prev)
added["objective steps"] += 1
pre_elems.append("T\t%s\t%d\t" % (class_cond(quests, prev), prev))
track["did_t"].add(prev)
added["hand-ins"] += 1
if pre_steps:
# the new step goes before this line's step
last_s = max(i for i, l in enumerate(body) if l.startswith("S\t"))
body[last_s:last_s] = pre_steps
count += 1
body.extend(pre_elems)
step_at = len(body) - 1 - next(i for i, l in enumerate(reversed(body)) if l.startswith("S\t"))
after = []
for k, (tag, qid) in enumerate(ids):
if qid and k in later_get:
after.append((tag, qid))
continue
if qid:
if tag == "GET":
track["accepted"][qid] = (z or zone_now, x, y)
elif tag == "DO":
track["did_c"].add(qid)
else:
track["did_t"].add(qid)
kind = {"GET": "A", "IN": "T", "DO": "C"}[tag]
cc = class_cond(quests, qid)
body.append(("C\t%s\t%d\t\t" if kind == "C" else kind + "\t%s\t%d\t") % (cc, qid))
count += 1
# a step with no quest of its own is named by its first clause
if not any(l.startswith(("A\t", "T\t", "C\t")) for l in body[step_at + 1:]) and tip:
title_flag = short_title(tip)
if title_flag:
body[step_at] = body[step_at] + ";title=" + title_flag
tidied["titles"] += 1
handin = [q for q in handin if q not in track["did_t"]]
if handin:
body.append("S\t\t\tvg=1")
cm = COORD.search(s, tin.start())
if cm and (z or zone_now):
body.append("G\t\t%s\t%s\t%s\t\t\t" % (z or zone_now, cm.group(1), cm.group(2)))
for q in handin:
body.append("T\t%s\t%d\t" % (class_cond(quests, q), q))
track["did_t"].add(q)
added["hand-ins"] += 1
for tag, qid in after:
track["accepted"][qid] = (z or zone_now, x, y)
body.append("A\t%s\t%d\t" % (class_cond(quests, qid), qid))
count += 1
if not count:
continue
band = "1-20" if lo < 20 else ("20-40" if lo < 40 else "40-60")
guides.append({
"name": "%s (%s)" % (title.strip(), faction), "title": title.strip(), "group": "VanillaGuide " + band,
"faction": faction, "lo": lo, "hi": hi, "defaultFor": START.get(base, ""), "cond": faction,
"base": base, "steps": "\n".join(body), "count": count,
})
# each guide goes on to the next one of its faction; a starting zone goes on to the shared route's first guide
mine = [g for g in guides if g["faction"] == faction]
first_shared = next((g for g in mine if g["base"] not in START), None)
for i, g in enumerate(mine):
if g["base"] in START:
later = [h for h in mine[i + 1:] if h["base"] == g["base"]]
g["next"] = later[0]["name"] if later else (first_shared["name"] if first_shared else "")
else:
later = mine[i + 1:]
g["next"] = later[0]["name"] if later else ""
lines = [
"-- Generated by build_vanillaguide.py from VanillaGuide's English guides (VanillaGuide Enhanced). Do not edit by hand.",
"-- The guides are Joana's (Joana/Mancow) and Brian Kopps', as written up for the VanillaGuide addon by rsheep,",
"-- mrmr and Lanjelin. Changed from VanillaGuide's tables: one step per item, the words kept (its colour tags turned",
"-- into colours), quest names matched to quest numbers so the steps follow your quest log. No licence came with",
"-- VanillaGuide; credit as in its README.",
"pfQuest_xpGuide_Guides = pfQuest_xpGuide_Guides or {}",
"pfQuest_xpGuide_VanillaGuide = { guides = %d }" % len(guides),
"for _, g in ipairs({",
]
for g in guides:
lines.append(' { name = "%s", title = "%s", group = "%s", faction = "%s", lo = %d, hi = %d, next = "%s", defaultFor = "%s", cond = "%s", vanilla = true,'
% (esc(g["name"]), esc(g["title"]), esc(g["group"]), g["faction"], g["lo"], g["hi"], esc(g["next"]),
esc(g["defaultFor"]), esc(g["cond"])))
lines.append(' steps = "%s" },' % esc(g["steps"]))
lines.append("}) do table.insert(pfQuest_xpGuide_Guides, g) end")
open(dest, "w", encoding="utf-8").write("\n".join(lines) + "\n")
print("%d guides, %d steps; quest names matched %d, not matched %d; zone names fixed %d, zone labels fixed %d; added %d objective steps and %d hand-ins"
% (len(guides), sum(g["count"] for g in guides), res.hits, res.misses, fixes["zone names"], fixes["zone labels"],
added["objective steps"], added["hand-ins"]))
print("lines split into stops:", split_count[0], "; tips changed:", tidied["tips"], "(left out altogether:", tidied["dropped"], "); titles made:", tidied["titles"])
for g in guides[:4]:
print(" %s | %s | next: %s | for: %s | %d steps" % (g["group"], g["name"], g["next"], g["defaultFor"], g["count"]))
top = sorted(res.missed.items(), key=lambda kv: -kv[1])[:25]
print("not matched:", ", ".join("%s (%d)" % kv for kv in top))
if __name__ == "__main__":
main()