From d8ccf0433d53402be11092ff1f4e6da3b07d09ee Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:43:15 +0000 Subject: [PATCH 1/5] WIP: contracts, featured weapon and daily history in Core Partial work handed off to the contracts thread: settings, DailyRotation, Season, ContractCatalog, PlayerProgress contract and day rows, and the engine changes. Storage, plugin, panel and site parts aren't done yet. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Dhvs6sGQ3Kj3VwN2cijCCo --- .../Contracts/ContractCatalog.cs | 116 +++++++++++ .../Contracts/ContractDefinition.cs | 70 +++++++ .../Progression/PlayerProgress.cs | 57 ++++++ .../Progression/ProgressionEngine.cs | 191 +++++++++++++++--- .../Progression/ProgressionNotice.cs | 12 +- .../ProgressionSettings.cs | 33 +++ .../Rotation/DailyRotation.cs | 108 ++++++++++ .../Rotation/Season.cs | 47 +++++ 8 files changed, 609 insertions(+), 25 deletions(-) create mode 100644 CounterStrikeProgression.Core/Contracts/ContractCatalog.cs create mode 100644 CounterStrikeProgression.Core/Contracts/ContractDefinition.cs create mode 100644 CounterStrikeProgression.Core/Rotation/DailyRotation.cs create mode 100644 CounterStrikeProgression.Core/Rotation/Season.cs 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/Progression/PlayerProgress.cs b/CounterStrikeProgression.Core/Progression/PlayerProgress.cs index a94128d..ffbe181 100644 --- a/CounterStrikeProgression.Core/Progression/PlayerProgress.cs +++ b/CounterStrikeProgression.Core/Progression/PlayerProgress.cs @@ -20,6 +20,42 @@ 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; } +} + +/// +/// What a player did on one UTC day, for history graphs and seasons. +/// +internal sealed class DayProgress +{ + /// Gets or sets the rank XP earned that day. + public long Xp { get; set; } + + /// Gets or sets the kills made that day. + public long Kills { get; set; } + + /// Gets or sets the skill shots earned that day. + public long SkillShots { get; set; } + + /// Gets or sets the player's rank XP at the end of the day, or as it stands today. + public long RankXp { 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,9 +136,30 @@ 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 what the player did each day. Only today is loaded, and earlier days are dropped once saved. + public Dictionary Days { get; } = []; + /// 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 day's progress, creating it when the player hasn't played that day yet. + /// + /// The UTC day. + /// The day's progress. + public DayProgress Day(DateOnly day) => Days.GetOrCreate(day); + /// /// 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 8e253f1..318693f 100644 --- a/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs +++ b/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs @@ -3,8 +3,10 @@ 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; using ktsu.CounterStrikeProgression.Core.SkillShots; using ktsu.CounterStrikeProgression.Core.Weapons; @@ -14,14 +16,29 @@ namespace ktsu.CounterStrikeProgression.Core.Progression; /// /// Rank XP from anything done to a bot is scaled by , but /// weapon XP and ladder counts aren't, so practice against bots still moves a weapon forward. Tier and -/// level-up bonuses are paid in full, because they reward the ladder rather than one event. +/// 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 XP for each event, and +/// contracts count what each event did once it's applied. /// /// The XP values and thresholds. -internal sealed class ProgressionEngine(ProgressionSettings settings) +/// The clock that decides the day, or the system clock when omitted. +internal sealed class ProgressionEngine(ProgressionSettings settings, TimeProvider? time = null) { /// Gets the settings in use. public ProgressionSettings Settings { get; } = settings; + /// Gets the clock that decides the day. + public TimeProvider Time { get; } = time ?? TimeProvider.System; + + /// Gets the current UTC day. + public DateOnly Today => DailyRotation.Day(Time.GetUtcNow().UtcDateTime); + + /// Gets the weapon class featured today, or when the featured weapon is off. + public WeaponClass? FeaturedClass => Settings.FeaturedWeaponMultiplier > 1 ? DailyRotation.FeaturedClass(Today) : null; + + /// Gets the contracts running today. + public IReadOnlyList ActiveContracts => ContractCatalog.Active(Today, Settings); + /// Gets the rank thresholds. public RankLadder Ranks { get; } = new(settings.FirstRankXp, settings.RankGrowth); @@ -88,7 +105,7 @@ public ProgressionResult ApplyCombat(PlayerProgress player, CombatEvent combat) return result; } - Award award = new(combat.Weapon, combat.VictimIsBot); + Award award = NewAward(combat.Weapon, combat.VictimIsBot); WeaponProgress weapon = player.Weapon(combat.Weapon.Key); weapon.IsDirty = true; @@ -96,6 +113,11 @@ public ProgressionResult ApplyCombat(PlayerProgress player, CombatEvent combat) { award.EventXp += Settings.KillXp; weapon.Kills++; + result.Kills++; + DayProgress day = player.Day(Today); + day.Kills++; + day.IsDirty = true; + result.Signals.Add(new(SignalKind.Kill, combat.Weapon, combat.IsHeadshot)); Advance(weapon, award, ChallengeDefinition.KillsId, result); if (combat.IsHeadshot) { @@ -116,12 +138,12 @@ public ProgressionResult ApplyCombat(PlayerProgress player, CombatEvent combat) { if (skillShot.AppliesTo(combat.Weapon) && (skillShot.Detect?.Invoke(combat, Settings) == true)) { - EarnSkillShot(weapon, award, skillShot, result); + EarnSkillShot(player, weapon, award, skillShot, result); } } Credit(player, weapon, award, result); - return result; + return Settle(player, result); } /// @@ -137,21 +159,22 @@ public ProgressionResult ApplyChickenKill(PlayerProgress player, CombatEvent chi Ensure.NotNull(chicken); ProgressionResult result = new(); - Award award = new(chicken.Weapon, vsBot: false); + Award award = NewAward(chicken.Weapon, vsBot: false); 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)) { if (skillShot.AppliesTo(chicken.Weapon) && (skillShot.Detect?.Invoke(chicken, Settings) == true)) { - EarnSkillShot(progress, award, skillShot, result); + EarnSkillShot(player, progress, award, skillShot, result); } } Credit(player, progress, award, result); - return result; + return Settle(player, result); } /// @@ -192,7 +215,7 @@ public ProgressionResult ApplyReload(PlayerProgress player, ReloadEvent reload) AwardSkillShot(player, reload.Weapon, SkillShotCatalog.EfficientReload, vsBot: false, result); } - return result; + return Settle(player, result); } /// @@ -231,7 +254,7 @@ public ProgressionResult ApplyLifeEnd(PlayerProgress player, WeaponLifeStats lif AwardSkillShot(player, life.Weapon, SkillShotCatalog.Headhunter, life.MostlyBots, result); } - return result; + return Settle(player, result); } /// @@ -246,18 +269,20 @@ public ProgressionResult ApplyAssist(PlayerProgress player, AssistEvent assist) Ensure.NotNull(assist); ProgressionResult result = new(); - Award award = new(assist.Weapon, assist.VictimIsBot) { EventXp = Settings.AssistXp }; + Award award = NewAward(assist.Weapon, assist.VictimIsBot); + 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)) { - EarnSkillShot(weapon, award, flashAssist, result); + EarnSkillShot(player, weapon, award, flashAssist, result); } Credit(player, weapon, award, result); - return result; + return Settle(player, result); } /// @@ -277,7 +302,7 @@ public ProgressionResult ApplyFlash(PlayerProgress player, FlashEvent flash) AwardSkillShot(player, flash.Weapon, SkillShotCatalog.LongFlash, flash.VictimIsBot, result); } - return result; + return Settle(player, result); } /// @@ -303,12 +328,14 @@ 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)); + CountSkillShotToday(player); 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); } /// @@ -331,21 +358,30 @@ private void AwardSkillShot(PlayerProgress player, WeaponInfo weaponInfo, SkillS return; } - Award award = new(weaponInfo, vsBot); + Award award = NewAward(weaponInfo, vsBot); WeaponProgress weapon = player.Weapon(weaponInfo.Key); weapon.IsDirty = true; - EarnSkillShot(weapon, award, skillShot, result); + EarnSkillShot(player, weapon, award, skillShot, result); Credit(player, weapon, award, result); } - private void EarnSkillShot(WeaponProgress weapon, Award award, SkillShotDefinition skillShot, ProgressionResult result) + private void EarnSkillShot(PlayerProgress player, WeaponProgress weapon, Award award, SkillShotDefinition skillShot, ProgressionResult result) { 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.Notices.Add(new() { Kind = NoticeKind.SkillShot, Weapon = award.Weapon, SkillShot = skillShot, Xp = (long)Math.Round(ScaleForBots(xp * award.Multiplier, award.VsBot)) }); + result.Signals.Add(new(SignalKind.SkillShot, award.Weapon, SkillShot: skillShot)); + CountSkillShotToday(player); Advance(weapon, award, skillShot.Id.WeakString, result); } + private void CountSkillShotToday(PlayerProgress player) + { + DayProgress day = player.Day(Today); + day.SkillShots++; + day.IsDirty = true; + } + private void Advance(WeaponProgress weapon, Award award, string challengeId, ProgressionResult result) { ChallengeDefinition? definition = Challenges.Find(award.Weapon, challengeId); @@ -374,13 +410,14 @@ private void Advance(WeaponProgress weapon, Award award, string challengeId, Pro Xp = bonus, Broadcast = true, }); + result.Signals.Add(new(SignalKind.Tier, award.Weapon)); } } private void Credit(PlayerProgress player, WeaponProgress weapon, Award award, ProgressionResult result) { int levelBefore = weapon.Level; - weapon.Xp += award.EventXp; + weapon.Xp += (long)Math.Round(award.EventXp * award.Multiplier); weapon.Level = Math.Max(weapon.Level, Levels.LevelFor(weapon.Xp)); for (int level = levelBefore + 1; level <= weapon.Level; level++) { @@ -388,13 +425,108 @@ 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; + double rankXp = ScaleForBots(award.EventXp * award.Multiplier, award.VsBot) + award.BonusXp; CreditRankXp(player, rankXp, result); } - private void CreditRankXp(PlayerProgress player, double xp, ProgressionResult result) + /// + /// Counts what an event did toward the running contracts, pays for any it finishes, and drops contract and + /// day 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 void DropStale(PlayerProgress player, IReadOnlyList active) + { + if (player.Contracts.Count > active.Count) + { + foreach ((string Period, string Contract) key in player.Contracts.Keys.ToList()) + { + if (!player.Contracts[key].IsDirty && !active.Any(a => (a.PeriodKey == key.Period) && (a.Definition.Id == key.Contract))) + { + player.Contracts.Remove(key); + } + } + } + + if (player.Days.Count > 1) + { + DateOnly today = Today; + foreach (DateOnly day in player.Days.Keys.ToList()) + { + if ((day != today) && !player.Days[day].IsDirty) + { + player.Days.Remove(day); + } + } + } + } + + /// + /// Adds or removes rank XP by hand, for an admin putting a mistake right. Added XP announces any rank-ups it + /// reaches, but neither counts toward the day's XP nor seasons. Removing XP is the one way a rank can go down. + /// + /// The player's progress. + /// The XP to add, or a negative amount to remove. + /// What it earned. + public ProgressionResult Grant(PlayerProgress player, long xp) + { + Ensure.NotNull(player); + + ProgressionResult result = new(); + if (xp > 0) + { + CreditRankXp(player, xp, result, countToday: false); + return result; + } + + player.RankXp = Math.Max(0, player.RankXp + xp); + player.Rank = Ranks.RankFor(player.RankXp); + player.IsDirty = true; + DayProgress day = player.Day(Today); + day.RankXp = player.RankXp; + day.IsDirty = true; + return result; + } + + private Award NewAward(WeaponInfo weapon, bool vsBot) => + new(weapon, vsBot, weapon.Class == FeaturedClass ? Settings.FeaturedWeaponMultiplier : 1); + + private void CreditRankXp(PlayerProgress player, double xp, ProgressionResult result, bool countToday = true) { result.XpEarned += Math.Max(0, xp); double total = player.PendingXp + xp; @@ -412,6 +544,15 @@ private void CreditRankXp(PlayerProgress player, double xp, ProgressionResult re player.IsDirty = true; result.XpGained += whole; + DayProgress day = player.Day(Today); + day.RankXp = player.RankXp; + if (countToday) + { + day.Xp += whole; + } + + day.IsDirty = true; + int rank = Ranks.RankFor(player.RankXp); player.Rank = Math.Max(before, rank); if (rank > before) @@ -422,12 +563,14 @@ private void CreditRankXp(PlayerProgress player, double xp, ProgressionResult re private double ScaleForBots(double xp, bool vsBot) => vsBot ? xp * Settings.BotXpMultiplier : xp; - private sealed class Award(WeaponInfo weapon, bool vsBot) + private sealed class Award(WeaponInfo weapon, bool vsBot, double multiplier) { public WeaponInfo Weapon { get; } = weapon; public bool VsBot { get; } = vsBot; + public double Multiplier { get; } = multiplier; + public long EventXp { get; set; } public long BonusXp { get; set; } diff --git a/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs b/CounterStrikeProgression.Core/Progression/ProgressionNotice.cs index badfd78..b9da85b 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,10 @@ internal sealed class ProgressionResult /// Gets the moments worth telling the player about, in the order they happened. public IList Notices { get; } = []; + + /// Gets the kills the event made, for the map recap. + public int Kills { get; internal set; } + + /// 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 31ea6cb..0b40ae4 100644 --- a/CounterStrikeProgression.Core/ProgressionSettings.cs +++ b/CounterStrikeProgression.Core/ProgressionSettings.cs @@ -166,4 +166,37 @@ public sealed class ProgressionSettings /// Gets or sets the level interval announced to the whole server. Levels in between are told to the player only. public int AnnounceWeaponLevelEvery { get; set; } = 5; + + /// + /// Gets or sets how much more XP the day's featured weapon class earns, for both rank XP and weapon XP. Tier and + /// level-up bonuses aren't multiplied. 1 turns the featured weapon off. + /// + 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; + + /// Gets or sets the kills in one life that earn Unstoppable. + public int UnstoppableKills { get; set; } = 10; + + /// Gets or sets the kills in one life that earn Godlike. + public int GodlikeKills { get; set; } = 20; + + /// Gets or sets the kills in a row, without taking damage in between, that earn Untouchable. + public int UntouchableKills { get; set; } = 3; + + /// Gets or sets the kills in one round that earn Ace. Ace is never earned in deathmatch, where a round is the whole map. + public int AceKills { get; set; } = 5; } diff --git a/CounterStrikeProgression.Core/Rotation/DailyRotation.cs b/CounterStrikeProgression.Core/Rotation/DailyRotation.cs new file mode 100644 index 0000000..4d82f2d --- /dev/null +++ b/CounterStrikeProgression.Core/Rotation/DailyRotation.cs @@ -0,0 +1,108 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Core.Rotation; + +using System.Globalization; +using ktsu.CounterStrikeProgression.Core.Weapons; + +/// +/// The days, weeks, and seasons that progression rotates on, and the picks made for each. Days run on UTC. Every +/// pick comes from a hash of the day's date, so the plugin and the site always agree without storing anything. +/// +internal static class DailyRotation +{ + /// Gets the weapon classes that can be featured, in a fixed order the pick indexes into. + public static IReadOnlyList FeaturedClasses { get; } = + [ + WeaponClass.Pistol, + WeaponClass.Smg, + WeaponClass.Rifle, + WeaponClass.Sniper, + WeaponClass.Shotgun, + WeaponClass.MachineGun, + ]; + + /// + /// Gets the UTC day a moment falls on. + /// + /// The moment, in UTC. + /// The day. + public static DateOnly Day(DateTime utc) => DateOnly.FromDateTime(utc); + + /// + /// Gets the key a day's contracts are stored under, such as 2026-10-17. + /// + /// The day. + /// The key. + public static string DayKey(DateOnly day) => day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + /// + /// Gets the key a week's contracts are stored under, its ISO week such as 2026-W42. Weeks start on Monday. + /// + /// Any day in the week. + /// The key. + public static string WeekKey(DateOnly day) + { + DateTime date = day.ToDateTime(TimeOnly.MinValue); + return string.Create(CultureInfo.InvariantCulture, $"{ISOWeek.GetYear(date)}-W{ISOWeek.GetWeekOfYear(date):00}"); + } + + /// + /// Gets the Monday that starts a day's week. + /// + /// The day. + /// The Monday. + public static DateOnly WeekStart(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7)); + + /// + /// Gets the weapon class featured on a day. + /// + /// The day. + /// The featured class. + public static WeaponClass FeaturedClass(DateOnly day) => + FeaturedClasses[(int)(Hash(DayKey(day), "featured") % (ulong)FeaturedClasses.Count)]; + + /// + /// Gets the plural name players see for a weapon class, such as SMGs. + /// + /// The class. + /// The name. + public static string ClassName(WeaponClass weaponClass) => weaponClass switch + { + WeaponClass.Pistol => "pistols", + WeaponClass.Smg => "SMGs", + WeaponClass.Rifle => "rifles", + WeaponClass.Sniper => "snipers", + WeaponClass.Shotgun => "shotguns", + WeaponClass.MachineGun => "machine guns", + WeaponClass.Knife => "knives", + WeaponClass.Grenade => "grenades", + WeaponClass.Taser => "the Zeus", + _ => "weapons", + }; + + /// + /// Hashes a key and a salt into a number the picks are made from. FNV-1a, so it never changes between runs or + /// .NET versions the way does. + /// + /// The period key. + /// What the pick is for, so different picks on one day don't line up. + /// The hash. + public static ulong Hash(string key, string salt) + { + Ensure.NotNull(key); + Ensure.NotNull(salt); + + const ulong offset = 14695981039346656037; + const ulong prime = 1099511628211; + ulong hash = offset; + foreach (char c in salt + "|" + key) + { + hash ^= c; + hash *= prime; + } + + // FNV's low bits mix poorly, so fold the high half in before the caller takes a remainder. + return hash ^ (hash >> 29); + } +} diff --git a/CounterStrikeProgression.Core/Rotation/Season.cs b/CounterStrikeProgression.Core/Rotation/Season.cs new file mode 100644 index 0000000..ab46e7d --- /dev/null +++ b/CounterStrikeProgression.Core/Rotation/Season.cs @@ -0,0 +1,47 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Core.Rotation; + +using System.Globalization; + +/// +/// One season: a stretch of months whose XP is ranked on its own, while lifetime rank keeps going up. +/// +/// The first day of the season. +/// The day after the season's last day. +internal sealed record Season(DateOnly Start, DateOnly End) +{ + /// + /// Gets the season a day falls in. Seasons start on 1 January and every months after. + /// + /// The day. + /// How long a season lasts, in months. It must divide 12, so a season never crosses a year; other values count as 3. + /// The season. + public static Season For(DateOnly day, int months) + { + int length = months is 1 or 2 or 3 or 4 or 6 or 12 ? months : 3; + int index = (day.Month - 1) / length; + DateOnly start = new(day.Year, (index * length) + 1, 1); + return new(start, start.AddMonths(length)); + } + + /// + /// Gets the season before this one. + /// + /// How long a season lasts, in months. + /// The previous season. + public Season Previous(int months) => For(Start.AddDays(-1), months); + + /// Gets the name players see, such as Oct–Dec 2026. + public string Name + { + get + { + DateOnly last = End.AddDays(-1); + string first = Start.ToString("MMM", CultureInfo.InvariantCulture); + string final = last.ToString("MMM", CultureInfo.InvariantCulture); + string year = last.Year.ToString(CultureInfo.InvariantCulture); + return (Start.Month == last.Month) ? $"{first} {year}" : $"{first}–{final} {year}"; + } + } +} From 93a5d10ff9c9b868c8f19d3c515f817b8ed1c028 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:54:08 +0000 Subject: [PATCH 2/5] Add daily and weekly contracts [minor] Three daily contracts and one weekly, picked from the UTC date, pay 500 and 2,500 rank XP. Progress is saved per period in a new csp_contracts table, shown on a new panel page (and !contracts), on the site's player page, and as feed lines. Daily completions go to the player and weekly ones to the server. Builds on the shared contracts groundwork in Core, and fixes its stale row cleanup, which never ran while fewer rows than contracts were held. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01KcGfJHYSEsAtduJxwCwnwB --- CLAUDE.md | 1 + .../Live/FeedBuilder.cs | 14 + .../Live/LiveContracts.cs | 1 + .../Live/ProgressChangeTracker.cs | 15 +- .../Panel/PanelBuilder.cs | 96 ++++- .../Progression/ProgressionEngine.cs | 6 +- .../Storage/InMemoryProgressionStore.cs | 9 +- .../Storage/MySqlProgressionStore.cs | 30 +- .../Storage/ProgressSnapshot.cs | 43 ++- CounterStrikeProgression.Site/Endpoints.cs | 5 +- .../Live/ProgressMerge.cs | 31 +- .../Views/PlayerViewBuilder.cs | 26 +- .../Views/ViewModels.cs | 16 +- .../wwwroot/site.css | 17 + CounterStrikeProgression.Site/wwwroot/site.js | 33 +- .../ContractTests.cs | 341 ++++++++++++++++++ CounterStrikeProgression.Test/PanelTests.cs | 2 +- CounterStrikeProgression.Test/TestHelpers.cs | 7 +- CounterStrikeProgression/Announcer.cs | 13 +- .../Panel/PanelPresenter.cs | 16 +- CounterStrikeProgression/PlayerCommands.cs | 12 +- README.md | 4 +- 22 files changed, 702 insertions(+), 36 deletions(-) create mode 100644 CounterStrikeProgression.Test/ContractTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index a4dbdc8..e7011ec 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`. 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 3cb1933..0104d44 100644 --- a/CounterStrikeProgression.Core/Live/LiveContracts.cs +++ b/CounterStrikeProgression.Core/Live/LiveContracts.cs @@ -14,6 +14,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 ece92bf..a2936c9 100644 --- a/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs +++ b/CounterStrikeProgression.Core/Live/ProgressChangeTracker.cs @@ -61,7 +61,18 @@ internal sealed class ProgressChangeTracker } } - ProgressSnapshot changes = new(player, weapons, challenges); + 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; + } + } + + ProgressSnapshot changes = new(player, weapons, challenges) { Contracts = contracts }; return changes.IsEmpty ? null : changes; } @@ -83,5 +94,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 c3177ea..2edaa5e 100644 --- a/CounterStrikeProgression.Core/Panel/PanelBuilder.cs +++ b/CounterStrikeProgression.Core/Panel/PanelBuilder.cs @@ -4,12 +4,13 @@ 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.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) @@ -22,7 +23,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); @@ -37,15 +38,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) { @@ -55,8 +61,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 == true) + { + 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"); } /// @@ -84,9 +156,17 @@ public PanelPage Overview(PlayerProgress player) new("Headshots", Number(headshots), LineState.InProgress), new("Weapons levelled", $"{levelled} of {WeaponCatalog.All.Count}", LineState.InProgress), new("Tiers finished", Number(tiers), 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 == true); + 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)); return new PanelPage(RankLadder.Names[rank], "Overview", engine.Ranks.ProgressToNext(player.RankXp), progressLabel, lines); } diff --git a/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs b/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs index 318693f..2eb037e 100644 --- a/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs +++ b/CounterStrikeProgression.Core/Progression/ProgressionEngine.cs @@ -472,11 +472,13 @@ private ProgressionResult Settle(PlayerProgress player, ProgressionResult result private void DropStale(PlayerProgress player, IReadOnlyList active) { - if (player.Contracts.Count > active.Count) + // 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 && !active.Any(a => (a.PeriodKey == key.Period) && (a.Definition.Id == key.Contract))) + if (!player.Contracts[key].IsDirty && !IsRunning(key)) { player.Contracts.Remove(key); } diff --git a/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs b/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs index ef5d8d1..378c91a 100644 --- a/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs +++ b/CounterStrikeProgression.Core/Storage/InMemoryProgressionStore.cs @@ -14,6 +14,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(); /// Gets the number of successful saves, for tests. public int SaveCount { get; private set; } @@ -32,7 +33,8 @@ internal sealed class InMemoryProgressionStore : IProgressionStore PlayerProgress progress = ProgressSnapshot.Rebuild( player, weapons.Values.Where(w => w.SteamId == steamId), - challenges.Values.Where(c => c.SteamId == steamId)); + challenges.Values.Where(c => c.SteamId == steamId), + contracts.Values.Where(c => c.SteamId == steamId)); return Task.FromResult(progress); } @@ -56,6 +58,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; + } + SaveCount++; return Task.CompletedTask; } diff --git a/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs b/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs index a258052..dd9db83 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 MySqlConnector; /// @@ -56,6 +57,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; + INSERT IGNORE INTO csp_schema (id, version) VALUES (1, @version); """; @@ -82,6 +92,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 readonly string connectionString = ConnectionStringFor(settings); /// @@ -146,7 +162,14 @@ public async Task InitializeAsync(CancellationToken cancellationToken) parameters, cancellationToken: cancellationToken)).ConfigureAwait(false); - return ProgressSnapshot.Rebuild(player, weapons, challenges); + // 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( + "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)", + new { steamId, day = DailyRotation.DayKey(today), week = DailyRotation.WeekKey(today) }, + cancellationToken: cancellationToken)).ConfigureAwait(false); + + return ProgressSnapshot.Rebuild(player, weapons, challenges, contracts); } /// @@ -178,6 +201,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); + } + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); } diff --git a/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs b/CounterStrikeProgression.Core/Storage/ProgressSnapshot.cs index c91dd73..bc3675b 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); + /// /// The rows of one player that changed since the last save, copied on the game thread so the database /// write can happen elsewhere. Every row holds full values, never increments, so saving the same snapshot @@ -43,8 +51,11 @@ internal sealed record ChallengeRow(ulong SteamId, string Weapon, string Challen /// 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 a value indicating whether there's nothing to save. - public bool IsEmpty => (Player is null) && (Weapons.Count == 0) && (Challenges.Count == 0); + public bool IsEmpty => (Player is null) && (Weapons.Count == 0) && (Challenges.Count == 0) && (Contracts.Count == 0); /// /// Copies a player's changed rows and clears their dirty flags. @@ -82,7 +93,17 @@ public static ProgressSnapshot Capture(PlayerProgress progress) } } - return new(player, weapons, challenges); + 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; + } + } + + return new(player, weapons, challenges) { Contracts = contracts }; } /// @@ -105,7 +126,8 @@ public static ProgressSnapshot CaptureAll(PlayerProgress progress) } } - return new(ToRow(progress), weapons, challenges); + 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 }; } /// @@ -141,6 +163,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; + } } /// @@ -149,8 +176,9 @@ public void Restore(PlayerProgress progress) /// The player row. /// The player's weapon rows. /// The player's challenge rows. + /// The player's contract rows, if any. /// The progress, with nothing flagged dirty. - public static PlayerProgress Rebuild(PlayerRow player, IEnumerable weapons, IEnumerable challenges) + public static PlayerProgress Rebuild(PlayerRow player, IEnumerable weapons, IEnumerable challenges, IEnumerable? contracts = null) { Ensure.NotNull(player); Ensure.NotNull(weapons); @@ -193,6 +221,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 2131330..a2d6b32 100644 --- a/CounterStrikeProgression.Site/Endpoints.cs +++ b/CounterStrikeProgression.Site/Endpoints.cs @@ -294,5 +294,8 @@ 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 })); } diff --git a/CounterStrikeProgression.Site/Live/ProgressMerge.cs b/CounterStrikeProgression.Site/Live/ProgressMerge.cs index bda4b75..7e002d8 100644 --- a/CounterStrikeProgression.Site/Live/ProgressMerge.cs +++ b/CounterStrikeProgression.Site/Live/ProgressMerge.cs @@ -70,7 +70,15 @@ public static ProgressSnapshot Combine(ProgressSnapshot older, ProgressSnapshot (var o, var n) => LargerPlayer(o!, n!), }; - return new(player, [.. weapons.Values], [.. challenges.Values]); + 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; + } + + return new(player, [.. weapons.Values], [.. challenges.Values]) { Contracts = [.. contracts.Values] }; } /// @@ -95,7 +103,12 @@ public static ProgressSnapshot Combine(ProgressSnapshot older, ProgressSnapshot return snapshot.Weapons[0].SteamId; } - return snapshot.Challenges.Count > 0 ? snapshot.Challenges[0].SteamId : null; + if (snapshot.Challenges.Count > 0) + { + return snapshot.Challenges[0].SteamId; + } + + return snapshot.Contracts.Count > 0 ? snapshot.Contracts[0].SteamId : null; } private static void CopyStored(PlayerProgress stored, PlayerProgress result) @@ -121,6 +134,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) @@ -161,6 +181,13 @@ private static void ApplyLive(PlayerProgress result, ProgressSnapshot live, bool challenge.Count = Math.Max(challenge.Count, row.Count); 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; + } } private static WeaponRow LargerWeapon(WeaponRow a, WeaponRow b) => a with diff --git a/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs b/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs index 28be253..93a7bd8 100644 --- a/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs +++ b/CounterStrikeProgression.Site/Views/PlayerViewBuilder.cs @@ -5,9 +5,11 @@ 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.Rotation; using ktsu.CounterStrikeProgression.Core.SkillShots; using ktsu.CounterStrikeProgression.Core.Weapons; @@ -24,8 +26,9 @@ internal static class PlayerViewBuilder /// The plugin's settings. /// Whether the player is on the server now. /// The player's feed, newest first. 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) + public static PlayerView Build(PlayerProgress merged, ProgressionSettings settings, bool online, IReadOnlyList? feed = null, DateTime? now = null) { Ensure.NotNull(merged); Ensure.NotNull(settings); @@ -63,9 +66,28 @@ .. merged.Weapons.Values weapons, 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)); + FeedCaptions.For(feed ?? [], settings), + 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 WeaponView BuildWeapon(WeaponProgress weapon, WeaponLevelCurve curve, ChallengeCatalog catalog) { WeaponInfo? info = WeaponCatalog.Find(weapon.Weapon); diff --git a/CounterStrikeProgression.Site/Views/ViewModels.cs b/CounterStrikeProgression.Site/Views/ViewModels.cs index ba45739..0e4bb74 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; @@ -66,6 +67,7 @@ internal sealed record WeaponView( /// The challenges to try next, closest to a tier first. /// Every feat, earned or not, with the player's progress toward it. /// The player's feed, newest first. +/// The contracts running now, today's first, with the player's progress on each. internal sealed record PlayerView( string SteamId, string Name, @@ -81,7 +83,19 @@ internal sealed record PlayerView( IReadOnlyList Weapons, IReadOnlyList Suggestions, IReadOnlyList Feats, - IReadOnlyList Feed); + IReadOnlyList Feed, + 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); /// One feat on a player's page. /// The feat id. diff --git a/CounterStrikeProgression.Site/wwwroot/site.css b/CounterStrikeProgression.Site/wwwroot/site.css index 5d37163..e1c25ed 100644 --- a/CounterStrikeProgression.Site/wwwroot/site.css +++ b/CounterStrikeProgression.Site/wwwroot/site.css @@ -416,6 +416,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 7983f9a..f8e699b 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) { @@ -714,6 +714,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 }; @@ -850,11 +871,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..3ca0822 --- /dev/null +++ b/CounterStrikeProgression.Test/ContractTests.cs @@ -0,0 +1,341 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.CounterStrikeProgression.Test; + +using ktsu.CounterStrikeProgression.Core; +using ktsu.CounterStrikeProgression.Core.Contracts; +using ktsu.CounterStrikeProgression.Core.Live; +using ktsu.CounterStrikeProgression.Core.Panel; +using ktsu.CounterStrikeProgression.Core.Progression; +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 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); + } +} 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/TestHelpers.cs b/CounterStrikeProgression.Test/TestHelpers.cs index bb6a7a8..0de851a 100644 --- a/CounterStrikeProgression.Test/TestHelpers.cs +++ b/CounterStrikeProgression.Test/TestHelpers.cs @@ -14,11 +14,12 @@ internal static class TestHelpers public static WeaponInfo Weapon(string name) => WeaponCatalog.Resolve(name) ?? throw new InvalidOperationException($"No weapon named {name}."); - public static ProgressionEngine Engine(Action? configure = null) + // 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(); + ProgressionSettings settings = new() { ContractsEnabled = false, FeaturedWeaponMultiplier = 1 }; configure?.Invoke(settings); - return new ProgressionEngine(settings); + return new ProgressionEngine(settings, time); } public static PlayerProgress Player() => new(SteamId) { Name = "Tester" }; diff --git a/CounterStrikeProgression/Announcer.cs b/CounterStrikeProgression/Announcer.cs index 4c5c6a4..dbef775 100644 --- a/CounterStrikeProgression/Announcer.cs +++ b/CounterStrikeProgression/Announcer.cs @@ -6,12 +6,13 @@ namespace ktsu.CounterStrikeProgression; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; +using ktsu.CounterStrikeProgression.Core.Contracts; using ktsu.CounterStrikeProgression.Core.Progression; 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. @@ -59,6 +60,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?.Definition.Period == ContractPeriod.Weekly: + Server.PrintToChatAll($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} {ChatColors.Green}{player.PlayerName}{ChatColors.Default} finished the weekly contract {ChatColors.Gold}{notice.Contract.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 c76bec5..c5e7d24 100644 --- a/CounterStrikeProgression/PlayerCommands.cs +++ b/CounterStrikeProgression/PlayerCommands.cs @@ -8,11 +8,12 @@ namespace ktsu.CounterStrikeProgression; using CounterStrikeSharp.API.Modules.Admin; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Utils; +using ktsu.CounterStrikeProgression.Core.Panel; using ktsu.CounterStrikeProgression.Core.Progression; using ktsu.CounterStrikeProgression.Core.Storage; /// -/// The chat and console commands: !rank (also !xp and !progress), !top, and the +/// The chat and console commands: !rank (also !xp and !progress), !contracts, !top, and the /// admin-only css_csp_status. /// /// The shared plugin pieces. @@ -35,6 +36,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", OnTop); plugin.AddCommand("css_csp_status", "Show progression storage and session diagnostics", OnStatus); } @@ -47,6 +49,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 550565d..e7b7657 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. - **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. - **XP floaties**: every XP gain floats up as "+XP" text from the center of your screen. Only you see your own. Quick gains add up in one floatie, and skill shots, tiers, and level-ups are named under the number in gold. A `World` mode floats them above the target instead. @@ -46,9 +47,10 @@ 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 | -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 command From f6a64fb6977c12f83dd13b9ce6380e806390043c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:57:31 +0000 Subject: [PATCH 3/5] Tidy two code scanning findings in contracts Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01KcGfJHYSEsAtduJxwCwnwB --- CounterStrikeProgression.Core/Panel/PanelBuilder.cs | 4 ++-- CounterStrikeProgression/Announcer.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CounterStrikeProgression.Core/Panel/PanelBuilder.cs b/CounterStrikeProgression.Core/Panel/PanelBuilder.cs index 2edaa5e..07828c3 100644 --- a/CounterStrikeProgression.Core/Panel/PanelBuilder.cs +++ b/CounterStrikeProgression.Core/Panel/PanelBuilder.cs @@ -100,7 +100,7 @@ public PanelPage Contracts(PlayerProgress player) ContractProgress? progress = player.Contracts.GetValueOrDefault((contract.PeriodKey, contract.Definition.Id)); long count = Math.Min(progress?.Count ?? 0, contract.Definition.Target); - if (progress?.Completed == true) + if (progress?.Completed ?? false) { done++; lines.Add(new(contract.Definition.Description, "Done", LineState.Done)); @@ -161,7 +161,7 @@ public PanelPage Overview(PlayerProgress player) IReadOnlyList contracts = engine.ActiveContracts; if (contracts.Count > 0) { - int done = contracts.Count(c => player.Contracts.GetValueOrDefault((c.PeriodKey, c.Definition.Id))?.Completed == true); + 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)); } diff --git a/CounterStrikeProgression/Announcer.cs b/CounterStrikeProgression/Announcer.cs index dbef775..bddb252 100644 --- a/CounterStrikeProgression/Announcer.cs +++ b/CounterStrikeProgression/Announcer.cs @@ -60,8 +60,8 @@ 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?.Definition.Period == ContractPeriod.Weekly: - Server.PrintToChatAll($" {ChatColors.Gold}{config.ChatPrefix}{ChatColors.Default} {ChatColors.Green}{player.PlayerName}{ChatColors.Default} finished the weekly contract {ChatColors.Gold}{notice.Contract.Definition.Description}{ChatColors.Default} (+{Xp(notice.Xp)} XP)"); + 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: From 9329c7cdf874c940b2d8a9e06343670280594199 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 13:07:37 +0000 Subject: [PATCH 4/5] Cover the contracts groundwork with tests Weekly contract rules, ISO week keys, the featured class, Grant, day pruning, seasons, and contract rows on ingest. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01KcGfJHYSEsAtduJxwCwnwB --- .../ContractTests.cs | 128 ++++++++++++++++++ .../SiteEndpointTests.cs | 15 ++ 2 files changed, 143 insertions(+) diff --git a/CounterStrikeProgression.Test/ContractTests.cs b/CounterStrikeProgression.Test/ContractTests.cs index 3ca0822..1fce188 100644 --- a/CounterStrikeProgression.Test/ContractTests.cs +++ b/CounterStrikeProgression.Test/ContractTests.cs @@ -7,6 +7,8 @@ namespace ktsu.CounterStrikeProgression.Test; 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; @@ -338,4 +340,130 @@ public void MergingKeepsTheLargerContractCount() 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] + public void TheFeaturedClassEarnsMoreWeaponXp() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(s => s.FeaturedWeaponMultiplier = 2, time); + WeaponClass featured = engine.FeaturedClass!.Value; + WeaponInfo boosted = WeaponCatalog.All.First(w => w.Class == featured); + WeaponInfo plain = WeaponCatalog.All.First(w => w.IsGun && w.Class != featured); + PlayerProgress player = TestHelpers.Player(); + + engine.ApplyCombat(player, TestHelpers.Hit(boosted.Key.WeakString)); + engine.ApplyCombat(player, TestHelpers.Hit(plain.Key.WeakString)); + + Assert.AreEqual(2 * player.Weapons[plain.Key].Xp, player.Weapons[boosted.Key].Xp); + Assert.IsNull(TestHelpers.Engine(time: time).FeaturedClass); + } + + [TestMethod] + public void GrantAddsAndRemovesRankXp() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(time: time); + PlayerProgress player = TestHelpers.Player(); + + engine.Grant(player, 20_000); + Assert.AreEqual(20_000, player.RankXp); + Assert.AreEqual(0, player.Day(engine.Today).Xp); + + engine.Grant(player, -30_000); + Assert.AreEqual(0, player.RankXp); + Assert.AreEqual(0, player.Rank); + Assert.AreEqual(0, player.Day(engine.Today).RankXp); + } + + [TestMethod] + public void DaysOtherThanTodayAreDroppedOnceSaved() + { + ManualTime time = new(); + ProgressionEngine engine = TestHelpers.Engine(time: time); + PlayerProgress player = TestHelpers.Player(); + DateOnly yesterday = engine.Today; + engine.ApplyCombat(player, TestHelpers.Kill("ak47")); + player.Day(yesterday).IsDirty = false; + + time.Advance(TimeSpan.FromDays(1)); + engine.ApplyCombat(player, TestHelpers.Kill("ak47")); + + Assert.IsFalse(player.Days.ContainsKey(yesterday)); + Assert.AreEqual(1, player.Day(engine.Today).Kills); + } + + [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, [], []))); + } } diff --git a/CounterStrikeProgression.Test/SiteEndpointTests.cs b/CounterStrikeProgression.Test/SiteEndpointTests.cs index 9b280f7..c02fba1 100644 --- a/CounterStrikeProgression.Test/SiteEndpointTests.cs +++ b/CounterStrikeProgression.Test/SiteEndpointTests.cs @@ -357,6 +357,21 @@ 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 body = JsonSerializer.Serialize(Batch() with { Progress = [rows] }, LiveJson.Options).Replace("\"contracts\":[{", "\"contracts\":[null,{", StringComparison.Ordinal); + 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)); + } + [TestMethod] public async Task Ingest_OversizedBody_Returns413() { From 313446bc25ff4e067b10504d7f39ab907e78870f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 13:47:01 +0000 Subject: [PATCH 5/5] Cover the contract ingest checks, the weekly feed title, and an all-done overview Moves the contract load query into a constant like the season one. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01KcGfJHYSEsAtduJxwCwnwB --- .../Storage/MySqlProgressionStore.cs | 5 +++- .../ContractTests.cs | 30 +++++++++++++++++++ .../SiteEndpointTests.cs | 13 +++++--- 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs b/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs index 691d468..4046485 100644 --- a/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs +++ b/CounterStrikeProgression.Core/Storage/MySqlProgressionStore.cs @@ -132,6 +132,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)"; + private const string DeletePlayerRows = """ DELETE FROM csp_challenges WHERE steam_id = @SteamId; DELETE FROM csp_weapons WHERE steam_id = @SteamId; @@ -211,7 +214,7 @@ public async Task InitializeAsync(CancellationToken cancellationToken) // 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( - "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)", + SelectContracts, new { steamId, day = DailyRotation.DayKey(today), week = DailyRotation.WeekKey(today) }, cancellationToken: cancellationToken)).ConfigureAwait(false); diff --git a/CounterStrikeProgression.Test/ContractTests.cs b/CounterStrikeProgression.Test/ContractTests.cs index e589ad4..d043c44 100644 --- a/CounterStrikeProgression.Test/ContractTests.cs +++ b/CounterStrikeProgression.Test/ContractTests.cs @@ -244,6 +244,36 @@ public void TheFeedNamesTheContract() 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() { diff --git a/CounterStrikeProgression.Test/SiteEndpointTests.cs b/CounterStrikeProgression.Test/SiteEndpointTests.cs index 343cf54..42ad344 100644 --- a/CounterStrikeProgression.Test/SiteEndpointTests.cs +++ b/CounterStrikeProgression.Test/SiteEndpointTests.cs @@ -369,10 +369,15 @@ public async Task Ingest_ContractRows_AreAcceptedAndANullRowIsRejected() IResult accepted = await Endpoints.IngestAsync(good, new SiteOptions { Token = "dev" }, live, new Broadcaster(), new FeatIndex()).ConfigureAwait(false); Assert.AreEqual(StatusCodes.Status204NoContent, StatusOf(accepted)); - string body = JsonSerializer.Serialize(Batch() with { Progress = [rows] }, LiveJson.Options).Replace("\"contracts\":[{", "\"contracts\":[null,{", StringComparison.Ordinal); - 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)); + 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]