RynthSuite/Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs

383 lines
19 KiB
C#

// Where a guide quest stands for this character (2026-11-27), worked out from the quest flags (/myquests) and the
// stamps seen in chat this session. The four states, the kill tasks' counts and "first time / done before", and the
// kill lines in chat follow SilentKelpie's Guide (Forgejo rynth PR #12); re-implemented here.
// - A stamp is held when /myquests has its flag (any spelling: GuideStamp.Key) or it was stamped this session.
// - For a repeatable quest, a held stamp counts for this run while its flag's timer runs (or, with no timer on the
// flag, while the quest's repeat time since it was stamped hasn't passed); after that it was done "earlier".
// - The quest's wait is the longest redo time left on any held stamp.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>A quest's state in the guide's lists.</summary>
internal enum GuideState
{
/// <summary>No stamp held.</summary>
NotDone,
/// <summary>Some stamps held, some still to get, the held ones' redo timer still running.</summary>
PartWaiting,
/// <summary>Some stamps held, some still to get, no timer left.</summary>
PartReady,
/// <summary>Every stamp held.</summary>
Done,
}
/// <summary>A stamp of a quest for this run.</summary>
internal enum StampState { Missing, Done, Earlier }
/// <summary>A kill task's progress, in the order the Kill Tasks list shows them.</summary>
internal enum KillState { TurnIn, Counting, Ready, NotStarted, Waiting, Completed }
/// <summary>What the guide knows of this character: its flags, the stamps seen this session and the kill lines.</summary>
internal sealed class GuideProgress
{
private readonly QuestFlagStore _flags;
private readonly HashSet<string> _sessionStamps;
private readonly KillChat _kills;
private Dictionary<string, QuestFlag>? _byKey;
private int _byKeyRevision = -1;
public GuideProgress(QuestFlagStore flags, HashSet<string> sessionStamps, KillChat kills)
{
_flags = flags;
_sessionStamps = sessionStamps;
_kills = kills;
}
/// <summary>The flag a stamp is in /myquests, by any spelling of it, or null.</summary>
public QuestFlag? FlagOf(string stamp)
{
if (_flags.TryGet(stamp, out QuestFlag f)) return f;
if (_byKeyRevision != _flags.Revision || _byKey == null)
{
_byKey = new Dictionary<string, QuestFlag>(StringComparer.Ordinal);
foreach (KeyValuePair<string, QuestFlag> kv in _flags.Flags) _byKey.TryAdd(GuideStamp.Key(kv.Key), kv.Value);
_byKeyRevision = _flags.Revision;
}
return _byKey.TryGetValue(GuideStamp.Key(stamp), out QuestFlag? byKey) ? byKey : null;
}
public bool StampedThisSession(string stamp) => _sessionStamps.Contains(GuideStamp.Key(stamp));
/// <summary>A stamp of <paramref name="q"/> for this run (see the file's note).</summary>
public StampState StateOf(GuideQuest q, string stamp, DateTime utcNow)
{
if (StampedThisSession(stamp)) return StampState.Done;
if (FlagOf(stamp) is not QuestFlag f) return StampState.Missing;
if (q.RepeatSec == 0) return StampState.Done;
if (f.RepeatTime > TimeSpan.Zero) return f.NextAvailableTime(utcNow) > TimeSpan.Zero ? StampState.Done : StampState.Earlier;
if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue)
return f.CompletedOnUtc.AddSeconds(q.RepeatSec) > utcNow ? StampState.Done : StampState.Earlier;
return StampState.Done;
}
/// <summary>The longest redo time left on the quest's held stamps; zero when none runs.</summary>
public TimeSpan Wait(GuideQuest q, DateTime utcNow)
{
TimeSpan wait = TimeSpan.Zero;
foreach (string st in q.AllStamps())
{
if (FlagOf(st) is not QuestFlag f) continue;
TimeSpan left = TimeSpan.Zero;
if (f.RepeatTime > TimeSpan.Zero) left = f.NextAvailableTime(utcNow);
else if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue) left = f.CompletedOnUtc.AddSeconds(q.RepeatSec) - utcNow;
if (left > wait) wait = left;
}
return wait;
}
/// <summary>A quest's row: its state, the list's short text, the tooltip's sentence, and whether "Hide done" leaves it out.</summary>
public readonly record struct Row(GuideState State, string Status, string Tip, bool HideWhenDone, int Held, int All);
/// <summary>
/// A quest with stamps: the four states from the stamps held and the wait. Without stamps (the AC Community Wiki
/// lists none for most quests), <paramref name="flagDone"/> (the quest list's flag of its name) gives Done or Not done,
/// and null means its state isn't known.
/// </summary>
public Row RowOf(GuideQuest q, DateTime utcNow, bool? flagDone = null)
{
List<string> stamps = q.AllStamps();
if (stamps.Count == 0)
{
if (flagDone is bool fd)
return fd ? new Row(GuideState.Done, "Done", "Done: the quest list's flag for it is held.", q.RepeatSec == 0, 1, 1)
: new Row(GuideState.NotDone, "Not done", "Not done: the quest list's flag for it isn't held yet.", false, 0, 1);
return new Row(GuideState.NotDone, "no stamps", "The wiki lists no stamps for this quest and the quest list has no flag of its name, so its state isn't known.", false, 0, 0);
}
int held = 0, now = 0;
foreach (string st in stamps)
{
StampState s = StateOf(q, st, utcNow);
if (s != StampState.Missing) held++;
if (s == StampState.Done) now++;
}
TimeSpan wait = Wait(q, utcNow);
bool repeats = q.RepeatSec != 0 || wait > TimeSpan.Zero;
GuideState state = held == 0 ? GuideState.NotDone : held >= stamps.Count ? GuideState.Done
: wait > TimeSpan.Zero ? GuideState.PartWaiting : GuideState.PartReady;
(string status, string tip) = Text(state, held, stamps.Count, wait, repeats);
bool hide = state == GuideState.Done && (!repeats || wait > TimeSpan.Zero || now == stamps.Count);
return new Row(state, status, tip, hide, held, stamps.Count);
}
/// <summary>The list's short status and the tooltip's sentence.</summary>
public static (string Status, string Tip) Text(GuideState s, int held, int all, TimeSpan wait, bool repeats) => s switch
{
GuideState.Done when wait > TimeSpan.Zero => ("Done " + Short(wait), $"Done: all {all} stamps held. It can be done again in {Short(wait)}."),
GuideState.Done when repeats => ("Done, redo", $"Done: all {all} stamps held, and its timer is up: it can be done again now."),
GuideState.Done => ("Done", $"Done: all {all} stamps held."),
GuideState.PartWaiting => ($"{held}/{all} wait {Short(wait)}", $"Part done: {held} of {all} stamps held, {all - held} still to get. The redo timer has {Short(wait)} left."),
GuideState.PartReady => ($"{held}/{all} ready", $"Part done: {held} of {all} stamps held, {all - held} still to get. No timer is running: go get them."),
_ => ("Not done", $"Not done: none of its {all} stamps held yet."),
};
/// <summary>"3d 4h", "5h 12m", "9m".</summary>
public static string Short(TimeSpan t)
{
if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d {t.Hours}h";
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes:00}m";
return $"{Math.Max(1, (int)Math.Ceiling(t.TotalMinutes))}m";
}
/// <summary>"Daily (every 20h 00m)", "Weekly (every 7d 0h)", "One-time", or the wiki's own words.</summary>
public static string RepeatText(GuideQuest q)
{
if (q.RepeatSec == 0) return q.Repeat.Length > 0 ? "One-time (" + q.Repeat + ")" : "One-time";
if (q.RepeatSec < 0) return "Repeats: " + q.Repeat;
string every = Short(TimeSpan.FromSeconds(q.RepeatSec));
return q.IsDaily ? $"Daily (every {every})" : q.IsWeekly ? $"Weekly (every {every})" : $"Repeats every {every}";
}
// ── Kill tasks ──────────────────────────────────────────────────────────
/// <summary>A kill task's progress: kills and goal, where the count came from, its state and whether it was done before.</summary>
public sealed record Kill(KillState State, int Kills, int Goal, QuestFlag? Counter, bool FromChat, string Status, bool DoneBefore);
/// <summary>
/// The task's counter flag: a stamp of it /myquests holds with a solve limit over 1, else a kill-task flag that names its creature.
/// </summary>
public QuestFlag? KillCounter(GuideQuest q)
{
foreach (string st in q.AllStamps())
if (FlagOf(st) is QuestFlag f && f.MaxSolves > 1) return f;
string key = q.KillCreatureKey;
if (key.Length < 5) return null;
foreach (QuestFlag f in _flags.Flags.Values)
if (QuestTimer.IsKillTask(f) && GuideStamp.Key(f.Key).Contains(key, StringComparison.Ordinal)) return f;
return null;
}
public Kill KillOf(GuideQuest q, DateTime utcNow, bool? flagDone = null)
{
int goal = q.KillTarget, kills = 0;
QuestFlag? counter = KillCounter(q);
if (counter != null)
{
kills = counter.Solves;
if (counter.MaxSolves > 1) goal = counter.MaxSolves;
}
bool fromChat = false;
// A kill line newer than the last /myquests read wins: it moves with every kill.
if (_kills.For(q.KillCreatureKey) is KillCount k && k.AtUtc > _flags.LastReadUtc && (k.Goal > 0 || k.Kills > 0))
{
kills = k.Kills;
if (k.Goal > 0) goal = k.Goal;
fromChat = true;
}
Row row = RowOf(q, utcNow, flagDone);
TimeSpan wait = Wait(q, utcNow);
bool counted = counter != null || fromChat;
KillState state;
string status;
if (counted && goal > 0 && kills < goal && !(row.HideWhenDone && wait > TimeSpan.Zero)) { state = KillState.Counting; status = $"{kills} / {goal}"; }
else if (counted && goal > 0 && kills >= goal && wait <= TimeSpan.Zero && row.State != GuideState.Done) { state = KillState.TurnIn; status = "Turn in"; }
else if (row.State == GuideState.Done && wait > TimeSpan.Zero) { state = KillState.Waiting; status = "Done " + Short(wait); }
else if (row.State == GuideState.Done && q.RepeatSec == 0) { state = KillState.Completed; status = "Completed"; }
else if (row.State == GuideState.Done || counter != null) { state = KillState.Ready; status = "Ready"; }
else { state = KillState.NotStarted; status = goal > 0 ? $"0 / {goal}" : "Not started"; }
bool before = state is KillState.Waiting or KillState.Completed || DoneBefore(q, counter, flagDone);
return new Kill(state, kills, goal, counter, fromChat, status, before);
}
/// <summary>
/// Done before: a stamp of the task is held other than those a first run holds too (the live counter, a "start" flag,
/// the first step's), a flag of it is on a redo timer, or the quest list's flag of its name is held.
/// </summary>
private bool DoneBefore(GuideQuest q, QuestFlag? counter, bool? flagDone)
{
string counterKey = counter != null ? GuideStamp.Key(counter.Key) : "";
var first = new HashSet<string>(StringComparer.Ordinal);
if (q.Steps.Count > 1)
foreach (string st in q.Steps[0].Stamps) first.Add(GuideStamp.Key(st));
foreach (string st in q.AllStamps())
{
string k = GuideStamp.Key(st);
if (k == counterKey || first.Contains(k) || k.Contains("start", StringComparison.Ordinal)) continue;
if (StampedThisSession(st) || FlagOf(st) != null) return true;
}
return flagDone == true;
}
/// <summary>The two-word tag a kill task row shows, and its tooltip.</summary>
public static (string Tag, string Tip) KillTag(bool doneBefore) => doneBefore
? ("Again", "Done before: a stamp or flag of this kill task is held.")
: ("1st", "First time: no stamp or flag of this kill task held yet.");
/// <summary>"KillTaskSampleBeasts_0101" -> "Kill Task Sample Beasts 0101".</summary>
public static string FlagLabel(string flag)
{
var sb = new System.Text.StringBuilder(flag.Length + 8);
for (int i = 0; i < flag.Length; i++)
{
char c = flag[i];
if (c == '_') { if (sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); continue; }
bool brk = i > 0 && (char.IsUpper(c) && (char.IsLower(flag[i - 1]) || char.IsDigit(flag[i - 1])) || char.IsDigit(c) && char.IsLetter(flag[i - 1]));
if (brk && sb.Length > 0 && sb[^1] != ' ') sb.Append(' ');
sb.Append(c);
}
return sb.ToString().Trim();
}
}
/// <summary>One creature's last kill line this session: the count and the goal (0: the line gave none), and when.</summary>
internal readonly record struct KillCount(string Creature, int Kills, int Goal, DateTime AtUtc);
/// <summary>
/// Kill task counts from chat: the server's "You have killed 27 Sample Beasts! You must kill 50 to complete your task."
/// (and "You have killed some ..."), so the Kill Tasks list moves with every kill though /myquests is read at most once a
/// minute. The last line per creature this session. Pump thread.
/// </summary>
internal sealed class KillChat
{
private static readonly Regex CountRx = new(
@"^You have killed (?<n>\d{1,6}) (?<what>.+?)! You must kill (?<max>\d{1,6}) to complete your task", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static readonly Regex SomeRx = new(@"^You have killed (?:some|enough|all(?: the)?) (?<what>.+?)[.!]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private readonly Dictionary<string, KillCount> _byKey = new(StringComparer.Ordinal);
/// <summary>Goes up with every kill line taken.</summary>
public int Revision { get; private set; }
public void Clear()
{
if (_byKey.Count == 0) return;
_byKey.Clear();
Revision++;
}
/// <summary>Takes a chat line; true when it was a kill task's kill line.</summary>
public bool OnChatLine(string? line, DateTime utcNow)
{
if (string.IsNullOrEmpty(line) || !line.StartsWith("You have killed ", StringComparison.OrdinalIgnoreCase)) return false;
string text = line.Trim();
Match m = CountRx.Match(text);
if (m.Success)
{
string what = m.Groups["what"].Value.Trim();
_byKey[GuideQuest.KillKey(what)] = new KillCount(what,
int.Parse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture),
int.Parse(m.Groups["max"].Value, NumberStyles.None, CultureInfo.InvariantCulture), utcNow);
Revision++;
return true;
}
m = SomeRx.Match(text);
if (!m.Success) return false;
string some = m.Groups["what"].Value.Trim();
string key = GuideQuest.KillKey(some);
_byKey[key] = _byKey.TryGetValue(key, out KillCount had) ? had with { AtUtc = utcNow } : new KillCount(some, 0, 0, utcNow);
Revision++;
return true;
}
/// <summary>The last line for a creature key: the same key, else one holding the other (keys of 5+ letters only), newest first.</summary>
public KillCount? For(string creatureKey)
{
if (creatureKey.Length == 0) return null;
if (_byKey.TryGetValue(creatureKey, out KillCount k)) return k;
if (creatureKey.Length < 5) return null;
KillCount? best = null;
foreach (KeyValuePair<string, KillCount> kv in _byKey)
if (kv.Key.Length >= 5 && (kv.Key.Contains(creatureKey, StringComparison.Ordinal) || creatureKey.Contains(kv.Key, StringComparison.Ordinal))
&& (best == null || kv.Value.AtUtc > best.Value.AtUtc))
best = kv.Value;
return best;
}
}
/// <summary>
/// The guides in use, merged: the active server plugin's own guide first (its quests replace the AC Community Wiki's of the
/// same name), then the AC Community Wiki's. Kill tasks, society ranks and contracts come from either.
/// </summary>
internal sealed class GuideSet
{
public readonly List<GuideQuest> Quests = new();
public readonly List<GuideContract> Contracts = new();
private readonly QuestGuide? _server;
private readonly QuestGuide _wiki;
private readonly HashSet<GuideQuest> _fromServer = new();
public GuideSet(QuestGuide? server, QuestGuide wiki)
{
_server = server is { IsEmpty: false } ? server : null;
_wiki = wiki;
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (_server != null)
foreach (GuideQuest q in _server.Quests)
if (names.Add(q.Title)) { Quests.Add(q); _fromServer.Add(q); }
foreach (GuideQuest q in wiki.Quests)
if (names.Add(q.Title)) Quests.Add(q);
var contracts = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (_server != null)
foreach (GuideContract c in _server.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c);
foreach (GuideContract c in wiki.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c);
}
public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0;
/// <summary>The quest came from the server plugin's guide.</summary>
public bool FromServer(GuideQuest q) => _fromServer.Contains(q);
public bool IsKillTask(GuideQuest q) => (_server?.IsKillTask(q) ?? false) || _wiki.IsKillTask(q);
public string SocietyRankOf(GuideQuest q)
{
string r = _server?.SocietyRankOf(q) ?? "";
return r.Length > 0 ? r : _wiki.SocietyRankOf(q);
}
public GuideQuest? Find(string title)
{
foreach (GuideQuest q in Quests)
if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q;
return null;
}
/// <summary>Society ranks in order (the wiki's names); a rank not in the list sorts last.</summary>
public static readonly string[] SocietyRanks = { "Joining", "Initiate", "Adept", "Knight", "Lord", "Master" };
public static int RankOrder(string rank)
{
for (int i = 0; i < SocietyRanks.Length; i++)
if (string.Equals(SocietyRanks[i], rank, StringComparison.OrdinalIgnoreCase)) return i;
return SocietyRanks.Length;
}
}
/// <summary>
/// The seam for running a guide quest later (RynthNav walking its steps; not in this version). Nothing implements it
/// yet: the Guide tab draws run controls only when <see cref="OracleContext.GuideRunner"/> is set.
/// </summary>
internal interface IGuideQuestRunner
{
/// <summary>The quest being run, or null.</summary>
GuideQuest? Running { get; }
/// <summary>The step under way (0-based), -1 none.</summary>
int Step { get; }
/// <summary>Starts the quest at a step; the answer to show.</summary>
string Start(GuideQuest q, int fromStep);
void Stop();
}