Compare commits

...

9 Commits

Author SHA1 Message Date
MSWS
7ca4a6bef4 Update README 2025-10-30 21:46:49 -07:00
MSWS
d589a222c8 Format and Cleanup, make Ts sound like they're being damaged by hurtstation 2025-10-30 21:44:00 -07:00
MSWS
a3fdb590fd fix: Fake traitors getting damaged by hurt stations 2025-10-30 21:00:55 -07:00
MSWS
987df197bc Fix concurrent dictionary issue 2025-10-30 18:14:27 -07:00
MSWS
acb3be9132 Require on actual team to be alive 2025-10-30 18:09:14 -07:00
MSWS
bbcc998559 Up 1 knife item 2025-10-30 17:57:00 -07:00
MSWS
56781c6ae8 More item balancing, name updating, bug fix 2025-10-30 17:56:09 -07:00
MSWS
0ca983943d Revert "Fetch playername from object if available"
This reverts commit 8cd8e14e18.
2025-10-29 16:28:56 -07:00
MSWS
8cd8e14e18 Fetch playername from object if available 2025-10-29 15:27:13 -07:00
107 changed files with 477 additions and 503 deletions

View File

@@ -16,7 +16,9 @@ survive while eliminating the traitors among them.
- [X] Innocents
- [X] Shop
- [X] Karma
- [ ] Statistics
- [X] Statistics
- [X] Map Integrations
- [X] Special Rounds
## Versioning

View File

@@ -14,13 +14,13 @@ public abstract class AbstractSpecialRound(IServiceProvider 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 void Dispose() { }
public void Start() { }
public abstract void ApplyRoundEffects();
[UsedImplicitly]

View File

@@ -2,9 +2,9 @@
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.
/// 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>

View File

@@ -7,9 +7,9 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Locale\Locale.csproj" />
<ProjectReference Include="..\..\TTT\API\API.csproj" />
<ProjectReference Include="..\..\TTT\Game\Game.csproj" />
<ProjectReference Include="..\..\Locale\Locale.csproj"/>
<ProjectReference Include="..\..\TTT\API\API.csproj"/>
<ProjectReference Include="..\..\TTT\Game\Game.csproj"/>
</ItemGroup>
</Project>

View File

@@ -18,6 +18,6 @@ public interface IActionLogger {
void PrintLogs();
void PrintLogs(IOnlinePlayer? player);
string[] MakeLogs();
}

View File

@@ -1,3 +1,3 @@
namespace TTT.API.Player;
public interface IMuted : ISet<string> { }

View File

@@ -7,7 +7,7 @@ public interface IPlayer : IEquatable<IPlayer> {
/// </summary>
string Id { get; }
string Name { get; }
string Name { get; set; }
bool IEquatable<IPlayer>.Equals(IPlayer? other) {
if (other is null) return false;

View File

@@ -9,7 +9,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj" />
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj"/>
<ProjectReference Include="..\API\API.csproj"/>
<ProjectReference Include="..\Game\Game.csproj"/>
<ProjectReference Include="..\Karma\Karma.csproj"/>

View File

@@ -1,4 +1,3 @@
using System.Runtime.CompilerServices;
using CounterStrikeSharp.API.Core;
using Microsoft.Extensions.DependencyInjection;
using ShopAPI.Configs;
@@ -82,6 +81,7 @@ public static class CS2ServiceCollection {
collection.AddModBehavior<TraitorChatHandler>();
collection.AddModBehavior<PlayerMuter>();
collection.AddModBehavior<MapChangeCausesEndListener>();
collection.AddModBehavior<NameUpdater>();
// collection.AddModBehavior<EntityTargetHandlers>();
// Damage Cancelers

View File

@@ -6,7 +6,6 @@ using TTT.API;
using TTT.API.Command;
using TTT.API.Messages;
using TTT.API.Player;
using TTT.Game;
using TTT.Game.Commands;
using TTT.Game.lang;

View File

@@ -9,17 +9,12 @@ namespace TTT.CS2.Command.Test;
public class ReloadModuleCommand(IServiceProvider provider)
: ICommand, IPluginModule {
private BasePlugin? plugin;
public void Dispose() { }
public void Start() { }
private BasePlugin? plugin;
public string Id => "reload";
public void Start(BasePlugin? plugin) {
if (plugin == null) return;
this.plugin = plugin;
}
public string[] Usage => ["<module>"];
public Task<CommandResult>
@@ -59,4 +54,9 @@ public class ReloadModuleCommand(IServiceProvider provider)
return Task.FromResult(CommandResult.SUCCESS);
}
public void Start(BasePlugin? plugin) {
if (plugin == null) return;
this.plugin = plugin;
}
}

View File

@@ -1,13 +1,8 @@
using System.Numerics;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Memory;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Command;
using TTT.API.Player;
using TTT.CS2.Extensions;
using TTT.CS2.Utils;
using Vector = CounterStrikeSharp.API.Modules.Utils.Vector;
namespace TTT.CS2.Command.Test;

View File

@@ -22,7 +22,7 @@ public class CS2BodyPaintConfig : IStorage<BodyPaintConfig>, IPluginModule {
public static readonly FakeConVar<string> CV_COLOR = new(
"css_ttt_shop_bodypaint_color",
"Color to apply to the player's body (HTML hex or known color name)",
"GreenYellow", ConVarFlags.FCVAR_NONE);
"GreenYellow");
public void Dispose() { }

View File

@@ -12,7 +12,7 @@ public class CS2ClusterGrenadeConfig : IStorage<ClusterGrenadeConfig>,
IPluginModule {
public static readonly FakeConVar<int> CV_PRICE = new(
"css_ttt_shop_clustergrenade_price",
"Price of the Cluster Grenade item (Traitor)", 90, ConVarFlags.FCVAR_NONE,
"Price of the Cluster Grenade item (Traitor)", 100, ConVarFlags.FCVAR_NONE,
new RangeValidator<int>(0, 10000));
public static readonly FakeConVar<int> CV_GRENADE_COUNT = new(
@@ -22,8 +22,7 @@ public class CS2ClusterGrenadeConfig : IStorage<ClusterGrenadeConfig>,
public static readonly FakeConVar<string> CV_WEAPON_ID = new(
"css_ttt_shop_clustergrenade_weapon",
"Weapon entity ID used for the Cluster Grenade", "weapon_hegrenade",
ConVarFlags.FCVAR_NONE);
"Weapon entity ID used for the Cluster Grenade", "weapon_hegrenade");
public static readonly FakeConVar<float> CV_UP_FORCE = new(
"css_ttt_shop_clustergrenade_up_force",

View File

@@ -17,8 +17,7 @@ public class CS2HealthStationConfig : IStorage<HealthStationConfig>,
public static readonly FakeConVar<string> CV_USE_SOUND = new(
"css_ttt_shop_healthstation_use_sound",
"Sound played when using the Health Station", "sounds/buttons/blip1",
ConVarFlags.FCVAR_NONE);
"Sound played when using the Health Station", "sounds/buttons/blip1");
public static readonly FakeConVar<int> CV_HEALTH_INCREMENTS = new(
"css_ttt_shop_healthstation_increments",

View File

@@ -16,8 +16,7 @@ public class CS2OneHitKnifeConfig : IStorage<OneHitKnifeConfig>, IPluginModule {
public static readonly FakeConVar<bool> CV_FRIENDLY_FIRE = new(
"css_ttt_shop_onehitknife_friendly_fire",
"Whether the One-Hit Knife can damage teammates", false,
ConVarFlags.FCVAR_NONE);
"Whether the One-Hit Knife can damage teammates");
public void Dispose() { }

View File

@@ -12,7 +12,7 @@ namespace TTT.CS2.Configs.ShopItems;
public class CS2OneShotDeagleConfig : IStorage<OneShotDeagleConfig>,
IPluginModule {
public static readonly FakeConVar<int> CV_PRICE = new(
"css_ttt_shop_onedeagle_price", "Price of the One-Shot Deagle item", 125,
"css_ttt_shop_onedeagle_price", "Price of the One-Shot Deagle item", 130,
ConVarFlags.FCVAR_NONE, new RangeValidator<int>(0, 10000));
public static readonly FakeConVar<bool> CV_FRIENDLY_FIRE = new(

View File

@@ -19,7 +19,7 @@ public class CS2SilentAWPConfig : IStorage<SilentAWPConfig>, IPluginModule {
public static readonly FakeConVar<string> CV_WEAPON_ID = new(
"css_ttt_shop_silentawp_weapon", "Weapon entity ID for the Silent AWP",
"weapon_awp", ConVarFlags.FCVAR_NONE);
"weapon_awp");
public static readonly FakeConVar<int> CV_RESERVE_AMMO = new(
"css_ttt_shop_silentawp_reserve_ammo",

View File

@@ -10,7 +10,7 @@ namespace TTT.CS2.Configs.ShopItems;
public class CS2StickersConfig : IStorage<StickersConfig>, IPluginModule {
public static readonly FakeConVar<int> CV_PRICE = new(
"css_ttt_shop_stickers_price", "Price of the Stickers item (Detective)", 25,
"css_ttt_shop_stickers_price", "Price of the Stickers item (Detective)", 35,
ConVarFlags.FCVAR_NONE, new RangeValidator<int>(0, 10000));
public void Dispose() { }

View File

@@ -119,8 +119,11 @@ public static class PlayerExtensions {
SELF(player.Slot), 0.2f, 1);
}
private static RecipientFilter SELF(int slot) => new(slot);
private static RecipientFilter SELF(int slot) {
return new RecipientFilter(slot);
}
private static RecipientFilter OTHERS(int slot)
=> new(ulong.MaxValue & ~(1ul << slot));
private static RecipientFilter OTHERS(int slot) {
return new RecipientFilter(ulong.MaxValue & ~(1ul << slot));
}
}

View File

@@ -1,5 +1,4 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Commands;
using JetBrains.Annotations;
@@ -32,7 +31,7 @@ public class BuyMenuHandler(IServiceProvider provider) : IPluginModule {
{ "weapon_mp5sd", "M4A1" },
{ "weapon_awp", "AWP" },
{ "weapon_hegrenade", "Cluster" },
{ "weapon_decoy", "Teleport Decoy" },
{ "weapon_decoy", "Teleport Decoy" }
};
public void Dispose() { }

View File

@@ -0,0 +1,22 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Events;
using TTT.API.Player;
using TTT.Game.Events.Game;
using TTT.Game.Listeners;
namespace TTT.CS2.GameHandlers;
public class NameUpdater(IServiceProvider provider) : BaseListener(provider) {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
[UsedImplicitly]
[EventHandler]
public void OnGameInit(GameInitEvent ev) {
foreach (var player in Utilities.GetPlayers())
converter.GetPlayer(player).Name = player.PlayerName;
}
}

View File

@@ -18,15 +18,15 @@ public class PlayerMuter(IServiceProvider provider) : IPluginModule {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly IGameManager game =
provider.GetRequiredService<IGameManager>();
private readonly IMsgLocalizer locale =
provider.GetRequiredService<IMsgLocalizer>();
private readonly IMessenger messenger =
provider.GetRequiredService<IMessenger>();
private readonly IGameManager game =
provider.GetRequiredService<IGameManager>();
public void Dispose() { }
public void Start() { }
@@ -66,8 +66,6 @@ public class PlayerMuter(IServiceProvider provider) : IPluginModule {
public void OnGameEvent(GameStateUpdateEvent ev) {
if (ev.NewState != State.FINISHED) return;
foreach (var p in Utilities.GetPlayers()) {
p.VoiceFlags &= ~VoiceFlags.Muted;
}
foreach (var p in Utilities.GetPlayers()) p.VoiceFlags &= ~VoiceFlags.Muted;
}
}

View File

@@ -6,7 +6,6 @@ using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using TTT.API;
using TTT.API.Events;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Role;
using TTT.CS2.Extensions;

View File

@@ -12,18 +12,18 @@ namespace TTT.CS2.GameHandlers;
public class RoundStart_GameStartHandler(IServiceProvider provider)
: IPluginModule {
private TTTConfig config
=> provider.GetService<IStorage<TTTConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
private readonly IGameManager games =
provider.GetRequiredService<IGameManager>();
private TTTConfig config
=> provider.GetService<IStorage<TTTConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
public void Dispose() { }
public void Start() { }

View File

@@ -11,12 +11,14 @@ using TTT.API.Game;
using TTT.API.Player;
using TTT.CS2.API;
using TTT.CS2.Extensions;
using TTT.Game;
using TTT.Game.Events.Player;
namespace TTT.CS2.GameHandlers;
public class TeamChangeHandler(IServiceProvider provider) : IPluginModule {
private readonly IBodyTracker bodies =
provider.GetRequiredService<IBodyTracker>();
private readonly IEventBus bus = provider.GetRequiredService<IEventBus>();
private readonly IPlayerConverter<CCSPlayerController> converter =
@@ -25,9 +27,6 @@ public class TeamChangeHandler(IServiceProvider provider) : IPluginModule {
private readonly IGameManager games =
provider.GetRequiredService<IGameManager>();
private readonly IBodyTracker bodies =
provider.GetRequiredService<IBodyTracker>();
public void Dispose() { }
public void Start() { }

View File

@@ -29,11 +29,11 @@ public class TraitorChatHandler(IServiceProvider provider) : IPluginModule {
private readonly IMessenger messenger =
provider.GetRequiredService<IMessenger>();
private readonly IMuted? mutedPlayers = provider.GetService<IMuted>();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
private readonly IMuted? mutedPlayers = provider.GetService<IMuted>();
private IActain? maulService;
public void Start(BasePlugin? plugin) {

View File

@@ -16,15 +16,15 @@ public static class ArmorItemServicesCollection {
}
public class ArmorItem(IServiceProvider provider) : BaseItem(provider) {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private ArmorConfig config
=> Provider.GetService<IStorage<ArmorConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new ArmorConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
public override string Name => Locale[ArmorMsgs.SHOP_ITEM_ARMOR];
public override string Description => Locale[ArmorMsgs.SHOP_ITEM_ARMOR_DESC];
public override ShopItemConfig Config => config;

View File

@@ -17,16 +17,16 @@ public class BodyPaintListener(IServiceProvider provider)
private readonly IBodyTracker bodies =
provider.GetRequiredService<IBodyTracker>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly Dictionary<IPlayer, int> uses = new();
private BodyPaintConfig config
=> Provider.GetService<IStorage<BodyPaintConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new BodyPaintConfig();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly Dictionary<IPlayer, int> uses = new();
[UsedImplicitly]
[EventHandler(Priority = Priority.HIGH)]
public void BodyIdentify(BodyIdentifyEvent ev) {

View File

@@ -18,15 +18,15 @@ public static class CamoServiceCollection {
}
public class CamouflageItem(IServiceProvider provider) : BaseItem(provider) {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private CamoConfig config
=> Provider.GetService<IStorage<CamoConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new CamoConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
public override string Name => Locale[CamoMsgs.SHOP_ITEM_CAMO];
public override string Description => Locale[CamoMsgs.SHOP_ITEM_CAMO_DESC];
public override ShopItemConfig Config => config;

View File

@@ -1,9 +1,6 @@
using System.Reactive.Concurrency;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using CounterStrikeSharp.API.Modules.Utils;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
@@ -11,23 +8,25 @@ using ShopAPI;
using ShopAPI.Configs.Traitor;
using TTT.API;
using TTT.API.Player;
using TTT.API.Role;
using TTT.API.Storage;
using TTT.CS2.Utils;
namespace TTT.CS2.Items.ClusterGrenade;
public class ClusterGrenadeListener(IServiceProvider provider) : IPluginModule {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private ClusterGrenadeConfig config
=> provider.GetService<IStorage<ClusterGrenadeConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new ClusterGrenadeConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
public void Dispose() { }
public void Start() { }
[UsedImplicitly]
[GameEventHandler]
@@ -60,7 +59,4 @@ public class ClusterGrenadeListener(IServiceProvider provider) : IPluginModule {
return HookResult.Continue;
}
public void Dispose() { }
public void Start() { }
}

View File

@@ -1,5 +1,3 @@
using System.Linq;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
@@ -10,7 +8,6 @@ using ShopAPI.Configs;
using ShopAPI.Configs.Traitor;
using TTT.API;
using TTT.API.Events;
using TTT.API.Extensions;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Role;
@@ -18,17 +15,15 @@ using TTT.API.Storage;
using TTT.CS2.Extensions;
using TTT.CS2.Utils;
using TTT.Game.Events.Game;
using TTT.Game.Roles;
namespace TTT.CS2.Items.Compass;
/// <summary>
/// Base compass that renders a heading toward the nearest target returned by GetTargets.
/// Child classes decide which targets to expose and who owns the item.
/// Base compass that renders a heading toward the nearest target returned by GetTargets.
/// Child classes decide which targets to expose and who owns the item.
/// </summary>
public abstract class AbstractCompassItem<TRole> : RoleRestrictedItem<TRole>,
IListener, IPluginModule where TRole : class, IRole {
protected CompassConfig _Config { get; }
protected readonly IPlayerConverter<CCSPlayerController> Converter;
protected readonly ISet<IPlayer> Owners = new HashSet<IPlayer>();
@@ -42,6 +37,8 @@ public abstract class AbstractCompassItem<TRole> : RoleRestrictedItem<TRole>,
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
}
protected CompassConfig _Config { get; }
public override ShopItemConfig Config => _Config;
public void Start(BasePlugin? plugin) {
@@ -56,14 +53,14 @@ public abstract class AbstractCompassItem<TRole> : RoleRestrictedItem<TRole>,
}
/// <summary>
/// Return world positions to point at for this player.
/// Return world positions to point at for this player.
/// </summary>
protected abstract IList<Vector> GetTargets(IOnlinePlayer requester);
abstract protected IList<Vector> GetTargets(IOnlinePlayer requester);
/// <summary>
/// Whether this player currently owns/has this compass effect.
/// Whether this player currently owns/has this compass effect.
/// </summary>
protected abstract bool OwnsItem(IOnlinePlayer player);
abstract protected bool OwnsItem(IOnlinePlayer player);
public override void OnPurchase(IOnlinePlayer player) { Owners.Add(player); }

View File

@@ -27,11 +27,11 @@ public class BodyCompassItem(IServiceProvider provider)
=> Locale[CompassMsgs.SHOP_ITEM_COMPASS_BODY_DESC];
/// <summary>
/// For innocents: point to nearest traitor.
/// For traitors: point to nearest non-traitor (ally list in original code).
/// Returns target world positions as vectors.
/// For innocents: point to nearest traitor.
/// For traitors: point to nearest non-traitor (ally list in original code).
/// Returns target world positions as vectors.
/// </summary>
protected override IList<Vector> GetTargets(IOnlinePlayer requester) {
override protected IList<Vector> GetTargets(IOnlinePlayer requester) {
if (Games.ActiveGame is not { State: State.IN_PROGRESS or State.FINISHED })
return Array.Empty<Vector>();

View File

@@ -23,11 +23,11 @@ public class InnoCompassItem(IServiceProvider provider)
=> Locale[CompassMsgs.SHOP_ITEM_COMPASS_PLAYER_DESC];
/// <summary>
/// For innocents: point to nearest traitor.
/// For traitors: point to nearest non-traitor (ally list in original code).
/// Returns target world positions as vectors.
/// For innocents: point to nearest traitor.
/// For traitors: point to nearest non-traitor (ally list in original code).
/// Returns target world positions as vectors.
/// </summary>
protected override IList<Vector> GetTargets(IOnlinePlayer requester) {
override protected IList<Vector> GetTargets(IOnlinePlayer requester) {
if (Games.ActiveGame is not { State: State.IN_PROGRESS or State.FINISHED })
return Array.Empty<Vector>();

View File

@@ -28,15 +28,15 @@ public class DnaListener(IServiceProvider provider) : BaseListener(provider) {
private readonly IBodyTracker bodies =
provider.GetRequiredService<IBodyTracker>();
private readonly Dictionary<string, DateTime> lastMessages = new();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private DnaScannerConfig config
=> Provider.GetService<IStorage<DnaScannerConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new DnaScannerConfig();
private readonly Dictionary<string, DateTime> lastMessages = new();
private readonly IShop shop = provider.GetRequiredService<IShop>();
// Low priority to allow body identification to happen first
[UsedImplicitly]
[EventHandler(Priority = Priority.LOW)]

View File

@@ -1,6 +1,5 @@
using TTT.API.Player;
using TTT.API.Role;
using TTT.Game;
using TTT.Game.lang;
using TTT.Locale;

View File

@@ -4,7 +4,6 @@ using ShopAPI;
using ShopAPI.Configs.Traitor;
using TTT.API.Events;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Storage;
using TTT.Game.Events.Player;
using TTT.Game.Listeners;
@@ -13,14 +12,14 @@ namespace TTT.CS2.Items.OneHitKnife;
public class OneHitKnifeListener(IServiceProvider provider)
: BaseListener(provider) {
private readonly IShop shop = provider.GetRequiredService<IShop>();
private OneHitKnifeConfig config
=> Provider.GetService<IStorage<OneHitKnifeConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new OneHitKnifeConfig();
private readonly IShop shop = provider.GetRequiredService<IShop>();
[UsedImplicitly]
[EventHandler]
public void OnDamage(PlayerDamagedEvent ev) {

View File

@@ -24,15 +24,11 @@ public class PoisonShotsListener(IServiceProvider provider)
: BaseListener(provider), IPluginModule {
private readonly IEventBus bus = provider.GetRequiredService<IEventBus>();
private PoisonShotsConfig config
=> Provider.GetService<IStorage<PoisonShotsConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new PoisonShotsConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly Dictionary<string, IPlayer> killedWithPoison = new();
private readonly Dictionary<IPlayer, int> poisonShots = new();
private readonly List<IDisposable> poisonTimers = [];
@@ -42,7 +38,11 @@ public class PoisonShotsListener(IServiceProvider provider)
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly Dictionary<string, IPlayer> killedWithPoison = new();
private PoisonShotsConfig config
=> Provider.GetService<IStorage<PoisonShotsConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new PoisonShotsConfig();
public override void Dispose() {
base.Dispose();
@@ -156,13 +156,6 @@ public class PoisonShotsListener(IServiceProvider provider)
return 0;
}
private class PoisonEffect(IPlayer player, IPlayer shooter) {
public IPlayer Player { get; } = player;
public IPlayer Shooter { get; } = shooter;
public int Ticks { get; set; }
public int DamageGiven { get; set; }
}
[UsedImplicitly]
[EventHandler]
@@ -173,4 +166,11 @@ public class PoisonShotsListener(IServiceProvider provider)
return;
ev.Body.Killer = shooter as IOnlinePlayer;
}
private class PoisonEffect(IPlayer player, IPlayer shooter) {
public IPlayer Player { get; } = player;
public IPlayer Shooter { get; } = shooter;
public int Ticks { get; set; }
public int DamageGiven { get; set; }
}
}

View File

@@ -12,7 +12,6 @@ using TTT.API;
using TTT.API.Events;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Role;
using TTT.API.Storage;
using TTT.CS2.Extensions;
using TTT.Game.Events.Body;
@@ -25,20 +24,20 @@ namespace TTT.CS2.Items.PoisonSmoke;
public class PoisonSmokeListener(IServiceProvider provider)
: BaseListener(provider), IPluginModule {
private PoisonSmokeConfig config
=> Provider.GetService<IStorage<PoisonSmokeConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new PoisonSmokeConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly ISet<string> killedWithPoison = new HashSet<string>();
private readonly List<IDisposable> poisonSmokes = [];
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly ISet<string> killedWithPoison = new HashSet<string>();
private PoisonSmokeConfig config
=> Provider.GetService<IStorage<PoisonSmokeConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new PoisonSmokeConfig();
public override void Dispose() {
base.Dispose();
@@ -129,15 +128,6 @@ public class PoisonSmokeListener(IServiceProvider provider)
return effect.DamageGiven < config.PoisonConfig.TotalDamage;
}
private class PoisonEffect(CSmokeGrenadeProjectile projectile,
IOnlinePlayer attacker) {
public int Ticks { get; set; }
public int DamageGiven { get; set; }
public Vector Origin { get; } = projectile.AbsOrigin.Clone()!;
public CSmokeGrenadeProjectile Projectile { get; } = projectile;
public IPlayer Attacker { get; } = attacker;
}
[UsedImplicitly]
[EventHandler]
public void OnGameEnd(GameStateUpdateEvent ev) {
@@ -153,4 +143,13 @@ public class PoisonSmokeListener(IServiceProvider provider)
if (ev.Body.Killer == null || ev.Body.Killer.Id == ev.Body.OfPlayer.Id)
ev.IsCanceled = true;
}
private class PoisonEffect(CSmokeGrenadeProjectile projectile,
IOnlinePlayer attacker) {
public int Ticks { get; set; }
public int DamageGiven { get; set; }
public Vector Origin { get; } = projectile.AbsOrigin.Clone()!;
public CSmokeGrenadeProjectile Projectile { get; } = projectile;
public IPlayer Attacker { get; } = attacker;
}
}

View File

@@ -24,18 +24,18 @@ public static class SilentAWPServiceCollection {
public class SilentAWPItem(IServiceProvider provider)
: RoleRestrictedItem<TraitorRole>(provider), IPluginModule {
private SilentAWPConfig config
=> Provider.GetService<IStorage<SilentAWPConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new SilentAWPConfig();
private readonly IPlayerConverter<CCSPlayerController> playerConverter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly IDictionary<string, int> silentShots =
new Dictionary<string, int>();
private SilentAWPConfig config
=> Provider.GetService<IStorage<SilentAWPConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new SilentAWPConfig();
public override string Name => Locale[SilentAWPMsgs.SHOP_ITEM_SILENT_AWP];
public override string Description

View File

@@ -1,5 +1,4 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using ShopAPI.Configs.Traitor;
@@ -7,10 +6,8 @@ using TTT.API.Events;
using TTT.API.Extensions;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Role;
using TTT.API.Storage;
using TTT.CS2.Extensions;
using TTT.CS2.Utils;
using TTT.Game.Events.Body;
using TTT.Game.Events.Game;
using TTT.Game.Events.Player;
@@ -38,17 +35,13 @@ public class DamageStation(IServiceProvider provider)
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
private readonly Dictionary<string, StationInfo> killedWithStation = new();
public override string Name => Locale[StationMsgs.SHOP_ITEM_STATION_HURT];
public override string Description
=> Locale[StationMsgs.SHOP_ITEM_STATION_HURT_DESC];
private Dictionary<string, StationInfo> killedWithStation =
new Dictionary<string, StationInfo>();
override protected void onInterval() {
var players = finder.GetOnline();
var toRemove = new List<CPhysicsPropMultiplayer>();
@@ -71,7 +64,6 @@ public class DamageStation(IServiceProvider provider)
.Where(m => m.GamePlayer != null);
var playerDists = playerMapping
.Where(t => !roles.GetRoles(t.ApiPlayer).OfType<TraitorRole>().Any())
.Select(t => (t.ApiPlayer, Origin: t.GamePlayer!.Pawn.Value?.AbsOrigin,
t.GamePlayer))
.Where(t => t is { Origin: not null, ApiPlayer.IsAlive: true })
@@ -81,6 +73,9 @@ public class DamageStation(IServiceProvider provider)
.ToList();
foreach (var (player, dist, gamePlayer) in playerDists) {
gamePlayer.EmitSound("Player.DamageFall", null, 0.2f);
if (Roles.GetRoles(player).Any(r => r is TraitorRole)) continue;
var healthScale = 1.0 - dist / _Config.MaxRange;
var damageAmount =
(int)Math.Floor(_Config.HealthIncrements * healthScale);
@@ -102,8 +97,6 @@ public class DamageStation(IServiceProvider provider)
player.Health += damageAmount;
info.HealthGiven += damageAmount;
gamePlayer.EmitSound("Player.DamageFall", null, 0.2f);
}
}

View File

@@ -10,7 +10,8 @@ using TTT.Game.Roles;
namespace TTT.CS2.Items.Station;
public static class HealthStationCollection {
public static void AddHealthStationServices(this IServiceCollection collection) {
public static void
AddHealthStationServices(this IServiceCollection collection) {
collection.AddModBehavior<HealthStation>();
}
}

View File

@@ -23,7 +23,7 @@ public abstract class StationItem<T>(IServiceProvider provider,
protected readonly IPlayerConverter<CCSPlayerController> Converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly long PROP_SIZE_SQUARED = 500;
private readonly long PROP_SIZE_SQUARED = 700;
protected readonly Dictionary<CPhysicsPropMultiplayer, StationInfo> props =
new();
@@ -105,8 +105,8 @@ public abstract class StationItem<T>(IServiceProvider provider,
"weapon_deagle" => 40,
_ when Tag.PISTOLS.Contains(designerWeapon) => 10,
_ when Tag.SMGS.Contains(designerWeapon) => 15,
_ when Tag.SHOTGUNS.Contains(designerWeapon) => 25,
_ when Tag.RIFLES.Contains(designerWeapon) => 45,
_ when Tag.SHOTGUNS.Contains(designerWeapon) => 15,
_ when Tag.RIFLES.Contains(designerWeapon) => 35,
_ => 5
};
}

View File

@@ -1,5 +1,4 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Utils;
using JetBrains.Annotations;

View File

@@ -1,5 +1,4 @@
using System.Drawing;
using System.Reactive.Concurrency;
using System.Reactive.Concurrency;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
@@ -11,27 +10,25 @@ using TTT.API.Player;
using TTT.API.Storage;
using TTT.CS2.Extensions;
using TTT.CS2.lang;
using TTT.CS2.Utils;
using TTT.Game;
using TTT.Game.Events.Game;
using TTT.Game.Listeners;
using TTT.Game.Roles;
namespace TTT.CS2.Listeners;
public class AfkTimerListener(IServiceProvider provider)
: BaseListener(provider) {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private IDisposable? specTimer, specWarnTimer;
private TTTConfig config
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private IDisposable? specTimer, specWarnTimer;
public override void Dispose() {
base.Dispose();

View File

@@ -8,7 +8,6 @@ using TTT.API.Player;
using TTT.CS2.API;
using TTT.CS2.Events;
using TTT.CS2.Extensions;
using TTT.Game;
using TTT.Game.Events.Body;
using TTT.Game.lang;
using TTT.Game.Listeners;

View File

@@ -15,12 +15,6 @@ using TTT.Karma.lang;
namespace TTT.CS2.Listeners;
public class KarmaBanner(IServiceProvider provider) : BaseListener(provider) {
private KarmaConfig config
=> Provider.GetService<IStorage<KarmaConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new KarmaConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
@@ -31,6 +25,12 @@ public class KarmaBanner(IServiceProvider provider) : BaseListener(provider) {
private readonly Dictionary<IPlayer, DateTime> lastWarned = new();
private KarmaConfig config
=> Provider.GetService<IStorage<KarmaConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new KarmaConfig();
[UsedImplicitly]
[EventHandler(Priority = Priority.MONITOR, IgnoreCanceled = true)]
public void OnKarmaUpdate(KarmaUpdateEvent ev) {

View File

@@ -23,12 +23,6 @@ public class PlayerStatsTracker(IServiceProvider provider) : IListener {
private readonly IDictionary<int, RoundData> roundStats =
new Dictionary<int, RoundData>();
record RoundData {
public int Kills;
public int Assists;
public int Damage;
}
public void Dispose() { }
[UsedImplicitly]
@@ -135,4 +129,10 @@ public class PlayerStatsTracker(IServiceProvider provider) : IListener {
"m_pActionTrackingServices");
}
}
private record RoundData {
public int Assists;
public int Damage;
public int Kills;
}
}

View File

@@ -22,17 +22,17 @@ namespace TTT.CS2.Listeners;
public class RoundTimerListener(IServiceProvider provider)
: BaseListener(provider) {
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
public IDisposable? EndTimer;
private TTTConfig config
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
public IDisposable? EndTimer;
[UsedImplicitly]
[EventHandler(IgnoreCanceled = true)]
public void OnRoundStart(GameStateUpdateEvent ev) {

View File

@@ -9,8 +9,8 @@ namespace TTT.CS2.Player;
public class CS2AliveSpoofer : IAliveSpoofer, IPluginModule {
private readonly HashSet<CCSPlayerController> _fakeAlivePlayers = new();
private BasePlugin? plugin;
public ISet<CCSPlayerController> FakeAlivePlayers => _fakeAlivePlayers;
private BasePlugin? plugin = null;
public void SpoofAlive(CCSPlayerController player) {
if (player.IsBot) {

View File

@@ -1,5 +1,6 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using TTT.API.Player;
namespace TTT.CS2.Player;
@@ -53,7 +54,7 @@ public class CS2Player : IOnlinePlayer, IEquatable<CS2Player> {
}
public string Id { get; }
public string Name { get; }
public string Name { get; set; }
public int Health {
get => Player?.Pawn.Value != null ? Player.Pawn.Value.Health : 0;
@@ -96,7 +97,11 @@ public class CS2Player : IOnlinePlayer, IEquatable<CS2Player> {
}
public bool IsAlive {
get => Player != null && Player.Pawn.Value is { Health: > 0 };
get
=> Player != null && Player is {
Team : CsTeam.CounterTerrorist or CsTeam.Terrorist,
Pawn.Value.Health: > 0
};
set
=> throw new NotSupportedException(

View File

@@ -1,7 +1,4 @@
using System.Net;
using System.Numerics;
using System.Runtime.InteropServices;
using CounterStrikeSharp.API;
using System.Runtime.InteropServices;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Memory;
using Vector = CounterStrikeSharp.API.Modules.Utils.Vector;

View File

@@ -18,13 +18,13 @@ public class GrenadeDataHelper {
heGrenadeSignature);
}
private delegate int CHEGrenadeProjectile_CreateDelegate(IntPtr position,
IntPtr angle, IntPtr velocity, IntPtr velocityAngle, IntPtr thrower,
int weaponId, byte team);
public static int CreateGrenade(Vector position, QAngle angle,
Vector velocity, Vector velocityAngle, IntPtr thrower, CsTeam team) {
return CHEGrenadeProjectile_CreateFunc(position.Handle, angle.Handle,
velocity.Handle, velocityAngle.Handle, thrower, 44, (byte)team);
}
private delegate int CHEGrenadeProjectile_CreateDelegate(IntPtr position,
IntPtr angle, IntPtr velocity, IntPtr velocityAngle, IntPtr thrower,
int weaponId, byte team);
}

View File

@@ -1,6 +1,5 @@
using TTT.API.Player;
using TTT.API.Role;
using TTT.Game;
using TTT.Game.lang;
using TTT.Locale;
@@ -13,6 +12,8 @@ public static class CS2Msgs {
public static IMsg DEAD_MUTE_REMINDER
=> MsgFactory.Create(nameof(DEAD_MUTE_REMINDER));
public static IMsg AFK_MOVED => MsgFactory.Create(nameof(AFK_MOVED));
public static IMsg TASER_SCANNED(IPlayer scannedPlayer, IRole role) {
var rolePrefix = GameMsgs.GetRolePrefix(role);
return MsgFactory.Create(nameof(TASER_SCANNED),
@@ -23,8 +24,6 @@ public static class CS2Msgs {
return MsgFactory.Create(nameof(AFK_WARNING), span.TotalSeconds);
}
public static IMsg AFK_MOVED => MsgFactory.Create(nameof(AFK_MOVED));
public static IMsg TRAITOR_CHAT_FORMAT(IOnlinePlayer player, string msg) {
return MsgFactory.Create(nameof(TRAITOR_CHAT_FORMAT), player.Name, msg);
}

View File

@@ -13,7 +13,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Listeners\Stats\" />
<Folder Include="Listeners\Stats\"/>
</ItemGroup>
</Project>

View File

@@ -11,7 +11,7 @@ namespace TTT.Game.Listeners;
public class GameRestartListener(IServiceProvider provider)
: BaseListener(provider) {
private TTTConfig config =
private readonly TTTConfig config =
provider.GetService<IStorage<TTTConfig>>()?.Load().GetAwaiter().GetResult()
?? new TTTConfig();

View File

@@ -10,12 +10,6 @@ using TTT.Locale;
namespace TTT.Game.Roles;
public abstract class BaseRole(IServiceProvider provider) : IRole {
protected TTTConfig Config
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
protected readonly IInventoryManager Inventory =
provider.GetRequiredService<IInventoryManager>();
@@ -29,6 +23,12 @@ public abstract class BaseRole(IServiceProvider provider) : IRole {
protected readonly IRoleAssigner Roles =
provider.GetRequiredService<IRoleAssigner>();
protected TTTConfig Config
=> Provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
public abstract string Id { get; }
public abstract string Name { get; }
public abstract Color Color { get; }

View File

@@ -8,8 +8,10 @@ using TTT.Game.Events.Player;
namespace TTT.Game.Roles;
public class RoleAssigner(IServiceProvider provider) : IRoleAssigner {
private readonly IDictionary<IPlayer, ICollection<IRole>> assignedRoles =
new Dictionary<IPlayer, ICollection<IRole>>();
private static readonly Random rng = new();
private readonly IDictionary<string, ICollection<IRole>> assignedRoles =
new Dictionary<string, ICollection<IRole>>();
private readonly IEventBus bus = provider.GetRequiredService<IEventBus>();
@@ -18,18 +20,18 @@ public class RoleAssigner(IServiceProvider provider) : IRoleAssigner {
public void AssignRoles(ISet<IOnlinePlayer> players, IList<IRole> roles) {
assignedRoles.Clear();
var shuffled = players.OrderBy(_ => Guid.NewGuid()).ToHashSet();
var shuffled = players.OrderBy(_ => rng.NextDouble()).ToHashSet();
bool roleAssigned;
do { roleAssigned = tryAssignRole(shuffled, roles); } while (roleAssigned);
}
public Task<ICollection<IRole>?> Load(IPlayer key) {
assignedRoles.TryGetValue(key, out var roles);
assignedRoles.TryGetValue(key.Id, out var roles);
return Task.FromResult(roles);
}
public Task Write(IPlayer key, ICollection<IRole> newData) {
assignedRoles[key] = newData;
assignedRoles[key.Id] = newData;
return Task.CompletedTask;
}
@@ -44,9 +46,9 @@ public class RoleAssigner(IServiceProvider provider) : IRoleAssigner {
if (ev.IsCanceled) continue;
if (!assignedRoles.ContainsKey(player))
assignedRoles[player] = new List<IRole>();
assignedRoles[player].Add(ev.Role);
if (!assignedRoles.ContainsKey(player.Id))
assignedRoles[player.Id] = new List<IRole>();
assignedRoles[player.Id].Add(ev.Role);
ev.Role.OnAssign(player);
onlineMessenger?.Debug(

View File

@@ -16,12 +16,6 @@ using TTT.Locale;
namespace TTT.Game;
public class RoundBasedGame(IServiceProvider provider) : IGame {
private TTTConfig config
=> provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
protected readonly IMsgLocalizer Locale =
provider.GetRequiredService<IMsgLocalizer>();
@@ -29,6 +23,12 @@ public class RoundBasedGame(IServiceProvider provider) : IGame {
protected State state = State.WAITING;
private TTTConfig config
=> provider.GetRequiredService<IStorage<TTTConfig>>()
.Load()
.GetAwaiter()
.GetResult() ?? new TTTConfig();
public virtual IList<IRole> Roles { get; } = [
new InnocentRole(provider), new TraitorRole(provider),
new DetectiveRole(provider)

View File

@@ -15,12 +15,6 @@ namespace TTT.Karma;
public class KarmaListener(IServiceProvider provider) : BaseListener(provider) {
private readonly Dictionary<string, int> badKills = new();
private KarmaConfig config
=> Provider.GetService<IStorage<KarmaConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new KarmaConfig();
private readonly IGameManager games =
provider.GetRequiredService<IGameManager>();
@@ -34,6 +28,12 @@ public class KarmaListener(IServiceProvider provider) : BaseListener(provider) {
public bool GiveKarmaOnRoundEnd = true;
private KarmaConfig config
=> Provider.GetService<IStorage<KarmaConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new KarmaConfig();
[EventHandler]
[UsedImplicitly]
public void OnRoundStart(GameStateUpdateEvent ev) { badKills.Clear(); }

View File

@@ -1,9 +1,5 @@
using System.Collections.Concurrent;
using System.Data;
using System.Diagnostics;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Events;
using TTT.API.Player;
@@ -28,7 +24,7 @@ public sealed class KarmaStorage(IServiceProvider provider) : IKarmaService {
if (!result.IsSuccessStatusCode) return config.DefaultKarma;
var content = await result.Content.ReadAsStringAsync();
var json = System.Text.Json.JsonDocument.Parse(content);
var json = JsonDocument.Parse(content);
if (!json.RootElement.TryGetProperty("karma", out var karmaElement))
return config.DefaultKarma;
@@ -42,9 +38,8 @@ public sealed class KarmaStorage(IServiceProvider provider) : IKarmaService {
if (karmaUpdateEvent.IsCanceled) return;
var data = new { steam_id = key.Id, karma = karmaUpdateEvent.Karma };
var payload = new StringContent(
System.Text.Json.JsonSerializer.Serialize(data),
System.Text.Encoding.UTF8, "application/json");
var payload = new StringContent(JsonSerializer.Serialize(data),
Encoding.UTF8, "application/json");
await client.PatchAsync("user/" + key.Id, payload);
}

View File

@@ -64,5 +64,4 @@ public class TTT(IServiceProvider provider) : BasePlugin {
base.Dispose(disposing);
}
}

View File

@@ -1,7 +1,6 @@
using System.Reactive.Concurrency;
using CounterStrikeSharp.API.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SpecialRound;
using Stats;
using TTT.CS2;

View File

@@ -1,13 +1,10 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using JetBrains.Annotations;
using MAULActainShared.plugin.models;
using Microsoft.Extensions.DependencyInjection;
using TTT.API;
using TTT.API.Command;
using TTT.API.Events;
using TTT.API.Game;
using TTT.API.Messages;
using TTT.API.Player;
using TTT.CS2.Command;
@@ -19,18 +16,19 @@ using TTT.RTD.lang;
namespace TTT.RTD;
public class AutoRTDCommand(IServiceProvider provider) : ICommand, IListener {
public string Id => "autortd";
private ICookie? autoRtdCookie;
private readonly ICommandManager commands =
provider.GetRequiredService<ICommandManager>();
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
private readonly ICommandManager commands =
provider.GetRequiredService<ICommandManager>();
private readonly IMsgLocalizer localizer =
provider.GetRequiredService<IMsgLocalizer>();
private readonly Dictionary<string, bool> playerStatuses = new();
private ICookie? autoRtdCookie;
public string Id => "autortd";
public bool MustBeOnMainThread => true;
public void Dispose() { }
@@ -47,7 +45,6 @@ public class AutoRTDCommand(IServiceProvider provider) : ICommand, IListener {
}
public string[] RequiredFlags => ["@ttt/autortd"];
private Dictionary<string, bool> playerStatuses = new();
public async Task<CommandResult> Execute(IOnlinePlayer? executor,
ICommandInfo info) {

View File

@@ -8,11 +8,11 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\API\API.csproj" />
<ProjectReference Include="..\CS2\CS2.csproj" />
<ProjectReference Include="..\Game\Game.csproj" />
<ProjectReference Include="..\ShopAPI\ShopAPI.csproj" />
<ProjectReference Include="..\Shop\Shop.csproj" />
<ProjectReference Include="..\API\API.csproj"/>
<ProjectReference Include="..\CS2\CS2.csproj"/>
<ProjectReference Include="..\Game\Game.csproj"/>
<ProjectReference Include="..\ShopAPI\ShopAPI.csproj"/>
<ProjectReference Include="..\Shop\Shop.csproj"/>
</ItemGroup>
<ItemGroup>

View File

@@ -13,8 +13,6 @@ namespace TTT.RTD;
public class RewardGenerator(IServiceProvider provider)
: IRewardGenerator, IPluginModule {
private readonly List<(IRtdReward, float)> rewards = new();
private const float PROB_LOTTERY = 1 / 5000f;
private const float PROB_EXTREMELY_LOW = 1 / 800f;
private const float PROB_VERY_LOW = 1 / 100f;
@@ -22,28 +20,7 @@ public class RewardGenerator(IServiceProvider provider)
private const float PROB_MEDIUM = 1 / 10f;
private const float PROB_OFTEN = 1 / 5f;
private const float PROB_VERY_OFTEN = 1 / 2f;
public IEnumerator<(IRtdReward, float)> GetEnumerator() {
return rewards.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public int Count => rewards.Count;
public IRtdReward GetReward() {
var totalWeight = 0f;
foreach (var (_, weight) in rewards) { totalWeight += weight; }
var randomValue = Random.Shared.NextSingle() * totalWeight;
var cumulativeWeight = 0f;
foreach (var (reward, weight) in rewards) {
cumulativeWeight += weight;
if (randomValue <= cumulativeWeight) { return reward; }
}
return rewards[^1].Item1;
}
private readonly List<(IRtdReward, float)> rewards = new();
public void Start() {
rewards.AddRange([
@@ -65,7 +42,7 @@ public class RewardGenerator(IServiceProvider provider)
(new ShopItemReward<HealthStation>(provider), PROB_EXTREMELY_LOW),
(new HealthReward(provider, 1), PROB_EXTREMELY_LOW),
(new CreditReward(provider, 100), PROB_EXTREMELY_LOW),
(new HealthReward(provider, 200), PROB_EXTREMELY_LOW),
(new HealthReward(provider, 200), PROB_EXTREMELY_LOW)
]);
rewards.ForEach(r => r.Item1.Start());
@@ -73,10 +50,32 @@ public class RewardGenerator(IServiceProvider provider)
public void Start(BasePlugin? plugin) {
Start();
foreach (var (reward, _) in rewards) {
if (reward is IPluginModule module) { module.Start(plugin); }
}
foreach (var (reward, _) in rewards)
if (reward is IPluginModule module)
module.Start(plugin);
}
public void Dispose() { }
public IEnumerator<(IRtdReward, float)> GetEnumerator() {
return rewards.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public int Count => rewards.Count;
public IRtdReward GetReward() {
var totalWeight = 0f;
foreach (var (_, weight) in rewards) totalWeight += weight;
var randomValue = Random.Shared.NextSingle() * totalWeight;
var cumulativeWeight = 0f;
foreach (var (reward, weight) in rewards) {
cumulativeWeight += weight;
if (randomValue <= cumulativeWeight) return reward;
}
return rewards[^1].Item1;
}
}

View File

@@ -1,21 +1,18 @@
using CounterStrikeSharp.API;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using ShopAPI;
using TTT.API.Player;
using TTT.RTD.lang;
using TTT.Shop;
namespace TTT.RTD.Rewards;
public class CreditReward(IServiceProvider provider, int amo)
: RoundStartReward(provider) {
private readonly IShop shop = provider.GetRequiredService<IShop>();
public override string Name => Locale[RtdMsgs.CREDITS_REWARD(amo)];
public override string Description
=> Locale[RtdMsgs.CREDITS_REWARD_DESC(amo)];
private readonly IShop shop = provider.GetRequiredService<IShop>();
public override void GiveOnRound(IOnlinePlayer player) {
shop.AddBalance(player, amo, "RTD Reward");
}

View File

@@ -3,7 +3,6 @@ using CounterStrikeSharp.API.Core;
using Microsoft.Extensions.DependencyInjection;
using TTT.API;
using TTT.API.Game;
using TTT.API.Messages;
using TTT.API.Player;
using TTT.Game.Events.Game;
using TTT.Locale;
@@ -13,24 +12,23 @@ namespace TTT.RTD.Rewards;
public class MuteReward(IServiceProvider provider)
: RoundStartReward(provider), IPluginModule {
private readonly IMsgLocalizer locale =
provider.GetRequiredService<IMsgLocalizer>();
private readonly IMuted mutedPlayers = provider.GetRequiredService<IMuted>();
public override string Name => "Mute";
public override string Description
=> "you will not be able to communicate next round";
private readonly IMuted mutedPlayers = provider.GetRequiredService<IMuted>();
private readonly IMsgLocalizer locale =
provider.GetRequiredService<IMsgLocalizer>();
public void Start(BasePlugin? plugin) {
plugin?.RegisterListener<Listeners.OnClientVoice>(onVoice);
}
public override void GiveOnRound(IOnlinePlayer player) {
mutedPlayers.Add(player.Id);
}
public void Start(BasePlugin? plugin) {
plugin?.RegisterListener<Listeners.OnClientVoice>(onVoice);
}
private void onVoice(int playerSlot) {
var player = Utilities.GetPlayerFromSlot(playerSlot);
if (player == null) return;

View File

@@ -7,12 +7,12 @@ namespace TTT.RTD.Rewards;
public class ProvenReward(IServiceProvider provider)
: RoundStartReward(provider) {
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
private readonly IIconManager icons =
provider.GetRequiredService<IIconManager>();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
public override string Name => "Proven If Inno";
public override string Description

View File

@@ -1,5 +1,4 @@
using CounterStrikeSharp.API;
using JetBrains.Annotations;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Events;
using TTT.API.Game;
@@ -13,10 +12,13 @@ namespace TTT.RTD;
public abstract class RoundStartReward(IServiceProvider provider)
: IRtdReward, IListener {
private readonly IEventBus bus = provider.GetRequiredService<IEventBus>();
private readonly ISet<IOnlinePlayer> givenPlayers =
new HashSet<IOnlinePlayer>();
private readonly IEventBus bus = provider.GetRequiredService<IEventBus>();
protected readonly IMsgLocalizer Locale =
provider.GetRequiredService<IMsgLocalizer>();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
@@ -25,10 +27,11 @@ public abstract class RoundStartReward(IServiceProvider provider)
public abstract string Description { get; }
public void GrantReward(IOnlinePlayer player) { givenPlayers.Add(player); }
public abstract void GiveOnRound(IOnlinePlayer player);
protected readonly IMsgLocalizer Locale =
provider.GetRequiredService<IMsgLocalizer>();
public void Start() { bus.RegisterListener(this); }
public void Dispose() { bus.UnregisterListener(this); }
public abstract void GiveOnRound(IOnlinePlayer player);
[UsedImplicitly]
[EventHandler(Priority = Priority.LOW)]
@@ -42,8 +45,4 @@ public abstract class RoundStartReward(IServiceProvider provider)
givenPlayers.Clear();
}
public void Start() { bus.RegisterListener(this); }
public void Dispose() { bus.UnregisterListener(this); }
}

View File

@@ -13,10 +13,9 @@ namespace TTT.RTD;
public class RTDCommand(IRewardGenerator generator, IPermissionManager perms,
IMsgLocalizer locale) : ICommand, IPluginModule, IListener {
private readonly Dictionary<string, IRtdReward> playerRewards = new();
private bool inBetweenRounds = true;
private Dictionary<string, IRtdReward> playerRewards = new();
public bool MustBeOnMainThread => true;
public string Id => "rtd";
@@ -34,12 +33,11 @@ public class RTDCommand(IRewardGenerator generator, IPermissionManager perms,
return Task.FromResult(CommandResult.SUCCESS);
}
if (!bypass) {
if (!bypass)
if (!inBetweenRounds && !RoundUtil.IsWarmup() && executor.IsAlive) {
info.ReplySync(locale[RtdMsgs.RTD_CANNOT_ROLL_YET]);
return Task.FromResult(CommandResult.SUCCESS);
}
}
var reward = generator.GetReward();
if (bypass) {
@@ -67,6 +65,9 @@ public class RTDCommand(IRewardGenerator generator, IPermissionManager perms,
return Task.FromResult(CommandResult.SUCCESS);
}
public void Dispose() { }
public void Start() { }
[UsedImplicitly]
[EventHandler]
public void OnGameState(GameStateUpdateEvent ev) {
@@ -80,7 +81,4 @@ public class RTDCommand(IRewardGenerator generator, IPermissionManager perms,
break;
}
}
public void Dispose() { }
public void Start() { }
}

View File

@@ -18,7 +18,7 @@ public class RtdStatsCommand(IRewardGenerator generator) : ICommand {
var index = 0;
foreach (var (reward, prob) in rewards) {
var percent = (prob / total) * 100;
var percent = prob / total * 100;
info.ReplySync(
$" {ChatColors.Orange}{index}. {ChatColors.Default}{reward.Name}{ChatColors.Grey}: {ChatColors.Yellow}{percent:0.00}%");
index++;

View File

@@ -3,27 +3,31 @@
namespace TTT.RTD.lang;
public class RtdMsgs {
public static IMsg RTD_ALREADY_ROLLED(IRtdReward reward)
=> MsgFactory.Create(nameof(RTD_ALREADY_ROLLED), reward.Name);
public static IMsg RTD_CANNOT_ROLL_YET
=> MsgFactory.Create(nameof(RTD_CANNOT_ROLL_YET));
public static IMsg RTD_ROLLED(IRtdReward reward)
=> MsgFactory.Create(nameof(RTD_ROLLED), reward.Name, reward.Description);
public static IMsg RTD_MUTED
=> MsgFactory.Create(nameof(RTD_MUTED));
public static IMsg CREDITS_REWARD(int amo)
=> MsgFactory.Create(nameof(CREDITS_REWARD), amo);
public static IMsg CREDITS_REWARD_DESC(int amo)
=> MsgFactory.Create(nameof(CREDITS_REWARD_DESC), amo);
public static IMsg COMMAND_AUTORTD_ENABLED
public static IMsg RTD_MUTED => MsgFactory.Create(nameof(RTD_MUTED));
public static IMsg COMMAND_AUTORTD_ENABLED
=> MsgFactory.Create(nameof(COMMAND_AUTORTD_ENABLED));
public static IMsg COMMAND_AUTORTD_DISABLED
public static IMsg COMMAND_AUTORTD_DISABLED
=> MsgFactory.Create(nameof(COMMAND_AUTORTD_DISABLED));
public static IMsg RTD_ALREADY_ROLLED(IRtdReward reward) {
return MsgFactory.Create(nameof(RTD_ALREADY_ROLLED), reward.Name);
}
public static IMsg RTD_ROLLED(IRtdReward reward) {
return MsgFactory.Create(nameof(RTD_ROLLED), reward.Name,
reward.Description);
}
public static IMsg CREDITS_REWARD(int amo) {
return MsgFactory.Create(nameof(CREDITS_REWARD), amo);
}
public static IMsg CREDITS_REWARD_DESC(int amo) {
return MsgFactory.Create(nameof(CREDITS_REWARD_DESC), amo);
}
}

View File

@@ -112,7 +112,6 @@ public class ListCommand(IServiceProvider provider) : ICommand, IItemSorter {
}
private string formatItem(IShopItem item, int index, bool canBuy) {
return
$" {formatPrefix(item, index, canBuy)}";
return $" {formatPrefix(item, index, canBuy)}";
}
}

View File

@@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection;
using ShopAPI;
using TTT.API.Command;
using TTT.API.Player;
using TTT.Game;
using TTT.Game.lang;
using TTT.Locale;

View File

@@ -20,6 +20,8 @@ public static class HealthshotServiceCollection {
public class HealthshotItem(IServiceProvider provider)
: BaseItem(provider), IListener {
private readonly Dictionary<string, int> purchaseCounts = new();
private HealthshotConfig config
=> Provider.GetService<IStorage<HealthshotConfig>>()
?.Load()
@@ -33,8 +35,6 @@ public class HealthshotItem(IServiceProvider provider)
public override ShopItemConfig Config => config;
private readonly Dictionary<string, int> purchaseCounts = new();
public override void OnPurchase(IOnlinePlayer player) {
Inventory.GiveWeapon(player, new BaseWeapon(config.Weapon));
@@ -45,9 +45,9 @@ public class HealthshotItem(IServiceProvider provider)
public override PurchaseResult CanPurchase(IOnlinePlayer player) {
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]

View File

@@ -4,7 +4,6 @@ using ShopAPI;
using ShopAPI.Configs;
using TTT.API.Events;
using TTT.API.Game;
using TTT.API.Player;
using TTT.API.Storage;
using TTT.Game.Events.Player;
using TTT.Game.Listeners;
@@ -14,14 +13,14 @@ namespace TTT.Shop.Items;
public class DeagleDamageListener(IServiceProvider provider)
: BaseListener(provider) {
private readonly IShop shop = provider.GetRequiredService<IShop>();
private OneShotDeagleConfig config
=> Provider.GetService<IStorage<OneShotDeagleConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new OneShotDeagleConfig();
private readonly IShop shop = provider.GetRequiredService<IShop>();
[UsedImplicitly]
[EventHandler]
public void OnDamage(PlayerDamagedEvent ev) {

View File

@@ -21,16 +21,17 @@ public static class C4ServiceCollection {
public class C4ShopItem(IServiceProvider provider)
: RoleRestrictedItem<TraitorRole>(provider), IListener {
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
private int c4sBought;
private C4Config config
=> Provider.GetService<IStorage<C4Config>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new C4Config();
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
private int c4sBought;
public override string Name => Locale[C4Msgs.SHOP_ITEM_C4];
public override string Description => Locale[C4Msgs.SHOP_ITEM_C4_DESC];

View File

@@ -14,15 +14,15 @@ namespace TTT.Shop.Items.Traitor.Gloves;
public class GlovesListener(IServiceProvider provider)
: BaseListener(provider) {
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly Dictionary<IPlayer, int> uses = new();
private GlovesConfig config
=> Provider.GetService<IStorage<GlovesConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new GlovesConfig();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly Dictionary<IPlayer, int> uses = new();
[UsedImplicitly]
[EventHandler(Priority = Priority.LOW)]
public void BodyCreate(BodyCreateEvent ev) {

View File

@@ -13,6 +13,11 @@ namespace TTT.Shop.Listeners;
public class RoleAssignCreditor(IServiceProvider provider)
: BaseListener(provider) {
private readonly IKarmaService? karmaService =
provider.GetService<IKarmaService>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private ShopConfig config
=> Provider.GetService<IStorage<ShopConfig>>()
?.Load()
@@ -25,11 +30,6 @@ public class RoleAssignCreditor(IServiceProvider provider)
.GetAwaiter()
.GetResult() ?? new KarmaConfig();
private readonly IKarmaService? karmaService =
provider.GetService<IKarmaService>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
[UsedImplicitly]
[EventHandler]
public void OnRoleAssign(PlayerRoleAssignEvent ev) {

View File

@@ -14,11 +14,8 @@ using TTT.CS2.Extensions;
namespace TTT.Shop;
public class PeriodicRewarder(IServiceProvider provider) : ITerrorModule {
private ShopConfig config
=> provider.GetService<IStorage<ShopConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new ShopConfig(provider);
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private readonly IPlayerFinder finder =
provider.GetRequiredService<IPlayerFinder>();
@@ -26,23 +23,26 @@ public class PeriodicRewarder(IServiceProvider provider) : ITerrorModule {
private readonly IGameManager games =
provider.GetRequiredService<IGameManager>();
private readonly Dictionary<string, List<Vector>> playerPositions = new();
private readonly IScheduler scheduler =
provider.GetRequiredService<IScheduler>();
private readonly IShop shop = provider.GetRequiredService<IShop>();
private readonly IPlayerConverter<CCSPlayerController> converter =
provider.GetRequiredService<IPlayerConverter<CCSPlayerController>>();
private IDisposable? rewardTimer, updateTimer;
private ShopConfig config
=> provider.GetService<IStorage<ShopConfig>>()
?.Load()
.GetAwaiter()
.GetResult() ?? new ShopConfig(provider);
public void Dispose() {
rewardTimer?.Dispose();
updateTimer?.Dispose();
}
private readonly Dictionary<string, List<Vector>> playerPositions = new();
public void Start() {
rewardTimer = scheduler.SchedulePeriodic(config.CreditRewardInterval,
issueRewards);
@@ -105,8 +105,8 @@ public class PeriodicRewarder(IServiceProvider provider) : ITerrorModule {
}
/// <summary>
/// Scales a reward amount between min and max based on position (0-1).
/// 0 = min, 1 = max.
/// Scales a reward amount between min and max based on position (0-1).
/// 0 = min, 1 = max.
/// </summary>
/// <param name="position"></param>
/// <param name="min"></param>

View File

@@ -2,8 +2,8 @@
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve">
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=items_005Coneshotdeagle/@EntryIndexedValue">True</s:Boolean>
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=items_005Coneshotdeagle/@EntryIndexedValue">True</s:Boolean>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=lang/@EntryIndexedValue">True</s:Boolean>
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=lang/@EntryIndexedValue">True</s:Boolean>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=shop/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=shop/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -7,6 +7,11 @@ public record HealthStationConfig : StationConfig {
public override int Price { get; init; } = 50;
public override TimeSpan HealthInterval { get; init; } =
TimeSpan.FromSeconds(2);
public override int HealthIncrements { get; init; } = 10;
public override Color GetColor(float health) {
// 100% health = white
// 10% health = blue
@@ -15,9 +20,4 @@ public record HealthStationConfig : StationConfig {
var b = 255;
return Color.FromArgb(r, g, b);
}
public override TimeSpan HealthInterval { get; init; } =
TimeSpan.FromSeconds(2);
public override int HealthIncrements { get; init; } = 10;
}

View File

@@ -5,9 +5,9 @@ namespace ShopAPI.Configs.Traitor;
public record ClusterGrenadeConfig : ShopItemConfig, IWeapon {
public override int Price { get; init; } = 100;
public int GrenadeCount { get; init; } = 8;
public float UpForce { get; init; } = 200f;
public float ThrowForce { get; init; } = 300f;
public string WeaponId { get; } = "weapon_hegrenade";
public int? ReserveAmmo { get; } = null;
public int? CurrentAmmo { get; } = null;
public float UpForce { get; init; } = 200f;
public float ThrowForce { get; init; } = 300f;
}

View File

@@ -1,6 +1,6 @@
namespace ShopAPI.Configs.Traitor;
public record OneHitKnifeConfig : ShopItemConfig {
public override int Price { get; init; } = 70;
public override int Price { get; init; } = 80;
public bool FriendlyFire { get; init; } = true;
}

View File

@@ -19,15 +19,17 @@ 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>();
private readonly IScheduler scheduler =
provider.GetRequiredService<IScheduler>();
private IDisposable? endTimer;
public override string Name => "Speed";
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_SPEED;
@@ -39,8 +41,6 @@ public class SpeedRound(IServiceProvider provider)
.GetAwaiter()
.GetResult() ?? new SpeedRoundConfig();
private IDisposable? endTimer;
public override void ApplyRoundEffects() {
Provider.GetService<RoundTimerListener>()?.EndTimer?.Dispose();

View File

@@ -13,14 +13,14 @@ namespace SpecialRound.Rounds;
public class VanillaRound(IServiceProvider provider)
: AbstractSpecialRound(provider) {
public override string Name => "Vanilla";
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_VANILLA;
private readonly IMsgLocalizer locale =
provider.GetRequiredService<IMsgLocalizer>();
private readonly IMessenger messenger =
provider.GetRequiredService<IMessenger>();
private readonly IMsgLocalizer locale =
provider.GetRequiredService<IMsgLocalizer>();
public override string Name => "Vanilla";
public override IMsg Description => RoundMsgs.SPECIAL_ROUND_VANILLA;
private VanillaRoundConfig config
=> Provider.GetService<IStorage<VanillaRoundConfig>>()

View File

@@ -7,10 +7,10 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj" />
<ProjectReference Include="..\API\API.csproj" />
<ProjectReference Include="..\CS2\CS2.csproj" />
<ProjectReference Include="..\Game\Game.csproj" />
<ProjectReference Include="..\..\SpecialRoundAPI\SpecialRoundAPI\SpecialRoundAPI.csproj"/>
<ProjectReference Include="..\API\API.csproj"/>
<ProjectReference Include="..\CS2\CS2.csproj"/>
<ProjectReference Include="..\Game\Game.csproj"/>
</ItemGroup>
</Project>

View File

@@ -1,5 +1,4 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using SpecialRound.lang;
@@ -18,18 +17,30 @@ public class SpecialRoundStarter(IServiceProvider provider)
private readonly ISpecialRoundTracker tracker =
provider.GetRequiredService<ISpecialRoundTracker>();
private int roundsSinceMapChange;
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);
}
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;
}
private void onMapChange(string mapName) { roundsSinceMapChange = 0; }
[UsedImplicitly]
@@ -66,16 +77,4 @@ public class SpecialRoundStarter(IServiceProvider provider)
throw new InvalidOperationException(
"Failed to select a special round. This should never happen.");
}
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;
}
}

View File

@@ -4,10 +4,6 @@ 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));
@@ -19,4 +15,8 @@ public class RoundMsgs {
public static IMsg VANILLA_ROUND_REMINDER
=> MsgFactory.Create(nameof(VANILLA_ROUND_REMINDER));
public static IMsg SPECIAL_ROUND_STARTED(AbstractSpecialRound round) {
return MsgFactory.Create(nameof(SPECIAL_ROUND_STARTED), round.Name);
}
}

View File

@@ -1,4 +1,6 @@
using JetBrains.Annotations;
using System.Text;
using System.Text.Json;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Events;
using TTT.API.Game;
@@ -31,9 +33,8 @@ public class KillListener(IServiceProvider provider) : IListener {
weapon = ev.Weapon
};
var payload = new StringContent(
System.Text.Json.JsonSerializer.Serialize(data),
System.Text.Encoding.UTF8, "application/json");
var payload = new StringContent(JsonSerializer.Serialize(data),
Encoding.UTF8, "application/json");
Task.Run(async () => await client.PostAsync("kill", payload));
}

View File

@@ -1,4 +1,6 @@
using JetBrains.Annotations;
using System.Text;
using System.Text.Json;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Stats.lang;
using TTT.API.Events;
@@ -13,15 +15,15 @@ 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>();
private readonly IRoundTracker roundTracker =
provider.GetRequiredService<IRoundTracker>();
public void Dispose() { }
[UsedImplicitly]
@@ -33,9 +35,8 @@ public class LogsUploader(IServiceProvider provider) : IListener {
var data = new { logs };
var payload = new StringContent(
System.Text.Json.JsonSerializer.Serialize(data),
System.Text.Encoding.UTF8, "application/json");
var payload = new StringContent(JsonSerializer.Serialize(data),
Encoding.UTF8, "application/json");
Task.Run(async () => {
var id = roundTracker.CurrentRoundId;

View File

@@ -1,7 +1,7 @@
using CounterStrikeSharp.API;
using System.Text;
using System.Text.Json;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TTT.API.Events;
using TTT.API.Player;
using TTT.Game.Events.Player;
@@ -29,9 +29,8 @@ public class PlayerCreationListener(IServiceProvider provider) : IListener {
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 content = new StringContent(JsonSerializer.Serialize(userJson),
Encoding.UTF8, "application/json");
var response = await client.PutAsync("user/" + player.Id, content);
response.EnsureSuccessStatusCode();

View File

@@ -1,4 +1,6 @@
using JetBrains.Annotations;
using System.Text;
using System.Text.Json;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using ShopAPI.Events;
using TTT.API.Events;
@@ -23,9 +25,8 @@ public class PurchaseListener(IServiceProvider provider) : IListener {
round_id = roundTracker?.CurrentRoundId
};
var payload = new StringContent(
System.Text.Json.JsonSerializer.Serialize(body),
System.Text.Encoding.UTF8, "application/json");
var payload = new StringContent(JsonSerializer.Serialize(body),
Encoding.UTF8, "application/json");
Task.Run(async () => await client.PostAsync("purchase", payload));
}

View File

@@ -1,13 +1,13 @@
using System.Net;
using System.Text;
using System.Text.Json;
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;
@@ -19,22 +19,25 @@ namespace Stats;
public class RoundListener(IServiceProvider provider)
: IListener, IRoundTracker {
public void Dispose() {
provider.GetRequiredService<IEventBus>().UnregisterListener(this);
}
private readonly Dictionary<string, int> bodiesFound = new();
private readonly HashSet<string> deaths = new();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
private readonly IMessenger messenger =
provider.GetRequiredService<IMessenger>();
private readonly Dictionary<string, (int, int, int)> kills = new();
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();
private readonly IMessenger messenger =
provider.GetRequiredService<IMessenger>();
private readonly IRoleAssigner roles =
provider.GetRequiredService<IRoleAssigner>();
public void Dispose() {
provider.GetRequiredService<IEventBus>().UnregisterListener(this);
}
public int? CurrentRoundId { get; set; }
[UsedImplicitly]
[EventHandler(Priority = Priority.MONITOR, IgnoreCanceled = true)]
@@ -97,16 +100,15 @@ public class RoundListener(IServiceProvider provider)
map_name, startedAt, participants = getParticipants(game)
};
var content = new StringContent(
System.Text.Json.JsonSerializer.Serialize(data),
System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(data),
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);
var jsonDoc = JsonDocument.Parse(json);
CurrentRoundId = jsonDoc.RootElement.GetProperty("round_id").GetInt32();
if (response.StatusCode == HttpStatusCode.Created) {
@@ -120,12 +122,10 @@ public class RoundListener(IServiceProvider provider)
// Retry
response = await client.PostAsync("round", content);
jsonDoc = System.Text.Json.JsonDocument.Parse(
await response.Content.ReadAsStringAsync());
jsonDoc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
CurrentRoundId = jsonDoc.RootElement.GetProperty("round_id").GetInt32();
if (response.StatusCode == HttpStatusCode.Created) {
if (response.StatusCode == HttpStatusCode.Created)
await notifyNewRound(CurrentRoundId.Value);
}
}
private Task notifyNewRound(int id) {
@@ -143,9 +143,8 @@ public class RoundListener(IServiceProvider provider)
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 content = new StringContent(JsonSerializer.Serialize(data),
Encoding.UTF8, "application/json");
var client = provider.GetRequiredService<HttpClient>();
@@ -153,16 +152,6 @@ public class RoundListener(IServiceProvider provider)
});
}
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>();
@@ -188,5 +177,13 @@ public class RoundListener(IServiceProvider provider)
return list;
}
public int? CurrentRoundId { get; set; }
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; }
}
}

View File

@@ -1,4 +1,5 @@
using System.Numerics;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using ShopAPI;
using TTT.API;
@@ -37,9 +38,8 @@ public class ShopRegistrar(IServiceProvider provider) : ITerrorModule {
_ => data
};
var payload = new StringContent(
System.Text.Json.JsonSerializer.Serialize(data),
System.Text.Encoding.UTF8, "application/json");
var payload = new StringContent(JsonSerializer.Serialize(data),
Encoding.UTF8, "application/json");
Console.WriteLine(
$"[Stats] Registering shop item '{item.Name}' at '{client.BaseAddress}item/{item.Id}'");

View File

@@ -7,8 +7,8 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Game\Game.csproj" />
<ProjectReference Include="..\ShopAPI\ShopAPI.csproj" />
<ProjectReference Include="..\Game\Game.csproj"/>
<ProjectReference Include="..\ShopAPI\ShopAPI.csproj"/>
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
using System.Net.Http.Json;
using System.Text.Json;
using CounterStrikeSharp.API.Modules.Utils;
using Microsoft.Extensions.DependencyInjection;
using TTT.API.Command;
@@ -25,8 +25,7 @@ public class StatsCommand(IServiceProvider provider) : ICommand {
var body = await response.Content.ReadAsStringAsync();
var statsInfo =
System.Text.Json.JsonSerializer.Deserialize<StatsResponse>(body);
var statsInfo = JsonSerializer.Deserialize<StatsResponse>(body);
if (statsInfo == null) return CommandResult.ERROR;
@@ -68,7 +67,7 @@ public class StatsCommand(IServiceProvider provider) : ICommand {
+ ChatColors.Yellow + dict.GetValueOrDefault("detective", 0));
}
record StatsResponse {
private record StatsResponse {
public required string steam_id { get; init; }
public required string name { get; init; }
public float kdr { get; init; }

View File

@@ -16,7 +16,8 @@ public static class StatsServiceCollection {
collection.AddModBehavior<LogsUploader>();
collection.AddModBehavior<KillListener>();
collection.AddModBehavior<StatsCommand>();
Console.WriteLine($"[Stats] Stats services registered with API URL: {client.BaseAddress.ToString()}");
Console.WriteLine(
$"[Stats] Stats services registered with API URL: {client.BaseAddress.ToString()}");
}
}

View File

@@ -3,9 +3,11 @@
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_START(int roundId) {
return MsgFactory.Create(nameof(API_ROUND_START), roundId);
}
public static IMsg API_ROUND_END(int roundId)
=> MsgFactory.Create(nameof(API_ROUND_END), roundId);
public static IMsg API_ROUND_END(int roundId) {
return MsgFactory.Create(nameof(API_ROUND_END), roundId);
}
}

Some files were not shown because too many files have changed in this diff Show More