mirror of
https://github.com/MSWS/TTT.git
synced 2025-12-07 23:06:33 -08:00
Compare commits
39 Commits
0.19.0-dev
...
0.20.0-dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c7bc22395 | ||
|
|
c95fba0fc5 | ||
|
|
40c7a6d471 | ||
|
|
b79519f6b4 | ||
|
|
bea87d20f3 | ||
|
|
5bbc621d86 | ||
|
|
5ed244f84c | ||
|
|
31d2354e6f | ||
|
|
44d9644694 | ||
|
|
cf1d040b44 | ||
|
|
8158206101 | ||
|
|
06f8f083df | ||
|
|
5c18a046b8 | ||
|
|
063813baca | ||
|
|
a10ce25846 | ||
|
|
89077c8361 | ||
|
|
fd3ffc6d59 | ||
|
|
f9e2734390 | ||
|
|
251d8efeaf | ||
|
|
e83fbdd3fe | ||
|
|
99742efc5b | ||
|
|
c802f468ed | ||
|
|
43becefb0a | ||
|
|
f8f2617b09 | ||
|
|
3eb59dec13 | ||
|
|
792a737102 | ||
|
|
85dd4edb08 | ||
|
|
2f78a62385 | ||
|
|
247f7de49b | ||
|
|
c523a9f015 | ||
|
|
8363265e39 | ||
|
|
f3363da9bb | ||
|
|
ec2355eb6d | ||
|
|
fd14728a27 | ||
|
|
556657d249 | ||
|
|
26c5d0e367 | ||
|
|
536662a500 | ||
|
|
64889de2fa | ||
|
|
7a6676e6ac |
29
SpecialRoundAPI/SpecialRoundAPI/AbstractSpecialRound.cs
Normal file
29
SpecialRoundAPI/SpecialRoundAPI/AbstractSpecialRound.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API;
|
||||
using TTT.API.Events;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public abstract class AbstractSpecialRound(IServiceProvider provider)
|
||||
: ITerrorModule, IListener {
|
||||
protected readonly IServiceProvider Provider = provider;
|
||||
|
||||
protected readonly ISpecialRoundTracker Tracker =
|
||||
provider.GetRequiredService<ISpecialRoundTracker>();
|
||||
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
|
||||
public abstract string Name { get; }
|
||||
public abstract IMsg Description { get; }
|
||||
public abstract SpecialRoundConfig Config { get; }
|
||||
|
||||
public abstract void ApplyRoundEffects();
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public abstract void OnGameState(GameStateUpdateEvent ev);
|
||||
}
|
||||
5
SpecialRoundAPI/SpecialRoundAPI/BhopRoundConfig.cs
Normal file
5
SpecialRoundAPI/SpecialRoundAPI/BhopRoundConfig.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public record BhopRoundConfig : SpecialRoundConfig {
|
||||
public override float Weight { get; init; } = 0.2f;
|
||||
}
|
||||
13
SpecialRoundAPI/SpecialRoundAPI/ISpecialRoundStarter.cs
Normal file
13
SpecialRoundAPI/SpecialRoundAPI/ISpecialRoundStarter.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public interface ISpecialRoundStarter {
|
||||
/// <summary>
|
||||
/// Attempts to start the given special round.
|
||||
/// Will bypass most checks, but may still return null if starting the round
|
||||
/// is not possible.
|
||||
/// </summary>
|
||||
/// <param name="round"></param>
|
||||
/// <returns></returns>
|
||||
public AbstractSpecialRound?
|
||||
TryStartSpecialRound(AbstractSpecialRound? round);
|
||||
}
|
||||
6
SpecialRoundAPI/SpecialRoundAPI/ISpecialRoundTracker.cs
Normal file
6
SpecialRoundAPI/SpecialRoundAPI/ISpecialRoundTracker.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public interface ISpecialRoundTracker {
|
||||
public AbstractSpecialRound? CurrentRound { get; set; }
|
||||
public int RoundsSinceLastSpecial { get; set; }
|
||||
}
|
||||
15
SpecialRoundAPI/SpecialRoundAPI/SpecialRoundAPI.csproj
Normal file
15
SpecialRoundAPI/SpecialRoundAPI/SpecialRoundAPI.csproj
Normal file
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Locale\Locale.csproj" />
|
||||
<ProjectReference Include="..\..\TTT\API\API.csproj" />
|
||||
<ProjectReference Include="..\..\TTT\Game\Game.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
5
SpecialRoundAPI/SpecialRoundAPI/SpecialRoundConfig.cs
Normal file
5
SpecialRoundAPI/SpecialRoundAPI/SpecialRoundConfig.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public abstract record SpecialRoundConfig {
|
||||
public abstract float Weight { get; init; }
|
||||
}
|
||||
8
SpecialRoundAPI/SpecialRoundAPI/SpeedRoundConfig.cs
Normal file
8
SpecialRoundAPI/SpecialRoundAPI/SpeedRoundConfig.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public record SpeedRoundConfig : SpecialRoundConfig {
|
||||
public override float Weight { get; init; } = 0.4f;
|
||||
|
||||
public TimeSpan InitialSeconds { get; init; } = TimeSpan.FromSeconds(60);
|
||||
public TimeSpan SecondsPerKill { get; init; } = TimeSpan.FromSeconds(10);
|
||||
}
|
||||
5
SpecialRoundAPI/SpecialRoundAPI/VanillaRoundConfig.cs
Normal file
5
SpecialRoundAPI/SpecialRoundAPI/VanillaRoundConfig.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
namespace SpecialRoundAPI;
|
||||
|
||||
public record VanillaRoundConfig : SpecialRoundConfig {
|
||||
public override float Weight { get; init; } = 0.3f;
|
||||
}
|
||||
18
TTT.sln
18
TTT.sln
@@ -25,6 +25,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopAPI", "TTT\ShopAPI\Shop
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RTD", "TTT\RTD\RTD.csproj", "{8A426E84-45DA-4558-A218-E042F1AC60B2}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Stats", "TTT\Stats\Stats.csproj", "{256473A2-6ACD-440C-83FA-6056147656C7}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpecialRound", "TTT\SpecialRound\SpecialRound.csproj", "{5092069A-3CFA-41C8-B685-341040AB435C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpecialRoundAPI", "SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj", "{360FEF16-54DA-42EE-995A-3D31C699287D}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -78,6 +84,18 @@ Global
|
||||
{8A426E84-45DA-4558-A218-E042F1AC60B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8A426E84-45DA-4558-A218-E042F1AC60B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8A426E84-45DA-4558-A218-E042F1AC60B2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{256473A2-6ACD-440C-83FA-6056147656C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{256473A2-6ACD-440C-83FA-6056147656C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{256473A2-6ACD-440C-83FA-6056147656C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{256473A2-6ACD-440C-83FA-6056147656C7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5092069A-3CFA-41C8-B685-341040AB435C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5092069A-3CFA-41C8-B685-341040AB435C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5092069A-3CFA-41C8-B685-341040AB435C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5092069A-3CFA-41C8-B685-341040AB435C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{360FEF16-54DA-42EE-995A-3D31C699287D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{360FEF16-54DA-42EE-995A-3D31C699287D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{360FEF16-54DA-42EE-995A-3D31C699287D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{360FEF16-54DA-42EE-995A-3D31C699287D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
EndGlobalSection
|
||||
|
||||
@@ -18,4 +18,6 @@ public interface IActionLogger {
|
||||
|
||||
void PrintLogs();
|
||||
void PrintLogs(IOnlinePlayer? player);
|
||||
|
||||
string[] MakeLogs();
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj" />
|
||||
<ProjectReference Include="..\API\API.csproj"/>
|
||||
<ProjectReference Include="..\Game\Game.csproj"/>
|
||||
<ProjectReference Include="..\Karma\Karma.csproj"/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API;
|
||||
using TTT.API.Command;
|
||||
@@ -6,7 +7,8 @@ using TTT.API.Player;
|
||||
|
||||
namespace TTT.CS2.Command.Test;
|
||||
|
||||
public class ReloadModule(IServiceProvider provider) : ICommand, IPluginModule {
|
||||
public class ReloadModuleCommand(IServiceProvider provider)
|
||||
: ICommand, IPluginModule {
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
private BasePlugin? plugin;
|
||||
@@ -34,12 +36,12 @@ public class ReloadModule(IServiceProvider provider) : ICommand, IPluginModule {
|
||||
return Task.FromResult(CommandResult.INVALID_ARGS);
|
||||
}
|
||||
|
||||
info.ReplySync("Reloading module '{moduleName}'...");
|
||||
info.ReplySync($"Reloading module '{moduleName}'...");
|
||||
module.Dispose();
|
||||
|
||||
info.ReplySync("Starting module '{moduleName}'...");
|
||||
info.ReplySync($"Starting module '{moduleName}'...");
|
||||
module.Start();
|
||||
info.ReplySync("Module '{moduleName}' reloaded successfully.");
|
||||
info.ReplySync($"Module '{moduleName}' reloaded successfully.");
|
||||
|
||||
if (plugin == null) {
|
||||
info.ReplySync("Plugin context not found; skipping hotload steps.");
|
||||
@@ -49,9 +51,11 @@ public class ReloadModule(IServiceProvider provider) : ICommand, IPluginModule {
|
||||
if (module is not IPluginModule pluginModule)
|
||||
return Task.FromResult(CommandResult.SUCCESS);
|
||||
|
||||
info.ReplySync("Hotloading plugin module '{moduleName}'...");
|
||||
pluginModule.Start(plugin, true);
|
||||
info.ReplySync("Plugin module '{moduleName}' hotloaded successfully.");
|
||||
Server.NextWorldUpdate(() => {
|
||||
info.ReplySync($"Hotloading plugin module '{moduleName}'...");
|
||||
pluginModule.Start(plugin, true);
|
||||
info.ReplySync($"Plugin module '{moduleName}' hotloaded successfully.");
|
||||
});
|
||||
|
||||
return Task.FromResult(CommandResult.SUCCESS);
|
||||
}
|
||||
41
TTT/CS2/Command/Test/SpecialRoundCommand.cs
Normal file
41
TTT/CS2/Command/Test/SpecialRoundCommand.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API;
|
||||
using TTT.API.Command;
|
||||
using TTT.API.Player;
|
||||
|
||||
namespace TTT.CS2.Command.Test;
|
||||
|
||||
public class SpecialRoundCommand(IServiceProvider provider) : ICommand {
|
||||
private readonly ISpecialRoundStarter tracker =
|
||||
provider.GetRequiredService<ISpecialRoundStarter>();
|
||||
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
|
||||
public string Id => "specialround";
|
||||
|
||||
public Task<CommandResult>
|
||||
Execute(IOnlinePlayer? executor, ICommandInfo info) {
|
||||
if (info.ArgCount == 1) {
|
||||
tracker.TryStartSpecialRound(null);
|
||||
info.ReplySync("Started a random special round.");
|
||||
return Task.FromResult(CommandResult.SUCCESS);
|
||||
}
|
||||
|
||||
var rounds = provider.GetServices<ITerrorModule>()
|
||||
.OfType<AbstractSpecialRound>()
|
||||
.ToDictionary(r => r.GetType().Name.ToLower(), r => r);
|
||||
|
||||
var roundName = info.Args[1].ToLower();
|
||||
if (!rounds.TryGetValue(roundName, out var round)) {
|
||||
info.ReplySync($"No special round found with name '{roundName}'.");
|
||||
foreach (var name in rounds.Keys) info.ReplySync($"- {name}");
|
||||
return Task.FromResult(CommandResult.INVALID_ARGS);
|
||||
}
|
||||
|
||||
tracker.TryStartSpecialRound(round);
|
||||
info.ReplySync($"Started special round '{roundName}'.");
|
||||
return Task.FromResult(CommandResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,8 @@ public class TestCommand(IServiceProvider provider) : ICommand, IPluginModule {
|
||||
subCommands.Add("emitsound", new EmitSoundCommand(provider));
|
||||
subCommands.Add("credits", new CreditsCommand(provider));
|
||||
subCommands.Add("spec", new SpecCommand(provider));
|
||||
subCommands.Add("reload", new ReloadModule(provider));
|
||||
subCommands.Add("reload", new ReloadModuleCommand(provider));
|
||||
subCommands.Add("specialround", new SpecialRoundCommand(provider));
|
||||
}
|
||||
|
||||
public Task<CommandResult>
|
||||
|
||||
@@ -24,7 +24,7 @@ public class CS2GameConfig : IStorage<TTTConfig>, IPluginModule {
|
||||
|
||||
public static readonly FakeConVar<int> CV_ROUND_DURATION_PER_PLAYER = new(
|
||||
"css_ttt_round_duration_per_player",
|
||||
"Additional round duration per player in seconds", 30,
|
||||
"Additional round duration per player in seconds", 10,
|
||||
ConVarFlags.FCVAR_NONE, new RangeValidator<int>(0, 60));
|
||||
|
||||
public static readonly FakeConVar<int> CV_ROUND_DURATION_MAX = new(
|
||||
|
||||
@@ -68,10 +68,14 @@ public class CombatHandler(IServiceProvider provider) : IPluginModule {
|
||||
"CCSPlayerController_ActionTrackingServices",
|
||||
"m_pActionTrackingServices");
|
||||
if (killerStats == null) return;
|
||||
killerStats.Kills -= 1;
|
||||
killerStats.Damage -= ev.DmgHealth;
|
||||
killerStats.Kills -= 1;
|
||||
killerStats.Damage -= ev.DmgHealth;
|
||||
killerStats.UtilityDamage = 0;
|
||||
if (ev.Attacker.ActionTrackingServices != null)
|
||||
ev.Attacker.ActionTrackingServices.NumRoundKills--;
|
||||
Utilities.SetStateChanged(ev.Attacker, "CSPerRoundStats_t", "m_iDamage");
|
||||
Utilities.SetStateChanged(ev.Attacker, "CSPerRoundStats_t",
|
||||
"m_iUtilityDamage");
|
||||
Utilities.SetStateChanged(ev.Attacker, "CCSPlayerController",
|
||||
"m_pActionTrackingServices");
|
||||
}
|
||||
|
||||
@@ -104,8 +104,7 @@ public class RoleIconsHandler(IServiceProvider provider)
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(IgnoreCanceled = true)]
|
||||
public void OnRoundStart(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.FINISHED) return;
|
||||
public void OnRoundStart(GameInitEvent ev) {
|
||||
for (var i = 0; i < icons.Length; i++) removeIcon(i);
|
||||
ClearAllVisibility();
|
||||
traitorsThisRound.Clear();
|
||||
|
||||
@@ -59,8 +59,12 @@ public class DamageStation(IServiceProvider provider)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!prop.IsValid || prop.AbsOrigin == null) {
|
||||
toRemove.Add(prop);
|
||||
continue;
|
||||
}
|
||||
|
||||
var propPos = prop.AbsOrigin;
|
||||
if (propPos == null) continue;
|
||||
|
||||
var playerMapping = players.Select(p
|
||||
=> (ApiPlayer: p, GamePlayer: converter.GetPlayer(p)))
|
||||
|
||||
@@ -36,8 +36,12 @@ public class HealthStation(IServiceProvider provider)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!prop.IsValid || prop.AbsOrigin == null) {
|
||||
toRemove.Add(prop);
|
||||
continue;
|
||||
}
|
||||
|
||||
var propPos = prop.AbsOrigin;
|
||||
if (propPos == null) continue;
|
||||
|
||||
var playerDists = players
|
||||
.Select(p => (Player: p, Pos: p.Pawn.Value?.AbsOrigin))
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace TTT.CS2.Listeners;
|
||||
public class AfkTimerListener(IServiceProvider provider)
|
||||
: BaseListener(provider) {
|
||||
private TTTConfig config
|
||||
=> provider.GetRequiredService<IStorage<TTTConfig>>()
|
||||
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
|
||||
.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new TTTConfig();
|
||||
@@ -32,19 +32,27 @@ public class AfkTimerListener(IServiceProvider provider)
|
||||
|
||||
private IDisposable? specTimer, specWarnTimer;
|
||||
|
||||
public override void Dispose() {
|
||||
base.Dispose();
|
||||
|
||||
specTimer?.Dispose();
|
||||
specWarnTimer?.Dispose();
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(IgnoreCanceled = true)]
|
||||
public void OnRoundStart(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.IN_PROGRESS) return;
|
||||
if (ev.NewState != State.IN_PROGRESS) {
|
||||
specTimer?.Dispose();
|
||||
specWarnTimer?.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
specWarnTimer?.Dispose();
|
||||
specWarnTimer = Scheduler.Schedule(config.RoundCfg.CheckAFKTimespan / 2, ()
|
||||
=> {
|
||||
Server.NextWorldUpdate(() => {
|
||||
foreach (var player in Utilities.GetPlayers()
|
||||
.Where(p
|
||||
=> p.PlayerPawn.Value != null
|
||||
&& !p.PlayerPawn.Value.HasMovedSinceSpawn)) {
|
||||
foreach (var player in getAfkPlayers()) {
|
||||
var apiPlayer = converter.GetPlayer(player);
|
||||
var timetill = config.RoundCfg.CheckAFKTimespan / 2;
|
||||
Messenger.Message(apiPlayer, Locale[CS2Msgs.AFK_WARNING(timetill)]);
|
||||
@@ -55,13 +63,21 @@ public class AfkTimerListener(IServiceProvider provider)
|
||||
specTimer?.Dispose();
|
||||
specTimer = Scheduler.Schedule(config.RoundCfg.CheckAFKTimespan, () => {
|
||||
Server.NextWorldUpdate(() => {
|
||||
foreach (var player in Utilities.GetPlayers()
|
||||
.Where(p
|
||||
=> p.PlayerPawn.Value != null
|
||||
&& !p.PlayerPawn.Value.HasMovedSinceSpawn)) {
|
||||
foreach (var player in getAfkPlayers()) {
|
||||
var apiPlayer = converter.GetPlayer(player);
|
||||
#if !DEBUG
|
||||
player.ChangeTeam(CsTeam.Spectator);
|
||||
#endif
|
||||
Messenger.Message(apiPlayer, Locale[CS2Msgs.AFK_MOVED]);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private List<CCSPlayerController> getAfkPlayers() {
|
||||
return Utilities.GetPlayers()
|
||||
.Where(p => p.PlayerPawn.Value != null
|
||||
&& !p.PlayerPawn.Value.HasMovedSinceSpawn)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ public class RoundTimerListener(IServiceProvider provider)
|
||||
private readonly IPlayerConverter<CCSPlayerController> converter =
|
||||
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
|
||||
|
||||
private IDisposable? endTimer;
|
||||
public IDisposable? EndTimer;
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(IgnoreCanceled = true)]
|
||||
@@ -63,14 +63,14 @@ public class RoundTimerListener(IServiceProvider provider)
|
||||
player.Respawn();
|
||||
});
|
||||
|
||||
if (ev.NewState == State.FINISHED) endTimer?.Dispose();
|
||||
if (ev.NewState == State.FINISHED) EndTimer?.Dispose();
|
||||
if (ev.NewState != State.IN_PROGRESS) return;
|
||||
var duration = config.RoundCfg.RoundDuration(ev.Game.Players.Count);
|
||||
Server.NextWorldUpdate(()
|
||||
=> RoundUtil.SetTimeRemaining((int)duration.TotalSeconds));
|
||||
|
||||
endTimer?.Dispose();
|
||||
endTimer = Scheduler.Schedule(duration,
|
||||
EndTimer?.Dispose();
|
||||
EndTimer = Scheduler.Schedule(duration,
|
||||
() => {
|
||||
Server.NextWorldUpdate(()
|
||||
=> ev.Game.EndGame(EndReason.TIMEOUT(new InnocentRole(Provider))));
|
||||
@@ -137,6 +137,6 @@ public class RoundTimerListener(IServiceProvider provider)
|
||||
public override void Dispose() {
|
||||
base.Dispose();
|
||||
|
||||
endTimer?.Dispose();
|
||||
EndTimer?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ namespace TTT.CS2.Player;
|
||||
public class CS2AliveSpoofer : IAliveSpoofer, IPluginModule {
|
||||
private readonly HashSet<CCSPlayerController> _fakeAlivePlayers = new();
|
||||
public ISet<CCSPlayerController> FakeAlivePlayers => _fakeAlivePlayers;
|
||||
private BasePlugin? plugin = null;
|
||||
|
||||
public void SpoofAlive(CCSPlayerController player) {
|
||||
if (player.IsBot) {
|
||||
@@ -46,10 +47,17 @@ public class CS2AliveSpoofer : IAliveSpoofer, IPluginModule {
|
||||
FakeAlivePlayers.Remove(player);
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
public void Dispose() {
|
||||
_fakeAlivePlayers.Clear();
|
||||
plugin?.RemoveListener<CounterStrikeSharp.API.Core.Listeners.OnTick>(
|
||||
onTick);
|
||||
}
|
||||
|
||||
public void Start() { }
|
||||
|
||||
public void Start(BasePlugin? plugin) {
|
||||
if (plugin == null) return;
|
||||
this.plugin = plugin;
|
||||
plugin?.RegisterListener<CounterStrikeSharp.API.Core.Listeners.OnTick>(
|
||||
onTick);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ ROLE_SPECTATOR: "Spectator"
|
||||
TRAITOR_CHAT_FORMAT: "{darkred}[TRAITORS] {red}{0}: {default}{1}"
|
||||
TASER_SCANNED: "%PREFIX%You scanned {0}{grey}, they are %an% {1}{grey}!"
|
||||
DNA_PREFIX: "{darkblue}D{blue}N{lightblue}A{grey} | {grey}"
|
||||
AFK_WARNING: "%PREFIX%You will be moved to spectators in {yellow}{{0} second%s%{grey} for being AFK."
|
||||
AFK_WARNING: "%PREFIX%You will be moved to spectators in {yellow}{0} second%s%{grey} for being AFK."
|
||||
AFK_MOVED: "%PREFIX%You were moved to spectators for being AFK."
|
||||
|
||||
DEAD_MUTE_REMINDER: "%PREFIX%You are dead and cannot be heard."
|
||||
|
||||
@@ -12,4 +12,8 @@
|
||||
<ProjectReference Include="..\API\API.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Listeners\Stats\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -11,11 +11,9 @@ namespace TTT.Game.Listeners;
|
||||
|
||||
public class GameRestartListener(IServiceProvider provider)
|
||||
: BaseListener(provider) {
|
||||
private TTTConfig config
|
||||
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
|
||||
.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new TTTConfig();
|
||||
private TTTConfig config =
|
||||
provider.GetService<IStorage<TTTConfig>>()?.Load().GetAwaiter().GetResult()
|
||||
?? new TTTConfig();
|
||||
|
||||
private readonly IScheduler scheduler =
|
||||
provider.GetRequiredService<IScheduler>();
|
||||
|
||||
@@ -61,6 +61,15 @@ public class SimpleLogger(IServiceProvider provider) : IActionLogger {
|
||||
msg.Value.BackgroundMsg(player, locale[GameMsgs.GAME_LOGS_FOOTER]);
|
||||
}
|
||||
|
||||
public string[] MakeLogs() {
|
||||
List<string> logLines = [];
|
||||
logLines.Add(locale[GameMsgs.GAME_LOGS_HEADER]);
|
||||
foreach (var (time, action) in GetActions())
|
||||
logLines.Add($"{formatTime(time)} {action.Format()}");
|
||||
logLines.Add(locale[GameMsgs.GAME_LOGS_FOOTER]);
|
||||
return logLines.ToArray();
|
||||
}
|
||||
|
||||
private string formatTime(DateTime time) {
|
||||
if (epoch == null) return time.ToString("o");
|
||||
var span = time - epoch.Value;
|
||||
|
||||
@@ -148,10 +148,11 @@ public class RoundBasedGame(IServiceProvider provider) : IGame {
|
||||
case > 0 when nonTraitorsAlive == 0:
|
||||
winningTeam = traitorRole;
|
||||
return true;
|
||||
case > 0 when nonTraitorsAlive == detectivesAlive:
|
||||
winningTeam = detectiveRole;
|
||||
return true;
|
||||
case 0 when nonTraitorsAlive > 0:
|
||||
winningTeam = nonTraitorsAlive == detectivesAlive ?
|
||||
detectiveRole :
|
||||
innocentRole;
|
||||
winningTeam = innocentRole;
|
||||
return true;
|
||||
default:
|
||||
winningTeam = null;
|
||||
|
||||
@@ -11,11 +11,4 @@
|
||||
<ProjectReference Include="..\Game\Game.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.66"/>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.9"/>
|
||||
<PackageReference Include="MySqlConnector" Version="2.4.0"/>
|
||||
<PackageReference Include="SQLite" Version="3.13.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -4,8 +4,6 @@ using System.Diagnostics;
|
||||
using System.Reactive.Concurrency;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Threading.Tasks;
|
||||
using Dapper;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Player;
|
||||
@@ -15,142 +13,38 @@ using TTT.Karma.Events;
|
||||
namespace TTT.Karma;
|
||||
|
||||
public sealed class KarmaStorage(IServiceProvider provider) : IKarmaService {
|
||||
// Toggle immediate writes. If false, every Write triggers a flush
|
||||
private const bool EnableCache = true;
|
||||
private readonly IEventBus _bus = provider.GetRequiredService<IEventBus>();
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
private readonly SemaphoreSlim _flushGate = new(1, 1);
|
||||
private KarmaConfig config
|
||||
=> provider.GetService<IStorage<KarmaConfig>>()
|
||||
?.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new KarmaConfig();
|
||||
|
||||
// Cache keyed by stable player id to avoid relying on IPlayer equality
|
||||
private readonly ConcurrentDictionary<string, int> _karmaCache = new();
|
||||
public async Task<int> Load(IPlayer key) {
|
||||
var result = await client.GetAsync("user/" + key.Id);
|
||||
|
||||
private readonly IScheduler _scheduler =
|
||||
provider.GetRequiredService<IScheduler>();
|
||||
if (!result.IsSuccessStatusCode) return config.DefaultKarma;
|
||||
|
||||
private KarmaConfig _config = new();
|
||||
private IDbConnection? _connection;
|
||||
private IDisposable? _flushSubscription;
|
||||
var content = await result.Content.ReadAsStringAsync();
|
||||
var json = System.Text.Json.JsonDocument.Parse(content);
|
||||
if (!json.RootElement.TryGetProperty("karma", out var karmaElement))
|
||||
return config.DefaultKarma;
|
||||
|
||||
public string Id => nameof(KarmaStorage);
|
||||
public string Version => GitVersionInformation.FullSemVer;
|
||||
|
||||
public void Start() {
|
||||
// Open a dedicated connection used only by this service
|
||||
_connection = new SqliteConnection(_config.DbString);
|
||||
_connection.Open();
|
||||
|
||||
// Ensure schema before any reads or writes
|
||||
_connection.Execute(@"CREATE TABLE IF NOT EXISTS PlayerKarma (
|
||||
PlayerId TEXT PRIMARY KEY,
|
||||
Karma INTEGER NOT NULL
|
||||
)");
|
||||
|
||||
// Periodic flush with proper error handling and serialization
|
||||
_flushSubscription = Observable
|
||||
.Interval(TimeSpan.FromSeconds(30), _scheduler)
|
||||
.SelectMany(_ => FlushAsync().ToObservable())
|
||||
.Subscribe(_ => { }, // no-op on success
|
||||
ex => {
|
||||
// Replace with your logger if available
|
||||
Trace.TraceError($"Karma flush failed: {ex}");
|
||||
});
|
||||
return karmaElement.GetInt32();
|
||||
}
|
||||
|
||||
public async Task<int> Load(IPlayer player) {
|
||||
if (player is null) throw new ArgumentNullException(nameof(player));
|
||||
var key = player.Id;
|
||||
public Task Write(IPlayer key, int newData) {
|
||||
var data = new { steam_id = key.Id, karma = newData };
|
||||
|
||||
if (EnableCache && _karmaCache.TryGetValue(key, out var cached))
|
||||
return cached;
|
||||
var payload = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
var conn = EnsureConnection();
|
||||
|
||||
// Parameterize the default value to keep SQL static
|
||||
var sql = @"
|
||||
SELECT COALESCE(
|
||||
(SELECT Karma FROM PlayerKarma WHERE PlayerId = @PlayerId),
|
||||
@DefaultKarma
|
||||
)";
|
||||
var karma = await conn.QuerySingleAsync<int>(sql,
|
||||
new { PlayerId = key, _config.DefaultKarma });
|
||||
|
||||
if (EnableCache) _karmaCache[key] = karma;
|
||||
return karma;
|
||||
return client.PatchAsync("user/" + key.Id, payload);
|
||||
}
|
||||
|
||||
public async Task Write(IPlayer player, int newValue) {
|
||||
if (player is null) throw new ArgumentNullException(nameof(player));
|
||||
var key = player.Id;
|
||||
|
||||
var max = _config.MaxKarma(player);
|
||||
if (newValue > max)
|
||||
throw new ArgumentOutOfRangeException(nameof(newValue),
|
||||
$"Karma must be less than {max} for player {key}.");
|
||||
|
||||
int oldValue;
|
||||
if (!_karmaCache.TryGetValue(key, out oldValue))
|
||||
oldValue = await Load(player);
|
||||
|
||||
if (oldValue == newValue) return;
|
||||
|
||||
var evt = new KarmaUpdateEvent(player, oldValue, newValue);
|
||||
try { _bus.Dispatch(evt); } catch {
|
||||
// Replace with your logger if available
|
||||
Trace.TraceError("Exception during KarmaUpdateEvent dispatch.");
|
||||
throw;
|
||||
}
|
||||
|
||||
if (evt.IsCanceled) return;
|
||||
|
||||
_karmaCache[key] = newValue;
|
||||
|
||||
if (!EnableCache) await FlushAsync();
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
try {
|
||||
_flushSubscription?.Dispose();
|
||||
// Best effort final flush
|
||||
if (_connection is { State: ConnectionState.Open })
|
||||
FlushAsync().GetAwaiter().GetResult();
|
||||
} catch (Exception ex) {
|
||||
Trace.TraceError($"Dispose flush failed: {ex}");
|
||||
} finally {
|
||||
_connection?.Dispose();
|
||||
_flushGate.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FlushAsync() {
|
||||
var conn = EnsureConnection();
|
||||
|
||||
// Fast path if there is nothing to flush
|
||||
if (_karmaCache.IsEmpty) return;
|
||||
|
||||
await _flushGate.WaitAsync().ConfigureAwait(false);
|
||||
try {
|
||||
// Snapshot to avoid long lock on dictionary and to provide a stable view
|
||||
var snapshot = _karmaCache.ToArray();
|
||||
if (snapshot.Length == 0) return;
|
||||
|
||||
using var tx = conn.BeginTransaction();
|
||||
const string upsert = @"
|
||||
INSERT INTO PlayerKarma (PlayerId, Karma)
|
||||
VALUES (@PlayerId, @Karma)
|
||||
ON CONFLICT(PlayerId) DO UPDATE SET Karma = excluded.Karma
|
||||
";
|
||||
foreach (var (playerId, karma) in snapshot)
|
||||
await conn.ExecuteAsync(upsert,
|
||||
new { PlayerId = playerId, Karma = karma }, tx);
|
||||
|
||||
tx.Commit();
|
||||
} finally { _flushGate.Release(); }
|
||||
}
|
||||
|
||||
private IDbConnection EnsureConnection() {
|
||||
if (_connection is not { State: ConnectionState.Open })
|
||||
throw new InvalidOperationException(
|
||||
"Storage connection is not initialized.");
|
||||
return _connection;
|
||||
}
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
}
|
||||
@@ -13,6 +13,8 @@
|
||||
<ProjectReference Include="..\Karma\Karma.csproj"/>
|
||||
<ProjectReference Include="..\Shop\Shop.csproj"/>
|
||||
<ProjectReference Include="..\RTD\RTD.csproj"/>
|
||||
<ProjectReference Include="..\Stats\Stats.csproj"/>
|
||||
<ProjectReference Include="..\SpecialRound\SpecialRound.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -64,4 +64,5 @@ public class TTT(IServiceProvider provider) : BasePlugin {
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
using System.Reactive.Concurrency;
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SpecialRound;
|
||||
using Stats;
|
||||
using TTT.CS2;
|
||||
using TTT.Game;
|
||||
using TTT.Karma;
|
||||
@@ -18,5 +21,9 @@ public class TTTServiceCollection : IPluginServiceCollection<TTT> {
|
||||
serviceCollection.AddCS2Services();
|
||||
serviceCollection.AddShopServices();
|
||||
serviceCollection.AddRtdServices();
|
||||
serviceCollection.AddSpecialRounds();
|
||||
|
||||
if (Environment.GetEnvironmentVariable("TTT_STATS_API_URL") == null) return;
|
||||
serviceCollection.AddStatsServices();
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,4 @@ RTD_CANNOT_ROLL_YET: "%RTD_PREFIX%You must wait until death to roll the die."
|
||||
RTD_ROLLED: "%RTD_PREFIX%You rolled {default}{0}{grey}, {1}."
|
||||
RTD_MUTED: "%RTD_PREFIX%You cannot speak due to your dice roll."
|
||||
CREDITS_REWARD: "{0} %CREDITS_NAME%%s%"
|
||||
CREDITS_REWARD_DESC: "you will receive {yellow}%CREDITS_NAME%%s%{grey} next round"
|
||||
CREDITS_REWARD_DESC: "you will receive {yellow}{0} %CREDITS_NAME%%s%{grey} next round"
|
||||
@@ -113,6 +113,6 @@ public class ListCommand(IServiceProvider provider) : ICommand, IItemSorter {
|
||||
|
||||
private string formatItem(IShopItem item, int index, bool canBuy) {
|
||||
return
|
||||
$" {formatPrefix(item, index, canBuy)} {ChatColors.Grey} | {item.Description}";
|
||||
$" {formatPrefix(item, index, canBuy)}";
|
||||
}
|
||||
}
|
||||
@@ -43,11 +43,11 @@ public class HealthshotItem(IServiceProvider provider)
|
||||
}
|
||||
|
||||
public override PurchaseResult CanPurchase(IOnlinePlayer player) {
|
||||
if (purchaseCounts.TryGetValue(player.Id, out var purchases))
|
||||
if (!purchaseCounts.TryGetValue(player.Id, out var purchases))
|
||||
return PurchaseResult.SUCCESS;
|
||||
return purchases < config.MaxPurchases ?
|
||||
PurchaseResult.SUCCESS :
|
||||
PurchaseResult.ALREADY_OWNED;
|
||||
return purchases < config.MaxPurchases
|
||||
? PurchaseResult.SUCCESS
|
||||
: PurchaseResult.ALREADY_OWNED;
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
|
||||
39
TTT/SpecialRound/Rounds/BhopRound.cs
Normal file
39
TTT/SpecialRound/Rounds/BhopRound.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using CounterStrikeSharp.API;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SpecialRound.lang;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API.Game;
|
||||
using TTT.API.Storage;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace SpecialRound.Rounds;
|
||||
|
||||
public class BhopRound(IServiceProvider provider)
|
||||
: AbstractSpecialRound(provider) {
|
||||
public override string Name => "BHop";
|
||||
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_BHOP;
|
||||
public override SpecialRoundConfig Config => config;
|
||||
|
||||
private BhopRoundConfig config
|
||||
=> Provider.GetService<IStorage<BhopRoundConfig>>()
|
||||
?.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new BhopRoundConfig();
|
||||
|
||||
public override void ApplyRoundEffects() {
|
||||
Server.NextWorldUpdate(() => {
|
||||
Server.ExecuteCommand("sv_enablebunnyhopping 1");
|
||||
Server.ExecuteCommand("sv_autobunnyhopping 1");
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnGameState(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.FINISHED) return;
|
||||
|
||||
Server.NextWorldUpdate(() => {
|
||||
Server.ExecuteCommand("sv_enablebunnyhopping 0");
|
||||
Server.ExecuteCommand("sv_autobunnyhopping 0");
|
||||
});
|
||||
}
|
||||
}
|
||||
88
TTT/SpecialRound/Rounds/SpeedRound.cs
Normal file
88
TTT/SpecialRound/Rounds/SpeedRound.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System.Reactive.Concurrency;
|
||||
using CounterStrikeSharp.API;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SpecialRound.lang;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Game;
|
||||
using TTT.API.Role;
|
||||
using TTT.API.Storage;
|
||||
using TTT.CS2.Listeners;
|
||||
using TTT.CS2.Utils;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Game.Events.Player;
|
||||
using TTT.Game.Roles;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace SpecialRound.Rounds;
|
||||
|
||||
public class SpeedRound(IServiceProvider provider)
|
||||
: AbstractSpecialRound(provider) {
|
||||
private readonly IScheduler scheduler =
|
||||
provider.GetRequiredService<IScheduler>();
|
||||
|
||||
private readonly IGameManager games =
|
||||
provider.GetRequiredService<IGameManager>();
|
||||
|
||||
private readonly IRoleAssigner roles =
|
||||
provider.GetRequiredService<IRoleAssigner>();
|
||||
|
||||
public override string Name => "Speed";
|
||||
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_SPEED;
|
||||
|
||||
public override SpecialRoundConfig Config => config;
|
||||
|
||||
private SpeedRoundConfig config
|
||||
=> Provider.GetService<IStorage<SpeedRoundConfig>>()
|
||||
?.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new SpeedRoundConfig();
|
||||
|
||||
private IDisposable? endTimer;
|
||||
|
||||
public override void ApplyRoundEffects() {
|
||||
Provider.GetService<RoundTimerListener>()?.EndTimer?.Dispose();
|
||||
|
||||
setTime(config.InitialSeconds);
|
||||
}
|
||||
|
||||
private void addTime(TimeSpan span) {
|
||||
Server.NextWorldUpdate(() => {
|
||||
var remaining = RoundUtil.GetTimeRemaining();
|
||||
var newSpan = TimeSpan.FromSeconds(remaining + (int)span.TotalSeconds);
|
||||
|
||||
setTime(newSpan);
|
||||
});
|
||||
}
|
||||
|
||||
private void setTime(TimeSpan span) {
|
||||
Server.NextWorldUpdate(() => {
|
||||
RoundUtil.SetTimeRemaining((int)span.TotalSeconds);
|
||||
});
|
||||
|
||||
endTimer?.Dispose();
|
||||
endTimer = scheduler.Schedule(span,
|
||||
() => Server.NextWorldUpdate(() => games.ActiveGame?.EndGame(
|
||||
EndReason.TIMEOUT(new InnocentRole(Provider)))));
|
||||
}
|
||||
|
||||
public override void OnGameState(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.FINISHED) return;
|
||||
|
||||
endTimer?.Dispose();
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnDeath(PlayerDeathEvent ev) {
|
||||
var game = games.ActiveGame;
|
||||
if (game == null) return;
|
||||
if (Tracker.CurrentRound != this) return;
|
||||
|
||||
var victimRoles = roles.GetRoles(ev.Victim);
|
||||
if (!victimRoles.Any(r => r is InnocentRole)) return;
|
||||
|
||||
addTime(config.SecondsPerKill);
|
||||
}
|
||||
}
|
||||
36
TTT/SpecialRound/Rounds/VanillaRound.cs
Normal file
36
TTT/SpecialRound/Rounds/VanillaRound.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ShopAPI.Events;
|
||||
using SpecialRound.lang;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Storage;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace SpecialRound.Rounds;
|
||||
|
||||
public class VanillaRound(IServiceProvider provider)
|
||||
: AbstractSpecialRound(provider) {
|
||||
public override string Name => "Vanilla";
|
||||
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_VANILLA;
|
||||
|
||||
private VanillaRoundConfig config
|
||||
=> Provider.GetService<IStorage<VanillaRoundConfig>>()
|
||||
?.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new VanillaRoundConfig();
|
||||
|
||||
public override SpecialRoundConfig Config => config;
|
||||
|
||||
public override void ApplyRoundEffects() { }
|
||||
|
||||
public override void OnGameState(GameStateUpdateEvent ev) { }
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(Priority = Priority.HIGH)]
|
||||
public void OnPurchase(PlayerPurchaseItemEvent ev) {
|
||||
if (Tracker.CurrentRound != this) return;
|
||||
ev.IsCanceled = true;
|
||||
}
|
||||
}
|
||||
16
TTT/SpecialRound/SpecialRound.csproj
Normal file
16
TTT/SpecialRound/SpecialRound.csproj
Normal file
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj" />
|
||||
<ProjectReference Include="..\API\API.csproj" />
|
||||
<ProjectReference Include="..\CS2\CS2.csproj" />
|
||||
<ProjectReference Include="..\Game\Game.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
17
TTT/SpecialRound/SpecialRoundCollection.cs
Normal file
17
TTT/SpecialRound/SpecialRoundCollection.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SpecialRound.Rounds;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API.Extensions;
|
||||
|
||||
namespace SpecialRound;
|
||||
|
||||
public static class SpecialRoundCollection {
|
||||
public static void AddSpecialRounds(this IServiceCollection services) {
|
||||
services.AddModBehavior<ISpecialRoundStarter, SpecialRoundStarter>();
|
||||
services.AddModBehavior<ISpecialRoundTracker, SpecialRoundTracker>();
|
||||
|
||||
services.AddModBehavior<SpeedRound>();
|
||||
services.AddModBehavior<BhopRound>();
|
||||
services.AddModBehavior<VanillaRound>();
|
||||
}
|
||||
}
|
||||
72
TTT/SpecialRound/SpecialRoundStarter.cs
Normal file
72
TTT/SpecialRound/SpecialRoundStarter.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using CounterStrikeSharp.API.Core;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SpecialRound.lang;
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Game;
|
||||
using TTT.API.Storage;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Game.Listeners;
|
||||
|
||||
namespace SpecialRound;
|
||||
|
||||
public class SpecialRoundStarter(IServiceProvider provider)
|
||||
: BaseListener(provider), IPluginModule, ISpecialRoundStarter {
|
||||
private readonly ISpecialRoundTracker tracker =
|
||||
provider.GetRequiredService<ISpecialRoundTracker>();
|
||||
|
||||
private SpecialRoundsConfig config
|
||||
=> Provider.GetService<IStorage<SpecialRoundsConfig>>()
|
||||
?.Load()
|
||||
.GetAwaiter()
|
||||
.GetResult() ?? new SpecialRoundsConfig();
|
||||
|
||||
private int roundsSinceMapChange = 0;
|
||||
|
||||
public void Start(BasePlugin? plugin) {
|
||||
plugin?.RegisterListener<Listeners.OnMapStart>(onMapChange);
|
||||
}
|
||||
|
||||
private void onMapChange(string mapName) { roundsSinceMapChange = 0; }
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnRound(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.IN_PROGRESS) return;
|
||||
|
||||
roundsSinceMapChange++;
|
||||
tracker.RoundsSinceLastSpecial++;
|
||||
|
||||
if (tracker.RoundsSinceLastSpecial < config.MinRoundsBetweenSpecial) return;
|
||||
|
||||
if (ev.Game.Players.Count < config.MinPlayersForSpecial) return;
|
||||
if (roundsSinceMapChange < config.MinRoundsAfterMapChange) return;
|
||||
if (Random.Shared.NextSingle() > config.SpecialRoundChance) return;
|
||||
|
||||
var specialRound = getSpecialRound();
|
||||
|
||||
TryStartSpecialRound(specialRound);
|
||||
}
|
||||
|
||||
private AbstractSpecialRound getSpecialRound() {
|
||||
return Provider.GetServices<ITerrorModule>()
|
||||
.OfType<AbstractSpecialRound>()
|
||||
.OrderBy(_ => Random.Shared.Next())
|
||||
.First();
|
||||
}
|
||||
|
||||
public AbstractSpecialRound?
|
||||
TryStartSpecialRound(AbstractSpecialRound? round) {
|
||||
round ??= getSpecialRound();
|
||||
Messenger.MessageAll(Locale[RoundMsgs.SPECIAL_ROUND_STARTED(round)]);
|
||||
Messenger.MessageAll(Locale[round.Description]);
|
||||
|
||||
round?.ApplyRoundEffects();
|
||||
tracker.CurrentRound = round;
|
||||
tracker.RoundsSinceLastSpecial = 0;
|
||||
return round;
|
||||
}
|
||||
}
|
||||
11
TTT/SpecialRound/SpecialRoundTracker.cs
Normal file
11
TTT/SpecialRound/SpecialRoundTracker.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using SpecialRoundAPI;
|
||||
using TTT.API;
|
||||
|
||||
namespace SpecialRound;
|
||||
|
||||
public class SpecialRoundTracker : ISpecialRoundTracker, ITerrorModule {
|
||||
public AbstractSpecialRound? CurrentRound { get; set; }
|
||||
public int RoundsSinceLastSpecial { get; set; }
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
}
|
||||
8
TTT/SpecialRound/SpecialRoundsConfig.cs
Normal file
8
TTT/SpecialRound/SpecialRoundsConfig.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace SpecialRound;
|
||||
|
||||
public record SpecialRoundsConfig {
|
||||
public int MinRoundsBetweenSpecial { get; init; } = 3;
|
||||
public int MinPlayersForSpecial { get; init; } = 8;
|
||||
public int MinRoundsAfterMapChange { get; init; } = 2;
|
||||
public float SpecialRoundChance { get; init; } = 0.2f;
|
||||
}
|
||||
18
TTT/SpecialRound/lang/RoundMsgs.cs
Normal file
18
TTT/SpecialRound/lang/RoundMsgs.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using SpecialRoundAPI;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace SpecialRound.lang;
|
||||
|
||||
public class RoundMsgs {
|
||||
public static IMsg SPECIAL_ROUND_STARTED(AbstractSpecialRound round) {
|
||||
return MsgFactory.Create(nameof(SPECIAL_ROUND_STARTED), round.Name);
|
||||
}
|
||||
|
||||
public static IMsg SPECIAL_ROUND_SPEED
|
||||
=> MsgFactory.Create(nameof(SPECIAL_ROUND_SPEED));
|
||||
|
||||
public static IMsg SPECIAL_ROUND_BHOP
|
||||
=> MsgFactory.Create(nameof(SPECIAL_ROUND_BHOP));
|
||||
|
||||
public static IMsg SPECIAL_ROUND_VANILLA
|
||||
=> MsgFactory.Create(nameof(SPECIAL_ROUND_VANILLA)); }
|
||||
4
TTT/SpecialRound/lang/en.yml
Normal file
4
TTT/SpecialRound/lang/en.yml
Normal file
@@ -0,0 +1,4 @@
|
||||
SPECIAL_ROUND_STARTED: "%PREFIX%This round is a {purple}Special Round{grey}! This round is a {lightpurple}{0}{grey} round!"
|
||||
SPECIAL_ROUND_SPEED: " {yellow}SPEED{grey}: The round is faster than usual! {red}Traitors{grey} must kill to gain more time."
|
||||
SPECIAL_ROUND_BHOP: " {Yellow}BHOP{grey}: Bunny hopping is enabled! Hold jump to move faster!"
|
||||
SPECIAL_ROUND_VANILLA: " {green}VANILLA{grey}: The shop has been disabled!"
|
||||
5
TTT/Stats/IRoundTracker.cs
Normal file
5
TTT/Stats/IRoundTracker.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
namespace Stats;
|
||||
|
||||
public interface IRoundTracker {
|
||||
public int? CurrentRoundId { get; set; }
|
||||
}
|
||||
40
TTT/Stats/KillListener.cs
Normal file
40
TTT/Stats/KillListener.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Game;
|
||||
using TTT.Game.Events.Player;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class KillListener(IServiceProvider provider) : IListener {
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
private readonly IGameManager game =
|
||||
provider.GetRequiredService<IGameManager>();
|
||||
|
||||
private readonly IRoundTracker? roundTracker =
|
||||
provider.GetService<IRoundTracker>();
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnPlayerKill(PlayerDeathEvent ev) {
|
||||
if (game.ActiveGame is not { State: State.IN_PROGRESS }) return;
|
||||
if (ev.Killer == null) return;
|
||||
|
||||
var data = new {
|
||||
killer_steam_id = ev.Killer.Id,
|
||||
victim_steam_id = ev.Victim.Id,
|
||||
round_id = roundTracker?.CurrentRoundId,
|
||||
weapon = ev.Weapon
|
||||
};
|
||||
|
||||
var payload = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
Task.Run(async () => await client.PostAsync("kill", payload));
|
||||
}
|
||||
}
|
||||
50
TTT/Stats/LogsUploader.cs
Normal file
50
TTT/Stats/LogsUploader.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Stats.lang;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Game;
|
||||
using TTT.API.Messages;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class LogsUploader(IServiceProvider provider) : IListener {
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
private readonly IRoundTracker roundTracker =
|
||||
provider.GetRequiredService<IRoundTracker>();
|
||||
|
||||
private readonly IMsgLocalizer localizer =
|
||||
provider.GetRequiredService<IMsgLocalizer>();
|
||||
|
||||
private readonly IMessenger messenger =
|
||||
provider.GetRequiredService<IMessenger>();
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(Priority = Priority.MONITOR)]
|
||||
public void OnGameEnd(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState != State.FINISHED) return;
|
||||
|
||||
var logs = string.Join('\n', ev.Game.Logger.MakeLogs());
|
||||
|
||||
var data = new { logs };
|
||||
|
||||
var payload = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
Task.Run(async () => {
|
||||
var id = roundTracker.CurrentRoundId;
|
||||
if (id == null) return;
|
||||
var result = await client.PatchAsync("round/" + id.Value, payload);
|
||||
|
||||
if (!result.IsSuccessStatusCode) return;
|
||||
|
||||
await messenger.MessageAll(localizer[StatsMsgs.API_ROUND_END(id.Value)]);
|
||||
});
|
||||
}
|
||||
}
|
||||
39
TTT/Stats/PlayerCreationListener.cs
Normal file
39
TTT/Stats/PlayerCreationListener.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using CounterStrikeSharp.API;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Player;
|
||||
using TTT.Game.Events.Player;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class PlayerCreationListener(IServiceProvider provider) : IListener {
|
||||
public void Dispose() {
|
||||
provider.GetRequiredService<IEventBus>().UnregisterListener(this);
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnJoin(PlayerJoinEvent ev) {
|
||||
Task.Run(async () => await putPlayer(ev.Player));
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnLeave(PlayerLeaveEvent ev) {
|
||||
Task.Run(async () => await putPlayer(ev.Player));
|
||||
}
|
||||
|
||||
private async Task putPlayer(IPlayer player) {
|
||||
var client = provider.GetRequiredService<HttpClient>();
|
||||
var userJson = new { name = player.Name };
|
||||
|
||||
var content = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(userJson),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
var response = await client.PutAsync("user/" + player.Id, content);
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
}
|
||||
32
TTT/Stats/PurchaseListener.cs
Normal file
32
TTT/Stats/PurchaseListener.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ShopAPI.Events;
|
||||
using TTT.API.Events;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class PurchaseListener(IServiceProvider provider) : IListener {
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
private readonly IRoundTracker? roundTracker =
|
||||
provider.GetService<IRoundTracker>();
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnPurchase(PlayerPurchaseItemEvent ev) {
|
||||
var body = new {
|
||||
steam_id = ev.Player.Id,
|
||||
item_id = ev.Item.Id,
|
||||
round_id = roundTracker?.CurrentRoundId
|
||||
};
|
||||
|
||||
var payload = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(body),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
Task.Run(async () => await client.PostAsync("purchase", payload));
|
||||
}
|
||||
}
|
||||
196
TTT/Stats/RoundListener.cs
Normal file
196
TTT/Stats/RoundListener.cs
Normal file
@@ -0,0 +1,196 @@
|
||||
using System.Net;
|
||||
using CounterStrikeSharp.API;
|
||||
using CounterStrikeSharp.API.Core.Attributes;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Stats.lang;
|
||||
using TTT.API.Events;
|
||||
using TTT.API.Game;
|
||||
using TTT.API.Messages;
|
||||
using TTT.API.Player;
|
||||
using TTT.API.Role;
|
||||
using TTT.Game.Events.Body;
|
||||
using TTT.Game.Events.Game;
|
||||
using TTT.Game.Events.Player;
|
||||
using TTT.Game.Roles;
|
||||
using TTT.Locale;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class RoundListener(IServiceProvider provider)
|
||||
: IListener, IRoundTracker {
|
||||
public void Dispose() {
|
||||
provider.GetRequiredService<IEventBus>().UnregisterListener(this);
|
||||
}
|
||||
|
||||
private readonly IRoleAssigner roles =
|
||||
provider.GetRequiredService<IRoleAssigner>();
|
||||
|
||||
private readonly IMessenger messenger =
|
||||
provider.GetRequiredService<IMessenger>();
|
||||
|
||||
private readonly IMsgLocalizer localizer =
|
||||
provider.GetRequiredService<IMsgLocalizer>();
|
||||
|
||||
private Dictionary<string, (int, int, int)> kills = new();
|
||||
private Dictionary<string, int> bodiesFound = new();
|
||||
private HashSet<string> deaths = new();
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(Priority = Priority.MONITOR, IgnoreCanceled = true)]
|
||||
public void OnGameState(GameStateUpdateEvent ev) {
|
||||
if (ev.NewState == State.IN_PROGRESS) {
|
||||
kills.Clear();
|
||||
bodiesFound.Clear();
|
||||
Task.Run(async () => await onRoundStart(ev.Game));
|
||||
}
|
||||
|
||||
var game = ev.Game;
|
||||
if (ev.NewState == State.FINISHED)
|
||||
Task.Run(async () => await onRoundEnd(game));
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler]
|
||||
public void OnDeath(PlayerDeathEvent ev) {
|
||||
var killer = ev.Killer;
|
||||
var victim = ev.Victim;
|
||||
|
||||
deaths.Add(victim.Id);
|
||||
|
||||
if (killer == null) return;
|
||||
|
||||
if (!kills.ContainsKey(killer.Id)) kills[killer.Id] = (0, 0, 0);
|
||||
|
||||
var (innoKills, traitorKills, detectiveKills) = kills[killer.Id];
|
||||
var victimRoles = roles.GetRoles(victim);
|
||||
|
||||
if (victimRoles.Any(r => r is InnocentRole))
|
||||
innoKills += 1;
|
||||
else if (victimRoles.Any(r => r is TraitorRole))
|
||||
traitorKills += 1;
|
||||
else if (victimRoles.Any(r => r is DetectiveRole)) detectiveKills += 1;
|
||||
|
||||
kills[killer.Id] = (innoKills, traitorKills, detectiveKills);
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
[EventHandler(Priority = Priority.MONITOR, IgnoreCanceled = true)]
|
||||
public void OnIdentify(BodyIdentifyEvent ev) {
|
||||
if (ev.Identifier == null) return;
|
||||
var identifies = bodiesFound.GetValueOrDefault(ev.Identifier.Id, 0);
|
||||
bodiesFound[ev.Identifier.Id] = identifies + 1;
|
||||
}
|
||||
|
||||
private async Task onRoundStart(IGame game) {
|
||||
Console.WriteLine("RoundListener: onRoundStart fired");
|
||||
await Server.NextWorldUpdateAsync(() => {
|
||||
var map_name = Server.MapName;
|
||||
var startedAt = DateTime.UtcNow;
|
||||
Task.Run(async () => await createNewRound(game, map_name, startedAt));
|
||||
});
|
||||
}
|
||||
|
||||
private async Task createNewRound(IGame game, string map_name,
|
||||
DateTime startedAt) {
|
||||
var data = new {
|
||||
map_name, startedAt, participants = getParticipants(game)
|
||||
};
|
||||
|
||||
var content = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
var client = provider.GetRequiredService<HttpClient>();
|
||||
var response = await provider.GetRequiredService<HttpClient>()
|
||||
.PostAsync("round", content);
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var jsonDoc = System.Text.Json.JsonDocument.Parse(json);
|
||||
CurrentRoundId = jsonDoc.RootElement.GetProperty("round_id").GetInt32();
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Created) {
|
||||
await notifyNewRound(CurrentRoundId.Value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Conflict)
|
||||
await client.DeleteAsync("round/" + CurrentRoundId);
|
||||
|
||||
// Retry
|
||||
response = await client.PostAsync("round", content);
|
||||
|
||||
jsonDoc = System.Text.Json.JsonDocument.Parse(
|
||||
await response.Content.ReadAsStringAsync());
|
||||
CurrentRoundId = jsonDoc.RootElement.GetProperty("round_id").GetInt32();
|
||||
if (response.StatusCode == HttpStatusCode.Created) {
|
||||
await notifyNewRound(CurrentRoundId.Value);
|
||||
}
|
||||
}
|
||||
|
||||
private Task notifyNewRound(int id) {
|
||||
return messenger.MessageAll(localizer[StatsMsgs.API_ROUND_START(id)]);
|
||||
}
|
||||
|
||||
private async Task onRoundEnd(IGame game) {
|
||||
Console.WriteLine("RoundListener: onRoundEnd fired");
|
||||
if (CurrentRoundId == null) {
|
||||
Console.WriteLine("RoundListener: currentRoundId is null, skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
var ended_at = DateTime.UtcNow;
|
||||
var winning_role = game.WinningRole != null ?
|
||||
StatsApi.ApiNameForRole(game.WinningRole) :
|
||||
null;
|
||||
var participants = getParticipants(game);
|
||||
await Task.Run(async () => {
|
||||
var data = new { ended_at, winning_role, participants };
|
||||
|
||||
var content = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
var client = provider.GetRequiredService<HttpClient>();
|
||||
|
||||
await client.PatchAsync("round/" + CurrentRoundId, content);
|
||||
});
|
||||
}
|
||||
|
||||
private record Participant {
|
||||
public required string steam_id { get; init; }
|
||||
public required string role { get; init; }
|
||||
public int? inno_kills { get; init; }
|
||||
public int? traitor_kills { get; init; }
|
||||
public int? detective_kills { get; init; }
|
||||
public int? bodies_found { get; init; }
|
||||
public bool? died { get; init; }
|
||||
}
|
||||
|
||||
private List<Participant> getParticipants(IGame game) {
|
||||
var list = new List<Participant>();
|
||||
|
||||
foreach (var player in game.Players) {
|
||||
var playerRoles = roles.GetRoles(player);
|
||||
if (playerRoles.Count == 0) continue;
|
||||
|
||||
var role = StatsApi.ApiNameForRole(playerRoles.First());
|
||||
kills.TryGetValue(player.Id, out var killCounts);
|
||||
bodiesFound.TryGetValue(player.Id, out var foundCount);
|
||||
|
||||
list.Add(new Participant {
|
||||
steam_id = player.Id,
|
||||
role = role,
|
||||
inno_kills = killCounts.Item1,
|
||||
traitor_kills = killCounts.Item2,
|
||||
detective_kills = killCounts.Item3,
|
||||
bodies_found = foundCount,
|
||||
died = deaths.Contains(player.Id)
|
||||
});
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public int? CurrentRoundId { get; set; }
|
||||
}
|
||||
53
TTT/Stats/ShopRegistrar.cs
Normal file
53
TTT/Stats/ShopRegistrar.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System.Numerics;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ShopAPI;
|
||||
using TTT.API;
|
||||
using TTT.Game.Roles;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class ShopRegistrar(IServiceProvider provider) : ITerrorModule {
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
private readonly IShop shop = provider.GetRequiredService<IShop>();
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
public void Start() {
|
||||
Task.Run(async () => {
|
||||
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||
List<Task> tasks = [];
|
||||
|
||||
foreach (var item in shop.Items) {
|
||||
var data = new {
|
||||
item_name = item.Name, cost = item.Config.Price, team_restriction = ""
|
||||
};
|
||||
|
||||
data = item switch {
|
||||
RoleRestrictedItem<TraitorRole> => data with {
|
||||
team_restriction = "traitor"
|
||||
},
|
||||
RoleRestrictedItem<DetectiveRole> => data with {
|
||||
team_restriction = "detective"
|
||||
},
|
||||
RoleRestrictedItem<InnocentRole> => data with {
|
||||
team_restriction = "innocent"
|
||||
},
|
||||
_ => data
|
||||
};
|
||||
|
||||
var payload = new StringContent(
|
||||
System.Text.Json.JsonSerializer.Serialize(data),
|
||||
System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
Console.WriteLine(
|
||||
$"[Stats] Registering shop item '{item.Name}' at '{client.BaseAddress}item/{item.Id}'");
|
||||
|
||||
tasks.Add(client.PutAsync("item/" + item.Id, payload));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
});
|
||||
}
|
||||
}
|
||||
14
TTT/Stats/Stats.csproj
Normal file
14
TTT/Stats/Stats.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Game\Game.csproj" />
|
||||
<ProjectReference Include="..\ShopAPI\ShopAPI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
18
TTT/Stats/StatsApi.cs
Normal file
18
TTT/Stats/StatsApi.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using TTT.API.Role;
|
||||
using TTT.Game.Roles;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class StatsApi {
|
||||
public static string? API_URL
|
||||
=> Environment.GetEnvironmentVariable("TTT_STATS_API_URL");
|
||||
|
||||
public static string ApiNameForRole(IRole role) {
|
||||
return role switch {
|
||||
_ when role is TraitorRole => "traitor",
|
||||
_ when role is DetectiveRole => "detective",
|
||||
_ when role is InnocentRole => "innocent",
|
||||
_ => "unknown"
|
||||
};
|
||||
}
|
||||
}
|
||||
84
TTT/Stats/StatsCommand.cs
Normal file
84
TTT/Stats/StatsCommand.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
using System.Net.Http.Json;
|
||||
using CounterStrikeSharp.API.Modules.Utils;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API.Command;
|
||||
using TTT.API.Player;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public class StatsCommand(IServiceProvider provider) : ICommand {
|
||||
private readonly HttpClient client =
|
||||
provider.GetRequiredService<HttpClient>();
|
||||
|
||||
public void Dispose() { }
|
||||
public void Start() { }
|
||||
|
||||
public string Id => "stats";
|
||||
|
||||
public async Task<CommandResult> Execute(IOnlinePlayer? executor,
|
||||
ICommandInfo info) {
|
||||
if (executor == null) return CommandResult.PLAYER_ONLY;
|
||||
|
||||
var response = await client.GetAsync("user/summary/" + executor.Id);
|
||||
|
||||
if (!response.IsSuccessStatusCode) return CommandResult.ERROR;
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
var statsInfo =
|
||||
System.Text.Json.JsonSerializer.Deserialize<StatsResponse>(body);
|
||||
|
||||
if (statsInfo == null) return CommandResult.ERROR;
|
||||
|
||||
info.ReplySync(
|
||||
$" {ChatColors.Grey}Stats for {ChatColors.Default}{statsInfo.name}");
|
||||
info.ReplySync(
|
||||
$" {ChatColors.DarkRed}K{ChatColors.Red}D{ChatColors.LightRed}R{ChatColors.Grey}: {ChatColors.Yellow}{statsInfo.kdr:F2}");
|
||||
info.ReplySync($" {ChatColors.Blue}Good Kills: {ChatColors.LightYellow}"
|
||||
+ statsInfo.good_kills);
|
||||
info.ReplySync(
|
||||
$" {ChatColors.Red}Bad Kills: {ChatColors.LightYellow}{statsInfo.bad_kills}");
|
||||
if (statsInfo.rounds_played != null)
|
||||
printRoleDictionary(info, $" {ChatColors.Default}Rounds Played",
|
||||
statsInfo.rounds_played);
|
||||
if (statsInfo.rounds_won != null)
|
||||
printRoleDictionary(info, $" {ChatColors.Green}Rounds Won",
|
||||
statsInfo.rounds_won);
|
||||
if (statsInfo.kills_as != null)
|
||||
printRoleDictionary(info, $" {ChatColors.Red}Kills As",
|
||||
statsInfo.kills_as);
|
||||
if (statsInfo.deaths_as != null)
|
||||
printRoleDictionary(info, $" {ChatColors.Grey}Deaths As",
|
||||
statsInfo.deaths_as);
|
||||
info.ReplySync(
|
||||
$" {ChatColors.Silver}Bodies Found: {ChatColors.LightYellow}{statsInfo.bodies_found}");
|
||||
|
||||
return CommandResult.SUCCESS;
|
||||
}
|
||||
|
||||
private void
|
||||
printRoleDictionary(ICommandInfo info, string title,
|
||||
Dictionary<string, int> dict) {
|
||||
info.ReplySync(title
|
||||
+ $"{ChatColors.Grey}: {ChatColors.Lime}Innocent {ChatColors.Default}- "
|
||||
+ ChatColors.Yellow + dict.GetValueOrDefault("innocent", 0)
|
||||
+ $"{ChatColors.Default}, {ChatColors.Red}Traitor {ChatColors.Default}- "
|
||||
+ ChatColors.Yellow + dict.GetValueOrDefault("traitor", 0)
|
||||
+ $"{ChatColors.Grey}, {ChatColors.LightBlue}Detective {ChatColors.Default}- "
|
||||
+ ChatColors.Yellow + dict.GetValueOrDefault("detective", 0));
|
||||
}
|
||||
|
||||
record StatsResponse {
|
||||
public required string steam_id { get; init; }
|
||||
public required string name { get; init; }
|
||||
public float kdr { get; init; }
|
||||
public int good_kills { get; init; }
|
||||
public int bad_kills { get; init; }
|
||||
public int bodies_found { get; init; }
|
||||
|
||||
public Dictionary<string, int>? rounds_played { get; init; }
|
||||
public Dictionary<string, int>? kills_as { get; init; }
|
||||
public Dictionary<string, int>? deaths_as { get; init; }
|
||||
public Dictionary<string, int>? rounds_won { get; init; }
|
||||
}
|
||||
}
|
||||
22
TTT/Stats/StatsServiceCollection.cs
Normal file
22
TTT/Stats/StatsServiceCollection.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TTT.API.Extensions;
|
||||
|
||||
namespace Stats;
|
||||
|
||||
public static class StatsServiceCollection {
|
||||
public static void AddStatsServices(this IServiceCollection collection) {
|
||||
var client = new HttpClient();
|
||||
client.BaseAddress = new Uri(StatsApi.API_URL!);
|
||||
|
||||
collection.AddSingleton<HttpClient>(_ => client);
|
||||
collection.AddModBehavior<PlayerCreationListener>();
|
||||
collection.AddModBehavior<IRoundTracker, RoundListener>();
|
||||
collection.AddModBehavior<ShopRegistrar>();
|
||||
collection.AddModBehavior<PurchaseListener>();
|
||||
collection.AddModBehavior<LogsUploader>();
|
||||
collection.AddModBehavior<KillListener>();
|
||||
collection.AddModBehavior<StatsCommand>();
|
||||
|
||||
Console.WriteLine($"[Stats] Stats services registered with API URL: {client.BaseAddress.ToString()}");
|
||||
}
|
||||
}
|
||||
11
TTT/Stats/lang/StatsMsgs.cs
Normal file
11
TTT/Stats/lang/StatsMsgs.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using TTT.Locale;
|
||||
|
||||
namespace Stats.lang;
|
||||
|
||||
public class StatsMsgs {
|
||||
public static IMsg API_ROUND_START(int roundId)
|
||||
=> MsgFactory.Create(nameof(API_ROUND_START), roundId);
|
||||
|
||||
public static IMsg API_ROUND_END(int roundId)
|
||||
=> MsgFactory.Create(nameof(API_ROUND_END), roundId);
|
||||
}
|
||||
2
TTT/Stats/lang/en.yml
Normal file
2
TTT/Stats/lang/en.yml
Normal file
@@ -0,0 +1,2 @@
|
||||
API_ROUND_START: "%PREFIX% Round {yellow}#{0} {grey}has started!"
|
||||
API_ROUND_END: "%PREFIX% Round end! Logs are available at {blue}http://ttt.localhost/round/{0}{grey}."
|
||||
@@ -91,7 +91,7 @@ public class KarmaListenerTests {
|
||||
bus.Dispatch(deathEvent);
|
||||
game.EndGame();
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(20),
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(50),
|
||||
TestContext.Current
|
||||
.CancellationToken); // Wait for the karma update to process
|
||||
|
||||
|
||||
@@ -42,29 +42,4 @@ public class BalanceClearTest(IServiceProvider provider) {
|
||||
|
||||
Assert.Equal(0, newBalance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RoleAssignCreditor_ShouldNotBeOverriden_OnGameStart() {
|
||||
bus.RegisterListener(new RoleAssignCreditor(provider));
|
||||
bus.RegisterListener(new RoundShopClearer(provider));
|
||||
var player = TestPlayer.Random();
|
||||
finder.AddPlayer(player);
|
||||
finder.AddPlayer(TestPlayer.Random());
|
||||
|
||||
var karmaService = provider.GetService<IKarmaService>();
|
||||
if (karmaService != null) await karmaService.Write(player, 80);
|
||||
|
||||
var game = games.CreateGame();
|
||||
game?.Start();
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(50),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
var newBalance = await shop.Load(player);
|
||||
|
||||
var expected = 100;
|
||||
if (roles.GetRoles(player).Any(r => r is TraitorRole)) expected = 120;
|
||||
|
||||
Assert.Equal(expected, newBalance);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user