diff --git a/CLAUDE.md b/CLAUDE.md index 9aae666..d2c5b49 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,7 @@ Nothing goes to NuGet. ktsu.Sdk marks every library packable from its targets, a - **`Core/Progression/ProgressionEngine.cs`:** turns hits, kills, reloads, life summaries, assists, flashes, and clutches into rank XP, weapon XP, ladder progress, and notices. - **`Core/SkillShots/SkillShotCatalog.cs`:** every skill shot, with its rarity, the weapons it applies to, and its detection rule. Ids are stored as challenge ids, so never rename one. +- **`Core/Contracts/ContractCatalog.cs`:** the daily and weekly contracts, and which run on a day. The picks hash the UTC date in `Core/Rotation/DailyRotation.cs`, so the plugin and site agree with nothing stored. Progress is saved per period key in `csp_contracts`, and contract ids are stored, so never rename one. - **`Core/Weapons/WeaponCatalog.cs`:** every tracked weapon, and the normalization of CS2's weapon names (prefixes, knife skins, grenade aliases, and alternates told apart by definition index). - **`Core/Tracking/`:** `RoundTracker` (opening kills, multi-kills, collaterals, trades, clutches), `PlayerCombatTracker` (landing, scope, weapon switch, reload, flick), and `LifeTracker` (per-life accuracy). - **`Core/Storage/`:** `ProgressSnapshot` (dirty rows copied on the game thread), `MySqlProgressionStore`, and `InMemoryProgressionStore`. Each save also upserts the player's total rank XP for the day into `csp_daily`, and `XpHistory` turns those rows into XP per day and XP since a date (the player page's History tab and the "XP this week" board on Ranks). diff --git a/CounterStrikeProgression.Core/Admin/AdminCorrection.cs b/CounterStrikeProgression.Core/Admin/AdminCorrection.cs index 47374e0..6fdabb1 100644 --- a/CounterStrikeProgression.Core/Admin/AdminCorrection.cs +++ b/CounterStrikeProgression.Core/Admin/AdminCorrection.cs @@ -81,6 +81,7 @@ public CorrectionOutcome Apply(PlayerProgress player, RankLadder ranks) { weaponsCleared = player.Weapons.Count; player.Weapons.Clear(); + player.Contracts.Clear(); player.RankXp = 0; player.Rank = 0; player.PendingXp = 0; diff --git a/CounterStrikeProgression.Core/Contracts/ContractCatalog.cs b/CounterStrikeProgression.Core/Contracts/ContractCatalog.cs new file mode 100644 index 0000000..c519cef --- /dev/null +++ b/CounterStrikeProgression.Core/Contracts/ContractCatalog.cs @@ -0,0 +1,116 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Core.Contracts; + +using System.Collections.Frozen; +using ktsu.CounterStrikeProgression.Core.Rotation; +using ktsu.CounterStrikeProgression.Core.SkillShots; +using ktsu.CounterStrikeProgression.Core.Weapons; + +/// +/// Every contract, and which ones run on a given day. The picks come from a hash of the date, so the plugin and +/// the site agree on them with nothing stored. Contract ids are stored with progress, so never rename one. +/// +internal static class ContractCatalog +{ + /// + /// Gets the daily pool, as groups of variants. A day draws whole groups, so it never gets two contracts of the + /// same kind, and then one variant from each group drawn. + /// + public static IReadOnlyList> DailyGroups { get; } = + [ + [ + ClassKills(WeaponClass.Pistol, "kills_pistol", 15), + ClassKills(WeaponClass.Smg, "kills_smg", 20), + ClassKills(WeaponClass.Rifle, "kills_rifle", 25), + ClassKills(WeaponClass.Sniper, "kills_sniper", 10), + ClassKills(WeaponClass.Shotgun, "kills_shotgun", 12), + ClassKills(WeaponClass.MachineGun, "kills_machine_gun", 12), + ], + [Daily("headshots", "Get 15 headshot kills", 15, s => (s.Kind == SignalKind.Kill) && s.Headshot)], + [Daily("skill_shots", "Earn 10 skill shots", 10, s => s.Kind == SignalKind.SkillShot)], + [Daily("rare_skill_shots", "Earn 3 rare or epic skill shots", 3, s => s.SkillShot is { Rarity: not Rarity.Common })], + [Daily("wallbangs", "Get 2 kills through walls", 2, SkillShots("wallbang"))], + [Daily("movement", "Earn 5 movement skill shots, such as Jumpshot or Moving target", 5, SkillShots("moving_target", "airborne_target", "jumpshot", "air_to_air", "run_and_gun", "landing_shot"))], + [Daily("multi_kills", "Earn Double kill or better 3 times", 3, SkillShots("double_kill", "triple_kill", "rampage"))], + [Daily("utility_kills", "Get 2 kills with the knife, a grenade, or the Zeus", 2, s => (s.Kind == SignalKind.Kill) && s.Weapon is { Class: WeaponClass.Knife or WeaponClass.Grenade or WeaponClass.Taser })], + [Daily("chickens", "Kill 5 chickens", 5, s => s.Kind == SignalKind.Chicken)], + [Daily("assists", "Get 5 assists", 5, s => s.Kind == SignalKind.Assist)], + [Daily("scope_tricks", "Earn 2 No-scopes, Quickscopes, or Scoped on the moves", 2, SkillShots("no_scope", "quickscope", "scoped_on_the_move"))], + [Daily("precision", "Earn One tap or Flick 3 times", 3, SkillShots("one_tap", "flick"))], + ]; + + /// Gets the weekly pool. A week draws one. + public static IReadOnlyList Weekly { get; } = + [ + Week("weekly_kills", "Get 250 kills", 250, s => s.Kind == SignalKind.Kill), + Week("weekly_headshots", "Get 100 headshot kills", 100, s => (s.Kind == SignalKind.Kill) && s.Headshot), + Week("weekly_skill_shots", "Earn 60 skill shots", 60, s => s.Kind == SignalKind.SkillShot), + Week("weekly_epic", "Earn 3 epic skill shots", 3, s => s.SkillShot is { Rarity: Rarity.Epic }), + Week("weekly_tiers", "Finish 5 challenge tiers", 5, s => s.Kind == SignalKind.Tier), + Week("weekly_levels", "Gain 10 weapon levels", 10, s => s.Kind == SignalKind.WeaponLevel), + ]; + + private static FrozenDictionary ById { get; } = + DailyGroups.SelectMany(g => g).Concat(Weekly).ToFrozenDictionary(c => c.Id, StringComparer.Ordinal); + + /// + /// Looks up a contract by id. + /// + /// The contract id. + /// The contract, or when there's no such id. + public static ContractDefinition? Find(string id) => ById.GetValueOrDefault(id); + + /// + /// Gets the contracts running on a day: its daily contracts first, then the week's. + /// + /// The UTC day. + /// How many daily contracts there are and what each pays. + /// The contracts, or none when contracts are off. + public static IReadOnlyList Active(DateOnly day, ProgressionSettings settings) + { + Ensure.NotNull(settings); + if (!settings.ContractsEnabled) + { + return []; + } + + string dayKey = DailyRotation.DayKey(day); + DateTime dayEnds = day.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + DateTime weekEnds = DailyRotation.WeekStart(day).AddDays(7).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + + int count = Math.Clamp(settings.DailyContracts, 0, DailyGroups.Count); + List active = + [ + .. Enumerable.Range(0, DailyGroups.Count) + .OrderBy(i => DailyRotation.Hash(dayKey, $"daily:{i}")) + .Take(count) + .Order() + .Select(i => Variant(DailyGroups[i], dayKey, i)) + .Select(c => new ActiveContract(c, dayKey, dayEnds, settings.DailyContractXp)), + ]; + + string weekKey = DailyRotation.WeekKey(day); + ContractDefinition weekly = Weekly[(int)(DailyRotation.Hash(weekKey, "weekly") % (ulong)Weekly.Count)]; + active.Add(new ActiveContract(weekly, weekKey, weekEnds, settings.WeeklyContractXp)); + return active; + } + + private static ContractDefinition Variant(IReadOnlyList group, string dayKey, int groupIndex) => + group.Count == 1 ? group[0] : group[(int)(DailyRotation.Hash(dayKey, $"variant:{groupIndex}") % (ulong)group.Count)]; + + private static ContractDefinition ClassKills(WeaponClass weaponClass, string id, int target) => + Daily(id, $"Get {target} kills with {DailyRotation.ClassName(weaponClass)}", target, s => (s.Kind == SignalKind.Kill) && (s.Weapon?.Class == weaponClass)); + + private static Func SkillShots(params string[] ids) + { + HashSet set = new(ids, StringComparer.Ordinal); + return s => (s.SkillShot is not null) && set.Contains(s.SkillShot.Id.WeakString); + } + + private static ContractDefinition Daily(string id, string description, int target, Func counts) => + new(id, description, ContractPeriod.Daily, target, counts); + + private static ContractDefinition Week(string id, string description, int target, Func counts) => + new(id, description, ContractPeriod.Weekly, target, counts); +} diff --git a/CounterStrikeProgression.Core/Contracts/ContractDefinition.cs b/CounterStrikeProgression.Core/Contracts/ContractDefinition.cs new file mode 100644 index 0000000..c764296 --- /dev/null +++ b/CounterStrikeProgression.Core/Contracts/ContractDefinition.cs @@ -0,0 +1,70 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Core.Contracts; + +using ktsu.CounterStrikeProgression.Core.SkillShots; +using ktsu.CounterStrikeProgression.Core.Weapons; + +/// +/// How long a contract runs. +/// +internal enum ContractPeriod +{ + /// One UTC day. + Daily = 0, + + /// One ISO week, Monday to Sunday in UTC. + Weekly, +} + +/// +/// The kinds of thing a contract can count. +/// +internal enum SignalKind +{ + /// A kill of a player or bot. + Kill = 0, + + /// A skill shot earned. + SkillShot, + + /// A chicken killed. + Chicken, + + /// An assist. + Assist, + + /// A challenge tier finished. + Tier, + + /// A weapon level gained. + WeaponLevel, +} + +/// +/// One thing a player did that a contract might count. +/// +/// What happened. +/// The weapon involved, if any. +/// For kills, whether it was a headshot. +/// For skill shots, which one. +internal readonly record struct ContractSignal(SignalKind Kind, WeaponInfo? Weapon = null, bool Headshot = false, SkillShotDefinition? SkillShot = null); + +/// +/// One contract: a short goal that pays a bonus once in its day or week. +/// +/// The stable id, stored with the period's key. Never rename one. +/// What the player has to do, such as "Get 20 kills with SMGs". +/// How long the contract runs. +/// How many matching signals finish it. +/// Whether a signal counts toward it. +internal sealed record ContractDefinition(string Id, string Description, ContractPeriod Period, int Target, Func Counts); + +/// +/// A contract running now. +/// +/// The contract. +/// The key of the day or week it runs in, such as 2026-10-17 or 2026-W42. +/// When it ends, in UTC. +/// The rank XP it pays. +internal sealed record ActiveContract(ContractDefinition Definition, string PeriodKey, DateTime EndsAt, int Xp); diff --git a/CounterStrikeProgression.Core/Live/FeedBuilder.cs b/CounterStrikeProgression.Core/Live/FeedBuilder.cs index dbcd0f3..537f4cc 100644 --- a/CounterStrikeProgression.Core/Live/FeedBuilder.cs +++ b/CounterStrikeProgression.Core/Live/FeedBuilder.cs @@ -2,6 +2,7 @@ namespace ktsu.CounterStrikeProgression.Core.Live; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Panel; using ktsu.CounterStrikeProgression.Core.Progression; @@ -33,6 +34,7 @@ public static IReadOnlyList From(ProgressionResult result, ulong stea NoticeKind.WeaponLevelUp => (FeedKind.WeaponLevelUp, $"{notice.Weapon?.DisplayName} level {notice.Value}"), NoticeKind.TierCompleted => (FeedKind.TierCompleted, $"{notice.ChallengeName} {PanelBuilder.Numeral(notice.Value)}"), NoticeKind.FeatEarned => (FeedKind.FeatEarned, notice.Feat?.Name), + NoticeKind.ContractCompleted => (FeedKind.ContractCompleted, notice.Contract is { } contract ? ContractTitle(contract) : null), _ => (FeedKind.SkillShot, null), }; @@ -44,4 +46,16 @@ public static IReadOnlyList From(ProgressionResult result, ulong stea return entries; } + + /// + /// Gets the feed title of a finished contract, such as Daily contract: Get 20 kills with SMGs. + /// + /// The contract. + /// The title. + public static string ContractTitle(ActiveContract contract) + { + Ensure.NotNull(contract); + string period = contract.Definition.Period == ContractPeriod.Weekly ? "Weekly" : "Daily"; + return $"{period} contract: {contract.Definition.Description}"; + } } diff --git a/CounterStrikeProgression.Core/Live/LiveContracts.cs b/CounterStrikeProgression.Core/Live/LiveContracts.cs index bca4eea..ffe125f 100644 --- a/CounterStrikeProgression.Core/Live/LiveContracts.cs +++ b/CounterStrikeProgression.Core/Live/LiveContracts.cs @@ -15,6 +15,7 @@ internal enum FeedKind WeaponLevelUp, TierCompleted, FeatEarned, + ContractCompleted, } /// One line of the live feed. diff --git a/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs b/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs index bd291d5..37734bc 100644 --- a/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs +++ b/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs @@ -61,6 +61,17 @@ internal sealed class ProgressChangeTracker } } + List contracts = []; + foreach (ContractRow row in all.Contracts) + { + (string, string) key = (row.Period, row.Contract); + if (!last.Contracts.TryGetValue(key, out ContractRow? previous) || (previous != row)) + { + contracts.Add(row); + last.Contracts[key] = row; + } + } + List seasons = []; foreach (SeasonRow row in all.Seasons) { @@ -71,7 +82,7 @@ internal sealed class ProgressChangeTracker } } - ProgressSnapshot changes = new(player, weapons, challenges) { Seasons = seasons }; + ProgressSnapshot changes = new(player, weapons, challenges) { Contracts = contracts, Seasons = seasons }; return changes.IsEmpty ? null : changes; } @@ -95,5 +106,7 @@ private sealed class Sent public Dictionary Weapons { get; } = new(StringComparer.Ordinal); public Dictionary<(string, string), ChallengeRow> Challenges { get; } = []; + + public Dictionary<(string, string), ContractRow> Contracts { get; } = []; } } diff --git a/CounterStrikeProgression.Core/Panel/PanelBuilder.cs b/CounterStrikeProgression.Core/Panel/PanelBuilder.cs index 764b300..990ccbe 100644 --- a/CounterStrikeProgression.Core/Panel/PanelBuilder.cs +++ b/CounterStrikeProgression.Core/Panel/PanelBuilder.cs @@ -4,13 +4,14 @@ namespace ktsu.CounterStrikeProgression.Core.Panel; using System.Globalization; using ktsu.CounterStrikeProgression.Core.Challenges; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Progression; using ktsu.CounterStrikeProgression.Core.Rotation; using ktsu.CounterStrikeProgression.Core.Weapons; /// -/// Builds the pages of the progress panel from a player's progress. Page 0 is the overview, and every later -/// page is one weapon, with the weapons the player uses most first. +/// Builds the pages of the progress panel from a player's progress. Page 0 is the overview, page 1 is the +/// contracts, and every later page is one weapon, with the weapons the player uses most first. /// /// The engine whose ranks, levels, and ladders to show. internal sealed class PanelBuilder(ProgressionEngine engine) @@ -23,7 +24,7 @@ internal sealed class PanelBuilder(ProgressionEngine engine) /// Gets the weapons in page order: those the player has used, most XP first, then the rest in catalogue order. /// /// The player's progress. - /// The weapons, one per page after the overview. + /// The weapons, one per page after the overview and the contracts. public static IReadOnlyList WeaponOrder(PlayerProgress player) { Ensure.NotNull(player); @@ -38,15 +39,20 @@ .. WeaponCatalog.All } /// - /// Gets the number of pages: the overview plus one per weapon. + /// Gets the number of pages: the overview, the contracts, and one per weapon. /// - public static int PageCount => WeaponCatalog.All.Count + 1; + public static int PageCount => WeaponCatalog.All.Count + FirstWeaponPage; + + /// Gets the index of the contracts page. + public static int ContractsPage => 1; + + private static int FirstWeaponPage => ContractsPage + 1; /// /// Builds one page. /// /// The player's progress. - /// The page, where 0 is the overview. + /// The page, where 0 is the overview and 1 the contracts. /// The page. public PanelPage Page(PlayerProgress player, int pageIndex) { @@ -56,8 +62,74 @@ public PanelPage Page(PlayerProgress player, int pageIndex) return Overview(player); } + if (pageIndex == ContractsPage) + { + return Contracts(player); + } + IReadOnlyList order = WeaponOrder(player); - return Weapon(player, order[Math.Min(pageIndex - 1, order.Count - 1)]); + return Weapon(player, order[Math.Min(pageIndex - FirstWeaponPage, order.Count - 1)]); + } + + /// + /// Builds the contracts page: today's contracts, then the week's, each with its count and reward. + /// + /// The player's progress. + /// The page. + public PanelPage Contracts(PlayerProgress player) + { + Ensure.NotNull(player); + + IReadOnlyList active = engine.ActiveContracts; + if (active.Count == 0) + { + return new PanelPage("Contracts", "Off", 0, "No contracts are running", []); + } + + DateTime now = engine.Time.GetUtcNow().UtcDateTime; + List lines = []; + int done = 0; + ContractPeriod? section = null; + foreach (ActiveContract contract in active) + { + if (contract.Definition.Period != section) + { + section = contract.Definition.Period; + string name = section == ContractPeriod.Weekly ? "This week" : "Today"; + lines.Add(PanelLine.Heading($"{name}, {Remaining(contract.EndsAt - now)} left")); + } + + ContractProgress? progress = player.Contracts.GetValueOrDefault((contract.PeriodKey, contract.Definition.Id)); + long count = Math.Min(progress?.Count ?? 0, contract.Definition.Target); + if (progress?.Completed ?? false) + { + done++; + lines.Add(new(contract.Definition.Description, "Done", LineState.Done)); + continue; + } + + string detail = $"{Number(count)}/{Number(contract.Definition.Target)} +{Number(contract.Xp)}"; + lines.Add(new(contract.Definition.Description, detail, count > 0 ? LineState.InProgress : LineState.NotStarted)); + } + + return new PanelPage("Contracts", "Daily and weekly", (double)done / active.Count, $"{done} of {active.Count} done", lines); + } + + /// + /// Writes how long is left in a contract's period, such as 5h 12m or 3d 4h. + /// + /// The time left. + /// The text. + public static string Remaining(TimeSpan left) + { + if (left < TimeSpan.Zero) + { + left = TimeSpan.Zero; + } + + return left.TotalDays >= 1 + ? string.Create(CultureInfo.InvariantCulture, $"{(int)left.TotalDays}d {left.Hours}h") + : string.Create(CultureInfo.InvariantCulture, $"{left.Hours}h {left.Minutes}m"); } /// @@ -92,9 +164,17 @@ public PanelPage Overview(PlayerProgress player) new("Weapons levelled", $"{levelled} of {WeaponCatalog.All.Count}", LineState.InProgress), new("Tiers finished", Number(tiers), LineState.InProgress), new($"Season {engine.CurrentSeason.Name}", $"{Number(engine.SeasonXp(player))} XP", LineState.InProgress), - PanelLine.Heading("Closest tiers"), ]); + IReadOnlyList contracts = engine.ActiveContracts; + if (contracts.Count > 0) + { + int done = contracts.Count(c => player.Contracts.GetValueOrDefault((c.PeriodKey, c.Definition.Id))?.Completed ?? false); + lines.Add(new("Contracts", $"{done} of {contracts.Count} done", done == contracts.Count ? LineState.Done : LineState.InProgress)); + } + + lines.Add(PanelLine.Heading("Closest tiers")); + lines.AddRange(ClosestTiers(player, ClosestTiersShown)); return new PanelPage(RankLadder.Names[rank], "Overview", engine.Ranks.ProgressToNext(player.RankXp), progressLabel, lines); } diff --git a/CounterStrikeProgression.Core/Progression/PlayerProgress.cs b/CounterStrikeProgression.Core/Progression/PlayerProgress.cs index 7af42c4..f9ab088 100644 --- a/CounterStrikeProgression.Core/Progression/PlayerProgress.cs +++ b/CounterStrikeProgression.Core/Progression/PlayerProgress.cs @@ -20,6 +20,21 @@ internal sealed class ChallengeProgress public bool IsDirty { get; set; } } +/// +/// One contract's count in one day or week. +/// +internal sealed class ContractProgress +{ + /// Gets or sets how many matching things the player has done. + public long Count { get; set; } + + /// Gets or sets a value indicating whether the contract is finished and paid. + public bool Completed { get; set; } + + /// Gets or sets a value indicating whether the row changed since it was last saved. + public bool IsDirty { get; set; } +} + /// /// A player's progress with one weapon. /// @@ -100,6 +115,9 @@ internal sealed class PlayerProgress(ulong steamId) /// Gets the player's weapons, keyed by weapon. public Dictionary Weapons { get; } = []; + /// Gets the player's contracts, keyed by the period's key and the contract id. Only current periods are loaded. + public Dictionary<(string Period, string Contract), ContractProgress> Contracts { get; } = []; + /// /// Gets or sets the first day of the season was earned in, or before /// the player has earned any. Only the latest season is loaded, so it can be a season that has already ended. @@ -121,6 +139,14 @@ internal sealed class PlayerProgress(ulong steamId) /// Gets or sets a value indicating whether the player row changed since it was last saved. public bool IsDirty { get; set; } + /// + /// Gets a contract's progress in a period, creating it when the player hasn't started it. + /// + /// The period's key, such as 2026-10-17 or 2026-W42. + /// The contract id. + /// The contract's progress. + public ContractProgress Contract(string period, string contract) => Contracts.GetOrCreate((period, contract)); + /// /// Gets a weapon's progress, creating it when the player hasn't used the weapon. /// diff --git a/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs b/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs index 24b98e0..1d69a35 100644 --- a/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs +++ b/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs @@ -3,6 +3,7 @@ namespace ktsu.CounterStrikeProgression.Core.Progression; using ktsu.CounterStrikeProgression.Core.Challenges; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Events; using ktsu.CounterStrikeProgression.Core.Feats; using ktsu.CounterStrikeProgression.Core.Rotation; @@ -18,7 +19,7 @@ namespace ktsu.CounterStrikeProgression.Core.Progression; /// level-up bonuses are paid in full, because they reward the ladder rather than one event. The day's featured /// weapon class earns times the weapon XP and ladder /// progress, but not the rank XP. Every point of rank XP also counts toward the current season, which starts again -/// from 0 when the next season begins. +/// from 0 when the next season begins. Contracts count what each event did once it's applied. /// /// The XP values and thresholds. /// The clock that decides the day and the season, or the system clock when omitted. @@ -47,6 +48,9 @@ public bool IsFeatured(WeaponInfo weapon) return weapon.Class == FeaturedClass; } + /// Gets the contracts running today. + public IReadOnlyList ActiveContracts => ContractCatalog.Active(Today, Settings); + /// Gets the season running now. public Season CurrentSeason => Season.For(DateOnly.FromDateTime(Time.GetUtcNow().UtcDateTime), Settings.SeasonMonths); @@ -135,6 +139,7 @@ public ProgressionResult ApplyCombat(PlayerProgress player, CombatEvent combat) { award.EventXp += Settings.KillXp; weapon.Kills++; + result.Signals.Add(new(SignalKind.Kill, combat.Weapon, combat.IsHeadshot)); Advance(weapon, award, ChallengeDefinition.KillsId, result); if (combat.IsHeadshot) { @@ -160,7 +165,7 @@ public ProgressionResult ApplyCombat(PlayerProgress player, CombatEvent combat) } Credit(player, weapon, award, result); - return result; + return Settle(player, result); } /// @@ -180,6 +185,7 @@ public ProgressionResult ApplyChickenKill(PlayerProgress player, CombatEvent chi WeaponProgress progress = player.Weapon(chicken.Weapon.Key); progress.IsDirty = true; award.EventXp += Settings.ChickenXp; + result.Signals.Add(new(SignalKind.Chicken, chicken.Weapon)); Advance(progress, award, ChallengeDefinition.ChickensId, result); foreach (SkillShotDefinition skillShot in SkillShotCatalog.For(SkillTrigger.Chicken)) { @@ -190,7 +196,7 @@ public ProgressionResult ApplyChickenKill(PlayerProgress player, CombatEvent chi } Credit(player, progress, award, result); - return result; + return Settle(player, result); } /// @@ -231,7 +237,7 @@ public ProgressionResult ApplyReload(PlayerProgress player, ReloadEvent reload) AwardSkillShot(player, reload.Weapon, SkillShotCatalog.EfficientReload, vsBot: false, result); } - return result; + return Settle(player, result); } /// @@ -270,7 +276,7 @@ public ProgressionResult ApplyLifeEnd(PlayerProgress player, WeaponLifeStats lif AwardSkillShot(player, life.Weapon, SkillShotCatalog.Headhunter, life.MostlyBots, result); } - return result; + return Settle(player, result); } /// @@ -289,6 +295,7 @@ public ProgressionResult ApplyAssist(PlayerProgress player, AssistEvent assist) award.EventXp = Settings.AssistXp; WeaponProgress weapon = player.Weapon(assist.Weapon.Key); weapon.IsDirty = true; + result.Signals.Add(new(SignalKind.Assist, assist.Weapon)); SkillShotDefinition flashAssist = SkillShotCatalog.Get(SkillShotCatalog.FlashAssist); if (assist.ByFlash && flashAssist.AppliesTo(assist.Weapon)) @@ -297,7 +304,7 @@ public ProgressionResult ApplyAssist(PlayerProgress player, AssistEvent assist) } Credit(player, weapon, award, result); - return result; + return Settle(player, result); } /// @@ -317,7 +324,7 @@ public ProgressionResult ApplyFlash(PlayerProgress player, FlashEvent flash) AwardSkillShot(player, flash.Weapon, SkillShotCatalog.LongFlash, flash.VictimIsBot, result); } - return result; + return Settle(player, result); } /// @@ -343,12 +350,13 @@ public ProgressionResult ApplyClutch(PlayerProgress player, ClutchEvent clutch) // No weapon to put the ladder progress on, so the clutch pays XP alone. ProgressionNotice notice = new() { Kind = NoticeKind.SkillShot, SkillShot = skillShot, Xp = SkillShotXp(skillShot.Rarity) }; result.Notices.Add(notice); + result.Signals.Add(new(SignalKind.SkillShot, SkillShot: skillShot)); CreditRankXp(player, SkillShotXp(skillShot.Rarity), result); - return result; + return Settle(player, result); } AwardSkillShot(player, clutch.LastWeapon, SkillShotCatalog.Clutch, vsBot: false, result); - return result; + return Settle(player, result); } /// @@ -383,6 +391,7 @@ private void EarnSkillShot(WeaponProgress weapon, Award award, SkillShotDefiniti int xp = SkillShotXp(skillShot.Rarity); award.EventXp += xp; result.Notices.Add(new() { Kind = NoticeKind.SkillShot, Weapon = award.Weapon, SkillShot = skillShot, Xp = (long)Math.Round(ScaleForBots(xp, award.VsBot)) }); + result.Signals.Add(new(SignalKind.SkillShot, award.Weapon, SkillShot: skillShot)); Advance(weapon, award, skillShot.Id.WeakString, result); } @@ -414,6 +423,7 @@ private void Advance(WeaponProgress weapon, Award award, string challengeId, Pro Xp = bonus, Broadcast = true, }); + result.Signals.Add(new(SignalKind.Tier, award.Weapon)); } } @@ -428,12 +438,67 @@ private void Credit(PlayerProgress player, WeaponProgress weapon, Award award, P award.BonusXp += bonus; bool broadcast = (Settings.AnnounceWeaponLevelEvery > 0) && ((level % Settings.AnnounceWeaponLevelEvery) == 0); result.Notices.Add(new() { Kind = NoticeKind.WeaponLevelUp, Weapon = award.Weapon, Value = level, Xp = bonus, Broadcast = broadcast }); + result.Signals.Add(new(SignalKind.WeaponLevel, award.Weapon)); } double rankXp = ScaleForBots(award.EventXp, award.VsBot) + award.BonusXp; CreditRankXp(player, rankXp, result); } + /// + /// Counts what an event did toward the running contracts, pays for any it finishes, and drops contract rows + /// from earlier periods once they're saved. + /// + private ProgressionResult Settle(PlayerProgress player, ProgressionResult result) + { + IReadOnlyList active = ActiveContracts; + DropStale(player, active); + foreach (ContractSignal signal in result.Signals) + { + foreach (ActiveContract contract in active) + { + if (!contract.Definition.Counts(signal)) + { + continue; + } + + ContractProgress progress = player.Contract(contract.PeriodKey, contract.Definition.Id); + if (progress.Completed) + { + continue; + } + + progress.Count++; + progress.IsDirty = true; + if (progress.Count >= contract.Definition.Target) + { + progress.Completed = true; + result.Notices.Add(new() { Kind = NoticeKind.ContractCompleted, Contract = contract, Xp = contract.Xp }); + CreditRankXp(player, contract.Xp, result); + } + } + } + + result.Signals.Clear(); + return result; + } + + private static void DropStale(PlayerProgress player, IReadOnlyList active) + { + // A row is stale once its contract stops running. It goes only after it has saved, so the count isn't lost. + bool IsRunning((string Period, string Contract) key) => active.Any(a => (a.PeriodKey == key.Period) && (a.Definition.Id == key.Contract)); + if (!player.Contracts.Keys.All(IsRunning)) + { + foreach ((string Period, string Contract) key in player.Contracts.Keys.ToList()) + { + if (!player.Contracts[key].IsDirty && !IsRunning(key)) + { + player.Contracts.Remove(key); + } + } + } + } + private void CreditRankXp(PlayerProgress player, double xp, ProgressionResult result) { result.XpEarned += Math.Max(0, xp); diff --git a/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs b/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs index badfd78..5b298ab 100644 --- a/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs +++ b/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs @@ -2,8 +2,8 @@ namespace ktsu.CounterStrikeProgression.Core.Progression; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Feats; - using ktsu.CounterStrikeProgression.Core.SkillShots; using ktsu.CounterStrikeProgression.Core.Weapons; @@ -17,6 +17,7 @@ internal enum NoticeKind WeaponLevelUp, RankUp, FeatEarned, + ContractCompleted, } /// @@ -36,6 +37,9 @@ internal sealed record ProgressionNotice /// Gets the feat earned, for feat notices. public FeatDefinition? Feat { get; init; } + /// Gets the contract finished, for contract notices. + public ActiveContract? Contract { get; init; } + /// Gets the challenge name, for tier notices. public string? ChallengeName { get; init; } @@ -65,4 +69,7 @@ internal sealed class ProgressionResult /// Gets the moments worth telling the player about, in the order they happened. public IList Notices { get; } = []; + + /// Gets what the event did that contracts might count. The engine empties it once they're counted. + internal IList Signals { get; } = []; } diff --git a/CounterStrikeProgression.Core/ProgressionSettings.cs b/CounterStrikeProgression.Core/ProgressionSettings.cs index 9399a34..9cd16dd 100644 --- a/CounterStrikeProgression.Core/ProgressionSettings.cs +++ b/CounterStrikeProgression.Core/ProgressionSettings.cs @@ -174,6 +174,18 @@ public sealed class ProgressionSettings /// public double FeaturedWeaponMultiplier { get; set; } = 2; + /// Gets or sets a value indicating whether daily and weekly contracts run. + public bool ContractsEnabled { get; set; } = true; + + /// Gets or sets how many contracts each day has, up to the size of the daily pool. + public int DailyContracts { get; set; } = 3; + + /// Gets or sets the rank XP for finishing a daily contract. + public int DailyContractXp { get; set; } = 500; + + /// Gets or sets the rank XP for finishing the weekly contract. + public int WeeklyContractXp { get; set; } = 2500; + /// Gets or sets how long each season lasts, in months. Seasons start on 1 January and every this many months after. public int SeasonMonths { get; set; } = 3; } diff --git a/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs b/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs index 28147fe..8389e1a 100644 --- a/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs +++ b/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs @@ -15,6 +15,7 @@ internal sealed class InMemoryProgressionStore : IProgressionStore private readonly ConcurrentDictionary players = new(); private readonly ConcurrentDictionary<(ulong, string), WeaponRow> weapons = new(); private readonly ConcurrentDictionary<(ulong, string, string), ChallengeRow> challenges = new(); + private readonly ConcurrentDictionary<(ulong, string, string), ContractRow> contracts = new(); private readonly ConcurrentDictionary<(ulong SteamId, DateOnly Day), long> daily = new(); private readonly ConcurrentDictionary<(ulong, DateTime), SeasonRow> seasons = new(); @@ -36,7 +37,8 @@ internal sealed class InMemoryProgressionStore : IProgressionStore player, weapons.Values.Where(w => w.SteamId == steamId), challenges.Values.Where(c => c.SteamId == steamId), - seasons.Values.Where(s => s.SteamId == steamId).MaxBy(s => s.Start)); + seasons.Values.Where(s => s.SteamId == steamId).MaxBy(s => s.Start), + contracts.Values.Where(c => c.SteamId == steamId)); return Task.FromResult(progress); } @@ -61,6 +63,11 @@ public Task SaveAsync(ProgressSnapshot snapshot, CancellationToken cancellationT challenges[(row.SteamId, row.Weapon, row.Challenge)] = row; } + foreach (ContractRow row in snapshot.Contracts) + { + contracts[(row.SteamId, row.Period, row.Contract)] = row; + } + foreach (SeasonRow row in snapshot.Seasons) { seasons[(row.SteamId, row.Start)] = row; @@ -85,6 +92,11 @@ public Task ResetAsync(PlayerRow player, CancellationToken cancellationToken) challenges.TryRemove(key, out _); } + foreach ((ulong, string, string) key in contracts.Keys.Where(k => k.Item1 == player.SteamId).ToList()) + { + contracts.TryRemove(key, out _); + } + foreach ((ulong, DateTime) key in seasons.Keys.Where(k => k.Item1 == player.SteamId).ToList()) { seasons.TryRemove(key, out _); diff --git a/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs b/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs index 96ac5a5..79e0e88 100644 --- a/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs +++ b/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs @@ -5,6 +5,7 @@ namespace ktsu.CounterStrikeProgression.Core.Storage; using System.Runtime.CompilerServices; using Dapper; using ktsu.CounterStrikeProgression.Core.Progression; +using ktsu.CounterStrikeProgression.Core.Rotation; using ktsu.CounterStrikeProgression.Core.Weapons; using MySqlConnector; @@ -62,6 +63,15 @@ challenge VARCHAR(48) NOT NULL, PRIMARY KEY (steam_id, weapon, challenge) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; + CREATE TABLE IF NOT EXISTS csp_contracts ( + steam_id BIGINT UNSIGNED NOT NULL, + period VARCHAR(16) NOT NULL, + contract VARCHAR(48) NOT NULL, + count BIGINT NOT NULL DEFAULT 0, + completed TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (steam_id, period, contract) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; + CREATE TABLE IF NOT EXISTS csp_daily ( steam_id BIGINT UNSIGNED NOT NULL, day DATE NOT NULL, @@ -151,6 +161,12 @@ INSERT INTO csp_challenges (steam_id, weapon, challenge, count, tier) ON DUPLICATE KEY UPDATE count = VALUES(count), tier = VALUES(tier); """; + private const string UpsertContract = """ + INSERT INTO csp_contracts (steam_id, period, contract, count, completed) + VALUES (@SteamId, @Period, @Contract, @Count, @Completed) + ON DUPLICATE KEY UPDATE count = VALUES(count), completed = VALUES(completed); + """; + private const string UpsertSeason = """ INSERT INTO csp_seasons (steam_id, season_start, xp) VALUES (@SteamId, @Start, @Xp) @@ -176,6 +192,9 @@ FROM csp_seasons s ORDER BY s.season_start DESC """; + private const string SelectContracts = + "SELECT steam_id AS SteamId, period AS Period, contract AS Contract, count AS `Count`, completed AS Completed FROM csp_contracts WHERE steam_id = @steamId AND period IN (@day, @week)"; + /// /// Clears a player's rows for a reset. Their daily history starts again from the day before, so the XP they /// keep isn't counted as earned. @@ -183,6 +202,7 @@ ORDER BY s.season_start DESC private const string DeletePlayerRows = """ DELETE FROM csp_challenges WHERE steam_id = @SteamId; DELETE FROM csp_weapons WHERE steam_id = @SteamId; + DELETE FROM csp_contracts WHERE steam_id = @SteamId; DELETE FROM csp_seasons WHERE steam_id = @SteamId; DELETE FROM csp_daily WHERE steam_id = @SteamId; INSERT INTO csp_daily (steam_id, day, rank_xp) VALUES (@SteamId, DATE(@LastSeen) - INTERVAL 1 DAY, @RankXp); @@ -258,7 +278,14 @@ public async Task InitializeAsync(CancellationToken cancellationToken) parameters, cancellationToken: cancellationToken)).ConfigureAwait(false); - return ProgressSnapshot.Rebuild(player, weapons, challenges, season); + // Only the running day and week matter, so older contract rows stay in the table but aren't read. + DateOnly today = DailyRotation.Day(DateTime.UtcNow); + IEnumerable contracts = await connection.QueryAsync(new CommandDefinition( + SelectContracts, + new { steamId, day = DailyRotation.DayKey(today), week = DailyRotation.WeekKey(today) }, + cancellationToken: cancellationToken)).ConfigureAwait(false); + + return ProgressSnapshot.Rebuild(player, weapons, challenges, season, contracts); } /// @@ -291,6 +318,11 @@ public async Task SaveAsync(ProgressSnapshot snapshot, CancellationToken cancell await connection.ExecuteAsync(new CommandDefinition(UpsertChallenge, snapshot.Challenges, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false); } + if (snapshot.Contracts.Count > 0) + { + await connection.ExecuteAsync(new CommandDefinition(UpsertContract, snapshot.Contracts, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false); + } + if (snapshot.Seasons.Count > 0) { await connection.ExecuteAsync(new CommandDefinition(UpsertSeason, snapshot.Seasons, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false); diff --git a/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs b/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs index 0e4e0da..0c7f7b6 100644 --- a/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs +++ b/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs @@ -33,6 +33,14 @@ internal sealed record WeaponRow(ulong SteamId, string Weapon, long Xp, int Leve /// The number of tiers finished. internal sealed record ChallengeRow(ulong SteamId, string Weapon, string Challenge, long Count, int Tier); +/// A contract row as stored. +/// The 64-bit Steam ID. +/// The key of the day or week, such as 2026-10-17 or 2026-W42. +/// The contract id. +/// How many matching things the player has done. +/// Whether the contract is finished and paid. +internal sealed record ContractRow(ulong SteamId, string Period, string Contract, long Count, bool Completed); + /// A player's XP in one season, as stored. /// The 64-bit Steam ID. /// The season's first day, at midnight UTC. @@ -49,6 +57,9 @@ internal sealed record SeasonRow(ulong SteamId, DateTime Start, long Xp); /// The challenge rows that changed. internal sealed record ProgressSnapshot(PlayerRow? Player, IReadOnlyList Weapons, IReadOnlyList Challenges) { + /// Gets the contract rows that changed. + public IReadOnlyList Contracts { get; init; } = []; + /// /// Gets the season rows that changed: usually the current season alone, and the season before it too when it /// ended between saves. @@ -56,7 +67,7 @@ internal sealed record ProgressSnapshot(PlayerRow? Player, IReadOnlyList Seasons { get; init; } = []; /// Gets a value indicating whether there's nothing to save. - public bool IsEmpty => (Player is null) && (Weapons.Count == 0) && (Challenges.Count == 0) && (Seasons.Count == 0); + public bool IsEmpty => (Player is null) && (Weapons.Count == 0) && (Challenges.Count == 0) && (Contracts.Count == 0) && (Seasons.Count == 0); /// /// Copies a player's changed rows and clears their dirty flags. @@ -94,6 +105,16 @@ public static ProgressSnapshot Capture(PlayerProgress progress) } } + List contracts = []; + foreach (((string period, string id), ContractProgress contract) in progress.Contracts) + { + if (contract.IsDirty) + { + contracts.Add(new(progress.SteamId, period, id, contract.Count, contract.Completed)); + contract.IsDirty = false; + } + } + List seasons = []; if (progress.EndedSeason is { } ended) { @@ -107,7 +128,7 @@ public static ProgressSnapshot Capture(PlayerProgress progress) progress.IsSeasonDirty = false; } - return new(player, weapons, challenges) { Seasons = seasons }; + return new(player, weapons, challenges) { Contracts = contracts, Seasons = seasons }; } /// @@ -130,7 +151,8 @@ public static ProgressSnapshot CaptureAll(PlayerProgress progress) } } - return new(ToRow(progress), weapons, challenges) { Seasons = ToSeasonRow(progress) is { } season ? [season] : [] }; + List contracts = [.. progress.Contracts.Select(c => new ContractRow(progress.SteamId, c.Key.Period, c.Key.Contract, c.Value.Count, c.Value.Completed))]; + return new(ToRow(progress), weapons, challenges) { Contracts = contracts, Seasons = ToSeasonRow(progress) is { } season ? [season] : [] }; } /// @@ -180,6 +202,11 @@ public void Restore(PlayerProgress progress) progress.Weapon(WeaponKey.Create(row.Weapon)).Challenge(row.Challenge).IsDirty = true; } + foreach (ContractRow row in Contracts) + { + progress.Contract(row.Period, row.Contract).IsDirty = true; + } + foreach (SeasonRow row in Seasons) { DateOnly start = DateOnly.FromDateTime(row.Start); @@ -201,8 +228,9 @@ public void Restore(PlayerProgress progress) /// The player's weapon rows. /// The player's challenge rows. /// The player's latest season row, if they have one. + /// The player's contract rows, if any. /// The progress, with nothing flagged dirty. - public static PlayerProgress Rebuild(PlayerRow player, IEnumerable weapons, IEnumerable challenges, SeasonRow? season = null) + public static PlayerProgress Rebuild(PlayerRow player, IEnumerable weapons, IEnumerable challenges, SeasonRow? season = null, IEnumerable? contracts = null) { Ensure.NotNull(player); Ensure.NotNull(weapons); @@ -247,6 +275,13 @@ public static PlayerProgress Rebuild(PlayerRow player, IEnumerable we challenge.TierReached = row.Tier; } + foreach (ContractRow row in contracts ?? []) + { + ContractProgress contract = progress.Contract(row.Period, row.Contract); + contract.Count = row.Count; + contract.Completed = row.Completed; + } + return progress; } } diff --git a/CounterStrikeProgression.Site/Endpoints.cs b/CounterStrikeProgression.Site/Endpoints.cs index 566eb76..629a1ad 100644 --- a/CounterStrikeProgression.Site/Endpoints.cs +++ b/CounterStrikeProgression.Site/Endpoints.cs @@ -331,6 +331,9 @@ private static bool IsComplete([System.Diagnostics.CodeAnalysis.NotNullWhen(true batch is { Snapshot.Players: { } players, Feed: { } feed, Progress: { } progress, Settings: not null } && players.All(p => p is not null) && feed.All(e => e is not null) - && progress.All(p => p is { Weapons: { } weapons, Challenges: { } challenges } && weapons.All(w => w is not null) && challenges.All(c => c is not null)) + && progress.All(p => p is { Weapons: { } weapons, Challenges: { } challenges, Contracts: { } contracts } + && weapons.All(w => w is not null) + && challenges.All(c => c is not null) + && contracts.All(c => c is { Period: not null, Contract: not null })) && (batch.Recaps?.All(r => r is { PlayerName: not null, Map: not null }) ?? true); } diff --git a/CounterStrikeProgression.Site/Live/ProgressMerge.cs b/CounterStrikeProgression.Site/Live/ProgressMerge.cs index 0864032..a2460c7 100644 --- a/CounterStrikeProgression.Site/Live/ProgressMerge.cs +++ b/CounterStrikeProgression.Site/Live/ProgressMerge.cs @@ -70,13 +70,21 @@ public static ProgressSnapshot Combine(ProgressSnapshot older, ProgressSnapshot (var o, var n) => LargerPlayer(o!, n!), }; + Dictionary<(string Period, string Contract), ContractRow> contracts = older.Contracts.ToDictionary(c => (c.Period, c.Contract)); + foreach (ContractRow row in newer.Contracts) + { + contracts[(row.Period, row.Contract)] = contracts.TryGetValue((row.Period, row.Contract), out ContractRow? existing) + ? existing with { Count = Math.Max(existing.Count, row.Count), Completed = existing.Completed || row.Completed } + : row; + } + Dictionary seasons = older.Seasons.ToDictionary(r => r.Start); foreach (SeasonRow row in newer.Seasons) { seasons[row.Start] = seasons.TryGetValue(row.Start, out SeasonRow? existing) && existing.Xp > row.Xp ? existing : row; } - return new(player, [.. weapons.Values], [.. challenges.Values]) { Seasons = [.. seasons.Values.OrderBy(r => r.Start)] }; + return new(player, [.. weapons.Values], [.. challenges.Values]) { Contracts = [.. contracts.Values], Seasons = [.. seasons.Values.OrderBy(r => r.Start)] }; } /// @@ -106,6 +114,11 @@ public static ProgressSnapshot Combine(ProgressSnapshot older, ProgressSnapshot return snapshot.Challenges[0].SteamId; } + if (snapshot.Contracts.Count > 0) + { + return snapshot.Contracts[0].SteamId; + } + return snapshot.Seasons.Count > 0 ? snapshot.Seasons[0].SteamId : null; } @@ -134,6 +147,13 @@ private static void CopyStored(PlayerProgress stored, PlayerProgress result) challengeCopy.TierReached = challenge.TierReached; } } + + foreach (((string period, string id), ContractProgress contract) in stored.Contracts) + { + ContractProgress copy = result.Contract(period, id); + copy.Count = contract.Count; + copy.Completed = contract.Completed; + } } private static void ApplyLive(PlayerProgress result, ProgressSnapshot live, bool noStored) @@ -175,6 +195,13 @@ private static void ApplyLive(PlayerProgress result, ProgressSnapshot live, bool challenge.TierReached = Math.Max(challenge.TierReached, row.Tier); } + foreach (ContractRow row in live.Contracts) + { + ContractProgress contract = result.Contract(row.Period, row.Contract); + contract.Count = Math.Max(contract.Count, row.Count); + contract.Completed = contract.Completed || row.Completed; + } + // Only the latest season is kept, so a live row for a later season replaces the stored one. foreach (SeasonRow row in live.Seasons) { diff --git a/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs b/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs index f0ff793..9a7f1f7 100644 --- a/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs +++ b/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs @@ -5,10 +5,12 @@ namespace ktsu.CounterStrikeProgression.Site.Views; using System.Globalization; using ktsu.CounterStrikeProgression.Core; using ktsu.CounterStrikeProgression.Core.Challenges; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Feats; using ktsu.CounterStrikeProgression.Core.Live; using ktsu.CounterStrikeProgression.Core.Progression; using ktsu.CounterStrikeProgression.Core.Recap; +using ktsu.CounterStrikeProgression.Core.Rotation; using ktsu.CounterStrikeProgression.Core.SkillShots; using ktsu.CounterStrikeProgression.Core.Weapons; @@ -26,8 +28,9 @@ internal static class PlayerViewBuilder /// Whether the player is on the server now. /// The player's feed, newest first. Omitted, the page shows none. /// The player's last map recap. Omitted, the page shows none. + /// The moment that decides which contracts are running, in UTC, or the current time when omitted. /// The page model. - public static PlayerView Build(PlayerProgress merged, ProgressionSettings settings, bool online, IReadOnlyList? feed = null, MapRecap? lastSession = null) + public static PlayerView Build(PlayerProgress merged, ProgressionSettings settings, bool online, IReadOnlyList? feed = null, MapRecap? lastSession = null, DateTime? now = null) { Ensure.NotNull(merged); Ensure.NotNull(settings); @@ -66,9 +69,28 @@ .. merged.Weapons.Values ChallengeSuggester.Suggest(merged, settings, catalog), [.. new FeatCatalog(settings).Measure(merged).Select(m => new FeatView(m.Feat.Id, m.Feat.Name, m.Feat.Description, m.Progress.IsEarned, Math.Min(m.Progress.Current, m.Progress.Target), m.Progress.Target))], FeedCaptions.For(feed ?? [], settings), - lastSession is null ? null : BuildSession(lastSession)); + lastSession is null ? null : BuildSession(lastSession), + Contracts(merged, settings, now ?? DateTime.UtcNow)); } + /// + /// Gets the contracts running at a moment, with the player's progress on each. + /// + /// The player's progress. + /// The plugin's settings, which decide how many contracts run and what they pay. + /// The moment, in UTC. + /// The contracts, today's first. + internal static IReadOnlyList Contracts(PlayerProgress merged, ProgressionSettings settings, DateTime now) => + [ + .. ContractCatalog.Active(DailyRotation.Day(now), settings).Select(c => + { + ContractProgress? progress = merged.Contracts.GetValueOrDefault((c.PeriodKey, c.Definition.Id)); + bool completed = progress?.Completed ?? false; + long count = completed ? c.Definition.Target : Math.Min(progress?.Count ?? 0, c.Definition.Target); + return new ContractView(c.Definition.Id, c.Definition.Description, c.Definition.Period, count, c.Definition.Target, completed, c.Xp, c.EndsAt); + }), + ]; + private static SessionView BuildSession(MapRecap recap) => new(recap.Map, recap.StartedAt, recap.EndedAt, recap.Xp, recap.Kills, recap.Deaths, recap.SkillShots, recap.Levels, recap.Tiers, recap.RankUps, recap.Feats, recap.Best); diff --git a/CounterStrikeProgression.Site/Views/ViewModels.cs b/CounterStrikeProgression.Site/Views/ViewModels.cs index 15c86e5..beca8ef 100644 --- a/CounterStrikeProgression.Site/Views/ViewModels.cs +++ b/CounterStrikeProgression.Site/Views/ViewModels.cs @@ -3,6 +3,7 @@ namespace ktsu.CounterStrikeProgression.Site.Views; using ktsu.CounterStrikeProgression.Core.Challenges; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Live; using ktsu.CounterStrikeProgression.Core.SkillShots; @@ -67,6 +68,7 @@ internal sealed record WeaponView( /// Every feat, earned or not, with the player's progress toward it. /// The player's feed, newest first. /// The player's last finished map, or when none has been seen. +/// The contracts running now, today's first, with the player's progress on each. internal sealed record PlayerView( string SteamId, string Name, @@ -83,7 +85,19 @@ internal sealed record PlayerView( IReadOnlyList Suggestions, IReadOnlyList Feats, IReadOnlyList Feed, - SessionView? LastSession); + SessionView? LastSession, + IReadOnlyList Contracts); + +/// One running contract on a player's page. +/// The contract id. +/// What the player has to do. +/// Whether it's a daily or a weekly contract. +/// How many matching things the player has done, up to the target. +/// The count that finishes it. +/// Whether the player has finished it. +/// The rank XP it pays. +/// When it ends, in UTC. +internal sealed record ContractView(string Id, string Description, ContractPeriod Period, long Count, int Target, bool Completed, int Xp, DateTime EndsAt); /// A player's last finished map, as the player page shows it. /// The map played. diff --git a/CounterStrikeProgression.Site/wwwroot/site.css b/CounterStrikeProgression.Site/wwwroot/site.css index 43842cf..af9ebe3 100644 --- a/CounterStrikeProgression.Site/wwwroot/site.css +++ b/CounterStrikeProgression.Site/wwwroot/site.css @@ -434,6 +434,23 @@ td.name { border-left-color: var(--green); } +.suggestion.contract { + border-left-color: var(--gold); +} + +.suggestion.contract.done { + border-left-color: var(--green); + opacity: 0.75; +} + +.suggestion.contract.done .xp { + color: var(--green); +} + +.suggestions + .section-title { + margin-top: 14px; +} + .suggestion .head { display: flex; justify-content: space-between; diff --git a/CounterStrikeProgression.Site/wwwroot/site.js b/CounterStrikeProgression.Site/wwwroot/site.js index 8b8057f..4a95010 100644 --- a/CounterStrikeProgression.Site/wwwroot/site.js +++ b/CounterStrikeProgression.Site/wwwroot/site.js @@ -49,7 +49,7 @@ const REFETCH_EVERY_MS = 2000; const STREAM_GRACE_MS = 15000; const STEAM_ID = /^\d{17}$/; - const GOLD_KINDS = new Set(["RankUp", "WeaponLevelUp", "TierCompleted", "FeatEarned"]); + const GOLD_KINDS = new Set(["RankUp", "WeaponLevelUp", "TierCompleted", "FeatEarned", "ContractCompleted"]); const ROMAN = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]; function el(tag, className, text) { @@ -780,6 +780,27 @@ return card; } + // Says how long a contract has left, such as "5h 12m left" or "3d 4h left". + function timeLeft(endsAt) { + const ms = Math.max(0, new Date(endsAt).getTime() - Date.now()); + const minutes = Math.floor(ms / 60000); + const days = Math.floor(minutes / 1440); + const hours = Math.floor((minutes % 1440) / 60); + return days > 0 ? `${days}d ${hours}h left` : `${hours}h ${minutes % 60}m left`; + } + + function contractCard(contract) { + const card = el("div", contract.completed ? "suggestion contract done" : "suggestion contract"); + const head = el("div", "head"); + head.append(el("b", null, contract.description), el("span", "xp", contract.completed ? "Done" : `+${formatXp(contract.xp)}`)); + const period = contract.period === "Weekly" ? "Weekly" : "Daily"; + card.append(head, el("div", "muted", `${period} contract · ${timeLeft(contract.endsAt)}`)); + const target = Number(contract.target) || 0; + const count = Math.min(Number(contract.count) || 0, target); + card.append(bar(target > 0 ? count / target : 0), el("div", "muted", `${formatXp(count)}/${formatXp(target)}`)); + return card; + } + // Skill shots on the weapons tab are listed commonest first. const RARITY_ORDER = { Common: 0, Rare: 1, Epic: 2 }; @@ -1066,11 +1087,19 @@ function nextTab(player) { const suggestions = Array.isArray(player.suggestions) ? player.suggestions : []; - return suggestions.length > 0 ? "next" : "weapons"; + const contracts = Array.isArray(player.contracts) ? player.contracts : []; + return suggestions.length > 0 || contracts.length > 0 ? "next" : "weapons"; } function renderNext(player) { const box = el("div", "pad"); + const contracts = Array.isArray(player.contracts) ? player.contracts : []; + if (contracts.length > 0) { + const done = contracts.filter((contract) => contract.completed).length; + const contractCards = el("div", "suggestions"); + contractCards.append(...contracts.map(contractCard)); + box.append(el("h2", "section-title", `Contracts · ${done}/${contracts.length} done`), contractCards); + } const suggestions = Array.isArray(player.suggestions) ? player.suggestions : []; if (suggestions.length === 0) { box.append(message("Nothing to suggest yet. Play a few rounds and the closest tiers show up here.")); diff --git a/CounterStrikeProgression.Test/ContractTests.cs b/CounterStrikeProgression.Test/ContractTests.cs new file mode 100644 index 0000000..d043c44 --- /dev/null +++ b/CounterStrikeProgression.Test/ContractTests.cs @@ -0,0 +1,467 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Test; + +using ktsu.CounterStrikeProgression.Core; +using ktsu.CounterStrikeProgression.Core.Admin; +using ktsu.CounterStrikeProgression.Core.Contracts; +using ktsu.CounterStrikeProgression.Core.Live; +using ktsu.CounterStrikeProgression.Core.Panel; +using ktsu.CounterStrikeProgression.Core.Progression; +using ktsu.CounterStrikeProgression.Core.Rotation; +using ktsu.CounterStrikeProgression.Core.SkillShots; +using ktsu.CounterStrikeProgression.Core.Storage; +using ktsu.CounterStrikeProgression.Core.Weapons; +using ktsu.CounterStrikeProgression.Site.Live; +using ktsu.CounterStrikeProgression.Site.Views; + +[TestClass] +public sealed class ContractTests +{ + private static readonly DateOnly Saturday = new(2026, 10, 17); + + public TestContext TestContext { get; set; } = null!; + + // Every daily group runs, so the class kills contract is always there to test against. + private static ProgressionEngine Engine(ManualTime time) => + TestHelpers.Engine(s => + { + s.ContractsEnabled = true; + s.DailyContracts = ContractCatalog.DailyGroups.Count; + }, time); + + private static ActiveContract ClassKills(ProgressionEngine engine) => + engine.ActiveContracts.Single(c => c.Definition.Id.StartsWith("kills_", StringComparison.Ordinal)); + + // A gun of the contract's class, picked so the kills don't also count toward the knife and grenade contract. + private static string WeaponFor(ActiveContract contract) => + WeaponCatalog.All.First(w => w.IsGun && contract.Definition.Counts(new ContractSignal(SignalKind.Kill, w))).Key.WeakString; + + private static void Kill(ProgressionEngine engine, PlayerProgress player, string weapon, int times, List? notices = null) + { + for (int i = 0; i < times; i++) + { + ProgressionResult result = engine.ApplyCombat(player, TestHelpers.Kill(weapon)); + notices?.AddRange(result.Notices); + } + } + + [TestMethod] + public void ADayHasThreeDailyContractsAndOneWeekly() + { + IReadOnlyList active = ContractCatalog.Active(Saturday, new ProgressionSettings()); + + Assert.HasCount(4, active); + Assert.HasCount(3, active.Where(c => c.Definition.Period == ContractPeriod.Daily)); + Assert.AreEqual(ContractPeriod.Weekly, active[^1].Definition.Period); + Assert.AreEqual("2026-10-17", active[0].PeriodKey); + Assert.AreEqual("2026-W42", active[^1].PeriodKey); + Assert.AreEqual(new DateTime(2026, 10, 18, 0, 0, 0, DateTimeKind.Utc), active[0].EndsAt); + Assert.AreEqual(new DateTime(2026, 10, 19, 0, 0, 0, DateTimeKind.Utc), active[^1].EndsAt); + Assert.AreEqual(500, active[0].Xp); + Assert.AreEqual(2500, active[^1].Xp); + } + + [TestMethod] + public void ThePickIsTheSameEveryTimeAndChangesDayToDay() + { + ProgressionSettings settings = new(); + string[] first = [.. ContractCatalog.Active(Saturday, settings).Select(c => c.Definition.Id)]; + string[] again = [.. ContractCatalog.Active(Saturday, settings).Select(c => c.Definition.Id)]; + CollectionAssert.AreEqual(first, again); + + HashSet days = [.. Enumerable.Range(0, 14).Select(d => string.Join(",", ContractCatalog.Active(Saturday.AddDays(d), settings).Take(3).Select(c => c.Definition.Id)))]; + Assert.IsGreaterThan(1, days.Count); + } + + [TestMethod] + public void ADayNeverDrawsTwoContractsFromOneGroup() + { + ProgressionSettings settings = new(); + for (int d = 0; d < 60; d++) + { + IReadOnlyList daily = [.. ContractCatalog.Active(Saturday.AddDays(d), settings).Where(c => c.Definition.Period == ContractPeriod.Daily)]; + int groups = daily.Select(c => ContractCatalog.DailyGroups.ToList().FindIndex(g => g.Any(v => v.Id == c.Definition.Id))).Distinct().Count(); + Assert.AreEqual(daily.Count, groups); + } + } + + [TestMethod] + public void ContractIdsAreUnique() + { + string[] ids = [.. ContractCatalog.DailyGroups.SelectMany(g => g).Concat(ContractCatalog.Weekly).Select(c => c.Id)]; + Assert.HasCount(ids.Length, ids.Distinct(StringComparer.Ordinal)); + Assert.IsTrue(ids.All(id => ContractCatalog.Find(id) is not null)); + } + + [TestMethod] + public void TurnedOffThereAreNoContracts() + { + Assert.IsEmpty(ContractCatalog.Active(Saturday, new ProgressionSettings { ContractsEnabled = false })); + } + + [TestMethod] + public void FinishingAContractPaysItsXpOnce() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract contract = ClassKills(engine); + string weapon = WeaponFor(contract); + + List notices = []; + Kill(engine, player, weapon, contract.Definition.Target - 1, notices); + Assert.IsFalse(notices.Any(n => n.Kind == NoticeKind.ContractCompleted && n.Contract == contract)); + Assert.AreEqual(contract.Definition.Target - 1, player.Contracts[(contract.PeriodKey, contract.Definition.Id)].Count); + + long before = player.RankXp; + ProgressionResult finishing = engine.ApplyCombat(player, TestHelpers.Kill(weapon)); + ProgressionNotice done = finishing.Notices.Single(n => n.Kind == NoticeKind.ContractCompleted && n.Contract == contract); + Assert.AreEqual(contract.Xp, done.Xp); + Assert.IsGreaterThanOrEqualTo(before + contract.Xp, player.RankXp); + Assert.IsTrue(player.Contracts[(contract.PeriodKey, contract.Definition.Id)].Completed); + + notices.Clear(); + Kill(engine, player, weapon, 5, notices); + Assert.IsFalse(notices.Any(n => n.Kind == NoticeKind.ContractCompleted && n.Contract == contract)); + } + + [TestMethod] + public void KillsWithOtherClassesDoNotCount() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract contract = ClassKills(engine); + string other = WeaponCatalog.All.First(w => w.IsGun && !contract.Definition.Counts(new ContractSignal(SignalKind.Kill, w))).Key.WeakString; + + Kill(engine, player, other, 3); + + Assert.IsFalse(player.Contracts.ContainsKey((contract.PeriodKey, contract.Definition.Id))); + } + + [TestMethod] + public void ANewDayStartsFreshAndDropsYesterdayOnceSaved() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract yesterday = ClassKills(engine); + Kill(engine, player, WeaponFor(yesterday), 2); + _ = ProgressSnapshot.Capture(player); + + time.Advance(TimeSpan.FromDays(1)); + ActiveContract today = ClassKills(engine); + Kill(engine, player, WeaponFor(today), 1); + + Assert.IsFalse(player.Contracts.ContainsKey((yesterday.PeriodKey, yesterday.Definition.Id))); + Assert.AreEqual(1, player.Contracts[(today.PeriodKey, today.Definition.Id)].Count); + } + + [TestMethod] + public void AnUnsavedRowFromYesterdayIsKeptUntilItSaves() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract yesterday = ClassKills(engine); + Kill(engine, player, WeaponFor(yesterday), 2); + + time.Advance(TimeSpan.FromDays(1)); + Kill(engine, player, WeaponFor(ClassKills(engine)), 1); + + ProgressSnapshot snapshot = ProgressSnapshot.Capture(player); + Assert.IsTrue(snapshot.Contracts.Any(c => c.Period == yesterday.PeriodKey && c.Contract == yesterday.Definition.Id && c.Count == 2)); + } + + [TestMethod] + public async Task ContractRowsSaveAndLoad() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract contract = ClassKills(engine); + Kill(engine, player, WeaponFor(contract), contract.Definition.Target); + + InMemoryProgressionStore store = new(); + ProgressSnapshot snapshot = ProgressSnapshot.Capture(player); + Assert.IsNotEmpty(snapshot.Contracts); + await store.SaveAsync(snapshot, TestContext.CancellationToken).ConfigureAwait(false); + + PlayerProgress? loaded = await store.LoadAsync(TestHelpers.SteamId, TestContext.CancellationToken).ConfigureAwait(false); + Assert.IsNotNull(loaded); + ContractProgress row = loaded.Contracts[(contract.PeriodKey, contract.Definition.Id)]; + Assert.AreEqual(contract.Definition.Target, row.Count); + Assert.IsTrue(row.Completed); + Assert.IsFalse(row.IsDirty); + } + + [TestMethod] + public void RestoreFlagsContractRowsAgain() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + Kill(engine, player, WeaponFor(ClassKills(engine)), 1); + + ProgressSnapshot failed = ProgressSnapshot.Capture(player); + failed.Restore(player); + + CollectionAssert.AreEquivalent(failed.Contracts.ToList(), ProgressSnapshot.Capture(player).Contracts.ToList()); + } + + [TestMethod] + public void TheChangeTrackerSendsOnlyChangedContracts() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + string weapon = WeaponFor(ClassKills(engine)); + Kill(engine, player, weapon, 1); + + ProgressChangeTracker tracker = new(); + Assert.IsNotEmpty(tracker.Changes(player)!.Contracts); + Assert.IsNull(tracker.Changes(player)); + + Kill(engine, player, weapon, 1); + Assert.IsNotEmpty(tracker.Changes(player)!.Contracts); + } + + [TestMethod] + public void TheFeedNamesTheContract() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract contract = ClassKills(engine); + Kill(engine, player, WeaponFor(contract), contract.Definition.Target - 1); + + ProgressionResult result = engine.ApplyCombat(player, TestHelpers.Kill(WeaponFor(contract))); + IReadOnlyList feed = FeedBuilder.From(result, player.SteamId, player.Name, DateTime.UtcNow); + + FeedEntry entry = feed.Single(e => e.Kind == FeedKind.ContractCompleted && e.Title.EndsWith(contract.Definition.Description, StringComparison.Ordinal)); + Assert.AreEqual($"Daily contract: {contract.Definition.Description}", entry.Title); + Assert.AreEqual(contract.Xp, entry.Xp); + } + + [TestMethod] + public void TheFeedNamesAWeeklyAndSkipsANoticeWithNoContract() + { + ActiveContract weekly = ContractCatalog.Active(Saturday, new ProgressionSettings())[^1]; + ProgressionResult result = new(); + result.Notices.Add(new ProgressionNotice { Kind = NoticeKind.ContractCompleted, Contract = weekly, Xp = weekly.Xp }); + result.Notices.Add(new ProgressionNotice { Kind = NoticeKind.ContractCompleted }); + + FeedEntry entry = FeedBuilder.From(result, TestHelpers.SteamId, "Player", DateTime.UtcNow).Single(); + + Assert.AreEqual($"Weekly contract: {weekly.Definition.Description}", entry.Title); + } + + [TestMethod] + public void TheOverviewShowsAllContractsDone() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(s => s.ContractsEnabled = true, time); + PlayerProgress player = TestHelpers.Player(); + foreach (ActiveContract contract in engine.ActiveContracts) + { + player.Contract(contract.PeriodKey, contract.Definition.Id).Completed = true; + } + + PanelLine line = new PanelBuilder(engine).Overview(player).Lines.Single(l => l.Label == "Contracts"); + + Assert.AreEqual(LineState.Done, line.State); + Assert.AreEqual("4 of 4 done", line.Detail); + } + + [TestMethod] + public void ThePanelListsTodayThenTheWeek() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(s => s.ContractsEnabled = true, time); + PlayerProgress player = TestHelpers.Player(); + + PanelPage page = new PanelBuilder(engine).Page(player, PanelBuilder.ContractsPage); + + Assert.AreEqual("Contracts", page.Title); + Assert.AreEqual("0 of 4 done", page.ProgressLabel); + Assert.AreEqual("Today, 12h 0m left", page.Lines[0].Label); + Assert.AreEqual(LineState.Heading, page.Lines[4].State); + Assert.AreEqual("This week, 1d 12h left", page.Lines[4].Label); + Assert.AreEqual(LineState.NotStarted, page.Lines[1].State); + StringAssert.EndsWith(page.Lines[1].Detail, "+500"); + StringAssert.EndsWith(page.Lines[5].Detail, "+2,500"); + } + + [TestMethod] + public void ThePanelMarksFinishedContractsDone() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + ActiveContract contract = ClassKills(engine); + Kill(engine, player, WeaponFor(contract), contract.Definition.Target); + + PanelPage page = new PanelBuilder(engine).Contracts(player); + + PanelLine line = page.Lines.Single(l => l.Label == contract.Definition.Description); + Assert.AreEqual(LineState.Done, line.State); + Assert.AreEqual("Done", line.Detail); + StringAssert.Contains(new PanelBuilder(engine).Overview(player).Lines.Single(l => l.Label == "Contracts").Detail, "done"); + } + + [TestMethod] + public void ContractsPageFitsTheWorldTextLimit() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(s => s.ContractsEnabled = true, time); + for (int d = 0; d < 28; d++) + { + string text = PanelFormatter.ToPlainText(new PanelBuilder(engine).Contracts(TestHelpers.Player()), 2, PanelBuilder.PageCount, 0, 40, 511); + Assert.IsLessThanOrEqualTo(511, System.Text.Encoding.UTF8.GetByteCount(text)); + StringAssert.Contains(text, "A/D page"); + time.Advance(TimeSpan.FromDays(1)); + } + } + + [TestMethod] + [DataRow(0, 0, 5, "0h 5m")] + [DataRow(0, 13, 0, "13h 0m")] + [DataRow(3, 4, 59, "3d 4h")] + [DataRow(-1, 0, 0, "0h 0m")] + public void RemainingTimeIsShort(int days, int hours, int minutes, string expected) => + Assert.AreEqual(expected, PanelBuilder.Remaining(new TimeSpan(days, hours, minutes, 0))); + + [TestMethod] + public void ThePlayerPageShowsTheRunningContracts() + { + ProgressionSettings settings = new(); + DateTime now = new(2026, 10, 17, 12, 0, 0, DateTimeKind.Utc); + ActiveContract first = ContractCatalog.Active(Saturday, settings)[0]; + PlayerProgress player = TestHelpers.Player(); + player.Contract(first.PeriodKey, first.Definition.Id).Count = first.Definition.Target + 3; + player.Contract(first.PeriodKey, first.Definition.Id).Completed = true; + player.Contract("2026-10-16", first.Definition.Id).Count = 1; + + PlayerView view = PlayerViewBuilder.Build(player, settings, online: false, now: now); + + Assert.HasCount(4, view.Contracts); + ContractView shown = view.Contracts[0]; + Assert.AreEqual(first.Definition.Id, shown.Id); + Assert.IsTrue(shown.Completed); + Assert.AreEqual(first.Definition.Target, shown.Count); + Assert.AreEqual(ContractPeriod.Weekly, view.Contracts[^1].Period); + Assert.IsTrue(view.Contracts.Skip(1).All(c => c.Count == 0 && !c.Completed)); + } + + [TestMethod] + public void MergingKeepsTheLargerContractCount() + { + ProgressSnapshot older = new(null, [], []) { Contracts = [new ContractRow(TestHelpers.SteamId, "2026-10-17", "headshots", 4, false)] }; + ProgressSnapshot newer = new(null, [], []) { Contracts = [new ContractRow(TestHelpers.SteamId, "2026-10-17", "headshots", 2, true)] }; + + ContractRow combined = ProgressMerge.Combine(older, newer).Contracts.Single(); + Assert.AreEqual(4, combined.Count); + Assert.IsTrue(combined.Completed); + Assert.AreEqual(TestHelpers.SteamId, ProgressMerge.SteamIdOf(newer)); + + PlayerProgress stored = TestHelpers.Player(); + stored.Contract("2026-10-17", "headshots").Count = 9; + PlayerProgress merged = ProgressMerge.Merge(stored, newer); + Assert.AreEqual(9, merged.Contracts[("2026-10-17", "headshots")].Count); + Assert.IsTrue(merged.Contracts[("2026-10-17", "headshots")].Completed); + } + + [TestMethod] + [DataRow("weekly_kills", (int)SignalKind.Kill, false, null)] + [DataRow("weekly_headshots", (int)SignalKind.Kill, true, null)] + [DataRow("weekly_skill_shots", (int)SignalKind.SkillShot, false, "wallbang")] + [DataRow("weekly_tiers", (int)SignalKind.Tier, false, null)] + [DataRow("weekly_levels", (int)SignalKind.WeaponLevel, false, null)] + public void WeeklyContractsCountTheirSignal(string id, int signal, bool headshot, string? skillShot) + { + SignalKind kind = (SignalKind)signal; + ContractDefinition contract = ContractCatalog.Find(id)!; + SkillShotDefinition? shot = skillShot is null ? null : SkillShotCatalog.All.Single(s => s.Id.WeakString == skillShot); + Assert.IsTrue(contract.Counts(new ContractSignal(kind, TestHelpers.Weapon("ak47"), headshot, shot))); + Assert.IsFalse(contract.Counts(new ContractSignal(SignalKind.Assist, TestHelpers.Weapon("ak47")))); + } + + [TestMethod] + public void TheEpicWeeklyCountsOnlyEpicSkillShots() + { + ContractDefinition contract = ContractCatalog.Find("weekly_epic")!; + SkillShotDefinition epic = SkillShotCatalog.All.First(s => s.Rarity == Rarity.Epic); + SkillShotDefinition common = SkillShotCatalog.All.First(s => s.Rarity == Rarity.Common); + Assert.IsTrue(contract.Counts(new ContractSignal(SignalKind.SkillShot, SkillShot: epic))); + Assert.IsFalse(contract.Counts(new ContractSignal(SignalKind.SkillShot, SkillShot: common))); + } + + [TestMethod] + public void EveryWeekDrawsAWeeklyFromThePool() + { + ProgressionSettings settings = new(); + HashSet weeklies = [.. Enumerable.Range(0, 52).Select(w => ContractCatalog.Active(Saturday.AddDays(7 * w), settings)[^1].Definition.Id)]; + Assert.IsGreaterThan(1, weeklies.Count); + Assert.IsTrue(weeklies.All(id => ContractCatalog.Weekly.Any(c => c.Id == id))); + } + + [TestMethod] + [DataRow(2026, 10, 17, "2026-W42", 2026, 10, 12)] + [DataRow(2027, 1, 1, "2026-W53", 2026, 12, 28)] + [DataRow(2026, 10, 19, "2026-W43", 2026, 10, 19)] + public void WeeksAreIsoWeeksStartingMonday(int year, int month, int day, string key, int startYear, int startMonth, int startDay) + { + DateOnly date = new(year, month, day); + Assert.AreEqual(key, DailyRotation.WeekKey(date)); + Assert.AreEqual(new DateOnly(startYear, startMonth, startDay), DailyRotation.WeekStart(date)); + } + + [TestMethod] + public void TheFeaturedClassIsOneOfTheGunClassesAndNamed() + { + HashSet featured = [.. Enumerable.Range(0, 60).Select(d => DailyRotation.FeaturedClass(Saturday.AddDays(d)))]; + Assert.IsGreaterThan(1, featured.Count); + Assert.IsTrue(featured.All(c => DailyRotation.FeaturedClasses.Contains(c))); + foreach (WeaponClass weaponClass in Enum.GetValues()) + { + Assert.IsFalse(string.IsNullOrEmpty(DailyRotation.ClassName(weaponClass))); + } + } + + [TestMethod] + [DataRow(2026, 10, 17, 3, "Oct–Dec 2026", 2026, 7, 1)] + [DataRow(2026, 2, 3, 1, "Feb 2026", 2026, 1, 1)] + [DataRow(2026, 5, 9, 5, "Apr–Jun 2026", 2026, 1, 1)] + public void SeasonsSplitTheYear(int year, int month, int day, int months, string name, int previousYear, int previousMonth, int previousDay) + { + Season season = Season.For(new DateOnly(year, month, day), months); + Assert.AreEqual(name, season.Name); + Assert.AreEqual(new DateOnly(previousYear, previousMonth, previousDay), season.Previous(months).Start); + } + + [TestMethod] + public void SteamIdComesFromAnyRow() + { + Assert.AreEqual(TestHelpers.SteamId, ProgressMerge.SteamIdOf(new ProgressSnapshot(null, [], [new ChallengeRow(TestHelpers.SteamId, "ak47", "kills", 1, 0)]))); + Assert.IsNull(ProgressMerge.SteamIdOf(new ProgressSnapshot(null, [], []))); + } + + [TestMethod] + public async Task AResetClearsContracts() + { + ManualTime time = new(); + ProgressionEngine engine = Engine(time); + PlayerProgress player = TestHelpers.Player(); + Kill(engine, player, WeaponFor(ClassKills(engine)), 1); + InMemoryProgressionStore store = new(); + await store.SaveAsync(ProgressSnapshot.Capture(player), TestContext.CancellationToken).ConfigureAwait(false); + + new AdminCorrection(CorrectionKind.Reset).Apply(player, engine.Ranks); + await store.ResetAsync(ProgressSnapshot.ToRow(player), TestContext.CancellationToken).ConfigureAwait(false); + + Assert.IsEmpty(player.Contracts); + PlayerProgress? loaded = await store.LoadAsync(TestHelpers.SteamId, TestContext.CancellationToken).ConfigureAwait(false); + Assert.IsEmpty(loaded!.Contracts); + } +} diff --git a/CounterStrikeProgression.Test/PanelTests.cs b/CounterStrikeProgression.Test/PanelTests.cs index 6e395d7..cb54b66 100644 --- a/CounterStrikeProgression.Test/PanelTests.cs +++ b/CounterStrikeProgression.Test/PanelTests.cs @@ -61,7 +61,7 @@ public void WeaponPagesComeInOrderOfUse() Assert.AreEqual("ak47", order[1].Key.WeakString); Assert.AreEqual("glock", order[2].Key.WeakString); Assert.HasCount(WeaponCatalog.All.Count, order); - Assert.AreEqual(WeaponCatalog.All.Count + 1, PanelBuilder.PageCount); + Assert.AreEqual(WeaponCatalog.All.Count + 2, PanelBuilder.PageCount); } [TestMethod] diff --git a/CounterStrikeProgression.Test/SiteEndpointTests.cs b/CounterStrikeProgression.Test/SiteEndpointTests.cs index 63752ce..a7ad1f2 100644 --- a/CounterStrikeProgression.Test/SiteEndpointTests.cs +++ b/CounterStrikeProgression.Test/SiteEndpointTests.cs @@ -360,6 +360,26 @@ public async Task Ingest_BadBody_Returns400(string body) Assert.IsNull(live.Snapshot); } + [TestMethod] + public async Task Ingest_ContractRows_AreAcceptedAndANullRowIsRejected() + { + ProgressSnapshot rows = new(null, [], []) { Contracts = [new ContractRow(TestHelpers.SteamId, "2026-10-17", "headshots", 3, false)] }; + LiveState live = NewState(); + DefaultHttpContext good = IngestContext("Bearer dev", JsonSerializer.Serialize(Batch() with { Progress = [rows] }, LiveJson.Options)); + IResult accepted = await Endpoints.IngestAsync(good, new SiteOptions { Token = "dev" }, live, new Broadcaster(), new FeatIndex()).ConfigureAwait(false); + Assert.AreEqual(StatusCodes.Status204NoContent, StatusOf(accepted)); + + string json = JsonSerializer.Serialize(Batch() with { Progress = [rows] }, LiveJson.Options); + foreach ((string from, string to) in new[] { ("\"contracts\":[{", "\"contracts\":[null,{"), ("\"period\":\"2026-10-17\"", "\"period\":null"), ("\"contract\":\"headshots\"", "\"contract\":null") }) + { + string body = json.Replace(from, to, StringComparison.Ordinal); + Assert.AreNotEqual(json, body); + DefaultHttpContext bad = IngestContext("Bearer dev", body); + IResult rejected = await Endpoints.IngestAsync(bad, new SiteOptions { Token = "dev" }, NewState(), new Broadcaster(), new FeatIndex()).ConfigureAwait(false); + Assert.AreEqual(StatusCodes.Status400BadRequest, StatusOf(rejected), to); + } + } + [TestMethod] public async Task Ingest_OversizedBody_Returns413() { diff --git a/CounterStrikeProgression.Test/TestHelpers.cs b/CounterStrikeProgression.Test/TestHelpers.cs index afcbf90..0de851a 100644 --- a/CounterStrikeProgression.Test/TestHelpers.cs +++ b/CounterStrikeProgression.Test/TestHelpers.cs @@ -14,10 +14,10 @@ internal static class TestHelpers public static WeaponInfo Weapon(string name) => WeaponCatalog.Resolve(name) ?? throw new InvalidOperationException($"No weapon named {name}."); - // The featured weapon changes with the date, so it's off unless a test asks for it. + // Contracts and the featured weapon depend on the day, so they're off unless a test turns them on with a fixed clock. public static ProgressionEngine Engine(Action? configure = null, TimeProvider? time = null) { - ProgressionSettings settings = new() { FeaturedWeaponMultiplier = 1 }; + ProgressionSettings settings = new() { ContractsEnabled = false, FeaturedWeaponMultiplier = 1 }; configure?.Invoke(settings); return new ProgressionEngine(settings, time); } diff --git a/CounterStrikeProgression/Announcer.cs b/CounterStrikeProgression/Announcer.cs index 8dbf3fc..999f291 100644 --- a/CounterStrikeProgression/Announcer.cs +++ b/CounterStrikeProgression/Announcer.cs @@ -6,14 +6,15 @@ namespace ktsu.CounterStrikeProgression; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Panel; using ktsu.CounterStrikeProgression.Core.Progression; using ktsu.CounterStrikeProgression.Core.Recap; using ktsu.CounterStrikeProgression.Core.SkillShots; /// -/// Turns what a player earned into chat lines. Rank-ups, finished tiers, and milestone weapon levels go to -/// everyone, other level-ups and rare skill shots go to the player, and common skill shots stay quiet unless +/// Turns what a player earned into chat lines. Rank-ups, finished tiers, milestone weapon levels, and weekly +/// contracts go to everyone, other level-ups, daily contracts, and rare skill shots go to the player, and common skill shots stay quiet unless /// the config turns them on. /// /// The chat prefix and announcement settings. @@ -61,6 +62,14 @@ public void Announce(CCSPlayerController player, PlayerSession session, Progress Server.PrintToChatAll($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} {ChatColors.Green}{player.PlayerName}{ChatColors.Default} earned the feat {ChatColors.Gold}{notice.Feat.Name}{ChatColors.Default}: {notice.Feat.Description}!"); break; + case NoticeKind.ContractCompleted when notice.Contract is { Definition.Period: ContractPeriod.Weekly } weekly: + Server.PrintToChatAll($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} {ChatColors.Green}{player.PlayerName}{ChatColors.Default} finished the weekly contract {ChatColors.Gold}{weekly.Definition.Description}{ChatColors.Default} (+{Xp(notice.Xp)} XP)"); + break; + + case NoticeKind.ContractCompleted when notice.Contract is not null: + player.PrintToChat($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} Daily contract done: {ChatColors.Yellow}{notice.Contract.Definition.Description}{ChatColors.Default} (+{Xp(notice.Xp)} XP)"); + break; + case NoticeKind.RankUp: Server.PrintToChatAll($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} {ChatColors.Green}{player.PlayerName}{ChatColors.Default} ranked up to {ChatColors.Gold}{RankLadder.Names[notice.Value]}{ChatColors.Default}!"); break; diff --git a/CounterStrikeProgression/Panel/PanelPresenter.cs b/CounterStrikeProgression/Panel/PanelPresenter.cs index 54a8a86..2fa5f8e 100644 --- a/CounterStrikeProgression/Panel/PanelPresenter.cs +++ b/CounterStrikeProgression/Panel/PanelPresenter.cs @@ -24,15 +24,25 @@ internal sealed class PanelPresenter(PanelSettings settings, PanelBuilder builde public WorldTextPanel WorldText { get; } = new(settings); /// - /// Opens the panel on the overview, or closes it when it's already open. + /// Opens the panel on a page, or closes it when it's already open. Asking for another page while the panel is + /// open turns to that page instead. /// /// The player. /// The player's session. - public void Toggle(CCSPlayerController player, PlayerSession session) + /// The page to open on, where 0 is the overview. + public void Toggle(CCSPlayerController player, PlayerSession session, int page = 0) { Ensure.NotNull(player); Ensure.NotNull(session); + if (session.Panel.IsOpen && (page != 0) && (session.Panel.Page != page)) + { + session.Panel.Page = page; + session.Panel.Scroll = 0; + session.Panel.IsStale = true; + return; + } + if (session.Panel.IsOpen) { Close(player, session); @@ -46,7 +56,7 @@ public void Toggle(CCSPlayerController player, PlayerSession session) } session.Panel.IsOpen = true; - session.Panel.Page = 0; + session.Panel.Page = page; session.Panel.Scroll = 0; session.Panel.IsStale = true; session.Panel.LastButtons = player.Buttons; diff --git a/CounterStrikeProgression/PlayerCommands.cs b/CounterStrikeProgression/PlayerCommands.cs index 3a0f95c..03b461f 100644 --- a/CounterStrikeProgression/PlayerCommands.cs +++ b/CounterStrikeProgression/PlayerCommands.cs @@ -14,7 +14,7 @@ namespace ktsu.CounterStrikeProgression; using ktsu.CounterStrikeProgression.Core.Weapons; /// -/// The chat and console commands: !rank (also !xp and !progress), !top and +/// The chat and console commands: !rank (also !xp and !progress), !contracts, !top and /// !top <weapon>, !next, !feats, !stats, !site, and the admin-only /// css_csp_status. /// @@ -38,6 +38,7 @@ public void Register(BasePlugin plugin) plugin.AddCommand("css_rank", "Open or close your progress panel", OnRank); plugin.AddCommand("css_xp", "Open or close your progress panel", OnRank); plugin.AddCommand("css_progress", "Open or close your progress panel", OnRank); + plugin.AddCommand("css_contracts", "Open your progress panel on today's contracts", OnContracts); plugin.AddCommand("css_top", "Show the players with the most rank XP, or with a weapon: !top ", OnTop); plugin.AddCommand("css_next", "Show your three challenges closest to their next tier", OnNext); plugin.AddCommand("css_feats", "Show the feats and how close you are to each", OnFeats); @@ -54,6 +55,14 @@ private void OnRank(CCSPlayerController? player, CommandInfo command) } } + private void OnContracts(CCSPlayerController? player, CommandInfo command) + { + if ((player is not null) && (services.Sessions.Get(player) is PlayerSession session)) + { + services.Panel.Toggle(player, session, PanelBuilder.ContractsPage); + } + } + private void OnTop(CCSPlayerController? player, CommandInfo command) { if ((player is null) || !player.IsValid || (services.Sessions.Get(player) is not PlayerSession session)) diff --git a/README.md b/README.md index 4f18536..b50d7a7 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Players climb an up-only rank ladder from Silver I to Global Elite. Every weapon - **Chickens**: every weapon has a Chickens challenge (1, 5, 15, 40, and 100 chickens), and each chicken pays 2 XP to the weapon and to rank. Twelve chicken skill shots sit on the weapon ladders too, from Nugget (headshot a chicken) and Fowl play (through a wall) to Fried chicken, Rotisserie, and Crossed the road (from long range). - **Weapon ladders**: Kills, Headshots, and Hits, plus one challenge for every skill shot the weapon can earn, each with five tiers. Skill tiers pay more than volume tiers. - **Skill shots**: about 50, covering movement, distance, wallbangs and smokes, scopes, utility and melee, timing and aim, multi-kills, and round situations. +- **Daily and weekly contracts**: three daily contracts and one weekly, such as "Get 20 kills with SMGs" or "Get 2 kills through walls", pay 500 and 2,500 rank XP. The picks come from the UTC date, so everyone gets the same ones, and they reset at midnight UTC and on Monday. `!contracts` opens them in the panel, and the site's player page shows your progress. - **Bots count, at a reduced rate**: rank XP against bots is scaled down, while weapon levels and ladders still move, so practice against bots isn't wasted. - **Featured weapon of the day**: one gun class (pistols, SMGs, rifles, snipers, shotguns, or machine guns) earns double weapon XP and ladder progress each UTC day. The pick comes from the date, so the panel overview and the site's live page always agree. `FeaturedWeaponMultiplier` sets the multiplier, and 1 turns it off. - **In-game panel**: `!rank` opens a side panel to the right of the view. It falls back to a center-screen card and then to chat if a way of drawing fails. @@ -49,6 +50,7 @@ With no database host set, progress is kept in memory and lost when the server r | Command | Effect | |---|---| | `!rank`, `!xp`, `!progress` | Open or close the progress panel | +| `!contracts` | Open the progress panel on today's contracts | | `!top` | Print the 10 players with the most rank XP | | `!top ` | Print the 10 players with the most XP with one weapon, such as `!top ak` or `!top awp` | | `!next` | Print your three challenges closest to their next tier | @@ -58,7 +60,7 @@ With no database host set, progress is kept in memory and lost when the server r When a player first spawns, they get a welcome line with their rank, a link to their page on the site (when `Site.PublicUrl` is set), and the commands. `"WelcomeMessage": false` turns it off. -While the panel is open, W and S scroll, A and D move between the overview and each weapon, and R closes it. It also closes when you take damage or die. +While the panel is open, W and S scroll, A and D move between the overview, the contracts, and each weapon, and R closes it. It also closes when you take damage or die. ### Admin commands