Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,16 @@ def quanah_update_item(identifier):
return jsonify(store.payload())


# FLAG is one of quanah.store.MARKS; anything else is refused there.
@app.put("/api/quanah/items/<identifier>/<flag>")
def quanah_mark_item(identifier, flag):
from quanah import store

body = request.get_json(silent=True) or {}
store.mark_item(identifier, flag, body.get(flag))
return jsonify(store.payload())


@app.delete("/api/quanah/items/<identifier>")
def quanah_delete_item(identifier):
from quanah import store
Expand Down
2 changes: 1 addition & 1 deletion src/quanah/data/lines.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"builds": [
{"key": "skill", "name": "Skill",
"targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "warrior": 1, "magician": 1, "bowman": 1, "thief": 1, "pirate": 1, "crit": 1}},
{"key": "gandi", "name": "GanDi",
{"key": "hybrid", "name": "Hybrid",
"targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3},
"jobs": {"count": 3, "default": ["magician", "thief", "bowman"]}},
{"key": "eu", "name": "EU",
Expand Down
160 changes: 127 additions & 33 deletions src/quanah/solver.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
"""Pick one event piece per slot to fill a build's skill-line targets.

A port of the community 3L, GanDi and EU set solvers: a DP over capped line
A port of the community 3L, GanDi (Hybrid) and EU set solvers: a DP over capped line
counts, one layer per slot. Lines above a target are wasted; a slot with no
eligible piece is left empty.

A piece marked "transfer" needs an orb: its lines count once moved onto the piece
worn in that slot (marked "worn"), or onto any on-class piece of the slot when none
is worn. Among equally good sets, the one needing the fewest transfers wins.

A piece marked "preferred" is locked into its slot: the rest of the set is solved
around it, even when another piece there would score more.
"""

from functools import lru_cache
Expand Down Expand Up @@ -96,43 +103,85 @@ def needs(self, state):
return [base + list(pick) for pick in combinations(open_jobs, missing)]


def _layers(plan, by_slot, skip=None):
current = {tuple(0 for _ in plan.keys): {"ways": 1}}
def _layers(plan, by_slot, locked, skip=None, edges=True):
"""One (slot, states) layer per slot. Each state keeps its combo count, "costs" (a bitmask:
bit N is set when some path reaches it with N transfers) and, with EDGES, the
(previous state, piece) pairs reaching it."""
current = {tuple(0 for _ in plan.keys): {"ways": 1, "costs": 1}}
layers = []
for slot in slot_keys():
if slot == skip:
continue
options = by_slot.get(slot) or [None]
options = by_slot.get(slot) or []
# Orbing costs a transfer, so a slot with a piece needing one may also stay as it is,
# unless a worn piece fills it anyway.
if not options or (slot not in locked and any(item.get("transfer") for item in options)
and not any(item.get("worn") for item in options)):
options = options + [None]
costs = [bool(item and item.get("transfer")) for item in options]
optional = options[-1] is None
following = {}
for state, info in current.items():
for item in options:
idle = False # Whether a kept piece adds nothing here, making the empty option no extra combo.
for item, cost in zip(options, costs, strict=True):
nxt = plan.add(state, item["lines"]) if item else state
# Never orb a piece that adds nothing, and leaving the slot empty is no extra
# combo when one of its pieces adds nothing anyway.
if nxt == state:
if (cost and slot not in locked) or (item is None and idle):
continue
idle = optional
reach = info["costs"] << cost
entry = following.get(nxt)
if entry:
entry["ways"] += info["ways"]
if entry is None:
entry = following[nxt] = {"ways": info["ways"], "costs": reach, "edges": []}
else:
following[nxt] = {"prev": state, "item": item, "slot": slot, "ways": info["ways"]}
layers.append(following)
entry["ways"] += info["ways"]
entry["costs"] |= reach
if edges:
entry["edges"].append((state, item))
layers.append((slot, following))
current = following
return layers


def solve(items, targets, jobs=None):
"""Best set for ITEMS (dicts with id, slot, lines) under TARGETS and an optional job rule."""
plan = _Plan(targets, jobs)
by_slot = {}
for item in items:
by_slot.setdefault(item["slot"], []).append(item)
layers = _layers(plan, by_slot)
final = layers[-1]
best_state = max(final, key=plan.score) # max() keeps the first of equal scores, like the sites.
best = plan.score(best_state)
picks, state = {}, best_state
for layer in reversed(layers):
entry = layer[state]
picks[entry["slot"]] = entry["item"]
state = entry["prev"]
# Which lines of the chosen pieces count toward the goal, in slot order.
def _combos(layers, finals, limit):
"""Up to LIMIT (final state, {slot: piece}) paths into FINALS, fewest transfers first.

Within a transfer count the first path found comes first, so the first combo is the
one the community sites pick when no piece needs a transfer.
"""
found = []

def walk(depth, state, budget, picks):
if len(found) >= limit:
return
if depth < 0:
if not budget:
found.append(dict(picks))
return
slot, layer = layers[depth]
for prev, item in layer[state]["edges"]:
left = budget - bool(item and item.get("transfer"))
# Only follow an edge whose previous state is reachable with exactly LEFT
# transfers, so every step leads to a combo and no path is walked in vain.
before = layers[depth - 1][1][prev]["costs"] if depth else 1
if left >= 0 and before >> left & 1:
picks[slot] = item
walk(depth - 1, prev, left, picks)

final = layers[-1][1]
for orbs in range(len(layers) + 1):
for state in finals:
if final[state]["costs"] >> orbs & 1:
start = len(found)
walk(len(layers) - 1, state, orbs, {})
found[start:] = [(state, picks) for picks in found[start:]]
return found


def _used(plan, picks):
"""Which lines of the chosen pieces count toward the goal, in slot order."""
run, jobs_used, used = dict.fromkeys(plan.keys, 0), 0, {}
for slot in slot_keys():
item = picks.get(slot)
Expand All @@ -149,24 +198,69 @@ def solve(items, targets, jobs=None):
run[key] += ok
flags.append(ok)
used[slot] = flags
return used


def _orbs(picks):
return sum(bool(item and item.get("transfer")) for item in picks.values())


def _ids(picks):
return {slot: (picks[slot]["id"] if picks.get(slot) else None) for slot in slot_keys()}


COMBO_LIMIT = 100


def solve(items, targets, jobs=None):
"""Best set for ITEMS (dicts with id, slot, lines, optional transfer and preferred)
under TARGETS and an optional job rule.

A complete set also lists its winning combos (at most COMBO_LIMIT), fewest transfers first.
"""
plan = _Plan(targets, jobs)
by_slot = {}
for item in items:
by_slot.setdefault(item["slot"], []).append(item)
locked = set()
for slot, pieces in by_slot.items():
preferred = [item for item in pieces if item.get("preferred")]
if preferred:
by_slot[slot] = preferred[:1]
locked.add(slot)
layers = _layers(plan, by_slot, locked)
final = layers[-1][1]
best = max(plan.score(state) for state in final)
finals = [state for state in final if plan.score(state) == best]
done = best >= plan.goal
combos = _combos(layers, finals, COMBO_LIMIT if done else 1)
best_state, picks = combos[0]
return {
"score": best,
"goal": plan.goal,
"counts": dict(zip(plan.keys, best_state, strict=True)),
"picks": {slot: (item["id"] if item else None) for slot, item in picks.items()},
"used": used,
"ways": final[best_state]["ways"],
"missing": plan.needs(best_state)[0] if best < plan.goal else [],
"hunt": _hunt(plan, by_slot) if best < plan.goal else [],
"picks": _ids(picks),
"used": _used(plan, picks),
"ways": sum(final[state]["ways"] for state in finals),
"orbs": _orbs(picks),
"combos": [{"picks": _ids(p), "used": _used(plan, p), "orbs": _orbs(p)} for _, p in combos]
if done else [],
"missing": plan.needs(best_state)[0] if not done else [],
"hunt": _hunt(plan, by_slot, locked) if not done else [],
}


def _hunt(plan, by_slot):
"""Pieces that would finish the set in one drop: (slot, lines) with no repeated line."""
def _hunt(plan, by_slot, locked):
"""Pieces that would finish the set in one drop: (slot, lines) with no repeated line.

Orb cost is not considered; the page notes that a drop for a slot with a worn piece needs one.
"""
limit = catalog()["max_lines"]
found, seen = [], set()
for slot in slot_keys():
for state in _layers(plan, by_slot, skip=slot)[-1]:
if slot in locked:
continue # A drop there would not be used.
for state in _layers(plan, by_slot, locked, skip=slot, edges=False)[-1][1]:
if plan.goal - plan.score(state) > limit:
continue
for need in plan.needs(state):
Expand Down
76 changes: 59 additions & 17 deletions src/quanah/store.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""The saved Quanah class, build and event pieces, plus the solved best set.

One global list, independent of Hascone's characters. Pieces of another class
are kept, flagged as unwearable and left out of the solver.
are kept and flagged as unwearable; the solver still uses them, as pieces whose
lines must be orbed onto an on-class piece of the same slot.
"""

import json
Expand All @@ -20,10 +21,10 @@


def _default():
gandi = next(b for b in solver.catalog()["builds"] if b["key"] == "gandi")
hybrid = next(b for b in solver.catalog()["builds"] if b["key"] == "hybrid")
return {
"class": None,
"build": {"preset": "skill", "job_mode": "custom", "jobs": list(gandi["jobs"]["default"]), "targets": {}},
"build": {"preset": "skill", "job_mode": "custom", "jobs": list(hybrid["jobs"]["default"]), "targets": {}},
"items": [],
}

Expand All @@ -35,9 +36,9 @@ def read():
saved = json.loads(PATH.read_text(encoding="utf-8"))
data["class"] = saved.get("class")
data["build"].update(saved.get("build") or {})
# The Skill build was first saved as "original".
if data["build"].get("preset") == "original":
data["build"]["preset"] = "skill"
# Builds first saved under older names.
renamed = {"original": "skill", "gandi": "hybrid"}
data["build"]["preset"] = renamed.get(data["build"].get("preset"), data["build"].get("preset"))
# So the page shows, and later changes validate, the same targets the solver uses.
data["build"]["targets"] = solver.trim_targets(data["build"].get("targets"))
data["items"] = saved.get("items") or []
Expand Down Expand Up @@ -142,29 +143,64 @@ def add_item(slot, lines, *, raw=None, name=None, item_class=None, source="manua
return item


def _piece(data, identifier):
item = next((i for i in data["items"] if i["id"] == identifier), None)
if item is None:
raise ValueError("That piece is already gone")
return item


def update_item(identifier, slot, lines):
"""Correct a piece's slot and lines by hand. A scanned piece keeps what was read, marked edited."""
if slot not in solver.slot_keys():
raise ValueError("Choose a slot")
lines = validate_lines(lines)
with lock:
data = read()
item = next((i for i in data["items"] if i["id"] == identifier), None)
if item is None:
raise ValueError("That piece is already gone")
item = _piece(data, identifier)
if (item["slot"], item["lines"]) != (slot, lines):
# A piece moved to another slot is no longer that slot's preferred or worn piece.
if item["slot"] != slot:
for flag in ONE_PER_SLOT:
item.pop(flag, None)
item.update(slot=slot, lines=lines, edited=datetime.now(UTC).isoformat())
_write(data)
return item


# "preferred" locks a piece into the best set and "worn" is what the player wears now, which
# the other pieces' lines would be orbed onto: one piece per slot each. "disabled" leaves a
# piece out of every combo.
ONE_PER_SLOT = ("preferred", "worn")
MARKS = (*ONE_PER_SLOT, "disabled")


def mark_item(identifier, flag, on):
"""Give a piece FLAG (taking a one-per-slot mark from the slot's other pieces), or clear it."""
if flag not in MARKS:
raise ValueError("Unknown mark")
if not isinstance(on, bool):
raise ValueError(f"{flag.capitalize()} must be true or false")
with lock:
data = read()
item = _piece(data, identifier)
item.pop(flag, None)
if flag in ONE_PER_SLOT:
for other in data["items"]:
if other["slot"] == item["slot"]:
other.pop(flag, None)
if on:
item[flag] = True
# A disabled piece can't be locked into the set, and starring a piece uses it again.
item.pop({"disabled": "preferred", "preferred": "disabled"}.get(flag), None)
_write(data)
return item


def delete_item(identifier):
with lock:
data = read()
kept = [item for item in data["items"] if item["id"] != identifier]
if len(kept) == len(data["items"]):
raise ValueError("That piece is already gone")
data["items"] = kept
data["items"].remove(_piece(data, identifier))
_write(data)


Expand All @@ -187,13 +223,19 @@ def payload():
"""Everything the page needs: catalog, settings, flagged pieces and the best set."""
data = read()
dupes = duplicates(data["items"])
items = [{**item, "duplicate": item["id"] in dupes,
"wearable": bool(data["class"]) and item.get("item_class") == data["class"]}
for item in data["items"]]
worn = {item["slot"] for item in data["items"] if item.get("worn")}
items = []
for item in data["items"]:
wearable = bool(data["class"]) and item.get("item_class") == data["class"]
# Using a piece costs an orb (a transfer) when its lines must move onto another piece:
# the piece worn in that slot, or, with none marked worn, any piece of your class.
transfer = not item.get("worn") if item["slot"] in worn else not wearable
items.append({**item, "duplicate": item["id"] in dupes, "wearable": wearable, "transfer": transfer,
**{flag: bool(item.get(flag)) for flag in MARKS}})
solution = None
if data["class"]:
targets, jobs = solver.resolve_build(data["build"])
solution = solver.solve([i for i in items if i["wearable"]], targets, jobs)
solution = solver.solve([i for i in items if not i["disabled"]], targets, jobs)
solution["targets"] = targets
solution["jobs"] = {"count": jobs[0], "keys": list(jobs[1])} if jobs else None
return {"catalog": solver.catalog(), "class": data["class"], "build": data["build"],
Expand Down
Loading
Loading