From abe2f6d0d493a1d468f1abcce09c4e8cd05c36a1 Mon Sep 17 00:00:00 2001 From: MSWS Date: Sat, 20 Jul 2024 10:00:11 -0700 Subject: [PATCH] Reformat --- gitignore => .gitignore | 24 +- TTT.sln.DotSettings | 95 ++++ a | 1 - mod/TTT.Detective/DetectiveConfig.cs | 6 +- mod/TTT.Detective/DetectiveManager.cs | 194 ++++---- .../DetectiveServiceExtension.cs | 10 +- mod/TTT.Detective/TTT.Detective.csproj | 18 +- mod/TTT.Logs/LogBehavior.cs | 112 ++--- mod/TTT.Logs/LogServiceExtension.cs | 15 +- mod/TTT.Logs/LogsCommand.cs | 95 ++-- mod/TTT.Logs/LogsListener.cs | 94 ++-- mod/TTT.Logs/RoundLog.cs | 62 +-- mod/TTT.Logs/TTT.Logs.csproj | 2 +- mod/TTT.Manager/ChatManager.cs | 74 ++- mod/TTT.Manager/InfoManager.cs | 239 +++++---- mod/TTT.Manager/ManagerServiceExtension.cs | 16 +- mod/TTT.Manager/MuteManager.cs | 149 +++--- mod/TTT.Manager/TTT.Manager.csproj | 2 +- mod/TTT.Manager/TraitorRoom.cs | 60 +-- mod/TTT.Player/AntiBlockManager.cs | 84 ++-- mod/TTT.Player/CreditManager.cs | 63 +-- mod/TTT.Player/KarmaManager.cs | 56 +-- mod/TTT.Player/PlayerBehavior.cs | 138 +++--- mod/TTT.Player/PlayerConfig.cs | 11 +- mod/TTT.Player/PlayerServiceExtension.cs | 18 +- mod/TTT.Player/TTT.Player.csproj | 4 +- mod/TTT.Roles/Commands/RolesCommand.cs | 80 ++- mod/TTT.Roles/ModelHandler.cs | 62 ++- mod/TTT.Roles/RoleBehavior.cs | 464 +++++++++--------- mod/TTT.Roles/RoleConfig.cs | 12 +- mod/TTT.Roles/RoleServiceExtension.cs | 12 +- mod/TTT.Roles/RoleTester.cs | 44 +- mod/TTT.Roles/TTT.Roles.csproj | 22 +- mod/TTT.Roles/TraitorRoom.cs | 9 +- mod/TTT.Round/Round.cs | 173 ++++--- mod/TTT.Round/RoundBehavior.cs | 229 +++++---- mod/TTT.Round/RoundConfig.cs | 7 +- mod/TTT.Round/RoundServiceExtension.cs | 9 +- mod/TTT.Round/TTT.Round.csproj | 16 +- mod/TTT.Shop/TTT.Shop.csproj | 4 +- public/TTT.Formatting/Base/IView.cs | 5 +- public/TTT.Formatting/Base/SimpleView.cs | 89 ++-- public/TTT.Formatting/Core/FormatObject.cs | 52 +- public/TTT.Formatting/Core/FormatWriter.cs | 31 +- .../Extensions/ViewExtensions.cs | 129 +++-- public/TTT.Formatting/Languages/English.cs | 4 +- public/TTT.Formatting/Logistics/IDialect.cs | 8 +- public/TTT.Formatting/Logistics/ILanguage.cs | 9 +- .../Logistics/LanguageConfig.cs | 21 +- .../Logistics/RegisterLanguageExtensions.cs | 16 +- .../Objects/HiddenFormatObject.cs | 60 +-- .../Objects/IntegerFormatObject.cs | 34 +- .../Objects/PlayerFormatObject.cs | 29 +- .../Objects/StringFormatObject.cs | 31 +- .../Objects/TreeFormatObject.cs | 139 +++--- public/TTT.Formatting/TTT.Formatting.csproj | 4 +- .../Views/IRoleNotifications.cs | 9 +- public/TTT.Public/Action/DamageAction.cs | 56 +-- public/TTT.Public/Action/DeathAction.cs | 27 +- public/TTT.Public/Action/IAction.cs | 14 +- public/TTT.Public/Action/KillAction.cs | 38 +- public/TTT.Public/Action/MiscAction.cs | 28 +- public/TTT.Public/Action/ShopAction.cs | 4 +- .../TTT.Public/Behaviors/IPluginBehavior.cs | 19 +- .../Configuration/IConfigService.cs | 22 +- public/TTT.Public/Database/DatabaseService.cs | 97 ++-- .../Extensions/EntityIOExtensions.cs | 30 +- .../TTT.Public/Extensions/PlayerExtensions.cs | 166 +++---- .../Extensions/ScoreboardExtension.cs | 179 ++++--- .../TTT.Public/Extensions/ServerExtensions.cs | 45 +- .../Extensions/ServiceCollectionExtensions.cs | 81 +-- .../TTT.Public/Extensions/StringExtensions.cs | 11 +- .../TTT.Public/Extensions/VectorExtensions.cs | 77 ++- public/TTT.Public/Formatting/Format.cs | 118 ++--- public/TTT.Public/Formatting/StringUtils.cs | 17 +- .../Mod/Detective/IDetectiveService.cs | 4 +- public/TTT.Public/Mod/Logs/ILogService.cs | 18 +- public/TTT.Public/Mod/Logs/IRoundLogs.cs | 15 +- public/TTT.Public/Mod/Manager/IMuteService.cs | 11 +- public/TTT.Public/Mod/Role/IRoleService.cs | 36 +- public/TTT.Public/Mod/Round/IRoundService.cs | 24 +- .../TTT.Public/Mod/Traitor/ITraitorService.cs | 5 +- public/TTT.Public/Player/GamePlayer.cs | 186 +++---- public/TTT.Public/Player/IPlayerService.cs | 18 +- public/TTT.Public/Shop/AbstractShopItem.cs | 32 +- public/TTT.Public/Shop/ShopConfig.cs | 9 +- public/TTT.Public/TTT.Public.csproj | 18 +- src/TTT.Generic/TTT.Generic.cs | 4 +- src/TTT/Config/ConfigService.cs | 112 ++--- src/TTT/TTT.csproj | 56 +-- src/TTT/TTTPlugin.cs | 93 ++-- src/TTT/TTTServiceCollection.cs | 19 +- 92 files changed, 2357 insertions(+), 2787 deletions(-) rename gitignore => .gitignore (88%) create mode 100644 TTT.sln.DotSettings delete mode 100644 a diff --git a/gitignore b/.gitignore similarity index 88% rename from gitignore rename to .gitignore index d3bf8e7..aad3b71 100644 --- a/gitignore +++ b/.gitignore @@ -1,12 +1,12 @@ - -# Repository build files -build/ -bin/ -obj/ - -Debug/ -Release/ - -# IDE files -.idea/ -.vs/ + +# Repository build files +build/ +bin/ +obj/ + +Debug/ +Release/ + +# IDE files +.idea/ +.vs/ diff --git a/TTT.sln.DotSettings b/TTT.sln.DotSettings new file mode 100644 index 0000000..f239129 --- /dev/null +++ b/TTT.sln.DotSettings @@ -0,0 +1,95 @@ + + Built-in: Full Cleanup + public private override virtual file new abstract internal protected sealed static readonly extern unsafe volatile async required + Remove + 0 + END_OF_LINE + END_OF_LINE + False + False + True + END_OF_LINE + END_OF_LINE + TOGETHER_SAME_LINE + False + True + True + True + True + True + True + INDENT + 2 + END_OF_LINE + True + True + True + True + True + True + END_OF_LINE + False + False + False + False + False + False + False + False + False + 10 + 5 + 5 + 10 + 5 + COMPACT + END_OF_LINE + True + True + NEVER + NEVER + False + False + NEVER + False + False + NEVER + True + True + True + False + 2 + END_OF_LINE + False + True + True + False + CHOP_IF_LONG + CHOP_IF_LONG + WRAP_IF_LONG + 80 + WRAP_IF_LONG + True + API + IO + LG + LR + ST + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, ProtectedInternal, Internal, PrivateProtected" Description="Non-Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, Public, FileLocal" Description="Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + True + True + True + True + + + + + \ No newline at end of file diff --git a/a b/a deleted file mode 100644 index 7898192..0000000 --- a/a +++ /dev/null @@ -1 +0,0 @@ -a diff --git a/mod/TTT.Detective/DetectiveConfig.cs b/mod/TTT.Detective/DetectiveConfig.cs index 04a1344..f91d36d 100644 --- a/mod/TTT.Detective/DetectiveConfig.cs +++ b/mod/TTT.Detective/DetectiveConfig.cs @@ -1,7 +1,5 @@ namespace TTT.Detective; -public class DetectiveConfig -{ - public bool DNAScannerEnabled { get; } = true; - +public class DetectiveConfig { + public bool DNAScannerEnabled { get; } = true; } \ No newline at end of file diff --git a/mod/TTT.Detective/DetectiveManager.cs b/mod/TTT.Detective/DetectiveManager.cs index f22acc3..ed2662f 100644 --- a/mod/TTT.Detective/DetectiveManager.cs +++ b/mod/TTT.Detective/DetectiveManager.cs @@ -1,9 +1,7 @@ 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 TTT.Player; using TTT.Public.Behaviors; using TTT.Public.Extensions; using TTT.Public.Formatting; @@ -13,135 +11,117 @@ namespace TTT.Detective; -public class DetectiveManager(IPlayerService roleService) : IDetectiveService, IPluginBehavior -{ - private const int TaserAmmoType = 18; +public class DetectiveManager(IPlayerService roleService) + : IDetectiveService, IPluginBehavior { + private const int TaserAmmoType = 18; - public void Start(BasePlugin parent) - { - parent.RegisterListener(() => - { - foreach (var player in Utilities.GetPlayers().Where(player => player.IsValid && player.IsReal()) - .Where(player => (player.Buttons & PlayerButtons.Use) != 0)) OnPlayerUse(player); - }); + public void Start(BasePlugin parent) { + parent.RegisterListener(() => { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsValid && player.IsReal()) + .Where(player => (player.Buttons & PlayerButtons.Use) != 0)) + OnPlayerUse(player); + }); - - VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(OnZeus, HookMode.Pre); + VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(OnZeus, HookMode.Pre); + } + + public HookResult OnZeus(DynamicHook hook) { + var ent = hook.GetParam(0); + + var playerWhoWasDamaged = player(ent); + + if (playerWhoWasDamaged == null) return HookResult.Continue; + + var info = hook.GetParam(1); + + CCSPlayerController? attacker = null; + + if (info.Attacker.Value != null) { + var playerWhoAttacked = info.Attacker.Value.As(); + + attacker = playerWhoAttacked.Controller.Value.As(); } - public HookResult OnZeus(DynamicHook hook) - { - var ent = hook.GetParam(0); + if (info.BitsDamageType is not 256) return HookResult.Continue; + if (attacker == null) return HookResult.Continue; - var playerWhoWasDamaged = player(ent); + info.Damage = 0; - if (playerWhoWasDamaged == null) return HookResult.Continue; + var targetRole = roleService.GetPlayer(playerWhoWasDamaged); - var info = hook.GetParam(1); + Server.NextFrame(() => { + attacker.PrintToChat(StringUtils.FormatTTT( + $"You tased player {playerWhoWasDamaged.PlayerName} they are a {targetRole.PlayerRole().FormatRoleFull()}")); + }); - CCSPlayerController? attacker = null; + return HookResult.Stop; + } - if (info.Attacker.Value != null) - { - var playerWhoAttacked = info.Attacker.Value.As(); - attacker = playerWhoAttacked.Controller.Value.As(); + private void OnPlayerUse(CCSPlayerController player) { IdentifyBody(player); } - } + private void IdentifyBody(CCSPlayerController caller) { + //add states - if (info.BitsDamageType is not 256) return HookResult.Continue; - if (attacker == null) return HookResult.Continue; + if (roleService.GetPlayer(caller).PlayerRole() != Role.Detective) return; - info.Damage = 0; + var entity = caller.GetClientRagdollAimTarget(); - var targetRole = roleService.GetPlayer(playerWhoWasDamaged); + if (entity == null) return; - Server.NextFrame(() => - { - attacker.PrintToChat( - StringUtils.FormatTTT( - $"You tased player {playerWhoWasDamaged.PlayerName} they are a {targetRole.PlayerRole().FormatRoleFull()}")); - }); - - return HookResult.Stop; - } + if (entity.PawnIsAlive) return; - - private void OnPlayerUse(CCSPlayerController player) - { - IdentifyBody(player); - } + var player = roleService.GetPlayer(entity); - private void IdentifyBody(CCSPlayerController caller) - { - //add states + if (player.IsFound()) return; - if (roleService.GetPlayer(caller).PlayerRole() != Role.Detective) return; + var killerEntity = player.Killer(); - var entity = caller.GetClientRagdollAimTarget(); + string message; - if (entity == null) return; - - if (entity.PawnIsAlive) return; - - var player = roleService.GetPlayer(entity); + var plr = player.Player(); + if (plr == null) return; - if (player.IsFound()) return; - - var killerEntity= player.Killer(); - - string message; + if (killerEntity == null || !killerEntity.IsReal()) + message = StringUtils.FormatTTT(player.PlayerRole() + .FormatStringFullAfter($"{plr.PlayerName} was killed by world")); + else + message = StringUtils.FormatTTT( + player.PlayerRole() + .FormatStringFullAfter($"{plr.PlayerName} was killed by ") + + roleService.GetPlayer(killerEntity) + .PlayerRole() + .FormatStringFullAfter(killerEntity.PlayerName)); - var plr = player.Player(); - if (plr == null) return; - if (killerEntity == null || !killerEntity.IsReal()) - message = StringUtils.FormatTTT(player.PlayerRole() - .FormatStringFullAfter($"{plr.PlayerName} was killed by world")); - else - message = StringUtils.FormatTTT( - player.PlayerRole().FormatStringFullAfter($"{plr.PlayerName} was killed by ") + - roleService.GetPlayer(killerEntity).PlayerRole().FormatStringFullAfter(killerEntity.PlayerName)); + player.SetFound(true); + Server.NextFrame(() => { Server.PrintToChatAll(message); }); + } - player.SetFound(true); - - Server.NextFrame(() => { Server.PrintToChatAll(message); }); - } - - //to be moved to a utility class - public static CCSPlayerController? player(CEntityInstance? instance) - { - if (instance == null) - { - return null; - } - - if (instance.DesignerName != "player") - { - return null; - } - - // grab the pawn index - int player_index = (int)instance.Index; - - // grab player controller from pawn - CCSPlayerPawn player_pawn = Utilities.GetEntityFromIndex(player_index); - - // pawn valid - if (player_pawn == null || !player_pawn.IsValid) - { - return null; - } - - // controller valid - if (player_pawn.OriginalController == null || !player_pawn.OriginalController.IsValid) - { - return null; - } - - // any further validity is up to the caller - return player_pawn.OriginalController.Value; - } + //to be moved to a utility class + public static CCSPlayerController? player(CEntityInstance? instance) { + if (instance == null) return null; + + if (instance.DesignerName != "player") return null; + + // grab the pawn index + var player_index = (int)instance.Index; + + // grab player controller from pawn + var player_pawn = Utilities.GetEntityFromIndex(player_index); + + // pawn valid + if (player_pawn == null || !player_pawn.IsValid) return null; + + // controller valid + if (player_pawn.OriginalController == null + || !player_pawn.OriginalController.IsValid) + return null; + + // any further validity is up to the caller + return player_pawn.OriginalController.Value; + } } \ No newline at end of file diff --git a/mod/TTT.Detective/DetectiveServiceExtension.cs b/mod/TTT.Detective/DetectiveServiceExtension.cs index e13d267..a3ba82e 100644 --- a/mod/TTT.Detective/DetectiveServiceExtension.cs +++ b/mod/TTT.Detective/DetectiveServiceExtension.cs @@ -4,10 +4,8 @@ namespace TTT.Detective; -public static class DetectiveServiceExtension -{ - public static void AddDetectiveBehavior(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - } +public static class DetectiveServiceExtension { + public static void AddDetectiveBehavior(this IServiceCollection collection) { + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/TTT.Detective/TTT.Detective.csproj b/mod/TTT.Detective/TTT.Detective.csproj index cf4da7c..961cd21 100644 --- a/mod/TTT.Detective/TTT.Detective.csproj +++ b/mod/TTT.Detective/TTT.Detective.csproj @@ -1,11 +1,11 @@  - - net8.0 - enable - enable - TTT.Detective - - - - + + net8.0 + enable + enable + TTT.Detective + + + + \ No newline at end of file diff --git a/mod/TTT.Logs/LogBehavior.cs b/mod/TTT.Logs/LogBehavior.cs index f53703b..248acd1 100644 --- a/mod/TTT.Logs/LogBehavior.cs +++ b/mod/TTT.Logs/LogBehavior.cs @@ -1,9 +1,6 @@ -using System.Collections.Generic; -using System.Linq; -using CounterStrikeSharp.API; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using TTT.Public.Action; using TTT.Public.Behaviors; using TTT.Public.Extensions; using TTT.Public.Mod.Logs; @@ -11,73 +8,50 @@ namespace TTT.Logs; -public class LogBehavior : ILogService, IPluginBehavior -{ - private int _round = 1; - - public void Start(BasePlugin plugin) - { - } - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart _, GameEventInfo __) - { - CreateRound(_round++); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd _, GameEventInfo __) - { - PrintLogs(_round); - return HookResult.Continue; - } - - private readonly Dictionary _logs = new(); - - public int GetCurrentRound() - { - return _round; - } - - public void AddLog(Action action) - { - _logs[_round].AddLog(action); - } +public class LogBehavior : ILogService, IPluginBehavior { + private readonly Dictionary _logs = new(); + private int _round = 1; - public bool PrintLogs(int round) - { - if (_logs.ContainsKey(round)) return false; - foreach (var player in Utilities.GetPlayers().Where(plr => plr.IsReal())) - { - PrintToPlayer(player, round); - } - - PrintToConsole(round); - return true; - } + public int GetCurrentRound() { return _round; } - public bool PrintToPlayer(CCSPlayerController player, int round) - { - if (!_logs.ContainsKey(round)) return false; - player.PrintToConsole(GetLogs(round).FormattedLogs()); - return true; - } + public void AddLog(Action action) { _logs[_round].AddLog(action); } - public bool PrintToConsole(int round) - { - if (!_logs.ContainsKey(round)) return false; - Server.PrintToConsole(GetLogs(round).FormattedLogs()); - return true; - } + public bool PrintLogs(int round) { + if (_logs.ContainsKey(round)) return false; + foreach (var player in Utilities.GetPlayers().Where(plr => plr.IsReal())) + PrintToPlayer(player, round); - public IRoundLogs GetLogs(int round) - { - return _logs[round]; - } - - public void CreateRound(int round) - { - _logs.Add(round, new RoundLog(round)); - } + PrintToConsole(round); + return true; + } + + public bool PrintToPlayer(CCSPlayerController player, int round) { + if (!_logs.ContainsKey(round)) return false; + player.PrintToConsole(GetLogs(round).FormattedLogs()); + return true; + } + + public bool PrintToConsole(int round) { + if (!_logs.ContainsKey(round)) return false; + Server.PrintToConsole(GetLogs(round).FormattedLogs()); + return true; + } + + public IRoundLogs GetLogs(int round) { return _logs[round]; } + + public void CreateRound(int round) { _logs.Add(round, new RoundLog(round)); } + + public void Start(BasePlugin plugin) { } + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart _, GameEventInfo __) { + CreateRound(_round++); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd _, GameEventInfo __) { + PrintLogs(_round); + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/TTT.Logs/LogServiceExtension.cs b/mod/TTT.Logs/LogServiceExtension.cs index f7b3feb..55dc6b2 100644 --- a/mod/TTT.Logs/LogServiceExtension.cs +++ b/mod/TTT.Logs/LogServiceExtension.cs @@ -1,16 +1,13 @@ using Microsoft.Extensions.DependencyInjection; using TTT.Public.Extensions; using TTT.Public.Mod.Logs; -using TTT.Public.Mod.Role; namespace TTT.Logs; -public static class LogServiceExtension -{ - public static void AddLogsService(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } +public static class LogServiceExtension { + public static void AddLogsService(this IServiceCollection collection) { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/TTT.Logs/LogsCommand.cs b/mod/TTT.Logs/LogsCommand.cs index 5e5458a..f5402fc 100644 --- a/mod/TTT.Logs/LogsCommand.cs +++ b/mod/TTT.Logs/LogsCommand.cs @@ -8,56 +8,51 @@ namespace TTT.Logs; -public class LogsCommand(ILogService service) : IPluginBehavior -{ - private readonly ILogService _service = service; +public class LogsCommand(ILogService service) : IPluginBehavior { + private readonly ILogService _service = service; - public void Start(BasePlugin plugin) - { - + public void Start(BasePlugin plugin) { } + + [ConsoleCommand("css_logs", "Prints logs to console")] + [CommandHelper(0, whoCanExecute: CommandUsage.CLIENT_ONLY)] + public void Command_Logs(CCSPlayerController? executor, CommandInfo info) { + if (!AdminManager.PlayerHasPermissions(executor, "@css/kick")) { + info.ReplyToCommand( + StringUtils.FormatTTT( + "You do not have permission to execute this command")); + return; + } + + var roundIdString = info.GetArg(1); + + var roundId = service.GetCurrentRound(); + + if (string.IsNullOrEmpty(roundIdString) + && !int.TryParse(roundIdString, out roundId)) { + info.ReplyToCommand( + StringUtils.FormatTTT("Invalid round id, /logs ")); + return; } - - [ConsoleCommand("css_logs", "Prints logs to console")] - [CommandHelper(minArgs: 0, whoCanExecute: CommandUsage.CLIENT_ONLY)] - public void Command_Logs(CCSPlayerController? executor, CommandInfo info) - { - - if (!AdminManager.PlayerHasPermissions(executor, "@css/kick")) - { - info.ReplyToCommand(StringUtils.FormatTTT("You do not have permission to execute this command")); - return; - } - - var roundIdString = info.GetArg(1); - - var roundId = service.GetCurrentRound(); - - if (string.IsNullOrEmpty(roundIdString) && !int.TryParse(roundIdString, out roundId)) - { - info.ReplyToCommand(StringUtils.FormatTTT("Invalid round id, /logs ")); - return; - } - - if (roundId <= 0) - { - info.ReplyToCommand( StringUtils.FormatTTT("Invalid round id")); - return; - } - - if (executor == null) - { - if (!service.PrintToConsole(roundId)) info.ReplyToCommand(StringUtils.FormatTTT("No logs found for round " + roundId)); - return; - } - - if (!AdminManager.PlayerHasPermissions(executor, "@css/kick")) - { - info.ReplyToCommand("You do not have permission to execute this command"); - return; - } - - info.ReplyToCommand(!service.PrintToPlayer(executor, roundId) - ? StringUtils.FormatTTT("No logs found for round " + roundId) - : StringUtils.FormatTTT("Logs printed to console")); + + if (roundId <= 0) { + info.ReplyToCommand(StringUtils.FormatTTT("Invalid round id")); + return; } -} + + if (executor == null) { + if (!service.PrintToConsole(roundId)) + info.ReplyToCommand( + StringUtils.FormatTTT("No logs found for round " + roundId)); + return; + } + + if (!AdminManager.PlayerHasPermissions(executor, "@css/kick")) { + info.ReplyToCommand("You do not have permission to execute this command"); + return; + } + + info.ReplyToCommand(!service.PrintToPlayer(executor, roundId) ? + StringUtils.FormatTTT("No logs found for round " + roundId) : + StringUtils.FormatTTT("Logs printed to console")); + } +} \ No newline at end of file diff --git a/mod/TTT.Logs/LogsListener.cs b/mod/TTT.Logs/LogsListener.cs index a59382e..787e454 100644 --- a/mod/TTT.Logs/LogsListener.cs +++ b/mod/TTT.Logs/LogsListener.cs @@ -1,5 +1,4 @@ -using System; -using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using TTT.Public.Action; using TTT.Public.Behaviors; @@ -10,49 +9,52 @@ namespace TTT.Logs; -public class LogsListener(ILogService logService, IPlayerService playerService) : IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - - } - - [GameEventHandler] - public HookResult OnPlayerDamage(EventPlayerHurt @event, GameEventInfo info) - { - var attackedPlayer = @event.Userid; - - if (attackedPlayer == null || !attackedPlayer.IsReal()) return HookResult.Continue; - - var attackedRole = playerService.GetPlayer(attackedPlayer).PlayerRole(); - - var attacker = @event.Attacker == null ? null : new Tuple(@event.Attacker, playerService.GetPlayer(@event.Attacker).PlayerRole()); - - logService.AddLog(new DamageAction(attacker,new Tuple(attackedPlayer, attackedRole), @event.DmgHealth, ServerExtensions.GetGameRules().RoundTime)); - - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var killedPlayer = @event.Userid; - var killer = @event.Attacker; - - if (killedPlayer == null || !killedPlayer.IsReal()) return HookResult.Continue; - - var killedRole = playerService.GetPlayer(killedPlayer).PlayerRole(); - - if (killer == null || !killer.IsReal()) - { - logService.AddLog(new DeathAction(new Tuple(killedPlayer, killedRole))); - return HookResult.Continue; - } - - var killerRole = playerService.GetPlayer(killer).PlayerRole(); - - logService.AddLog(new KillAction(new Tuple(killedPlayer, killedRole), - new Tuple(killer, killerRole))); - return HookResult.Continue; +public class LogsListener(ILogService logService, IPlayerService playerService) + : IPluginBehavior { + public void Start(BasePlugin plugin) { } + + [GameEventHandler] + public HookResult OnPlayerDamage(EventPlayerHurt @event, GameEventInfo info) { + var attackedPlayer = @event.Userid; + + if (attackedPlayer == null || !attackedPlayer.IsReal()) + return HookResult.Continue; + + var attackedRole = playerService.GetPlayer(attackedPlayer).PlayerRole(); + + var attacker = @event.Attacker == null ? + null : + new Tuple(@event.Attacker, + playerService.GetPlayer(@event.Attacker).PlayerRole()); + + logService.AddLog(new DamageAction(attacker, + new Tuple(attackedPlayer, attackedRole), + @event.DmgHealth, ServerExtensions.GetGameRules().RoundTime)); + + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + var killedPlayer = @event.Userid; + var killer = @event.Attacker; + + if (killedPlayer == null || !killedPlayer.IsReal()) + return HookResult.Continue; + + var killedRole = playerService.GetPlayer(killedPlayer).PlayerRole(); + + if (killer == null || !killer.IsReal()) { + logService.AddLog(new DeathAction( + new Tuple(killedPlayer, killedRole))); + return HookResult.Continue; } + + var killerRole = playerService.GetPlayer(killer).PlayerRole(); + + logService.AddLog(new KillAction( + new Tuple(killedPlayer, killedRole), + new Tuple(killer, killerRole))); + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/TTT.Logs/RoundLog.cs b/mod/TTT.Logs/RoundLog.cs index dcecb1e..a190563 100644 --- a/mod/TTT.Logs/RoundLog.cs +++ b/mod/TTT.Logs/RoundLog.cs @@ -1,45 +1,29 @@ -using System.Collections.Generic; -using System.Text; -using TTT.Public.Action; +using System.Text; using TTT.Public.Mod.Logs; using Action = TTT.Public.Action.Action; namespace TTT.Logs; -public class RoundLog : IRoundLogs -{ - private readonly List _logs = []; - private readonly int _roundId; - - public RoundLog(int roundId) - { - _roundId = roundId; - } - - public IList GetLogs() - { - return _logs; - } - - public void AddLog(Action action) - { - _logs.Add(action); - } - - public void RemoveLog(Action action) - { - _logs.Remove(action); - } - - public string FormattedLogs() - { - var builder = new StringBuilder(); - builder.AppendLine($"[TTT] Logs round {_roundId}"); - - foreach (var action in _logs) builder.AppendLine(action.ActionMessage()); - - builder.AppendLine("[TTT] Logs ended!"); - - return builder.ToString(); - } +public class RoundLog : IRoundLogs { + private readonly List _logs = []; + private readonly int _roundId; + + public RoundLog(int roundId) { _roundId = roundId; } + + public IList GetLogs() { return _logs; } + + public void AddLog(Action action) { _logs.Add(action); } + + public void RemoveLog(Action action) { _logs.Remove(action); } + + public string FormattedLogs() { + var builder = new StringBuilder(); + builder.AppendLine($"[TTT] Logs round {_roundId}"); + + foreach (var action in _logs) builder.AppendLine(action.ActionMessage()); + + builder.AppendLine("[TTT] Logs ended!"); + + return builder.ToString(); + } } \ No newline at end of file diff --git a/mod/TTT.Logs/TTT.Logs.csproj b/mod/TTT.Logs/TTT.Logs.csproj index ca14336..fc5f91b 100644 --- a/mod/TTT.Logs/TTT.Logs.csproj +++ b/mod/TTT.Logs/TTT.Logs.csproj @@ -7,7 +7,7 @@ - + diff --git a/mod/TTT.Manager/ChatManager.cs b/mod/TTT.Manager/ChatManager.cs index c34d37c..5b5b51f 100644 --- a/mod/TTT.Manager/ChatManager.cs +++ b/mod/TTT.Manager/ChatManager.cs @@ -1,52 +1,42 @@ -using System; -using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Utils; using TTT.Public.Behaviors; using TTT.Public.Mod.Role; -using TTT.Public.Player; namespace TTT.Manager; -public class ChatManager(IRoleService roleService) : IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - plugin.AddCommandListener("say_team", OnSayTeam); - } - - private HookResult OnSayTeam(CCSPlayerController? caller, CommandInfo info) - { - if (caller == null || !caller.IsValid) return HookResult.Continue; - var role = roleService.GetRole(caller); - switch (role) - { - case Role.Innocent: - return HookResult.Stop; - case Role.Detective: - { - var message = $" {ChatColors.DarkBlue} DETECTIVE {caller.PlayerName} {info.GetArg(1)}"; - foreach (var player in roleService.GetDetectives()) - { - player.PrintToChat(message); - } - break; - } - case Role.Traitor: - { - var message = $" {ChatColors.DarkRed} TRAITOR {caller.PlayerName} {info.GetArg(1)}"; - foreach (var player in roleService.GetTraitors()) - { - player.PrintToChat(message); - } - break; - } - case Role.Unassigned: - return HookResult.Continue; - default: - throw new ArgumentOutOfRangeException(); - } +public class ChatManager(IRoleService roleService) : IPluginBehavior { + public void Start(BasePlugin plugin) { + plugin.AddCommandListener("say_team", OnSayTeam); + } - return HookResult.Handled; + private HookResult OnSayTeam(CCSPlayerController? caller, CommandInfo info) { + if (caller == null || !caller.IsValid) return HookResult.Continue; + var role = roleService.GetRole(caller); + switch (role) { + case Role.Innocent: + return HookResult.Stop; + case Role.Detective: { + var message = + $" {ChatColors.DarkBlue} DETECTIVE {caller.PlayerName} {info.GetArg(1)}"; + foreach (var player in roleService.GetDetectives()) + player.PrintToChat(message); + break; + } + case Role.Traitor: { + var message = + $" {ChatColors.DarkRed} TRAITOR {caller.PlayerName} {info.GetArg(1)}"; + foreach (var player in roleService.GetTraitors()) + player.PrintToChat(message); + break; + } + case Role.Unassigned: + return HookResult.Continue; + default: + throw new ArgumentOutOfRangeException(); } + + return HookResult.Handled; + } } \ No newline at end of file diff --git a/mod/TTT.Manager/InfoManager.cs b/mod/TTT.Manager/InfoManager.cs index 1866918..2afe21e 100644 --- a/mod/TTT.Manager/InfoManager.cs +++ b/mod/TTT.Manager/InfoManager.cs @@ -1,154 +1,145 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using CounterStrikeSharp.API; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Admin; -using CounterStrikeSharp.API.Modules.Memory; -using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; using CounterStrikeSharp.API.Modules.Timers; -using CounterStrikeSharp.API.Modules.Utils; -using TTT.Player; using TTT.Public.Behaviors; using TTT.Public.Extensions; using TTT.Public.Formatting; using TTT.Public.Mod.Role; using TTT.Public.Mod.Round; using TTT.Public.Player; -using TTT.Round; -using Vector = CounterStrikeSharp.API.Modules.Utils.Vector; namespace TTT.Manager; -public class InfoManager : IPluginBehavior -{ - private readonly Dictionary> _playerLookAtRole = new(); - private readonly IPlayerService _playerService; - private readonly IRoundService _manager; - private readonly Dictionary> _spectatorLookAtRole = new(); - - public InfoManager(IPlayerService playerService, IRoleService manager) - { - _playerService = playerService; - _manager = manager.GetRoundService(); - } - - public void Start(BasePlugin plugin) - { - plugin.RegisterListener(OnTick); - plugin.AddTimer(0.1f, OnTickAll, TimerFlags.REPEAT); - } +public class InfoManager : IPluginBehavior { + private readonly IRoundService _manager; - public void Reset() - { - _playerLookAtRole.Clear(); - _spectatorLookAtRole.Clear(); - } - - public void RegisterLookAtRole(CCSPlayerController player, Tuple role) - { - _playerLookAtRole.TryAdd(player, role); - } + private readonly + Dictionary> + _playerLookAtRole = new(); - public void RemoveLookAtRole(CCSPlayerController player) - { - _playerLookAtRole.Remove(player); - } + private readonly IPlayerService _playerService; - public void OnTick() - { - foreach (var gamePlayer in _playerService.Players()) - { - if (_manager.GetRoundStatus() != RoundStatus.Started) return; + private readonly Dictionary> + _spectatorLookAtRole = new(); - var player = gamePlayer.Player(); + public InfoManager(IPlayerService playerService, IRoleService manager) { + _playerService = playerService; + _manager = manager.GetRoundService(); + } - if (player == null) continue; - if (!player.IsReal()) continue; + public void Start(BasePlugin plugin) { + plugin.RegisterListener(OnTick); + plugin.AddTimer(0.1f, OnTickAll, TimerFlags.REPEAT); + } - var playerRole = gamePlayer.PlayerRole(); + public void Reset() { + _playerLookAtRole.Clear(); + _spectatorLookAtRole.Clear(); + } - if (playerRole == Role.Unassigned) continue; + public void RegisterLookAtRole(CCSPlayerController player, + Tuple role) { + _playerLookAtRole.TryAdd(player, role); + } - if (!player.PawnIsAlive) continue; + public void RemoveLookAtRole(CCSPlayerController player) { + _playerLookAtRole.Remove(player); + } - if (!_playerLookAtRole.TryGetValue(player, out var value)) - { - Server.NextFrame(() => - player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}")); - continue; - } + public void OnTick() { + foreach (var gamePlayer in _playerService.Players()) { + if (_manager.GetRoundStatus() != RoundStatus.Started) return; - if (!value.Item1.IsReal()) continue; + var player = gamePlayer.Player(); - if (!value.Item1.PawnIsAlive) HandleDeadTarget(player, playerRole, value.Item1, value.Item2); - else HandleAliveTarget(player, playerRole, value.Item1, value.Item2); - } - } + if (player == null) continue; + if (!player.IsReal()) continue; - public void HandleDeadTarget(CCSPlayerController player, Role playerRole, CCSPlayerController target, Role targetRole) - { - Server.NextFrame(() => player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Corpse
" - + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); - } + var playerRole = gamePlayer.PlayerRole(); + + if (playerRole == Role.Unassigned) continue; + + if (!player.PawnIsAlive) continue; + + if (!_playerLookAtRole.TryGetValue(player, out var value)) { + Server.NextFrame(() + => player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}")); + continue; + } + + if (!value.Item1.IsReal()) continue; - public void HandleAliveTarget(CCSPlayerController player, Role playerRole, CCSPlayerController target, Role targetRole) - { - switch (targetRole) - { - case Role.Detective: - Server.NextFrame(() => player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); - return; - case Role.Traitor when playerRole == Role.Traitor: - Server.NextFrame(() => player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); - return; - default: - Server.NextFrame(() => player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {Role.Unassigned.GetCenterRole()}")); - break; - } + if (!value.Item1.PawnIsAlive) + HandleDeadTarget(player, playerRole, value.Item1, value.Item2); + else + HandleAliveTarget(player, playerRole, value.Item1, value.Item2); } - - public void OnTickAll() - { - var players = _playerService.Players().Select(plr => plr.Player()); - - _playerLookAtRole.Clear(); - - foreach (var player in players) - { - if (player == null) continue; - if (!player.IsReal()) continue; - - var target = player.GetClientPlayerAimTarget(); - - if (target == null) continue; - if (!target.IsReal()) continue; - - RegisterLookAtRole(player, new Tuple(target, _playerService.GetPlayer(target).PlayerRole())); - } + } + + public void + HandleDeadTarget(CCSPlayerController player, Role playerRole, + CCSPlayerController target, Role targetRole) { + Server.NextFrame(() => player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}
" + + $"{target.PlayerName}'s Corpse
" + + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); + } + + public void HandleAliveTarget(CCSPlayerController player, Role playerRole, + CCSPlayerController target, Role targetRole) { + switch (targetRole) { + case Role.Detective: + Server.NextFrame(() => player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}
" + + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); + return; + case Role.Traitor when playerRole == Role.Traitor: + Server.NextFrame(() => player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}
" + + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); + return; + default: + Server.NextFrame(() => player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}
" + + $"{target.PlayerName}'s Role: {Role.Unassigned.GetCenterRole()}")); + break; } + } + + public void OnTickAll() { + var players = _playerService.Players().Select(plr => plr.Player()); + + _playerLookAtRole.Clear(); + + foreach (var player in players) { + if (player == null) continue; + if (!player.IsReal()) continue; - [GameEventHandler] - private HookResult OnPlayerSpectateChange(EventSpecTargetUpdated @event, GameEventInfo info) - { - var player = @event.Userid; - var target = new CCSPlayerController(@event.Target); - - if (!player.IsReal() || !target.IsReal()) return HookResult.Continue; - - _spectatorLookAtRole.TryAdd(player, new Tuple(target.PlayerName, _playerService.GetPlayer(target).PlayerRole())); - - return HookResult.Continue; + var target = player.GetClientPlayerAimTarget(); + + if (target == null) continue; + if (!target.IsReal()) continue; + + RegisterLookAtRole(player, + new Tuple(target, + _playerService.GetPlayer(target).PlayerRole())); } + } + + [GameEventHandler] + private HookResult OnPlayerSpectateChange(EventSpecTargetUpdated @event, + GameEventInfo info) { + var player = @event.Userid; + var target = new CCSPlayerController(@event.Target); + + if (!player.IsReal() || !target.IsReal()) return HookResult.Continue; + + _spectatorLookAtRole.TryAdd(player, + new Tuple(target.PlayerName, + _playerService.GetPlayer(target).PlayerRole())); + + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/TTT.Manager/ManagerServiceExtension.cs b/mod/TTT.Manager/ManagerServiceExtension.cs index 73c6d15..cdafe34 100644 --- a/mod/TTT.Manager/ManagerServiceExtension.cs +++ b/mod/TTT.Manager/ManagerServiceExtension.cs @@ -4,13 +4,11 @@ namespace TTT.Manager; -public static class ManagerServiceExtension -{ - public static void AddManagerService(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } +public static class ManagerServiceExtension { + public static void AddManagerService(this IServiceCollection collection) { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/TTT.Manager/MuteManager.cs b/mod/TTT.Manager/MuteManager.cs index e602e1c..eff8794 100644 --- a/mod/TTT.Manager/MuteManager.cs +++ b/mod/TTT.Manager/MuteManager.cs @@ -1,5 +1,4 @@ -using System.Linq; -using CounterStrikeSharp.API; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; @@ -10,95 +9,77 @@ namespace TTT.Manager; -public class MuteManager : IMuteService, IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - plugin.RegisterListener(OnPlayerSpeak); - } +public class MuteManager : IMuteService, IPluginBehavior { + public void Mute(CCSPlayerController player) { + if (BypassMute(player)) return; - [GameEventHandler] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - if (@event.Userid == null) return HookResult.Continue; - Mute(@event.Userid); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - UnMuteAll(); - return HookResult.Continue; - } - - public void Mute(CCSPlayerController player) - { - if (BypassMute(player)) - return; - - player.VoiceFlags |= VoiceFlags.Muted; - } + player.VoiceFlags |= VoiceFlags.Muted; + } - public void UnMute(CCSPlayerController player) - { - player.VoiceFlags &= ~VoiceFlags.Muted; - } - - public void UnMuteAll() - { - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal() && player.Team == CsTeam.Terrorist)) - { - UnMute(player); - } - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal() && player.Team == CsTeam.CounterTerrorist)) - { - UnMute(player); - } - } + public void UnMute(CCSPlayerController player) { + player.VoiceFlags &= ~VoiceFlags.Muted; + } - public void MuteAll() - { - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal() && player.Team == CsTeam.Terrorist)) - { - Mute(player); - } - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal() && player.Team == CsTeam.CounterTerrorist)) - { - Mute(player); - } - } + public void UnMuteAll() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal() && player.Team == CsTeam.Terrorist)) + UnMute(player); + foreach (var player in Utilities.GetPlayers() + .Where(player + => player.IsReal() && player.Team == CsTeam.CounterTerrorist)) + UnMute(player); + } - private void OnPlayerSpeak(int playerSlot) - { - var player = Utilities.GetPlayerFromSlot(playerSlot); - if (!player.IsReal()) - return; + public void MuteAll() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal() && player.Team == CsTeam.Terrorist)) + Mute(player); + foreach (var player in Utilities.GetPlayers() + .Where(player + => player.IsReal() && player.Team == CsTeam.CounterTerrorist)) + Mute(player); + } - if (!player.PawnIsAlive && !BypassMute(player)) - { - // Normal players can't speak when dead - Mute(player); - Server.NextFrame(() => player.PrintToCenter("You are dead and muted!")); - return; - } + public void Start(BasePlugin plugin) { + plugin.RegisterListener(OnPlayerSpeak); + } - if (IsMuted(player)) - { - Server.NextFrame(() => player.PrintToCenter("You are muted!")); - return; - } - } - - private bool IsMuted(CCSPlayerController player) - { - if (!player.IsReal()) - return false; - return (player.VoiceFlags & VoiceFlags.Muted) != 0; + [GameEventHandler] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + if (@event.Userid == null) return HookResult.Continue; + Mute(@event.Userid); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { + UnMuteAll(); + return HookResult.Continue; + } + + private void OnPlayerSpeak(int playerSlot) { + var player = Utilities.GetPlayerFromSlot(playerSlot); + if (!player.IsReal()) return; + + if (!player.PawnIsAlive && !BypassMute(player)) { + // Normal players can't speak when dead + Mute(player); + Server.NextFrame(() => player.PrintToCenter("You are dead and muted!")); + return; } - private bool BypassMute(CCSPlayerController player) - { - return player.IsReal() && AdminManager.PlayerHasPermissions(player, "@css/chat"); + if (IsMuted(player)) { + Server.NextFrame(() => player.PrintToCenter("You are muted!")); } + } + + private bool IsMuted(CCSPlayerController player) { + if (!player.IsReal()) return false; + return (player.VoiceFlags & VoiceFlags.Muted) != 0; + } + + private bool BypassMute(CCSPlayerController player) { + return player.IsReal() + && AdminManager.PlayerHasPermissions(player, "@css/chat"); + } } \ No newline at end of file diff --git a/mod/TTT.Manager/TTT.Manager.csproj b/mod/TTT.Manager/TTT.Manager.csproj index d0b8182..72ebcba 100644 --- a/mod/TTT.Manager/TTT.Manager.csproj +++ b/mod/TTT.Manager/TTT.Manager.csproj @@ -7,6 +7,6 @@ - + diff --git a/mod/TTT.Manager/TraitorRoom.cs b/mod/TTT.Manager/TraitorRoom.cs index 2ef1705..c82ec0d 100644 --- a/mod/TTT.Manager/TraitorRoom.cs +++ b/mod/TTT.Manager/TraitorRoom.cs @@ -6,39 +6,33 @@ namespace TTT.Manager; -public class TraitorRoom(IPlayerService service) : IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - plugin.AddTimer(0.1f, () => - { - foreach (var plr in Utilities.GetPlayers().Where(player => player.IsReal())) - { - OpenTraitorRoom(plr); - } - }); +public class TraitorRoom(IPlayerService service) : IPluginBehavior { + public void Start(BasePlugin plugin) { + plugin.AddTimer(0.1f, () => { + foreach (var plr in Utilities.GetPlayers() + .Where(player => player.IsReal())) + OpenTraitorRoom(plr); + }); + } + + + public void OpenTraitorRoom(CCSPlayerController player) { + if ((player.Buttons & PlayerButtons.Use) == 0) return; + + var traitorRoom = player.GetClientPlayerTraitorRoom(); + + if (traitorRoom == null) { + Server.NextFrame(() => player.PrintToCenter("No door has been found!")); + return; } - - - public void OpenTraitorRoom(CCSPlayerController player) - { - if ((player.Buttons & PlayerButtons.Use) == 0) return; - - var traitorRoom = player.GetClientPlayerTraitorRoom(); - - if (traitorRoom == null) - { - Server.NextFrame(() => player.PrintToCenter("No door has been found!")); - return; - } - - if (traitorRoom.Globalname is not "traitor_door") - { - Server.NextFrame(() => player.PrintToCenter("Door is not a traitor room!")); - return; - } - - traitorRoom.AcceptInput("Open"); - Server.NextFrame(() => player.PrintToCenter("Found traitor room!")); + + if (traitorRoom.Globalname is not "traitor_door") { + Server.NextFrame( + () => player.PrintToCenter("Door is not a traitor room!")); + return; } + + traitorRoom.AcceptInput("Open"); + Server.NextFrame(() => player.PrintToCenter("Found traitor room!")); + } } \ No newline at end of file diff --git a/mod/TTT.Player/AntiBlockManager.cs b/mod/TTT.Player/AntiBlockManager.cs index 14dc7d3..c582a36 100644 --- a/mod/TTT.Player/AntiBlockManager.cs +++ b/mod/TTT.Player/AntiBlockManager.cs @@ -11,62 +11,58 @@ namespace TTT.Player; -public class AntiBlockManager : IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - } +public class AntiBlockManager : IPluginBehavior { + private readonly WIN_LINUX OnCollisionRulesChangedOffset = new(173, 172); - [GameEventHandler] - private HookResult Event_PlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) - { - if (!@event.Userid.IsValid) return HookResult.Continue; + public void Start(BasePlugin plugin) { } - var player = @event.Userid; + [GameEventHandler] + private HookResult Event_PlayerSpawn(EventPlayerSpawn @event, + GameEventInfo info) { + if (!@event.Userid.IsValid) return HookResult.Continue; - if (!player.IsReal()) return HookResult.Continue; + var player = @event.Userid; - if (!player.PlayerPawn.IsValid) return HookResult.Continue; + if (!player.IsReal()) return HookResult.Continue; - var pawn = player.PlayerPawn; + if (!player.PlayerPawn.IsValid) return HookResult.Continue; - Server.NextFrame(() => PlayerSpawnNextFrame(player, pawn)); + var pawn = player.PlayerPawn; - return HookResult.Continue; - } + Server.NextFrame(() => PlayerSpawnNextFrame(player, pawn)); + + return HookResult.Continue; + } - private readonly WIN_LINUX OnCollisionRulesChangedOffset = new(173, 172); + private void PlayerSpawnNextFrame(CCSPlayerController player, + CHandle pawn) { + pawn.Value.Collision.CollisionGroup = + (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; - private void PlayerSpawnNextFrame(CCSPlayerController player, CHandle pawn) - { - pawn.Value.Collision.CollisionGroup = (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; + pawn.Value.Collision.CollisionAttribute.CollisionGroup = + (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; - pawn.Value.Collision.CollisionAttribute.CollisionGroup = (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; + var collisionRulesChanged = new VirtualFunctionVoid(pawn.Value.Handle, + OnCollisionRulesChangedOffset.Get()); - var collisionRulesChanged = - new VirtualFunctionVoid(pawn.Value.Handle, OnCollisionRulesChangedOffset.Get()); + collisionRulesChanged.Invoke(pawn.Value.Handle); + } - collisionRulesChanged.Invoke(pawn.Value.Handle); + public class WIN_LINUX { + public WIN_LINUX(T windows, T linux) { + Windows = windows; + Linux = linux; } - - public class WIN_LINUX - { - [JsonPropertyName("Windows")] public T Windows { get; private set; } - - [JsonPropertyName("Linux")] public T Linux { get; private set; } - - public WIN_LINUX(T windows, T linux) - { - Windows = windows; - Linux = linux; - } - - public T Get() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - return Windows; - else - return Linux; - } + + [JsonPropertyName("Windows")] + public T Windows { get; } + + [JsonPropertyName("Linux")] + public T Linux { get; } + + public T Get() { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Windows; + return Linux; } + } } \ No newline at end of file diff --git a/mod/TTT.Player/CreditManager.cs b/mod/TTT.Player/CreditManager.cs index b694b93..2d5c17b 100644 --- a/mod/TTT.Player/CreditManager.cs +++ b/mod/TTT.Player/CreditManager.cs @@ -1,49 +1,40 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using TTT.Public.Behaviors; -using TTT.Public.Extensions; using TTT.Public.Mod.Role; using TTT.Public.Player; namespace TTT.Roles.Shop; -public class CreditManager(IPlayerService playerService) : IPluginBehavior -{ +public class CreditManager(IPlayerService playerService) : IPluginBehavior { + public void Start(BasePlugin plugin) { } - public void Start(BasePlugin plugin) - { - + + [GameEventHandler] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + var attacker = @event.Attacker; + var victim = @event.Userid; + + if (attacker == null || victim == null) return HookResult.Continue; + if (attacker == victim) return HookResult.Continue; + + var attackerPlayer = playerService.GetPlayer(attacker); + var victimPlayer = playerService.GetPlayer(victim); + + if (attackerPlayer.PlayerRole() == Role.Traitor + && victimPlayer.PlayerRole() != Role.Traitor) { + attackerPlayer.AddCredits(250); + return HookResult.Continue; } - - - [GameEventHandler] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var attacker = @event.Attacker; - var victim = @event.Userid; - - if (attacker == null || victim == null) return HookResult.Continue; - if (attacker == victim) return HookResult.Continue; - - var attackerPlayer = playerService.GetPlayer(attacker); - var victimPlayer = playerService.GetPlayer(victim); - - if (attackerPlayer.PlayerRole() == Role.Traitor && victimPlayer.PlayerRole() != Role.Traitor) - { - attackerPlayer.AddCredits(250); - return HookResult.Continue; - } - - if (attackerPlayer.PlayerRole() != Role.Traitor && victimPlayer.PlayerRole() == Role.Traitor) - { - attackerPlayer.AddCredits(250); - return HookResult.Continue; - } - - attackerPlayer.RemoveCredits(100); - - return HookResult.Continue; + + if (attackerPlayer.PlayerRole() != Role.Traitor + && victimPlayer.PlayerRole() == Role.Traitor) { + attackerPlayer.AddCredits(250); + return HookResult.Continue; } - + attackerPlayer.RemoveCredits(100); + + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/TTT.Player/KarmaManager.cs b/mod/TTT.Player/KarmaManager.cs index c5b9517..a58d35e 100644 --- a/mod/TTT.Player/KarmaManager.cs +++ b/mod/TTT.Player/KarmaManager.cs @@ -7,37 +7,29 @@ namespace TTT.Player; -public class KarmaManager(IPlayerService playerService) : IPluginBehavior -{ - public void Start(BasePlugin plugin) - { - - } - - [GameEventHandler] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var killedPlayer = @event.Userid; - var killer = @event.Attacker; - if (killedPlayer == null || !killedPlayer.IsReal()) return HookResult.Continue; - if (killer == null || !killer.IsReal()) return HookResult.Continue; - - var gpKiller = playerService.GetPlayer(killer); - var gpKilled = playerService.GetPlayer(killedPlayer); - - var killerRole = gpKiller.PlayerRole(); - var killedRole = gpKilled.PlayerRole(); +public class KarmaManager(IPlayerService playerService) : IPluginBehavior { + public void Start(BasePlugin plugin) { } + + [GameEventHandler] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + var killedPlayer = @event.Userid; + var killer = @event.Attacker; + if (killedPlayer == null || !killedPlayer.IsReal()) + return HookResult.Continue; + if (killer == null || !killer.IsReal()) return HookResult.Continue; + + var gpKiller = playerService.GetPlayer(killer); + var gpKilled = playerService.GetPlayer(killedPlayer); - if (killerRole == killedRole) - { - gpKiller.RemoveKarma(5); - return HookResult.Continue; - } - - if (killedRole == Role.Traitor) - { - gpKiller.AddKarma(2); - } - return HookResult.Continue; + var killerRole = gpKiller.PlayerRole(); + var killedRole = gpKilled.PlayerRole(); + + if (killerRole == killedRole) { + gpKiller.RemoveKarma(5); + return HookResult.Continue; } -} + + if (killedRole == Role.Traitor) gpKiller.AddKarma(2); + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/TTT.Player/PlayerBehavior.cs b/mod/TTT.Player/PlayerBehavior.cs index 9785918..61a03ee 100644 --- a/mod/TTT.Player/PlayerBehavior.cs +++ b/mod/TTT.Player/PlayerBehavior.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using TTT.Public.Behaviors; using TTT.Public.Mod.Role; @@ -10,82 +7,69 @@ namespace TTT.Player; -public class PlayerBehavior() : IPlayerService, IPluginBehavior -{ - - public void Start(BasePlugin plugin) - { - - } - - [GameEventHandler] - public HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info) - { - if (@event.Userid == null) throw new NullReferenceException("Could not find player object when connecting."); - CreatePlayer(@event.Userid); - return HookResult.Continue; - } - - private readonly Dictionary _players = []; - - public Dictionary GetPlayers() - { - return _players; - } - - public void CreatePlayer(CCSPlayerController player) - { - if (_players.ContainsKey(player)) return; - _players.Add(player, new GamePlayer(Role.Unassigned, 0, 110, player.UserId.Value)); - } - - public void AddKarma(CCSPlayerController player, int karma) - { - if (!_players.TryGetValue(player, out var value)) return; - if (karma < 0) return; - - if (karma + value.Karma() > 110) - value.SetKarma(110); - else - value.AddKarma(karma); - } - - public void RemoveKarma(CCSPlayerController player, int karma) - { - if (!_players.TryGetValue(player, out var value)) return; - if (karma < 0) return; - - if (value.Karma() - karma < 40) - value.SetKarma(40); - else - value.RemoveKarma(karma); - } +public class PlayerBehavior : IPlayerService, IPluginBehavior { + private readonly Dictionary _players = []; - public List Players() - { - return _players.Values.ToList(); - } + public void CreatePlayer(CCSPlayerController player) { + if (_players.ContainsKey(player)) return; + _players.Add(player, + new GamePlayer(Role.Unassigned, 0, 110, player.UserId.Value)); + } - public GamePlayer GetPlayer(CCSPlayerController player) - { - return _players[player]; - } + public void AddKarma(CCSPlayerController player, int karma) { + if (!_players.TryGetValue(player, out var value)) return; + if (karma < 0) return; - public void RemovePlayer(CCSPlayerController player) - { - _players.Remove(player); - } + if (karma + value.Karma() > 110) + value.SetKarma(110); + else + value.AddKarma(karma); + } - public void Clr() - { - foreach (var player in Players()) - { - player.SetKiller(null); - player.SetPlayerRole(Role.Unassigned); - player.ResetCredits(); - player.ModifyKarma(); - player.SetFound(false); - player.SetDead(); - } + public void RemoveKarma(CCSPlayerController player, int karma) { + if (!_players.TryGetValue(player, out var value)) return; + if (karma < 0) return; + + if (value.Karma() - karma < 40) + value.SetKarma(40); + else + value.RemoveKarma(karma); + } + + public List Players() { return _players.Values.ToList(); } + + public GamePlayer GetPlayer(CCSPlayerController player) { + return _players[player]; + } + + public void RemovePlayer(CCSPlayerController player) { + _players.Remove(player); + } + + public void Clr() { + foreach (var player in Players()) { + player.SetKiller(null); + player.SetPlayerRole(Role.Unassigned); + player.ResetCredits(); + player.ModifyKarma(); + player.SetFound(false); + player.SetDead(); } + } + + public void Start(BasePlugin plugin) { } + + [GameEventHandler] + public HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, + GameEventInfo info) { + if (@event.Userid == null) + throw new NullReferenceException( + "Could not find player object when connecting."); + CreatePlayer(@event.Userid); + return HookResult.Continue; + } + + public Dictionary GetPlayers() { + return _players; + } } \ No newline at end of file diff --git a/mod/TTT.Player/PlayerConfig.cs b/mod/TTT.Player/PlayerConfig.cs index 51d41de..fdea2c6 100644 --- a/mod/TTT.Player/PlayerConfig.cs +++ b/mod/TTT.Player/PlayerConfig.cs @@ -1,9 +1,8 @@ namespace TTT.Player; -public class PlayerConfig -{ - public int StartCredits { get; } = 1000; - public int StartKarma { get; } = 80; - public int MaxKarma { get; } = 110; - public int MinKarma { get; } = 40; +public class PlayerConfig { + public int StartCredits { get; } = 1000; + public int StartKarma { get; } = 80; + public int MaxKarma { get; } = 110; + public int MinKarma { get; } = 40; } \ No newline at end of file diff --git a/mod/TTT.Player/PlayerServiceExtension.cs b/mod/TTT.Player/PlayerServiceExtension.cs index 048c288..322892f 100644 --- a/mod/TTT.Player/PlayerServiceExtension.cs +++ b/mod/TTT.Player/PlayerServiceExtension.cs @@ -5,13 +5,11 @@ namespace TTT.Player; -public static class PlayerServiceExtension -{ - public static void AddPlayerService(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } -} +public static class PlayerServiceExtension { + public static void AddPlayerService(this IServiceCollection collection) { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/mod/TTT.Player/TTT.Player.csproj b/mod/TTT.Player/TTT.Player.csproj index ce5ec60..fc5f91b 100644 --- a/mod/TTT.Player/TTT.Player.csproj +++ b/mod/TTT.Player/TTT.Player.csproj @@ -7,7 +7,7 @@ - + - + diff --git a/mod/TTT.Roles/Commands/RolesCommand.cs b/mod/TTT.Roles/Commands/RolesCommand.cs index c396b49..ad15978 100644 --- a/mod/TTT.Roles/Commands/RolesCommand.cs +++ b/mod/TTT.Roles/Commands/RolesCommand.cs @@ -1,12 +1,9 @@ using System.Text; -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; using CounterStrikeSharp.API.Modules.Commands; -using CounterStrikeSharp.API.Modules.Menu; using TTT.Public.Behaviors; -using TTT.Public.Extensions; using TTT.Public.Formatting; using TTT.Public.Mod.Role; using TTT.Public.Mod.Round; @@ -14,49 +11,44 @@ namespace TTT.Roles.Commands; -public class RolesCommand : IPluginBehavior -{ - private readonly IPlayerService _roleService; - private readonly IRoundService _roundService; +public class RolesCommand : IPluginBehavior { + private readonly IPlayerService _roleService; + private readonly IRoundService _roundService; - public RolesCommand(IPlayerService roleService, IRoleService roundService) - { - _roleService = roleService; - _roundService = roundService.GetRoundService(); + public RolesCommand(IPlayerService roleService, IRoleService roundService) { + _roleService = roleService; + _roundService = roundService.GetRoundService(); + } + + public void Start(BasePlugin plugin) { } + + [ConsoleCommand("css_roles", "Get the roles of all players")] + [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] + public void Command_Toggle(CCSPlayerController? player, CommandInfo command) { + if (!AdminManager.PlayerHasPermissions(player, "@css/kick")) { + command.ReplyToCommand( + StringUtils.FormatTTT( + "You do not have permission to execute this command")); + return; } - - public void Start(BasePlugin plugin) - { - + + if (_roundService.GetRoundStatus() != RoundStatus.Started) { + command.ReplyToCommand( + StringUtils.FormatTTT("The round has not started yet.")); + return; } - - [ConsoleCommand("css_roles", "Get the roles of all players")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Toggle(CCSPlayerController? player, CommandInfo command) - { - if (!AdminManager.PlayerHasPermissions(player, "@css/kick")) - { - command.ReplyToCommand(StringUtils.FormatTTT("You do not have permission to execute this command")); - return; - } - - if (_roundService.GetRoundStatus() != RoundStatus.Started) - { - command.ReplyToCommand(StringUtils.FormatTTT("The round has not started yet.")); - return; - } - - StringBuilder sb = new(); - - command.ReplyToCommand(StringUtils.FormatTTT("List of all players roles:")); - - foreach (var gamePlayer in _roleService.Players()) - { - var plr = gamePlayer.Player(); - if (plr == null) continue; - command.ReplyToCommand(StringUtils.FormatTTT(gamePlayer.PlayerRole().FormatStringFullAfter(plr.PlayerName))); - } - - command.ReplyToCommand(StringUtils.FormatTTT("End.")); + + StringBuilder sb = new(); + + command.ReplyToCommand(StringUtils.FormatTTT("List of all players roles:")); + + foreach (var gamePlayer in _roleService.Players()) { + var plr = gamePlayer.Player(); + if (plr == null) continue; + command.ReplyToCommand(StringUtils.FormatTTT(gamePlayer.PlayerRole() + .FormatStringFullAfter(plr.PlayerName))); } + + command.ReplyToCommand(StringUtils.FormatTTT("End.")); + } } \ No newline at end of file diff --git a/mod/TTT.Roles/ModelHandler.cs b/mod/TTT.Roles/ModelHandler.cs index 986e14f..7dc4efd 100644 --- a/mod/TTT.Roles/ModelHandler.cs +++ b/mod/TTT.Roles/ModelHandler.cs @@ -3,36 +3,34 @@ namespace TTT.Roles; -public class ModelHandler -{ - public static readonly string ModelPathCtmHeavy = "characters\\models\\ctm_heavy\\ctm_heavy.vmdl"; - public static readonly string ModelPathCtmSas = "characters\\models\\ctm_sas\\ctm_sas.vmdl"; - public static readonly string ModelPathTmHeavy = "characters\\models\\tm_phoenix_heavy\\tm_phoenix_heavy.vmdl"; - public static readonly string ModelPathTmPhoenix = "characters\\models\\tm_phoenix\\tm_phoenix.vmdl"; - - - - public static void RegisterListener(BasePlugin plugin) - { - plugin.RegisterListener(map => - { - Server.PrecacheModel(ModelPathCtmHeavy); - Server.PrecacheModel(ModelPathCtmSas); - Server.PrecacheModel(ModelPathTmPhoenix); - Server.PrecacheModel(ModelPathTmHeavy); - }); - } - - public static void SetModel(CCSPlayerController player, string modelPath) - { - player.PlayerPawn.Value.SetModel(modelPath); - } - - public static void SetModelNextServerFrame(CCSPlayerController playerPawn, string model) - { - Server.NextFrame(() => - { - SetModel(playerPawn, model); - }); - } +public class ModelHandler { + public static readonly string ModelPathCtmHeavy = + "characters\\models\\ctm_heavy\\ctm_heavy.vmdl"; + + public static readonly string ModelPathCtmSas = + "characters\\models\\ctm_sas\\ctm_sas.vmdl"; + + public static readonly string ModelPathTmHeavy = + "characters\\models\\tm_phoenix_heavy\\tm_phoenix_heavy.vmdl"; + + public static readonly string ModelPathTmPhoenix = + "characters\\models\\tm_phoenix\\tm_phoenix.vmdl"; + + public static void RegisterListener(BasePlugin plugin) { + plugin.RegisterListener(_ => { + Server.PrecacheModel(ModelPathCtmHeavy); + Server.PrecacheModel(ModelPathCtmSas); + Server.PrecacheModel(ModelPathTmPhoenix); + Server.PrecacheModel(ModelPathTmHeavy); + }); + } + + public static void SetModel(CCSPlayerController player, string modelPath) { + player.PlayerPawn.Value.SetModel(modelPath); + } + + public static void SetModelNextServerFrame(CCSPlayerController playerPawn, + string model) { + Server.NextFrame(() => { SetModel(playerPawn, model); }); + } } \ No newline at end of file diff --git a/mod/TTT.Roles/RoleBehavior.cs b/mod/TTT.Roles/RoleBehavior.cs index be4a477..0f5ae4b 100644 --- a/mod/TTT.Roles/RoleBehavior.cs +++ b/mod/TTT.Roles/RoleBehavior.cs @@ -4,7 +4,6 @@ using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Entities.Constants; using CounterStrikeSharp.API.Modules.Utils; -using TTT.Player; using TTT.Public.Behaviors; using TTT.Public.Extensions; using TTT.Public.Formatting; @@ -15,286 +14,269 @@ namespace TTT.Roles; -public class RoleBehavior : IRoleService, IPluginBehavior -{ - private const int MaxDetectives = 3; - - private int _innocentsLeft; - private IRoundService _roundService; - private int _traitorsLeft; - private readonly IPlayerService service; - - public RoleBehavior(IPlayerService playerService) - { - _roundService = new RoundBehavior(this); - service = playerService; +public class RoleBehavior : IRoleService, IPluginBehavior { + private const int MaxDetectives = 3; + private readonly IPlayerService service; + + private int _innocentsLeft; + private readonly IRoundService _roundService; + private int _traitorsLeft; + + public RoleBehavior(IPlayerService playerService) { + _roundService = new RoundBehavior(this); + service = playerService; + } + + public void Start(BasePlugin parent) { + ModelHandler.RegisterListener(parent); + _roundService.Start(parent); + /* + parent.RegisterEventHandler(OnPlayerConnect); + parent.RegisterEventHandler(OnRoundStart); + parent.RegisterEventHandler(OnRoundEnd); + parent.RegisterEventHandler(OnPlayerDisconnect); + parent.RegisterEventHandler(OnPlayerDeath, HookMode.Pre); + parent.RegisterEventHandler(OnMapStart); + */ + } + + public IRoundService GetRoundService() { return _roundService; } + + public void AddRoles() { + var eligible = Utilities.GetPlayers() + .Where(player => player.IsReal()) + .Where(player => player.Team is not (CsTeam.Spectator or CsTeam.None)) + .ToList(); + + var traitorCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 3)); + var detectiveCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 8)); + + _traitorsLeft = traitorCount; + _innocentsLeft = eligible.Count - traitorCount; + + if (detectiveCount > MaxDetectives) detectiveCount = MaxDetectives; + + for (var i = 0; i < traitorCount; i++) { + var chosen = eligible[Random.Shared.Next(eligible.Count)]; + eligible.Remove(chosen); + AddTraitor(chosen); } - - public void Start(BasePlugin parent) - { - ModelHandler.RegisterListener(parent); - _roundService.Start(parent); - /* - parent.RegisterEventHandler(OnPlayerConnect); - parent.RegisterEventHandler(OnRoundStart); - parent.RegisterEventHandler(OnRoundEnd); - parent.RegisterEventHandler(OnPlayerDisconnect); - parent.RegisterEventHandler(OnPlayerDeath, HookMode.Pre); - parent.RegisterEventHandler(OnMapStart); - */ + + for (var i = 0; i < detectiveCount; i++) { + var chosen = eligible[Random.Shared.Next(eligible.Count)]; + eligible.Remove(chosen); + AddDetective(chosen); } - public IRoundService GetRoundService() - { - return _roundService; + AddInnocents(eligible); + } + + public ISet GetTraitors() { + return service.Players() + .Where(player => player.PlayerRole() == Role.Traitor) + .Select(player => player.Player()) + .ToHashSet(); + } + + public ISet GetDetectives() { + return service.Players() + .Where(player => player.PlayerRole() == Role.Detective) + .Select(player => player.Player()) + .ToHashSet(); + } + + public ISet GetInnocents() { + return service.Players() + .Where(player => player.PlayerRole() == Role.Innocent) + .Select(player => player.Player()) + .ToHashSet(); + } + + + public Role GetRole(CCSPlayerController player) { + return service.GetPlayer(player).PlayerRole(); + } + + public void AddTraitor(CCSPlayerController player) { + service.GetPlayer(player).SetPlayerRole(Role.Traitor); + player.SwitchTeam(CsTeam.Terrorist); + player.PrintToCenter( + Role.Traitor.FormatStringFullBefore("You are now a(n)")); + player.PrintToChat(Role.Traitor.FormatStringFullBefore("You are now a(n)")); + ModelHandler.SetModelNextServerFrame(player, + ModelHandler.ModelPathTmPhoenix); + } + + public void AddDetective(CCSPlayerController player) { + service.GetPlayer(player).SetPlayerRole(Role.Detective); + player.SwitchTeam(CsTeam.CounterTerrorist); + player.PrintToCenter( + Role.Detective.FormatStringFullBefore("You are now a(n)")); + player.GiveNamedItem(CsItem.Taser); + ModelHandler.SetModelNextServerFrame(player, ModelHandler.ModelPathCtmSas); + } + + public void AddInnocents(IEnumerable players) { + foreach (var player in players) { + service.GetPlayer(player).SetPlayerRole(Role.Innocent); + player.PrintToCenter( + Role.Innocent.FormatStringFullBefore("You are now an")); + player.SwitchTeam(CsTeam.Terrorist); + ModelHandler.SetModelNextServerFrame(player, + ModelHandler.ModelPathTmPhoenix); } - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundFreezeEnd @event, GameEventInfo info) - { - _roundService.SetRoundStatus(RoundStatus.Waiting); - foreach (var player in Utilities.GetPlayers().Where(player => - player.IsReal() && player.Team != CsTeam.None || player.Team != CsTeam.Spectator)) - { - player.RemoveWeapons(); - if (!string.IsNullOrEmpty("weapon_glock")) - player.GiveNamedItem("weapon_glock"); - - if (!string.IsNullOrEmpty(string.Empty)) - player.GiveNamedItem(string.Empty); - - player.GiveNamedItem("weapon_knife"); - service.GetPlayer(player).ModifyKarma(); - } - - return HookResult.Continue; + } + + public bool IsDetective(CCSPlayerController player) { + return service.GetPlayer(player).PlayerRole() == Role.Detective; + } + + public bool IsTraitor(CCSPlayerController player) { + return service.GetPlayer(player).PlayerRole() == Role.Traitor; + } + + public void Clear() { + service.Clr(); + foreach (var key in service.Players()) { + key.SetPlayerRole(Role.Unassigned); + if (key.Player() == null) continue; + RemoveColor(key.Player()); } - - [GameEventHandler] - public HookResult OnPlayerConnect(EventPlayerConnectFull @event, GameEventInfo info) - { - if (Utilities.GetPlayers().Count(player => - player.IsReal() && player.Team != CsTeam.None || player.Team == CsTeam.Spectator) < 3) - { - _roundService.ForceEnd(); - } - - return HookResult.Continue; + } + + [GameEventHandler] + public HookResult + OnRoundStart(EventRoundFreezeEnd @event, GameEventInfo info) { + _roundService.SetRoundStatus(RoundStatus.Waiting); + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal() && player.Team != CsTeam.None + || player.Team != CsTeam.Spectator)) { + player.RemoveWeapons(); + if (!string.IsNullOrEmpty("weapon_glock")) + player.GiveNamedItem("weapon_glock"); + + if (!string.IsNullOrEmpty(string.Empty)) + player.GiveNamedItem(string.Empty); + + player.GiveNamedItem("weapon_knife"); + service.GetPlayer(player).ModifyKarma(); } - [GameEventHandler(HookMode.Pre)] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - info.DontBroadcast = true; + return HookResult.Continue; + } - var playerWhoWasDamaged = @event.Userid; - var attacker = @event.Attacker; - - - - - if (playerWhoWasDamaged == null) return HookResult.Continue; + [GameEventHandler] + public HookResult OnPlayerConnect(EventPlayerConnectFull @event, + GameEventInfo info) { + if (Utilities.GetPlayers() + .Count(player => player.IsReal() && player.Team != CsTeam.None + || player.Team == CsTeam.Spectator) < 3) + _roundService.ForceEnd(); - SetColor(playerWhoWasDamaged); - - playerWhoWasDamaged.ModifyScoreBoard(); + return HookResult.Continue; + } - service.GetPlayer(playerWhoWasDamaged).SetKiller(attacker); - - if (IsTraitor(playerWhoWasDamaged)) _traitorsLeft--; + [GameEventHandler(HookMode.Pre)] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + info.DontBroadcast = true; - if (IsDetective(playerWhoWasDamaged) || IsInnocent(playerWhoWasDamaged)) _innocentsLeft--; + var playerWhoWasDamaged = @event.Userid; + var attacker = @event.Attacker; - if (_traitorsLeft == 0 || _innocentsLeft == 0) Server.NextFrame(() => _roundService.ForceEnd()); - Server.NextFrame(() => - { - Server.PrintToChatAll( - StringUtils.FormatTTT($"{GetRole(playerWhoWasDamaged).FormatStringFullAfter(" has been found.")}")); + if (playerWhoWasDamaged == null) return HookResult.Continue; - if (attacker == playerWhoWasDamaged || attacker == null) return; + SetColor(playerWhoWasDamaged); - attacker.ModifyScoreBoard(); + playerWhoWasDamaged.ModifyScoreBoard(); - playerWhoWasDamaged.PrintToChat(StringUtils.FormatTTT( - $"You were killed by {GetRole(attacker).FormatStringFullAfter(" " + attacker.PlayerName)}.")); - attacker.PrintToChat(StringUtils.FormatTTT( - $"You killed {GetRole(playerWhoWasDamaged).FormatStringFullAfter(" " + playerWhoWasDamaged.PlayerName)}.")); - }); - - return HookResult.Continue; - } + service.GetPlayer(playerWhoWasDamaged).SetKiller(attacker); - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - var players = Utilities.GetPlayers() - .Where(player => player.IsValid).Where(player => player.IsReal()).ToList(); + if (IsTraitor(playerWhoWasDamaged)) _traitorsLeft--; - foreach (var player in players) player.PrintToCenter(GetWinner().FormatStringFullAfter("s has won!")); + if (IsDetective(playerWhoWasDamaged) || IsInnocent(playerWhoWasDamaged)) + _innocentsLeft--; - Server.NextFrame(Clear); + if (_traitorsLeft == 0 || _innocentsLeft == 0) + Server.NextFrame(() => _roundService.ForceEnd()); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) - { - var player = @event.Userid; - Server.NextFrame(() => - { - service.RemovePlayer(player); - if (service.Players().Count == 0) _roundService.SetRoundStatus(RoundStatus.Paused); - }); - - return HookResult.Continue; - } + Server.NextFrame(() => { + Server.PrintToChatAll(StringUtils.FormatTTT( + $"{GetRole(playerWhoWasDamaged).FormatStringFullAfter(" has been found.")}")); - public void AddRoles() - { - var eligible = Utilities.GetPlayers() - .Where(player => player.IsReal()) - .Where(player => player.Team is not (CsTeam.Spectator or CsTeam.None)) - .ToList(); + if (attacker == playerWhoWasDamaged || attacker == null) return; - var traitorCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 3)); - var detectiveCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 8)); + attacker.ModifyScoreBoard(); - _traitorsLeft = traitorCount; - _innocentsLeft = eligible.Count - traitorCount; + playerWhoWasDamaged.PrintToChat(StringUtils.FormatTTT( + $"You were killed by {GetRole(attacker).FormatStringFullAfter(" " + attacker.PlayerName)}.")); + attacker.PrintToChat(StringUtils.FormatTTT( + $"You killed {GetRole(playerWhoWasDamaged).FormatStringFullAfter(" " + playerWhoWasDamaged.PlayerName)}.")); + }); - if (detectiveCount > MaxDetectives) detectiveCount = MaxDetectives; - - for (var i = 0; i < traitorCount; i++) - { - var chosen = eligible[Random.Shared.Next(eligible.Count)]; - eligible.Remove(chosen); - AddTraitor(chosen); - } - - for (var i = 0; i < detectiveCount; i++) - { - var chosen = eligible[Random.Shared.Next(eligible.Count)]; - eligible.Remove(chosen); - AddDetective(chosen); - } - - AddInnocents(eligible); - } - - public ISet GetTraitors() - { - return service.Players().Where(player => player.PlayerRole() == Role.Traitor).Select(player => player.Player()) - .ToHashSet(); - } + return HookResult.Continue; + } - public ISet GetDetectives() - { - return service.Players().Where(player => player.PlayerRole() == Role.Detective).Select(player => player.Player()) - .ToHashSet(); - } + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { + var players = Utilities.GetPlayers() + .Where(player => player.IsValid) + .Where(player => player.IsReal()) + .ToList(); - public ISet GetInnocents() - { - return service.Players().Where(player => player.PlayerRole() == Role.Innocent).Select(player => player.Player()) - .ToHashSet(); - } + foreach (var player in players) + player.PrintToCenter(GetWinner().FormatStringFullAfter("s has won!")); + Server.NextFrame(Clear); - public Role GetRole(CCSPlayerController player) - { - return service.GetPlayer(player).PlayerRole(); - } + return HookResult.Continue; + } - public void AddTraitor(CCSPlayerController player) - { - service.GetPlayer(player).SetPlayerRole(Role.Traitor); - player.SwitchTeam(CsTeam.Terrorist); - player.PrintToCenter(Role.Traitor.FormatStringFullBefore("You are now a(n)")); - player.PrintToChat(Role.Traitor.FormatStringFullBefore("You are now a(n)")); - ModelHandler.SetModelNextServerFrame(player, ModelHandler.ModelPathTmPhoenix); - } + [GameEventHandler] + public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, + GameEventInfo info) { + var player = @event.Userid; + Server.NextFrame(() => { + service.RemovePlayer(player); + if (service.Players().Count == 0) + _roundService.SetRoundStatus(RoundStatus.Paused); + }); - public void AddDetective(CCSPlayerController player) - { - service.GetPlayer(player).SetPlayerRole(Role.Detective); - player.SwitchTeam(CsTeam.CounterTerrorist); - player.PrintToCenter(Role.Detective.FormatStringFullBefore("You are now a(n)")); - player.GiveNamedItem(CsItem.Taser); - ModelHandler.SetModelNextServerFrame(player, ModelHandler.ModelPathCtmSas); - } + return HookResult.Continue; + } - public void AddInnocents(IEnumerable players) - { - foreach (var player in players) - { - service.GetPlayer(player).SetPlayerRole(Role.Innocent); - player.PrintToCenter(Role.Innocent.FormatStringFullBefore("You are now an")); - player.SwitchTeam(CsTeam.Terrorist); - ModelHandler.SetModelNextServerFrame(player, ModelHandler.ModelPathTmPhoenix); - } - } + public bool IsInnocent(CCSPlayerController player) { + return service.GetPlayer(player).PlayerRole() == Role.Innocent; + } - public bool IsDetective(CCSPlayerController player) - { - return service.GetPlayer(player).PlayerRole() == Role.Detective; - } + private Role GetWinner() { + return _traitorsLeft == 0 ? Role.Traitor : Role.Innocent; + } - public bool IsTraitor(CCSPlayerController player) - { - return service.GetPlayer(player).PlayerRole() == Role.Traitor; - } + public void SetColor(CCSPlayerController player) { + if (!player.IsReal()) return; - public void Clear() - { - service.Clr(); - foreach (var key in service.Players()) - { - key.SetPlayerRole(Role.Unassigned); - if (key.Player() == null) continue; - RemoveColor(key.Player()); - } - } + var pawn = player.PlayerPawn.Value; - public bool IsInnocent(CCSPlayerController player) - { - return service.GetPlayer(player).PlayerRole() == Role.Innocent; - } + if (pawn == null || !pawn.IsValid) return; - private Role GetWinner() - { - return _traitorsLeft == 0 ? Role.Traitor : Role.Innocent; - } + pawn.RenderMode = RenderMode_t.kRenderTransColor; + pawn.Render = GetRole(player).GetColor(); - public void SetColor(CCSPlayerController player) - { - if (!player.IsReal()) return; + Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); + } - var pawn = player.PlayerPawn.Value; - - if (pawn == null || !pawn.IsValid) return; + public void RemoveColor(CCSPlayerController player) { + if (!player.IsReal()) return; - pawn.RenderMode = RenderMode_t.kRenderTransColor; - pawn.Render = GetRole(player).GetColor(); - - Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); - } - - public void RemoveColor(CCSPlayerController player) - { - if (!player.IsReal()) return; + var pawn = player.PlayerPawn.Value; - var pawn = player.PlayerPawn.Value; - - if (pawn == null || !pawn.IsValid) return; + if (pawn == null || !pawn.IsValid) return; - pawn.RenderMode = RenderMode_t.kRenderTransColor; - pawn.Render = Color.FromArgb(254, 255, 255, 255); + pawn.RenderMode = RenderMode_t.kRenderTransColor; + pawn.Render = Color.FromArgb(254, 255, 255, 255); - - Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); - - } -} + Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); + } +} \ No newline at end of file diff --git a/mod/TTT.Roles/RoleConfig.cs b/mod/TTT.Roles/RoleConfig.cs index 74619c4..f367211 100644 --- a/mod/TTT.Roles/RoleConfig.cs +++ b/mod/TTT.Roles/RoleConfig.cs @@ -1,10 +1,8 @@ namespace TTT.Roles; -public class RoleConfig -{ - public int TraitorRatio { get; } = 3; - public int DetectiveRatio { get; } = 8; - public string? SecondaryWeapon { get; } = "weapon_glock"; - public string? PrimaryWeapon { get; } = ""; - +public class RoleConfig { + public int TraitorRatio { get; } = 3; + public int DetectiveRatio { get; } = 8; + public string? SecondaryWeapon { get; } = "weapon_glock"; + public string? PrimaryWeapon { get; } = ""; } \ No newline at end of file diff --git a/mod/TTT.Roles/RoleServiceExtension.cs b/mod/TTT.Roles/RoleServiceExtension.cs index af20a73..4bbd158 100644 --- a/mod/TTT.Roles/RoleServiceExtension.cs +++ b/mod/TTT.Roles/RoleServiceExtension.cs @@ -5,11 +5,9 @@ namespace TTT.Roles; -public static class RoleServiceExtension -{ - public static void AddTTTRoles(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } +public static class RoleServiceExtension { + public static void AddTTTRoles(this IServiceCollection collection) { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/TTT.Roles/RoleTester.cs b/mod/TTT.Roles/RoleTester.cs index 489cca3..3f3c06d 100644 --- a/mod/TTT.Roles/RoleTester.cs +++ b/mod/TTT.Roles/RoleTester.cs @@ -1,22 +1,30 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Modules.Cvars; +using CounterStrikeSharp.API.Modules.Cvars; namespace TTT.Roles; -public class RoleTester -{ - private readonly FakeConVar _traitorTesterBlockTester = new("traitor_tester_block_tester", - "For how long tester button should be disabled after using it. 0 to not block it."); - private readonly FakeConVar _traitorTesterBlockTesterTime = new("traitor_tester_block_tester_time", - "Determinate for how long tester button should be disabled. 0 to disable tester block.", 3); - private readonly FakeConVar _traitorTesterBlockTesterMessage = new("traitor_tester_block_tester_message", - "If 1 print to client info about tester cooldown. 0 to disable."); - private readonly FakeConVar _traitorTesterLightTime = new("traitor_tester_light_time", - "For how long the lights should be shown. Min value is 3 seconds.", 3); - private readonly FakeConVar _traitorTesterLightDelayTime = new("traitor_tester_light_delay_time", - "Determinate if the lights should be shown right away or after few secodns. 0 to disable."); - private readonly FakeConVar _traitorTesterMaxPlayers = new("traitor_tester_max_players", - "Determinate how many players can be checked at one. 0 to disable it."); - - +public class RoleTester { + private readonly FakeConVar _traitorTesterBlockTester = + new("traitor_tester_block_tester", + "For how long tester button should be disabled after using it. 0 to not block it."); + + private readonly FakeConVar _traitorTesterBlockTesterMessage = + new("traitor_tester_block_tester_message", + "If 1 print to client info about tester cooldown. 0 to disable."); + + private readonly FakeConVar _traitorTesterBlockTesterTime = + new("traitor_tester_block_tester_time", + "Determinate for how long tester button should be disabled. 0 to disable tester block.", + 3); + + private readonly FakeConVar _traitorTesterLightDelayTime = + new("traitor_tester_light_delay_time", + "Determinate if the lights should be shown right away or after few secodns. 0 to disable."); + + private readonly FakeConVar _traitorTesterLightTime = + new("traitor_tester_light_time", + "For how long the lights should be shown. Min value is 3 seconds.", 3); + + private readonly FakeConVar _traitorTesterMaxPlayers = + new("traitor_tester_max_players", + "Determinate how many players can be checked at one. 0 to disable it."); } \ No newline at end of file diff --git a/mod/TTT.Roles/TTT.Roles.csproj b/mod/TTT.Roles/TTT.Roles.csproj index dfd9e59..0d7766e 100644 --- a/mod/TTT.Roles/TTT.Roles.csproj +++ b/mod/TTT.Roles/TTT.Roles.csproj @@ -1,14 +1,14 @@  - - net8.0 - enable - enable - TTT.Roles - - - - - + + net8.0 + enable + enable + TTT.Roles + + + + + - + \ No newline at end of file diff --git a/mod/TTT.Roles/TraitorRoom.cs b/mod/TTT.Roles/TraitorRoom.cs index 2da0707..718c8a0 100644 --- a/mod/TTT.Roles/TraitorRoom.cs +++ b/mod/TTT.Roles/TraitorRoom.cs @@ -1,8 +1,3 @@ -using CounterStrikeSharp.API.Core; +namespace TTT.Roles; -namespace TTT.Roles; - -public class TraitorRoom -{ - -} \ No newline at end of file +public class TraitorRoom { } \ No newline at end of file diff --git a/mod/TTT.Round/Round.cs b/mod/TTT.Round/Round.cs index be705f7..d577c37 100644 --- a/mod/TTT.Round/Round.cs +++ b/mod/TTT.Round/Round.cs @@ -1,106 +1,99 @@ using System.Drawing; -using System.Text; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Modules.Utils; -using TTT.Public.Configuration; using TTT.Public.Extensions; -using TTT.Public.Mod.Role; using TTT.Public.Formatting; +using TTT.Public.Mod.Role; namespace TTT.Round; -public class Round -{ - private readonly IRoleService _roleService; - private readonly RoundConfig? _config; - private float _graceTime = 20 * 64; - private readonly int _roundId; +public class Round { + private readonly RoundConfig? _config; + private readonly IRoleService _roleService; + private readonly int _roundId; + private float _graceTime = 20 * 64; - public Round(IRoleService roleService, RoundConfig? config, int roundId) - { - _roleService = roleService; - _config = config; - _graceTime = 20 * 64; - _roundId = roundId; - } + public Round(IRoleService roleService, RoundConfig? config, int roundId) { + _roleService = roleService; + _config = config; + _graceTime = 20 * 64; + _roundId = roundId; + } - public void Tick() - { - _graceTime--; - - var players = Utilities.GetPlayers() - .Where(player => player.IsValid) - .Where(player => player.IsReal()) - .ToList(); - - var formattedColor = $""; - - foreach (var player in players) - { - Server.NextFrame(() => - { - player.PrintToCenterHtml( - $"{formattedColor}[TTT] Game is starting in {Math.Floor(_graceTime / 64)} seconds"); - }); - } - } + public void Tick() { + _graceTime--; - public float GraceTime() - { - return _graceTime; - } + var players = Utilities.GetPlayers() + .Where(player => player.IsValid) + .Where(player => player.IsReal()) + .ToList(); - public void Start() - { - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal()).Where(player => !player.PawnIsAlive).Where(player => player.Team is CsTeam.Terrorist or CsTeam.CounterTerrorist)) - { - player.Respawn(); - } - - _roleService.AddRoles(); - Server.NextFrame(() => Server.PrintToChatAll(StringUtils.FormatTTT($"Round #{_roundId} has started! {_roleService.GetTraitors().Count} traitors."))); - SendTraitorMessage(); - SendDetectiveMessage(); - SendInnocentMessage(); - } + var formattedColor = + $""; - private void SendInnocentMessage() - { - foreach (var player in _roleService.GetInnocents()) - { - Server.NextFrame(() => player.PrintToChat(StringUtils.FormatTTT("You are now an innocent"))); - } - } - - private void SendTraitorMessage() - { - var traitors = _roleService.GetTraitors(); - - foreach (var traitor in traitors) - { - Server.NextFrame(() => traitor.PrintToChat(StringUtils.FormatTTT("You are a Traitor"))); - Server.NextFrame(() => traitor.PrintToChat(StringUtils.FormatTTT("Traitors:"))); - foreach (var player in traitors) - { - var message = StringUtils.FormatTTT(Role.Traitor.FormatStringFullAfter(player.PlayerName)); - Server.NextFrame(() => traitor.PrintToChat(message)); - } - } + foreach (var player in players) + Server.NextFrame(() => { + player.PrintToCenterHtml( + $"{formattedColor}[TTT] Game is starting in {Math.Floor(_graceTime / 64)} seconds"); + }); + } + + public float GraceTime() { return _graceTime; } + + public void Start() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal()) + .Where(player => !player.PawnIsAlive) + .Where(player + => player.Team is CsTeam.Terrorist or CsTeam.CounterTerrorist)) + player.Respawn(); + + _roleService.AddRoles(); + Server.NextFrame(() + => Server.PrintToChatAll(StringUtils.FormatTTT( + $"Round #{_roundId} has started! {_roleService.GetTraitors().Count} traitors."))); + SendTraitorMessage(); + SendDetectiveMessage(); + SendInnocentMessage(); + } + + private void SendInnocentMessage() { + foreach (var player in _roleService.GetInnocents()) + Server.NextFrame(() + => player.PrintToChat( + StringUtils.FormatTTT("You are now an innocent"))); + } + + private void SendTraitorMessage() { + var traitors = _roleService.GetTraitors(); + + foreach (var traitor in traitors) { + Server.NextFrame(() + => traitor.PrintToChat(StringUtils.FormatTTT("You are a Traitor"))); + Server.NextFrame(() + => traitor.PrintToChat(StringUtils.FormatTTT("Traitors:"))); + foreach (var player in traitors) { + var message = + StringUtils.FormatTTT( + Role.Traitor.FormatStringFullAfter(player.PlayerName)); + Server.NextFrame(() => traitor.PrintToChat(message)); + } } + } + + private void SendDetectiveMessage() { + var detectives = _roleService.GetDetectives(); - private void SendDetectiveMessage() - { - var detectives = _roleService.GetDetectives(); - - foreach (var detective in detectives) - { - Server.NextFrame(() => detective.PrintToChat(StringUtils.FormatTTT("You are a Detective"))); - Server.NextFrame(() => detective.PrintToChat(StringUtils.FormatTTT("Detective:"))); - foreach (var player in detectives) - { - var message = StringUtils.FormatTTT(Role.Detective.FormatStringFullAfter(" " + player.PlayerName)); - Server.NextFrame(() => detective.PrintToChat(message)); - } - } + foreach (var detective in detectives) { + Server.NextFrame(() + => detective.PrintToChat(StringUtils.FormatTTT("You are a Detective"))); + Server.NextFrame(() + => detective.PrintToChat(StringUtils.FormatTTT("Detective:"))); + foreach (var player in detectives) { + var message = StringUtils.FormatTTT( + Role.Detective.FormatStringFullAfter(" " + player.PlayerName)); + Server.NextFrame(() => detective.PrintToChat(message)); + } } -} + } +} \ No newline at end of file diff --git a/mod/TTT.Round/RoundBehavior.cs b/mod/TTT.Round/RoundBehavior.cs index a227f9d..594819e 100644 --- a/mod/TTT.Round/RoundBehavior.cs +++ b/mod/TTT.Round/RoundBehavior.cs @@ -5,137 +5,134 @@ using CounterStrikeSharp.API.Modules.Memory; using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; using CounterStrikeSharp.API.Modules.Timers; -using TTT.Public.Action; -using TTT.Public.Behaviors; using TTT.Public.Extensions; using TTT.Public.Formatting; -using TTT.Public.Mod.Logs; using TTT.Public.Mod.Role; using TTT.Public.Mod.Round; -using TTT.Public.Player; namespace TTT.Round; -public class RoundBehavior(IRoleService _roleService) : IRoundService -{ - private Round? _round; - private RoundStatus _roundStatus = RoundStatus.Paused; - private int _roundId = 1; - - public void Start(BasePlugin plugin) - { - plugin.RegisterListener(TickWaiting); - plugin.AddCommandListener("jointeam", OnTeamJoin); - VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(BlockDamage, HookMode.Pre); - plugin.AddTimer(3, EndRound, TimerFlags.REPEAT); +public class RoundBehavior(IRoleService _roleService) : IRoundService { + private Round? _round; + private int _roundId = 1; + private RoundStatus _roundStatus = RoundStatus.Paused; + + public void Start(BasePlugin plugin) { + plugin.RegisterListener(TickWaiting); + plugin.AddCommandListener("jointeam", OnTeamJoin); + VirtualFunctions.CBaseEntity_TakeDamageOldFunc.Hook(BlockDamage, + HookMode.Pre); + plugin.AddTimer(3, EndRound, TimerFlags.REPEAT); + } + + public RoundStatus GetRoundStatus() { return _roundStatus; } + + public void SetRoundStatus(RoundStatus roundStatus) { + switch (roundStatus) { + case RoundStatus.Ended: + ForceEnd(); + break; + case RoundStatus.Waiting: + _round = new Round(_roleService, null, _roundId); + break; + case RoundStatus.Started: + ForceStart(); + break; + case RoundStatus.Paused: + break; + default: + throw new ArgumentOutOfRangeException(nameof(roundStatus), roundStatus, + "Invalid round status."); } - public RoundStatus GetRoundStatus() - { - return _roundStatus; - } + _roundStatus = roundStatus; + } - public void SetRoundStatus(RoundStatus roundStatus) - { - switch (roundStatus) - { - case RoundStatus.Ended: - ForceEnd(); - break; - case RoundStatus.Waiting: - _round = new Round(_roleService, null, _roundId); - break; - case RoundStatus.Started: - ForceStart(); - break; - case RoundStatus.Paused: - break; - default: - throw new ArgumentOutOfRangeException(nameof(roundStatus), roundStatus, "Invalid round status."); - } - _roundStatus = roundStatus; + public void TickWaiting() { + if (_round == null) { + _round = new Round(_roleService, null, _roundId); + return; } - public void TickWaiting() - { - if (_round == null) - { - _round = new Round(_roleService, null, _roundId); - return; - } - - if (_roundStatus != RoundStatus.Waiting) return; - - _round.Tick(); - - if (_round.GraceTime() != 0) return; - - - if (Utilities.GetPlayers().Where(player => player is { IsValid: true, PawnIsAlive: true }).ToList().Count <= 2) - { - Server.PrintToChatAll(StringUtils.FormatTTT("Not enough players to start the round. Round has been ended.")); - _roundStatus = RoundStatus.Paused; - return; - } - - SetRoundStatus(RoundStatus.Started); - - } + if (_roundStatus != RoundStatus.Waiting) return; - public void ForceStart() - { - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal()).Where(player => player.IsReal()) - .ToList()) player.VoiceFlags = VoiceFlags.Normal; - _round!.Start(); - ServerExtensions.GetGameRules().RoundTime = 360; - Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), "CCSGameRulesProxy", "m_pGameRules"); - } + _round.Tick(); - public void ForceEnd() - { - if (_roundStatus == RoundStatus.Ended) return; - _roundStatus = RoundStatus.Ended; - Utilities.FindAllEntitiesByDesignerName("cs_gamerules").First().GameRules!.TerminateRound(5, - RoundEndReason.RoundDraw); - } + if (_round.GraceTime() != 0) return; - private void EndRound() - { - if (_roundStatus == RoundStatus.Started && Utilities.GetPlayers().Count(player => player.PawnIsAlive) == 1) - { - ForceEnd(); - } - - var traitorCount = _roleService.GetTraitors().Count(player => player.PawnIsAlive); - var innocentCount = _roleService.GetInnocents().Count(player => player.PawnIsAlive); - var detectiveCount = _roleService.GetDetectives().Count(player => player.PawnIsAlive); - - if (_roundStatus == RoundStatus.Started && (traitorCount == 0 || innocentCount + detectiveCount == 0)) - { - ForceEnd(); - } - } - private HookResult BlockDamage(DynamicHook hook) - { - if (hook.GetParam(0).DesignerName is not "player") return HookResult.Continue; - return _roundStatus != RoundStatus.Waiting ? HookResult.Continue : HookResult.Stop; + if (Utilities.GetPlayers() + .Where(player => player is { IsValid: true, PawnIsAlive: true }) + .ToList() + .Count <= 2) { + Server.PrintToChatAll(StringUtils.FormatTTT( + "Not enough players to start the round. Round has been ended.")); + _roundStatus = RoundStatus.Paused; + return; } - private HookResult OnTeamJoin(CCSPlayerController? executor, CommandInfo info) - { - if (_roundStatus != RoundStatus.Started) return HookResult.Continue; - if (executor == null) return HookResult.Continue; - if (!executor.IsReal()) return HookResult.Continue; - if (_roleService.GetRole(executor) != Role.Unassigned) return HookResult.Continue; - Server.NextFrame(() => executor.CommitSuicide(false, true)); - - return HookResult.Continue; - } - - private HookResult OnRoundEnd(EventRoundEnd _, GameEventInfo __) - { - _roundId++; - return HookResult.Continue; - } -} + SetRoundStatus(RoundStatus.Started); + } + + public void ForceStart() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal()) + .Where(player => player.IsReal()) + .ToList()) + player.VoiceFlags = VoiceFlags.Normal; + _round!.Start(); + ServerExtensions.GetGameRules().RoundTime = 360; + Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), + "CCSGameRulesProxy", "m_pGameRules"); + } + + public void ForceEnd() { + if (_roundStatus == RoundStatus.Ended) return; + _roundStatus = RoundStatus.Ended; + Utilities.FindAllEntitiesByDesignerName("cs_gamerules") + .First() + .GameRules!.TerminateRound(5, RoundEndReason.RoundDraw); + } + + private void EndRound() { + if (_roundStatus == RoundStatus.Started + && Utilities.GetPlayers().Count(player => player.PawnIsAlive) == 1) + ForceEnd(); + + var traitorCount = + _roleService.GetTraitors().Count(player => player.PawnIsAlive); + var innocentCount = + _roleService.GetInnocents().Count(player => player.PawnIsAlive); + var detectiveCount = _roleService.GetDetectives() + .Count(player => player.PawnIsAlive); + + if (_roundStatus == RoundStatus.Started + && (traitorCount == 0 || innocentCount + detectiveCount == 0)) + ForceEnd(); + } + + private HookResult BlockDamage(DynamicHook hook) { + if (hook.GetParam(0).DesignerName is not "player") + return HookResult.Continue; + return _roundStatus != RoundStatus.Waiting ? + HookResult.Continue : + HookResult.Stop; + } + + private HookResult + OnTeamJoin(CCSPlayerController? executor, CommandInfo info) { + if (_roundStatus != RoundStatus.Started) return HookResult.Continue; + if (executor == null) return HookResult.Continue; + if (!executor.IsReal()) return HookResult.Continue; + if (_roleService.GetRole(executor) != Role.Unassigned) + return HookResult.Continue; + Server.NextFrame(() => executor.CommitSuicide(false, true)); + + return HookResult.Continue; + } + + private HookResult OnRoundEnd(EventRoundEnd _, GameEventInfo __) { + _roundId++; + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/TTT.Round/RoundConfig.cs b/mod/TTT.Round/RoundConfig.cs index a8e77f6..a229469 100644 --- a/mod/TTT.Round/RoundConfig.cs +++ b/mod/TTT.Round/RoundConfig.cs @@ -1,7 +1,6 @@ namespace TTT.Round; -public class RoundConfig -{ - public int GracePeriod { get; } = 20; - public int RoundTime { get; } = 360; +public class RoundConfig { + public int GracePeriod { get; } = 20; + public int RoundTime { get; } = 360; } \ No newline at end of file diff --git a/mod/TTT.Round/RoundServiceExtension.cs b/mod/TTT.Round/RoundServiceExtension.cs index b41b37b..588fedb 100644 --- a/mod/TTT.Round/RoundServiceExtension.cs +++ b/mod/TTT.Round/RoundServiceExtension.cs @@ -1,12 +1,7 @@ using Microsoft.Extensions.DependencyInjection; -using TTT.Public.Extensions; -using TTT.Public.Mod.Round; namespace TTT.Round; -public static class RoundServiceExtension -{ - public static void AddRoundService(this IServiceCollection collection) - { - } +public static class RoundServiceExtension { + public static void AddRoundService(this IServiceCollection collection) { } } \ No newline at end of file diff --git a/mod/TTT.Round/TTT.Round.csproj b/mod/TTT.Round/TTT.Round.csproj index 33298b6..f28455f 100644 --- a/mod/TTT.Round/TTT.Round.csproj +++ b/mod/TTT.Round/TTT.Round.csproj @@ -1,10 +1,10 @@  - - net8.0 - enable - enable - - - - + + net8.0 + enable + enable + + + + \ No newline at end of file diff --git a/mod/TTT.Shop/TTT.Shop.csproj b/mod/TTT.Shop/TTT.Shop.csproj index 31fb7ca..a056d1b 100644 --- a/mod/TTT.Shop/TTT.Shop.csproj +++ b/mod/TTT.Shop/TTT.Shop.csproj @@ -6,9 +6,9 @@ enable TTT.Shop - + - + diff --git a/public/TTT.Formatting/Base/IView.cs b/public/TTT.Formatting/Base/IView.cs index 2d15db0..e5bd4f7 100644 --- a/public/TTT.Formatting/Base/IView.cs +++ b/public/TTT.Formatting/Base/IView.cs @@ -2,7 +2,6 @@ namespace TTT.Formatting.Base; -public interface IView -{ - void Render(FormatWriter writer); +public interface IView { + void Render(FormatWriter writer); } \ No newline at end of file diff --git a/public/TTT.Formatting/Base/SimpleView.cs b/public/TTT.Formatting/Base/SimpleView.cs index b3382f8..28a8fae 100644 --- a/public/TTT.Formatting/Base/SimpleView.cs +++ b/public/TTT.Formatting/Base/SimpleView.cs @@ -1,70 +1,49 @@ using System.Collections; - using TTT.Formatting.Core; namespace TTT.Formatting.Base; -public class SimpleView : IView, IEnumerable> -{ - public struct Newline - { - - } - - public static Newline NEWLINE = new Newline(); - - private List> _lines = new(); +public class SimpleView : IView, IEnumerable> { + public static Newline NEWLINE = new(); - public SimpleView() - { + private readonly List> _lines = new(); - } + public IEnumerator> GetEnumerator() { + return _lines.GetEnumerator(); + } - /// - /// Add an item to the end of the last row in this SimpleView - /// Eg, { abc, 123, weee } is all one row - /// - /// - public void Add(FormatObject item) - { - if (_lines.Count == 0) - _lines.Add(new List()); + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - _lines[_lines.Count - 1].Add(item); - } + public void Render(FormatWriter writer) { + foreach (var formatObjects in _lines) writer.Line(formatObjects.ToArray()); + } - /// - /// Add multiple items at a time to this SimpleView - /// - /// - public void Add(params FormatObject[] line) - { - if (_lines.Count == 0) - _lines.Add(new List()); + /// + /// Add an item to the end of the last row in this SimpleView + /// Eg, { abc, 123, weee } is all one row + /// + /// + public void Add(FormatObject item) { + if (_lines.Count == 0) _lines.Add(new List()); - _lines[_lines.Count - 1].AddRange(line); - } + _lines[_lines.Count - 1].Add(item); + } - /// - /// Add a new line to this SimpleView - /// - /// - public void Add(Newline newline) - { - _lines.Add(new List()); - } + /// + /// Add multiple items at a time to this SimpleView + /// + /// + public void Add(params FormatObject[] line) { + if (_lines.Count == 0) _lines.Add(new List()); - public void Render(FormatWriter writer) - { - foreach (var formatObjects in _lines) - writer.Line(formatObjects.ToArray()); - } + _lines[_lines.Count - 1].AddRange(line); + } - public IEnumerator> GetEnumerator() - => _lines.GetEnumerator(); + /// + /// Add a new line to this SimpleView + /// + /// + public void Add(Newline newline) { _lines.Add(new List()); } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } -} + public struct Newline { } +} \ No newline at end of file diff --git a/public/TTT.Formatting/Core/FormatObject.cs b/public/TTT.Formatting/Core/FormatObject.cs index 956333d..d39b5c0 100644 --- a/public/TTT.Formatting/Core/FormatObject.cs +++ b/public/TTT.Formatting/Core/FormatObject.cs @@ -4,53 +4,41 @@ namespace TTT.Formatting.Core; -public abstract class FormatObject -{ +public abstract class FormatObject { /// - /// Output this format object compatible with CS2 chat formatting. + /// Output this format object compatible with CS2 chat formatting. /// /// - public virtual string ToChat() - { - return ToPlain(); - } + public virtual string ToChat() { return ToPlain(); } /// - /// Output this format object in a panorama-compatible format. + /// Output this format object in a panorama-compatible format. /// /// - public virtual string ToPanorama() - { - return ToPlain().Sanitize(); - } + public virtual string ToPanorama() { return ToPlain().Sanitize(); } /// - /// Output plaintext + /// Output plaintext /// /// public abstract string ToPlain(); - public static implicit operator FormatObject(string value) - { - return new StringFormatObject(value); - } + public static implicit operator FormatObject(string value) { + return new StringFormatObject(value); + } - public static implicit operator FormatObject(CCSPlayerController value) - { - return new PlayerFormatObject(value); - } + public static implicit operator FormatObject(CCSPlayerController value) { + return new PlayerFormatObject(value); + } - public static implicit operator FormatObject(int value) - { - return new IntegerFormatObject(value); - } + public static implicit operator FormatObject(int value) { + return new IntegerFormatObject(value); + } - public static FormatObject FromObject(object value) - { - return new StringFormatObject(value.ToString() ?? "null"); - } + public static FormatObject FromObject(object value) { + return new StringFormatObject(value.ToString() ?? "null"); + } - public override string ToString() - => ToPlain(); -} + public override string ToString() { return ToPlain(); } +} \ No newline at end of file diff --git a/public/TTT.Formatting/Core/FormatWriter.cs b/public/TTT.Formatting/Core/FormatWriter.cs index 78f66d7..d4034c4 100644 --- a/public/TTT.Formatting/Core/FormatWriter.cs +++ b/public/TTT.Formatting/Core/FormatWriter.cs @@ -1,25 +1,26 @@ namespace TTT.Formatting.Core; -public class FormatWriter -{ - private readonly List _lines = new(); +public class FormatWriter { + private readonly List _lines = new(); - public IEnumerable Lines => _lines; + public IEnumerable Lines => _lines; - public IEnumerable Chat - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToChat()))); + public IEnumerable Chat + => Lines.Select( + array => string.Join(' ', array.Select(obj => obj.ToChat()))); - public IEnumerable Panorama - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToPanorama()))); + public IEnumerable Panorama + => Lines.Select(array + => string.Join(' ', array.Select(obj => obj.ToPanorama()))); - public IEnumerable Plain - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToPlain()))); + public IEnumerable Plain + => Lines.Select(array + => string.Join(' ', array.Select(obj => obj.ToPlain()))); - public FormatWriter Line(params FormatObject[] args) - { - _lines.Add(args); + public FormatWriter Line(params FormatObject[] args) { + _lines.Add(args); - return this; - } + return this; + } } \ No newline at end of file diff --git a/public/TTT.Formatting/Extensions/ViewExtensions.cs b/public/TTT.Formatting/Extensions/ViewExtensions.cs index f03bfb6..8d17538 100644 --- a/public/TTT.Formatting/Extensions/ViewExtensions.cs +++ b/public/TTT.Formatting/Extensions/ViewExtensions.cs @@ -1,110 +1,93 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; - using TTT.Formatting.Base; using TTT.Formatting.Core; using TTT.Public.Extensions; namespace TTT.Formatting.Extensions; -public static class ViewExtensions -{ - - public static FormatWriter ToWriter(this IView view) - { - var writer = new FormatWriter(); +public static class ViewExtensions { + public static FormatWriter ToWriter(this IView view) { + var writer = new FormatWriter(); - view.Render(writer); + view.Render(writer); - return writer; - } + return writer; + } - public static IView ToServerConsole(this IView view) - { - var writer = view.ToWriter(); + public static IView ToServerConsole(this IView view) { + var writer = view.ToWriter(); - foreach (string s in writer.Plain) - { - Server.PrintToConsole(s); - } + foreach (var s in writer.Plain) Server.PrintToConsole(s); - return view; - } + return view; + } - #region Individual + public static IView ToAllConsole(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); - public static IView ToPlayerConsole(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + return view; + } - var writer = view.ToWriter(); + public static IView ToAllChat(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); - foreach (var writerLine in writer.Plain) - player.PrintToConsole(writerLine); + return view; + } - return view; - } + public static IView ToAllCenter(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); - public static IView ToPlayerChat(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + return view; + } - var writer = view.ToWriter(); + #region Individual - foreach (var writerLine in writer.Chat) - player.PrintToChat(writerLine); + public static IView ToPlayerConsole(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); - public static IView ToPlayerCenter(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + foreach (var writerLine in writer.Plain) player.PrintToConsole(writerLine); - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Plain); + return view; + } - player.PrintToCenter(merged); + public static IView + ToPlayerChat(this IView view, CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); - public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + foreach (var writerLine in writer.Chat) player.PrintToChat(writerLine); - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Panorama); + return view; + } - player.PrintToCenterHtml(merged); + public static IView ToPlayerCenter(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Plain); - #endregion + player.PrintToCenter(merged); - public static IView ToAllConsole(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); + return view; + } - return view; - } + public static IView ToPlayerCenterHtml(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - public static IView ToAllChat(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Panorama); - return view; - } + player.PrintToCenterHtml(merged); - public static IView ToAllCenter(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); + return view; + } - return view; - } -} + #endregion +} \ No newline at end of file diff --git a/public/TTT.Formatting/Languages/English.cs b/public/TTT.Formatting/Languages/English.cs index 727c519..7b5d539 100644 --- a/public/TTT.Formatting/Languages/English.cs +++ b/public/TTT.Formatting/Languages/English.cs @@ -2,6 +2,4 @@ namespace TTT.Formatting.Languages; -public class English : IDialect -{ -} \ No newline at end of file +public class English : IDialect { } \ No newline at end of file diff --git a/public/TTT.Formatting/Logistics/IDialect.cs b/public/TTT.Formatting/Logistics/IDialect.cs index 52b81ef..76a77f3 100644 --- a/public/TTT.Formatting/Logistics/IDialect.cs +++ b/public/TTT.Formatting/Logistics/IDialect.cs @@ -1,9 +1,7 @@ namespace TTT.Formatting.Logistics; /// -/// A specific language, such as "English" or "French", -/// should inherit this interface. +/// A specific language, such as "English" or "French", +/// should inherit this interface. /// -public interface IDialect -{ -} \ No newline at end of file +public interface IDialect { } \ No newline at end of file diff --git a/public/TTT.Formatting/Logistics/ILanguage.cs b/public/TTT.Formatting/Logistics/ILanguage.cs index d19e0d2..40b1479 100644 --- a/public/TTT.Formatting/Logistics/ILanguage.cs +++ b/public/TTT.Formatting/Logistics/ILanguage.cs @@ -1,11 +1,8 @@ namespace TTT.Formatting.Logistics; /// -/// Specifies that this class is written in a specific language -/// Eg, ILanguage<English> or ILanguage<French> +/// Specifies that this class is written in a specific language +/// Eg, ILanguage<English> or ILanguage<French> /// /// -public interface ILanguage - where TDialect : IDialect -{ -} \ No newline at end of file +public interface ILanguage where TDialect : IDialect { } \ No newline at end of file diff --git a/public/TTT.Formatting/Logistics/LanguageConfig.cs b/public/TTT.Formatting/Logistics/LanguageConfig.cs index 11c25ae..040be1b 100644 --- a/public/TTT.Formatting/Logistics/LanguageConfig.cs +++ b/public/TTT.Formatting/Logistics/LanguageConfig.cs @@ -1,18 +1,11 @@ -using TTT.Formatting.Views; - -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; namespace TTT.Formatting.Logistics; -public class LanguageConfig - where TDialect: IDialect -{ - - private IServiceCollection _collection; - - public LanguageConfig(IServiceCollection collection) - { - _collection = collection; - } +public class LanguageConfig where TDialect : IDialect { + private IServiceCollection _collection; -} + public LanguageConfig(IServiceCollection collection) { + _collection = collection; + } +} \ No newline at end of file diff --git a/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs b/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs index d2606f8..72ded0f 100644 --- a/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs +++ b/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs @@ -2,15 +2,11 @@ namespace TTT.Formatting.Logistics; -public static class RegisterLanguageExtensions -{ - public static void AddLanguage( - this IServiceCollection collection, - Action> factory) - where TDialect : IDialect - { - var config = new LanguageConfig(collection); +public static class RegisterLanguageExtensions { + public static void AddLanguage(this IServiceCollection collection, + Action> factory) where TDialect : IDialect { + var config = new LanguageConfig(collection); - factory(config); - } + factory(config); + } } \ No newline at end of file diff --git a/public/TTT.Formatting/Objects/HiddenFormatObject.cs b/public/TTT.Formatting/Objects/HiddenFormatObject.cs index ef4f112..d6fe3f1 100644 --- a/public/TTT.Formatting/Objects/HiddenFormatObject.cs +++ b/public/TTT.Formatting/Objects/HiddenFormatObject.cs @@ -2,39 +2,29 @@ namespace TTT.Formatting.Objects; -public class HiddenFormatObject : FormatObject -{ - public FormatObject Value; - - public HiddenFormatObject(FormatObject value) - { - Value = value; - } - - public bool Plain { get; set; } = true; - - public bool Panorama { get; set; } = true; - - public bool Chat { get; set; } = true; - - public override string ToChat() - { - if (Chat) - return Value.ToChat(); - return string.Empty; - } - - public override string ToPanorama() - { - if (Panorama) - return Value.ToPanorama(); - return string.Empty; - } - - public override string ToPlain() - { - if (Plain) - return Value.ToPlain(); - return string.Empty; - } +public class HiddenFormatObject : FormatObject { + public FormatObject Value; + + public HiddenFormatObject(FormatObject value) { Value = value; } + + public bool Plain { get; set; } = true; + + public bool Panorama { get; set; } = true; + + public bool Chat { get; set; } = true; + + public override string ToChat() { + if (Chat) return Value.ToChat(); + return string.Empty; + } + + public override string ToPanorama() { + if (Panorama) return Value.ToPanorama(); + return string.Empty; + } + + public override string ToPlain() { + if (Plain) return Value.ToPlain(); + return string.Empty; + } } \ No newline at end of file diff --git a/public/TTT.Formatting/Objects/IntegerFormatObject.cs b/public/TTT.Formatting/Objects/IntegerFormatObject.cs index 2f06eac..acea79d 100644 --- a/public/TTT.Formatting/Objects/IntegerFormatObject.cs +++ b/public/TTT.Formatting/Objects/IntegerFormatObject.cs @@ -1,32 +1,20 @@ -using CounterStrikeSharp.API.Modules.Utils; -using TTT.Formatting.Core; +using TTT.Formatting.Core; namespace TTT.Formatting.Objects; -public class IntegerFormatObject : FormatObject -{ - private readonly char _chatColor; +public class IntegerFormatObject : FormatObject { + private readonly char _chatColor; - public IntegerFormatObject(int value, char chatColor = '\x09') - { - Value = value; - _chatColor = chatColor; - } + public IntegerFormatObject(int value, char chatColor = '\x09') { + Value = value; + _chatColor = chatColor; + } - public int Value { get; } + public int Value { get; } - public override string ToChat() - { - return $"{_chatColor}{Value.ToString()}"; - } + public override string ToChat() { return $"{_chatColor}{Value.ToString()}"; } - public override string ToPanorama() - { - return Value.ToString(); - } + public override string ToPanorama() { return Value.ToString(); } - public override string ToPlain() - { - return Value.ToString(); - } + public override string ToPlain() { return Value.ToString(); } } \ No newline at end of file diff --git a/public/TTT.Formatting/Objects/PlayerFormatObject.cs b/public/TTT.Formatting/Objects/PlayerFormatObject.cs index 846fdcb..c03bd4b 100644 --- a/public/TTT.Formatting/Objects/PlayerFormatObject.cs +++ b/public/TTT.Formatting/Objects/PlayerFormatObject.cs @@ -5,27 +5,16 @@ namespace TTT.Formatting.Objects; -public class PlayerFormatObject : FormatObject -{ - private readonly string _name; +public class PlayerFormatObject : FormatObject { + private readonly string _name; - public PlayerFormatObject(CCSPlayerController player) - { - _name = player.PlayerName; - } + public PlayerFormatObject(CCSPlayerController player) { + _name = player.PlayerName; + } - public override string ToChat() - { - return $"{ChatColors.Yellow}{_name}"; - } + public override string ToChat() { return $"{ChatColors.Yellow}{_name}"; } - public override string ToPanorama() - { - return _name.Sanitize(); - } + public override string ToPanorama() { return _name.Sanitize(); } - public override string ToPlain() - { - return _name; - } -} + public override string ToPlain() { return _name; } +} \ No newline at end of file diff --git a/public/TTT.Formatting/Objects/StringFormatObject.cs b/public/TTT.Formatting/Objects/StringFormatObject.cs index 7c85915..511d9fc 100644 --- a/public/TTT.Formatting/Objects/StringFormatObject.cs +++ b/public/TTT.Formatting/Objects/StringFormatObject.cs @@ -2,30 +2,19 @@ namespace TTT.Formatting.Objects; -public class StringFormatObject : FormatObject -{ - private readonly char _chatColor; +public class StringFormatObject : FormatObject { + private readonly char _chatColor; - public StringFormatObject(string value, char chatColor = '\x01') - { - Value = value; - _chatColor = chatColor; - } + public StringFormatObject(string value, char chatColor = '\x01') { + Value = value; + _chatColor = chatColor; + } - public string Value { get; } + public string Value { get; } - public override string ToChat() - { - return $"{_chatColor}{Value}"; - } + public override string ToChat() { return $"{_chatColor}{Value}"; } - public override string ToPanorama() - { - return Value; - } + public override string ToPanorama() { return Value; } - public override string ToPlain() - { - return Value; - } + public override string ToPlain() { return Value; } } \ No newline at end of file diff --git a/public/TTT.Formatting/Objects/TreeFormatObject.cs b/public/TTT.Formatting/Objects/TreeFormatObject.cs index 647c812..da6f8d9 100644 --- a/public/TTT.Formatting/Objects/TreeFormatObject.cs +++ b/public/TTT.Formatting/Objects/TreeFormatObject.cs @@ -1,86 +1,67 @@ using System.Collections; - using TTT.Formatting.Core; namespace TTT.Formatting.Objects; /// -/// Merges several FormatObjects into one. -/// This class will throw an error if any of it's descendant formatobjects are itself, -/// to prevent looping. +/// Merges several FormatObjects into one. +/// This class will throw an error if any of it's descendant formatobjects are itself, +/// to prevent looping. /// -public class TreeFormatObject : FormatObject, IEnumerable -{ - private List _children = new(); - - private int _locked = 0; - - public TreeFormatObject() - { - - } - - /// - /// Lock this object, execute callback, then unlock. - /// - /// - private T Lock(Func callback) - { - // Achieve a re-entrant mutex for this thread. - // We can re-enter this lock as long as we are in the same thread, but others are blocked. - // this allows us to do the internal increment safely. - lock (this) - { - // set _locked to 1 if value is 0 - int old = Interlocked.CompareExchange(ref _locked, 1, 0); - - if (old == 1) - throw new Exception("Possible loop detected in TreeFormatObject! Already locked during traversal"); - - var result = callback(); - _locked = 0; - - return result; - } - } - - public override string ToPlain() - { - return Lock(() => - { - var childPlain = _children.Select(child => child.ToPlain()); - return string.Join(' ', childPlain); - }); - } - - public override string ToChat() - { - return Lock(() => - { - var childChat = _children.Select(child => child.ToChat()); - return string.Join(' ', childChat); - }); - } - - public override string ToPanorama() - { - return Lock(() => - { - var childPanorama = _children.Select(child => child.ToPanorama()); - return string.Join(' ', childPanorama); - }); - } - - public void Add(FormatObject formatObject) - => _children.Add(formatObject); - - public IEnumerator GetEnumerator() - { - return _children.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } -} +public class TreeFormatObject : FormatObject, IEnumerable { + private readonly List _children = new(); + + private int _locked; + + public IEnumerator GetEnumerator() { + return _children.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } + + /// + /// Lock this object, execute callback, then unlock. + /// + /// + private T Lock(Func callback) { + // Achieve a re-entrant mutex for this thread. + // We can re-enter this lock as long as we are in the same thread, but others are blocked. + // this allows us to do the internal increment safely. + lock (this) { + // set _locked to 1 if value is 0 + var old = Interlocked.CompareExchange(ref _locked, 1, 0); + + if (old == 1) + throw new Exception( + "Possible loop detected in TreeFormatObject! Already locked during traversal"); + + var result = callback(); + _locked = 0; + + return result; + } + } + + public override string ToPlain() { + return Lock(() => { + var childPlain = _children.Select(child => child.ToPlain()); + return string.Join(' ', childPlain); + }); + } + + public override string ToChat() { + return Lock(() => { + var childChat = _children.Select(child => child.ToChat()); + return string.Join(' ', childChat); + }); + } + + public override string ToPanorama() { + return Lock(() => { + var childPanorama = _children.Select(child => child.ToPanorama()); + return string.Join(' ', childPanorama); + }); + } + + public void Add(FormatObject formatObject) { _children.Add(formatObject); } +} \ No newline at end of file diff --git a/public/TTT.Formatting/TTT.Formatting.csproj b/public/TTT.Formatting/TTT.Formatting.csproj index 0d44a15..77467aa 100644 --- a/public/TTT.Formatting/TTT.Formatting.csproj +++ b/public/TTT.Formatting/TTT.Formatting.csproj @@ -7,7 +7,7 @@ - - + + diff --git a/public/TTT.Formatting/Views/IRoleNotifications.cs b/public/TTT.Formatting/Views/IRoleNotifications.cs index 35826a6..94be705 100644 --- a/public/TTT.Formatting/Views/IRoleNotifications.cs +++ b/public/TTT.Formatting/Views/IRoleNotifications.cs @@ -3,9 +3,8 @@ namespace TTT.Formatting.Views; -public interface IRoleNotifications -{ - IView GetRoleNotification(Role role); - IView KilledByRoleNotification(Role role); - IView KilledRoleNotification(Role role); +public interface IRoleNotifications { + IView GetRoleNotification(Role role); + IView KilledByRoleNotification(Role role); + IView KilledRoleNotification(Role role); } \ No newline at end of file diff --git a/public/TTT.Public/Action/DamageAction.cs b/public/TTT.Public/Action/DamageAction.cs index 842b0c9..160d780 100644 --- a/public/TTT.Public/Action/DamageAction.cs +++ b/public/TTT.Public/Action/DamageAction.cs @@ -4,38 +4,32 @@ namespace TTT.Public.Action; -public class DamageAction : Action -{ - private readonly Tuple? _actor; - private readonly Tuple _attackedPlayer; - private readonly int _damage; - private readonly int _roundTime; +public class DamageAction : Action { + private readonly Tuple? _actor; + private readonly Tuple _attackedPlayer; + private readonly int _damage; + private readonly int _roundTime; - public DamageAction(Tuple? actor, Tuple attackedPlayer, - int damage, int roundTime) - { - _actor = actor; - _attackedPlayer = attackedPlayer; - _damage = damage; - _roundTime = roundTime; - } + public DamageAction(Tuple? actor, + Tuple attackedPlayer, int damage, + int roundTime) { + _actor = actor; + _attackedPlayer = attackedPlayer; + _damage = damage; + _roundTime = roundTime; + } - public override CCSPlayerController Actor() - { - return _actor.Item1; - } - - private string GetActorName() - { - return _actor?.Item2.FormatStringFullAfter(" " + _actor?.Item1.PlayerName) ?? "World"; - } + public override CCSPlayerController Actor() { return _actor.Item1; } - public override string ActionMessage() - { - - var attackedPlayerRole = _attackedPlayer.Item2; - return $"[TTT] {GetActorName()}" + - $" damaged {attackedPlayerRole.FormatStringFullAfter(" " + _attackedPlayer.Item1.PlayerName)}" + - $" for {_damage} hp."; - } + private string GetActorName() { + return _actor?.Item2.FormatStringFullAfter(" " + _actor?.Item1.PlayerName) + ?? "World"; + } + + public override string ActionMessage() { + var attackedPlayerRole = _attackedPlayer.Item2; + return $"[TTT] {GetActorName()}" + + $" damaged {attackedPlayerRole.FormatStringFullAfter(" " + _attackedPlayer.Item1.PlayerName)}" + + $" for {_damage} hp."; + } } \ No newline at end of file diff --git a/public/TTT.Public/Action/DeathAction.cs b/public/TTT.Public/Action/DeathAction.cs index 4c4fa32..87bac54 100644 --- a/public/TTT.Public/Action/DeathAction.cs +++ b/public/TTT.Public/Action/DeathAction.cs @@ -4,24 +4,17 @@ namespace TTT.Public.Action; -public class DeathAction : Action -{ - private readonly Tuple _actor; +public class DeathAction : Action { + private readonly Tuple _actor; - public DeathAction(Tuple actor) - { - _actor = actor; - } + public DeathAction(Tuple actor) { _actor = actor; } - public override CCSPlayerController Actor() - { - return _actor.Item1; - } + public override CCSPlayerController Actor() { return _actor.Item1; } - public override string ActionMessage() - { - var actorRole = _actor.Item2; - return $"[TTT] {actorRole.FormatStringFullAfter(" " + _actor.Item1.PlayerName)}" + - $" was killed by world."; - } + public override string ActionMessage() { + var actorRole = _actor.Item2; + return + $"[TTT] {actorRole.FormatStringFullAfter(" " + _actor.Item1.PlayerName)}" + + $" was killed by world."; + } } \ No newline at end of file diff --git a/public/TTT.Public/Action/IAction.cs b/public/TTT.Public/Action/IAction.cs index a32097a..11ae959 100644 --- a/public/TTT.Public/Action/IAction.cs +++ b/public/TTT.Public/Action/IAction.cs @@ -3,13 +3,11 @@ namespace TTT.Public.Action; -public abstract class Action -{ - public abstract CCSPlayerController Actor(); - public abstract string ActionMessage(); +public abstract class Action { + public abstract CCSPlayerController Actor(); + public abstract string ActionMessage(); - protected static string GoodAction(Role actor, Role actor2) - { - return actor == actor2 ? "[Bad action!]" : ""; - } + protected static string GoodAction(Role actor, Role actor2) { + return actor == actor2 ? "[Bad action!]" : ""; + } } \ No newline at end of file diff --git a/public/TTT.Public/Action/KillAction.cs b/public/TTT.Public/Action/KillAction.cs index b383450..b5084bb 100644 --- a/public/TTT.Public/Action/KillAction.cs +++ b/public/TTT.Public/Action/KillAction.cs @@ -4,28 +4,24 @@ namespace TTT.Public.Action; -public class KillAction : Action -{ - private readonly Tuple _actor; - private readonly Tuple _attackedPlayer; +public class KillAction : Action { + private readonly Tuple _actor; + private readonly Tuple _attackedPlayer; - public KillAction(Tuple actor, Tuple attackedPlayer) - { - _actor = actor; - _attackedPlayer = attackedPlayer; - } + public KillAction(Tuple actor, + Tuple attackedPlayer) { + _actor = actor; + _attackedPlayer = attackedPlayer; + } - public override CCSPlayerController Actor() - { - return _actor.Item1; - } + public override CCSPlayerController Actor() { return _actor.Item1; } - public override string ActionMessage() - { - var actorRole = _actor.Item2; - var attackedPlayerRole = _attackedPlayer.Item2; - return $"[TTT] {actorRole.FormatStringFullAfter(" " + _actor.Item1.PlayerName)}" + - $" killed {attackedPlayerRole.FormatStringFullAfter(" " + _attackedPlayer.Item1.PlayerName)}. " + - $"{GoodAction(actorRole, attackedPlayerRole)}"; - } + public override string ActionMessage() { + var actorRole = _actor.Item2; + var attackedPlayerRole = _attackedPlayer.Item2; + return + $"[TTT] {actorRole.FormatStringFullAfter(" " + _actor.Item1.PlayerName)}" + + $" killed {attackedPlayerRole.FormatStringFullAfter(" " + _attackedPlayer.Item1.PlayerName)}. " + + $"{GoodAction(actorRole, attackedPlayerRole)}"; + } } \ No newline at end of file diff --git a/public/TTT.Public/Action/MiscAction.cs b/public/TTT.Public/Action/MiscAction.cs index f4cbdfb..63994d4 100644 --- a/public/TTT.Public/Action/MiscAction.cs +++ b/public/TTT.Public/Action/MiscAction.cs @@ -2,24 +2,18 @@ namespace TTT.Public.Action; -public class MiscAction : Action -{ - private readonly string _action; - private readonly CCSPlayerController _actor; +public class MiscAction : Action { + private readonly string _action; + private readonly CCSPlayerController _actor; - public MiscAction(string action, CCSPlayerController actor) - { - _action = action; - _actor = actor; - } + public MiscAction(string action, CCSPlayerController actor) { + _action = action; + _actor = actor; + } - public override CCSPlayerController Actor() - { - return _actor; - } + public override CCSPlayerController Actor() { return _actor; } - public override string ActionMessage() - { - return _actor.PlayerName + " " + _action; - } + public override string ActionMessage() { + return _actor.PlayerName + " " + _action; + } } \ No newline at end of file diff --git a/public/TTT.Public/Action/ShopAction.cs b/public/TTT.Public/Action/ShopAction.cs index 0d946ea..d852bdb 100644 --- a/public/TTT.Public/Action/ShopAction.cs +++ b/public/TTT.Public/Action/ShopAction.cs @@ -1,5 +1,3 @@ namespace TTT.Public.Action; -public class ShopAction -{ -} \ No newline at end of file +public class ShopAction { } \ No newline at end of file diff --git a/public/TTT.Public/Behaviors/IPluginBehavior.cs b/public/TTT.Public/Behaviors/IPluginBehavior.cs index ada7b0a..b070b6b 100644 --- a/public/TTT.Public/Behaviors/IPluginBehavior.cs +++ b/public/TTT.Public/Behaviors/IPluginBehavior.cs @@ -3,18 +3,13 @@ namespace TTT.Public.Behaviors; /// -/// A plugin extension class that is +/// A plugin extension class that is /// -public interface IPluginBehavior : IDisposable -{ - void IDisposable.Dispose() - { - } +public interface IPluginBehavior : IDisposable { + void IDisposable.Dispose() { } - /// - /// Tells the plugin that it will be starting imminently - /// - void Start(BasePlugin parent) - { - } + /// + /// Tells the plugin that it will be starting imminently + /// + void Start(BasePlugin parent) { } } \ No newline at end of file diff --git a/public/TTT.Public/Configuration/IConfigService.cs b/public/TTT.Public/Configuration/IConfigService.cs index 45f07c0..7eccf1a 100644 --- a/public/TTT.Public/Configuration/IConfigService.cs +++ b/public/TTT.Public/Configuration/IConfigService.cs @@ -1,16 +1,14 @@ namespace TTT.Public.Configuration; -public interface IConfigService -{ - public const string ConfigPath = "jailbreak.json"; +public interface IConfigService { + public const string ConfigPath = "jailbreak.json"; - /// - /// Get the configuration object with the provided name - /// - /// - /// If the configuration service would return the default value, fail instead. Loudly. - /// - /// - T Get(string path, bool failOnDefault = false) - where T : class, new(); + /// + /// Get the configuration object with the provided name + /// + /// + /// If the configuration service would return the default value, fail instead. Loudly. + /// + /// + T Get(string path, bool failOnDefault = false) where T : class, new(); } \ No newline at end of file diff --git a/public/TTT.Public/Database/DatabaseService.cs b/public/TTT.Public/Database/DatabaseService.cs index 39e8a51..e337c5c 100644 --- a/public/TTT.Public/Database/DatabaseService.cs +++ b/public/TTT.Public/Database/DatabaseService.cs @@ -2,66 +2,55 @@ using MySqlConnector; using TTT.Player; using TTT.Public.Mod.Role; -using TTT.Public.Player; namespace TTT.Public.Database; -public class DatabaseService -{ - private MySqlConnection _connector; +public class DatabaseService { + private readonly MySqlConnection _connector; - public DatabaseService() - { - _connector = new MySqlConnection(); - _connector.OpenAsync(); - CreateTable(); - } + public DatabaseService() { + _connector = new MySqlConnection(); + _connector.OpenAsync(); + CreateTable(); + } - public void CreateTable() - { - Task.Run(async () => - { - var command = new MySqlCommand("CREATE TABLE IF NOT EXISTS PlayerData(steamid VARCHAR(17) NOT NULL," + - "kills INT," + - "deaths INT," + - "karma INT," + - "traitor_kills INT," + - "traitors_killed INT," + - "PRIMARY KEY(steamid));"); - command.Connection = _connector; - await command.ExecuteNonQueryAsync(); - }); - - } + public void CreateTable() { + Task.Run(async () => { + var command = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS PlayerData(steamid VARCHAR(17) NOT NULL," + + "kills INT," + "deaths INT," + "karma INT," + "traitor_kills INT," + + "traitors_killed INT," + "PRIMARY KEY(steamid));"); + command.Connection = _connector; + await command.ExecuteNonQueryAsync(); + }); + } - public GamePlayer CreateProfile(CCSPlayerController player) - { - var id = player.SteamID; + public GamePlayer CreateProfile(CCSPlayerController player) { + var id = player.SteamID; - Task.Run(async () => - { - var command = new MySqlCommand("INSERT IGNORE INTO PlayerData(steamid, kills, deaths, karma, traitor_kills, traitors_killed)" + - $" VALUES ({id}, 0, 0, 80, 0, 0);"); - command.Connection = _connector; - await command.ExecuteNonQueryAsync(); - }); - return new GamePlayer(Role.Unassigned, 800, 0, player.UserId.Value); - } + Task.Run(async () => { + var command = new MySqlCommand( + "INSERT IGNORE INTO PlayerData(steamid, kills, deaths, karma, traitor_kills, traitors_killed)" + + $" VALUES ({id}, 0, 0, 80, 0, 0);"); + command.Connection = _connector; + await command.ExecuteNonQueryAsync(); + }); + return new GamePlayer(Role.Unassigned, 800, 0, player.UserId.Value); + } - public void UpdatePlayer(GamePlayer player) - { - Task.Run(async () => - { - var command = new MySqlCommand("UPDATE PlayerData SET kills = @kills, deaths = @deaths, karma = @karma, traitor_kills = @traitor_kills, traitors_killed = @traitors_killed" + - " WHERE steamid = @steamid;"); - command.Parameters.AddWithValue("@kills", 0); - command.Parameters.AddWithValue("@deaths", 0); - command.Parameters.AddWithValue("@karma", player.Karma()); - command.Parameters.AddWithValue("@traitor_kills", 0); - command.Parameters.AddWithValue("@traitors_killed", 0); - command.Parameters.AddWithValue("@steamid", player.Player().SteamID); - command.Connection = _connector; - await command.ExecuteNonQueryAsync(); - }); - } + public void UpdatePlayer(GamePlayer player) { + Task.Run(async () => { + var command = new MySqlCommand( + "UPDATE PlayerData SET kills = @kills, deaths = @deaths, karma = @karma, traitor_kills = @traitor_kills, traitors_killed = @traitors_killed" + + " WHERE steamid = @steamid;"); + command.Parameters.AddWithValue("@kills", 0); + command.Parameters.AddWithValue("@deaths", 0); + command.Parameters.AddWithValue("@karma", player.Karma()); + command.Parameters.AddWithValue("@traitor_kills", 0); + command.Parameters.AddWithValue("@traitors_killed", 0); + command.Parameters.AddWithValue("@steamid", player.Player().SteamID); + command.Connection = _connector; + await command.ExecuteNonQueryAsync(); + }); + } } \ No newline at end of file diff --git a/public/TTT.Public/Extensions/EntityIOExtensions.cs b/public/TTT.Public/Extensions/EntityIOExtensions.cs index 5183f40..63fd3fd 100644 --- a/public/TTT.Public/Extensions/EntityIOExtensions.cs +++ b/public/TTT.Public/Extensions/EntityIOExtensions.cs @@ -3,26 +3,22 @@ namespace TTT.Public.Extensions; -public static class EntityIOExtensions -{ - public static bool TryGetController(this CEntityInstance pawn, out CCSPlayerController? controller) - { - controller = null; +public static class EntityIOExtensions { + public static bool TryGetController(this CEntityInstance pawn, + out CCSPlayerController? controller) { + controller = null; - if (!pawn.IsValid) - return false; + if (!pawn.IsValid) return false; - var index = (int)pawn.Index; - var playerPawn = Utilities.GetEntityFromIndex(index); + var index = (int)pawn.Index; + var playerPawn = Utilities.GetEntityFromIndex(index); - if (!playerPawn.IsValid) - return false; + if (!playerPawn.IsValid) return false; - if (!playerPawn.OriginalController.IsValid) - return false; + if (!playerPawn.OriginalController.IsValid) return false; - controller = playerPawn.OriginalController.Value; + controller = playerPawn.OriginalController.Value; - return controller?.IsReal() == true; - } -} + return controller?.IsReal() == true; + } +} \ No newline at end of file diff --git a/public/TTT.Public/Extensions/PlayerExtensions.cs b/public/TTT.Public/Extensions/PlayerExtensions.cs index c73f338..22480b0 100644 --- a/public/TTT.Public/Extensions/PlayerExtensions.cs +++ b/public/TTT.Public/Extensions/PlayerExtensions.cs @@ -5,87 +5,87 @@ namespace TTT.Public.Extensions; -public static class PlayerExtensions -{ - public static CsTeam GetTeam(this CCSPlayerController controller) - { - return (CsTeam)controller.TeamNum; - } - - public static string GetActiveWeaponName(this CCSPlayerController player) - { - return player.PlayerPawn.Value?.WeaponServices?.ActiveWeapon.Value?.DesignerName ?? string.Empty; - } - - public static CCSPlayerController? GetClientPlayerAimTarget(this CCSPlayerController player) - { - var GameRules = Utilities.FindAllEntitiesByDesignerName("cs_gamerules").FirstOrDefault()?.GameRules; - - if (GameRules is null) - return null; - - VirtualFunctionWithReturn findPickerEntity = new(GameRules.Handle, 28); - var target = new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); - - if (target.DesignerName is "player") - { - return target.As().OriginalController.Value; - } - - return null; - - } - - public static CCSPlayerController? GetClientRagdollAimTarget(this CCSPlayerController player) - { - var GameRules = Utilities.FindAllEntitiesByDesignerName("cs_gamerules").FirstOrDefault()?.GameRules; - - if (GameRules is null) - return null; - - VirtualFunctionWithReturn findPickerEntity = new(GameRules.Handle, 28); - var target = new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); - - if (target.DesignerName is "player") - { - return target.As().OriginalController.Value; - } - - return null; - } - - public static CBaseDoor? GetClientPlayerTraitorRoom(this CCSPlayerController player) - { - var GameRules = Utilities.FindAllEntitiesByDesignerName("cs_gamerules").FirstOrDefault()?.GameRules; - - if (GameRules is null) - return null; - - VirtualFunctionWithReturn findPickerEntity = new(GameRules.Handle, 28); - var target = new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); - - if (target.DesignerName is "func_door" || target.DesignerName is "prop_door_rotating") - { - return target.As(); - } - - return null; - } - - - public static bool IsReal(this CCSPlayerController player) - { - // Do nothing else before this: - // Verifies the handle points to an entity within the global entity list. - if (!player.IsValid) - return false; - - if (player.Connected != PlayerConnectedState.PlayerConnected) - return false; - - if (player.IsBot || player.IsHLTV) - return false; - - return true; - } +public static class PlayerExtensions { + public static CsTeam GetTeam(this CCSPlayerController controller) { + return (CsTeam)controller.TeamNum; + } + + public static string GetActiveWeaponName(this CCSPlayerController player) { + return player.PlayerPawn.Value?.WeaponServices?.ActiveWeapon.Value + ?.DesignerName ?? string.Empty; + } + + public static CCSPlayerController? GetClientPlayerAimTarget( + this CCSPlayerController player) { + var GameRules = Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .FirstOrDefault() + ?.GameRules; + + if (GameRules is null) return null; + + VirtualFunctionWithReturn findPickerEntity = + new(GameRules.Handle, 28); + var target = + new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); + + if (target.DesignerName is "player") + return target.As().OriginalController.Value; + + return null; + } + + public static CCSPlayerController? GetClientRagdollAimTarget( + this CCSPlayerController player) { + var GameRules = Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .FirstOrDefault() + ?.GameRules; + + if (GameRules is null) return null; + + VirtualFunctionWithReturn findPickerEntity = + new(GameRules.Handle, 28); + var target = + new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); + + if (target.DesignerName is "player") + return target.As().OriginalController.Value; + + return null; + } + + public static CBaseDoor? GetClientPlayerTraitorRoom( + this CCSPlayerController player) { + var GameRules = Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .FirstOrDefault() + ?.GameRules; + + if (GameRules is null) return null; + + VirtualFunctionWithReturn findPickerEntity = + new(GameRules.Handle, 28); + var target = + new CBaseEntity(findPickerEntity.Invoke(GameRules.Handle, player.Handle)); + + if (target.DesignerName is "func_door" + || target.DesignerName is "prop_door_rotating") + return target.As(); + + return null; + } + + + public static bool IsReal(this CCSPlayerController player) { + // Do nothing else before this: + // Verifies the handle points to an entity within the global entity list. + if (!player.IsValid) return false; + + if (player.Connected != PlayerConnectedState.PlayerConnected) return false; + + if (player.IsBot || player.IsHLTV) return false; + + return true; + } } \ No newline at end of file diff --git a/public/TTT.Public/Extensions/ScoreboardExtension.cs b/public/TTT.Public/Extensions/ScoreboardExtension.cs index d7f9902..fc85647 100644 --- a/public/TTT.Public/Extensions/ScoreboardExtension.cs +++ b/public/TTT.Public/Extensions/ScoreboardExtension.cs @@ -5,104 +5,97 @@ namespace TTT.Round; -public static class ScoreboardExtension -{ - public static void ModifyScoreBoard(this CCSPlayerController? player) - { - if (player == null) return; - if (!player.IsReal()) return; - var actionService = player.ActionTrackingServices; - if (actionService == null) return; +public static class ScoreboardExtension { + public static void ModifyScoreBoard(this CCSPlayerController? player) { + if (player == null) return; + if (!player.IsReal()) return; + var actionService = player.ActionTrackingServices; + if (actionService == null) return; - RemoveKills(player); - RemoveDamage(player); - RemoveDeaths(player); - RemoveUtilityDamage(player); - RemoveAssists(player); - RemoveEnemiesFlashed(player); - RemoveHeadshotKills(player); - KillIconTest(player); - } - - public static void ModifyKarma(this GamePlayer gamePlayer) - { - var player = gamePlayer.Player(); - if (player == null) return; - SetScore(gamePlayer); - } + RemoveKills(player); + RemoveDamage(player); + RemoveDeaths(player); + RemoveUtilityDamage(player); + RemoveAssists(player); + RemoveEnemiesFlashed(player); + RemoveHeadshotKills(player); + KillIconTest(player); + } - private static void SetScore(GamePlayer gamePlayer) - { - var player = gamePlayer.Player(); - if (player == null) return; - - if (player.Score == gamePlayer.Karma()) return; - player.Score = gamePlayer.Karma(); - } - - private static void KillIconTest(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices; - if (matchStats.NumRoundKills == 0 && matchStats.NumRoundKillsHeadshots == 0) return; - matchStats.NumRoundKills = 0; - matchStats.NumRoundKillsHeadshots = 0; - Utilities.SetStateChanged(player, "CCSPlayerController_ActionTrackingServices", "m_iNumRoundKills"); - Utilities.SetStateChanged(player, "CCSPlayerController_ActionTrackingServices", "m_iNumRoundKillsHeadshots"); - } - - private static void RemoveKills(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.Kills == 0) return; - matchStats.Kills = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iKills"); - } + public static void ModifyKarma(this GamePlayer gamePlayer) { + var player = gamePlayer.Player(); + if (player == null) return; + SetScore(gamePlayer); + } - private static void RemoveDamage(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.Damage == 0) return; - matchStats.Damage = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iDamage"); - } - - private static void RemoveUtilityDamage(CCSPlayerController player) { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.UtilityDamage == 0) return; - matchStats.UtilityDamage = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iUtilityDamage"); - } + private static void SetScore(GamePlayer gamePlayer) { + var player = gamePlayer.Player(); + if (player == null) return; - private static void RemoveDeaths(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.Deaths == 0) return; - matchStats.Deaths = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iDeaths"); - } + if (player.Score == gamePlayer.Karma()) return; + player.Score = gamePlayer.Karma(); + } - private static void RemoveAssists(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.Assists == 0) return; - matchStats.Assists = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iAssists"); - } + private static void KillIconTest(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices; + if (matchStats.NumRoundKills == 0 && matchStats.NumRoundKillsHeadshots == 0) + return; + matchStats.NumRoundKills = 0; + matchStats.NumRoundKillsHeadshots = 0; + Utilities.SetStateChanged(player, + "CCSPlayerController_ActionTrackingServices", "m_iNumRoundKills"); + Utilities.SetStateChanged(player, + "CCSPlayerController_ActionTrackingServices", + "m_iNumRoundKillsHeadshots"); + } - private static void RemoveEnemiesFlashed(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.EnemiesFlashed == 0) return; - matchStats.EnemiesFlashed = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iEnemiesFlashed"); - } - - private static void RemoveHeadshotKills(CCSPlayerController player) - { - var matchStats = player.ActionTrackingServices!.MatchStats; - if (matchStats.HeadShotKills == 0) return; - matchStats.HeadShotKills = 0; - Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iHeadShotKills"); - } + private static void RemoveKills(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.Kills == 0) return; + matchStats.Kills = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iKills"); + } + + private static void RemoveDamage(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.Damage == 0) return; + matchStats.Damage = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iDamage"); + } + + private static void RemoveUtilityDamage(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.UtilityDamage == 0) return; + matchStats.UtilityDamage = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iUtilityDamage"); + } + + private static void RemoveDeaths(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.Deaths == 0) return; + matchStats.Deaths = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iDeaths"); + } + + private static void RemoveAssists(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.Assists == 0) return; + matchStats.Assists = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iAssists"); + } + + private static void RemoveEnemiesFlashed(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.EnemiesFlashed == 0) return; + matchStats.EnemiesFlashed = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iEnemiesFlashed"); + } + + private static void RemoveHeadshotKills(CCSPlayerController player) { + var matchStats = player.ActionTrackingServices!.MatchStats; + if (matchStats.HeadShotKills == 0) return; + matchStats.HeadShotKills = 0; + Utilities.SetStateChanged(player, "CSPerRoundStats_t", "m_iHeadShotKills"); + } } \ No newline at end of file diff --git a/public/TTT.Public/Extensions/ServerExtensions.cs b/public/TTT.Public/Extensions/ServerExtensions.cs index 4bda151..3f76c60 100644 --- a/public/TTT.Public/Extensions/ServerExtensions.cs +++ b/public/TTT.Public/Extensions/ServerExtensions.cs @@ -5,26 +5,27 @@ namespace TTT.Public.Extensions; -public static class ServerExtensions -{ - public static void PrintToCenterAll(string message) - { - VirtualFunctions.ClientPrintAll(HudDestination.Center, message, 0, 0, 0, 0); - } +public static class ServerExtensions { + public static void PrintToCenterAll(string message) { + VirtualFunctions.ClientPrintAll(HudDestination.Center, message, 0, 0, 0, 0); + } - /// - /// Get the current CCSGameRules for the server - /// - /// - public static CCSGameRules GetGameRules() - { - // From killstr3ak - return Utilities.FindAllEntitiesByDesignerName("cs_gamerules").First().GameRules!; - } - - public static CCSGameRulesProxy GetGameRulesProxy() - { - // From killstr3ak - return Utilities.FindAllEntitiesByDesignerName("cs_gamerules").First()!; - } -} + /// + /// Get the current CCSGameRules for the server + /// + /// + public static CCSGameRules GetGameRules() { + // From killstr3ak + return Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .First() + .GameRules!; + } + + public static CCSGameRulesProxy GetGameRulesProxy() { + // From killstr3ak + return Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .First()!; + } +} \ No newline at end of file diff --git a/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs b/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs index 1408fee..d647b78 100644 --- a/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs +++ b/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs @@ -1,63 +1,66 @@ -using TTT.Public.Behaviors; +using Microsoft.Extensions.DependencyInjection; +using TTT.Public.Behaviors; using TTT.Public.Configuration; -using Microsoft.Extensions.DependencyInjection; namespace TTT.Public.Extensions; -public static class ServiceCollectionExtensions -{ +public static class ServiceCollectionExtensions { /// - /// Add a to the global service collection + /// Add a to the global service collection /// /// /// - public static void AddPluginBehavior(this IServiceCollection collection) - where TExtension : class, IPluginBehavior - { - // Add the root extension itself as a scoped service. - // This means every time Load is called in the main Jailbreak loader, - // the extension will be fetched and kept as a singleton for the duration - // until "Unload" is called. - collection.AddScoped(); + public static void + AddPluginBehavior(this IServiceCollection collection) + where TExtension : class, IPluginBehavior { + // Add the root extension itself as a scoped service. + // This means every time Load is called in the main Jailbreak loader, + // the extension will be fetched and kept as a singleton for the duration + // until "Unload" is called. + collection.AddScoped(); - collection.AddTransient(provider => provider.GetRequiredService()); - } + collection.AddTransient(provider + => provider.GetRequiredService()); + } /// - /// Add a to the global service collection + /// Add a to the global service collection /// /// /// /// - public static void AddPluginBehavior(this IServiceCollection collection) - where TExtension : class, IPluginBehavior, TInterface - where TInterface : class - { - // Add the root extension itself as a scoped service. - // This means every time Load is called in the main Jailbreak loader, - // the extension will be fetched and kept as a singleton for the duration - // until "Unload" is called. - collection.AddScoped(); + public static void + AddPluginBehavior( + this IServiceCollection collection) + where TExtension : class, IPluginBehavior, TInterface + where TInterface : class { + // Add the root extension itself as a scoped service. + // This means every time Load is called in the main Jailbreak loader, + // the extension will be fetched and kept as a singleton for the duration + // until "Unload" is called. + collection.AddScoped(); - collection.AddTransient(provider => provider.GetRequiredService()); - collection.AddTransient(provider => provider.GetRequiredService()); - } + collection.AddTransient(provider + => provider.GetRequiredService()); + collection.AddTransient(provider + => provider.GetRequiredService()); + } /// - /// Add an object to be loaded from the configuration file + /// Add an object to be loaded from the configuration file /// /// /// The section where the configuration object will be loaded from /// The configuration object. Must auto-fill all default values! - public static void AddConfig(this IServiceCollection collection, string sectionName) - where TConfig : class, new() - { - // Get the object by resolving IConfigService - // and use the Get() method. + public static void AddConfig(this IServiceCollection collection, + string sectionName) where TConfig : class, new() { + // Get the object by resolving IConfigService + // and use the Get() method. - // Not *really* important... but do we want to fail here or return default if section - // isn't available? - collection.AddTransient(provider => provider.GetRequiredService() - .Get(sectionName)); - } + // Not *really* important... but do we want to fail here or return default if section + // isn't available? + collection.AddTransient(provider + => provider.GetRequiredService() + .Get(sectionName)); + } } \ No newline at end of file diff --git a/public/TTT.Public/Extensions/StringExtensions.cs b/public/TTT.Public/Extensions/StringExtensions.cs index 777310e..336bbe9 100644 --- a/public/TTT.Public/Extensions/StringExtensions.cs +++ b/public/TTT.Public/Extensions/StringExtensions.cs @@ -1,10 +1,7 @@ namespace TTT.Public.Extensions; -public static class StringExtensions -{ - public static string Sanitize(this string unknown) - { - return unknown - .Replace("<", "<"); - } +public static class StringExtensions { + public static string Sanitize(this string unknown) { + return unknown.Replace("<", "<"); + } } \ No newline at end of file diff --git a/public/TTT.Public/Extensions/VectorExtensions.cs b/public/TTT.Public/Extensions/VectorExtensions.cs index 5e80cd3..47f0b79 100644 --- a/public/TTT.Public/Extensions/VectorExtensions.cs +++ b/public/TTT.Public/Extensions/VectorExtensions.cs @@ -2,55 +2,40 @@ namespace TTT.Public.Extensions; -public static class VectorExtensions -{ - public static Vector Clone(this Vector vector) - { - var vec = new Vector - { - X = vector.X, - Y = vector.Y, - Z = vector.Z - }; - return vec; - } +public static class VectorExtensions { + public static Vector Clone(this Vector vector) { + var vec = new Vector { X = vector.X, Y = vector.Y, Z = vector.Z }; + return vec; + } - public static Vector Add(this Vector vector, Vector other) - { - vector.X += other.X; - vector.Y += other.Y; - vector.Z += other.Z; - return vector; - } + public static Vector Add(this Vector vector, Vector other) { + vector.X += other.X; + vector.Y += other.Y; + vector.Z += other.Z; + return vector; + } - public static Vector Scale(this Vector vector, float scale) - { - vector.X *= scale; - vector.Y *= scale; - vector.Z *= scale; - return vector; - } + public static Vector Scale(this Vector vector, float scale) { + vector.X *= scale; + vector.Y *= scale; + vector.Z *= scale; + return vector; + } - public static Vector Normalize(this Vector vector) - { - var length = vector.Length(); - vector.X /= length; - vector.Y /= length; - vector.Z /= length; - return vector; - } + public static Vector Normalize(this Vector vector) { + var length = vector.Length(); + vector.X /= length; + vector.Y /= length; + vector.Z /= length; + return vector; + } - public static float Distance(this Vector vector, Vector other) - { - return (float)Math.Sqrt(vector.DistanceSquared(other)); - } + public static float Distance(this Vector vector, Vector other) { + return (float)Math.Sqrt(vector.DistanceSquared(other)); + } - public static float DistanceSquared(this Vector vector, Vector other) - { - return (float)( - Math.Pow(vector.X - other.X, 2) + - Math.Pow(vector.Y - other.Y, 2) + - Math.Pow(vector.Z - other.Z, 2) - ); - } + public static float DistanceSquared(this Vector vector, Vector other) { + return (float)(Math.Pow(vector.X - other.X, 2) + + Math.Pow(vector.Y - other.Y, 2) + Math.Pow(vector.Z - other.Z, 2)); + } } \ No newline at end of file diff --git a/public/TTT.Public/Formatting/Format.cs b/public/TTT.Public/Formatting/Format.cs index ac77113..5e9c194 100644 --- a/public/TTT.Public/Formatting/Format.cs +++ b/public/TTT.Public/Formatting/Format.cs @@ -4,75 +4,65 @@ namespace TTT.Public.Formatting; -public static class Format -{ - public static string FormatStringAfter(this Role role, string message) - { - return FormatRole(role) + ChatColors.Lime + message; - } +public static class Format { + public static string FormatStringAfter(this Role role, string message) { + return FormatRole(role) + ChatColors.Lime + message; + } - public static string FormatStringBefore(this Role role, string message) - { - return " " + ChatColors.Green + message + " " + FormatRole(role) + ChatColors.Lime; - } + public static string FormatStringBefore(this Role role, string message) { + return " " + ChatColors.Green + message + " " + FormatRole(role) + + ChatColors.Lime; + } - public static string FormatStringFullAfter(this Role role, string message) - { - return role.FormatRoleFull() + ChatColors.Lime + message; - } + public static string FormatStringFullAfter(this Role role, string message) { + return role.FormatRoleFull() + ChatColors.Lime + message; + } - public static string FormatStringFullBefore(this Role role, string message) - { - return " " + ChatColors.Green + message + " " + role.FormatRoleFull() + ChatColors.Green; - } + public static string FormatStringFullBefore(this Role role, string message) { + return " " + ChatColors.Green + message + " " + role.FormatRoleFull() + + ChatColors.Green; + } - public static string FormatRole(this Role role) - { - return role switch - { - Role.Traitor => ChatColors.DarkRed + "T ", - Role.Detective => ChatColors.Blue + "D ", - Role.Innocent => ChatColors.Green + "I ", - _ => "" - }; - } + public static string FormatRole(this Role role) { + return role switch { + Role.Traitor => ChatColors.DarkRed + "T ", + Role.Detective => ChatColors.Blue + "D ", + Role.Innocent => ChatColors.Green + "I ", + _ => "" + }; + } - public static string FormatRoleFull(this Role role) - { - return role switch - { - Role.Traitor => ChatColors.DarkRed + "Traitor", - Role.Detective => ChatColors.Blue + "Detective", - Role.Innocent => ChatColors.Green + "Innocent", - Role.Unassigned => "", - _ => "" - }; - } + public static string FormatRoleFull(this Role role) { + return role switch { + Role.Traitor => ChatColors.DarkRed + "Traitor", + Role.Detective => ChatColors.Blue + "Detective", + Role.Innocent => ChatColors.Green + "Innocent", + Role.Unassigned => "", + _ => "" + }; + } - public static string GetCenterRole(this Role role) - { - return role switch - { - Role.Traitor => - $"Traitor", - Role.Detective => - $"Detective", - Role.Innocent => - $"Innocent", - Role.Unassigned => $"Unknown", - _ => "" - }; - } + public static string GetCenterRole(this Role role) { + return role switch { + Role.Traitor => + $"Traitor", + Role.Detective => + $"Detective", + Role.Innocent => + $"Innocent", + Role.Unassigned => + $"Unknown", + _ => "" + }; + } - public static Color GetColor(this Role role) - { - return role switch - { - Role.Traitor => Color.Red, - Role.Detective => Color.Blue, - Role.Innocent => Color.Lime, - Role.Unassigned => Color.DarkGray, - _ => Color.Black - }; - } + public static Color GetColor(this Role role) { + return role switch { + Role.Traitor => Color.Red, + Role.Detective => Color.Blue, + Role.Innocent => Color.Lime, + Role.Unassigned => Color.DarkGray, + _ => Color.Black + }; + } } \ No newline at end of file diff --git a/public/TTT.Public/Formatting/StringUtils.cs b/public/TTT.Public/Formatting/StringUtils.cs index a0aa8be..c619439 100644 --- a/public/TTT.Public/Formatting/StringUtils.cs +++ b/public/TTT.Public/Formatting/StringUtils.cs @@ -2,16 +2,11 @@ namespace TTT.Public.Formatting; -public class StringUtils -{ - private StringUtils() - { - throw new NotSupportedException("Utility class"); - } +public class StringUtils { + private StringUtils() { throw new NotSupportedException("Utility class"); } - public static string FormatTTT(string message) - { - - return $" {ChatColors.Purple}[{ChatColors.Red}TTT{ChatColors.Purple}]{ChatColors.Green} {message}"; - } + public static string FormatTTT(string message) { + return + $" {ChatColors.Purple}[{ChatColors.Red}TTT{ChatColors.Purple}]{ChatColors.Green} {message}"; + } } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Detective/IDetectiveService.cs b/public/TTT.Public/Mod/Detective/IDetectiveService.cs index 5f31633..ef1a1dc 100644 --- a/public/TTT.Public/Mod/Detective/IDetectiveService.cs +++ b/public/TTT.Public/Mod/Detective/IDetectiveService.cs @@ -1,5 +1,3 @@ namespace TTT.Public.Mod.Detective; -public interface IDetectiveService -{ -} \ No newline at end of file +public interface IDetectiveService { } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Logs/ILogService.cs b/public/TTT.Public/Mod/Logs/ILogService.cs index 8e6f727..0725094 100644 --- a/public/TTT.Public/Mod/Logs/ILogService.cs +++ b/public/TTT.Public/Mod/Logs/ILogService.cs @@ -1,15 +1,13 @@ using CounterStrikeSharp.API.Core; -using TTT.Public.Action; namespace TTT.Public.Mod.Logs; -public interface ILogService -{ - int GetCurrentRound(); - void AddLog(Action.Action action); - bool PrintLogs(int round); - bool PrintToPlayer(CCSPlayerController player, int round); - bool PrintToConsole(int round); - IRoundLogs GetLogs(int round); - void CreateRound(int round); +public interface ILogService { + int GetCurrentRound(); + void AddLog(Action.Action action); + bool PrintLogs(int round); + bool PrintToPlayer(CCSPlayerController player, int round); + bool PrintToConsole(int round); + IRoundLogs GetLogs(int round); + void CreateRound(int round); } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Logs/IRoundLogs.cs b/public/TTT.Public/Mod/Logs/IRoundLogs.cs index 8b07784..35c2fb7 100644 --- a/public/TTT.Public/Mod/Logs/IRoundLogs.cs +++ b/public/TTT.Public/Mod/Logs/IRoundLogs.cs @@ -1,11 +1,8 @@ -using TTT.Public.Action; +namespace TTT.Public.Mod.Logs; -namespace TTT.Public.Mod.Logs; - -public interface IRoundLogs -{ - IList GetLogs(); - void AddLog(Action.Action action); - void RemoveLog(Action.Action action); - string FormattedLogs(); +public interface IRoundLogs { + IList GetLogs(); + void AddLog(Action.Action action); + void RemoveLog(Action.Action action); + string FormattedLogs(); } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Manager/IMuteService.cs b/public/TTT.Public/Mod/Manager/IMuteService.cs index d61fb7f..c3faa0c 100644 --- a/public/TTT.Public/Mod/Manager/IMuteService.cs +++ b/public/TTT.Public/Mod/Manager/IMuteService.cs @@ -2,10 +2,9 @@ namespace TTT.Public.Mod.Manager; -public interface IMuteService -{ - void Mute(CCSPlayerController player); - void UnMute(CCSPlayerController player); - void UnMuteAll(); - void MuteAll(); +public interface IMuteService { + void Mute(CCSPlayerController player); + void UnMute(CCSPlayerController player); + void UnMuteAll(); + void MuteAll(); } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Role/IRoleService.cs b/public/TTT.Public/Mod/Role/IRoleService.cs index 43ed3e2..ece0934 100644 --- a/public/TTT.Public/Mod/Role/IRoleService.cs +++ b/public/TTT.Public/Mod/Role/IRoleService.cs @@ -1,29 +1,23 @@ using CounterStrikeSharp.API.Core; using TTT.Public.Mod.Round; -using TTT.Public.Player; namespace TTT.Public.Mod.Role; -public interface IRoleService -{ - Role GetRole(CCSPlayerController player); - void AddRoles(); - IRoundService GetRoundService(); - ISet GetTraitors(); - ISet GetDetectives(); - ISet GetInnocents(); - bool IsDetective(CCSPlayerController player); - bool IsTraitor(CCSPlayerController player); - void AddDetective(CCSPlayerController player); - void AddTraitor(CCSPlayerController player); - void AddInnocents(IEnumerable players); - void Clear(); +public interface IRoleService { + Role GetRole(CCSPlayerController player); + void AddRoles(); + IRoundService GetRoundService(); + ISet GetTraitors(); + ISet GetDetectives(); + ISet GetInnocents(); + bool IsDetective(CCSPlayerController player); + bool IsTraitor(CCSPlayerController player); + void AddDetective(CCSPlayerController player); + void AddTraitor(CCSPlayerController player); + void AddInnocents(IEnumerable players); + void Clear(); } -public enum Role -{ - Traitor = 0, - Detective = 1, - Innocent = 2, - Unassigned = 3 +public enum Role { + Traitor = 0, Detective = 1, Innocent = 2, Unassigned = 3 } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Round/IRoundService.cs b/public/TTT.Public/Mod/Round/IRoundService.cs index 4869e48..8a22566 100644 --- a/public/TTT.Public/Mod/Round/IRoundService.cs +++ b/public/TTT.Public/Mod/Round/IRoundService.cs @@ -1,23 +1,17 @@ using CounterStrikeSharp.API.Core; -using TTT.Public.Action; namespace TTT.Public.Mod.Round; -public interface IRoundService -{ - RoundStatus GetRoundStatus(); - void SetRoundStatus(RoundStatus roundStatus); - void Start(BasePlugin plugin); +public interface IRoundService { + RoundStatus GetRoundStatus(); + void SetRoundStatus(RoundStatus roundStatus); + void Start(BasePlugin plugin); - void TickWaiting(); - void ForceStart(); - void ForceEnd(); + void TickWaiting(); + void ForceStart(); + void ForceEnd(); } -public enum RoundStatus -{ - Waiting, - Started, - Paused, - Ended +public enum RoundStatus { + Waiting, Started, Paused, Ended } \ No newline at end of file diff --git a/public/TTT.Public/Mod/Traitor/ITraitorService.cs b/public/TTT.Public/Mod/Traitor/ITraitorService.cs index 9dc1b67..2d5f949 100644 --- a/public/TTT.Public/Mod/Traitor/ITraitorService.cs +++ b/public/TTT.Public/Mod/Traitor/ITraitorService.cs @@ -1,6 +1,3 @@ namespace TTT.Public.Mod.Traitor; -public class ITraitorService -{ - -} \ No newline at end of file +public class ITraitorService { } \ No newline at end of file diff --git a/public/TTT.Public/Player/GamePlayer.cs b/public/TTT.Public/Player/GamePlayer.cs index c5f2b70..5533462 100644 --- a/public/TTT.Public/Player/GamePlayer.cs +++ b/public/TTT.Public/Player/GamePlayer.cs @@ -1,127 +1,73 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using TTT.Public.Mod.Role; -using TTT.Public.Player; namespace TTT.Player; -public class GamePlayer -{ - - private Role _playerRole; - private int _playerId; - private int _karma; - private long _credits; - private CCSPlayerController? _killer; - private bool _shopOpen = false; - private bool _isFound = false; - private bool _isDead = false; - - public GamePlayer(Role playerRole, long credits, int karma, int playerId) - { - _playerRole = playerRole; - _credits = credits; - _karma = karma; - _killer = null; - _playerId = playerId; - } - - public bool IsDead() - { - return _isDead; - } - - public void SetDead(bool isDead = false) - { - _isDead = isDead; - } - - public CCSPlayerController? Player() - { - return Utilities.GetPlayerFromUserid(_playerId); - } - - public Role PlayerRole() - { - return _playerRole; - } - - public int Karma() - { - return _karma; - } - - public void SetKarma(int karma) - { - _karma = karma; - } - - public void AddKarma(int karma) - { - _karma += karma; - } - - public void RemoveKarma(int karma) - { - _karma -= karma; - if (_karma >= 40) return; - _karma = 80; - //Server.ExecuteCommand($"css_ban #{_playerId} 1440 Karma too low"); - } - - public void SetPlayerRole(Role role) - { - _playerRole = role; - } - - public long Credits() - { - return _credits; - } - - public void AddCredits(long increment) - { - _credits += increment; - } - - public void RemoveCredits(long decrement) - { - _credits -= decrement; - } - - public void ResetCredits() - { - _credits = 800; - } - - public CCSPlayerController? Killer() - { - return _killer; - } - - public void SetKiller(CCSPlayerController? killer) - { - _killer = killer; - } - - public void SetShopOpen(bool open) - { - _shopOpen = open; - } - - public bool ShopOpen() - { - return _shopOpen; - } - - public bool SetFound(bool found) - { - _isFound = found; - return _isFound; - } - - public bool IsFound() - { - return _isFound; - } +public class GamePlayer { + private long _credits; + private bool _isDead; + private bool _isFound; + private int _karma; + private CCSPlayerController? _killer; + private readonly int _playerId; + + private Role _playerRole; + private bool _shopOpen; + + public GamePlayer(Role playerRole, long credits, int karma, int playerId) { + _playerRole = playerRole; + _credits = credits; + _karma = karma; + _killer = null; + _playerId = playerId; + } + + public bool IsDead() { return _isDead; } + + public void SetDead(bool isDead = false) { _isDead = isDead; } + + public CCSPlayerController? Player() { + return Utilities.GetPlayerFromUserid(_playerId); + } + + public Role PlayerRole() { return _playerRole; } + + public int Karma() { return _karma; } + + public void SetKarma(int karma) { _karma = karma; } + + public void AddKarma(int karma) { _karma += karma; } + + public void RemoveKarma(int karma) { + _karma -= karma; + if (_karma >= 40) return; + _karma = 80; + //Server.ExecuteCommand($"css_ban #{_playerId} 1440 Karma too low"); + } + + public void SetPlayerRole(Role role) { _playerRole = role; } + + public long Credits() { return _credits; } + + public void AddCredits(long increment) { _credits += increment; } + + public void RemoveCredits(long decrement) { _credits -= decrement; } + + public void ResetCredits() { _credits = 800; } + + public CCSPlayerController? Killer() { return _killer; } + + public void SetKiller(CCSPlayerController? killer) { _killer = killer; } + + public void SetShopOpen(bool open) { _shopOpen = open; } + + public bool ShopOpen() { return _shopOpen; } + + public bool SetFound(bool found) { + _isFound = found; + return _isFound; + } + + public bool IsFound() { return _isFound; } } \ No newline at end of file diff --git a/public/TTT.Public/Player/IPlayerService.cs b/public/TTT.Public/Player/IPlayerService.cs index aa51184..b474f37 100644 --- a/public/TTT.Public/Player/IPlayerService.cs +++ b/public/TTT.Public/Player/IPlayerService.cs @@ -1,16 +1,14 @@ using CounterStrikeSharp.API.Core; using TTT.Player; -using TTT.Public.Mod.Role; namespace TTT.Public.Player; -public interface IPlayerService -{ - List Players(); - GamePlayer GetPlayer(CCSPlayerController player); - void RemovePlayer(CCSPlayerController player); - void CreatePlayer(CCSPlayerController player); - void Clr(); - void AddKarma(CCSPlayerController player, int karma); - void RemoveKarma(CCSPlayerController player, int karma); +public interface IPlayerService { + List Players(); + GamePlayer GetPlayer(CCSPlayerController player); + void RemovePlayer(CCSPlayerController player); + void CreatePlayer(CCSPlayerController player); + void Clr(); + void AddKarma(CCSPlayerController player, int karma); + void RemoveKarma(CCSPlayerController player, int karma); } \ No newline at end of file diff --git a/public/TTT.Public/Shop/AbstractShopItem.cs b/public/TTT.Public/Shop/AbstractShopItem.cs index d7028f6..6f57c07 100644 --- a/public/TTT.Public/Shop/AbstractShopItem.cs +++ b/public/TTT.Public/Shop/AbstractShopItem.cs @@ -2,23 +2,19 @@ namespace TTT.Public.Shop; -public abstract class AbstractShopItem -{ - public abstract string Name { get; } - public abstract string ShortName { get; } - public abstract string Description { get; } - public abstract void OnBuy(GamePlayer player); - - public bool CanBuy(GamePlayer player) - { - return player.Credits() >= ItemCost(); - } - - public int ItemCost() - { - //grab from config - // config.getCost(Name) - return 0; - } +public abstract class AbstractShopItem { + public abstract string Name { get; } + public abstract string ShortName { get; } + public abstract string Description { get; } + public abstract void OnBuy(GamePlayer player); + public bool CanBuy(GamePlayer player) { + return player.Credits() >= ItemCost(); + } + + public int ItemCost() { + //grab from config + // config.getCost(Name) + return 0; + } } \ No newline at end of file diff --git a/public/TTT.Public/Shop/ShopConfig.cs b/public/TTT.Public/Shop/ShopConfig.cs index a987316..bc29f3f 100644 --- a/public/TTT.Public/Shop/ShopConfig.cs +++ b/public/TTT.Public/Shop/ShopConfig.cs @@ -1,8 +1,3 @@ -using CounterStrikeSharp.API.Core; +namespace TTT.Public.Shop; -namespace TTT.Public.Shop; - -public class ShopConfig -{ - -} \ No newline at end of file +public class ShopConfig { } \ No newline at end of file diff --git a/public/TTT.Public/TTT.Public.csproj b/public/TTT.Public/TTT.Public.csproj index 4740ad1..9fad0d0 100644 --- a/public/TTT.Public/TTT.Public.csproj +++ b/public/TTT.Public/TTT.Public.csproj @@ -1,11 +1,11 @@  - - net8.0 - enable - enable - - - - - + + net8.0 + enable + enable + + + + + \ No newline at end of file diff --git a/src/TTT.Generic/TTT.Generic.cs b/src/TTT.Generic/TTT.Generic.cs index b6fe055..47b334f 100644 --- a/src/TTT.Generic/TTT.Generic.cs +++ b/src/TTT.Generic/TTT.Generic.cs @@ -1,5 +1,3 @@ namespace TTT.Generic; -public class Class1 -{ -} \ No newline at end of file +public class Class1 { } \ No newline at end of file diff --git a/src/TTT/Config/ConfigService.cs b/src/TTT/Config/ConfigService.cs index 21737e4..1150bae 100644 --- a/src/TTT/Config/ConfigService.cs +++ b/src/TTT/Config/ConfigService.cs @@ -1,68 +1,62 @@ -using System.Text.Json; +using System.Text.Json; using System.Text.Json.Nodes; using CounterStrikeSharp.API; -using TTT.Public.Configuration; using Microsoft.Extensions.Logging; +using TTT.Public.Configuration; namespace TTT.Config; /// -/// A service to load and parse configuration files. +/// A service to load and parse configuration files. /// -public class ConfigService : IConfigService -{ - private readonly ILogger _logger; - - /// - /// Constructor - /// - /// - public ConfigService(ILogger logger) - { - _logger = logger; - } - - /// - /// - /// - /// - /// - /// - public T Get(string path, bool fail = false) - where T : class, new() - { - var jsonPath = Path.Combine(Server.GameDirectory, IConfigService.ConfigPath); - - if (!File.Exists(jsonPath)) - return Fail(fail, "Config file does not exist"); - - var jsonText = File.ReadAllText(jsonPath); - - var jsonObject = JsonNode.Parse(jsonText); - if (jsonObject == null) - return Fail(fail, $"Unable to parse configuration file at {jsonPath}"); - - var configObject = jsonObject[path]; - if (configObject == null) - return Fail(fail, $"Unable to navigate to config section {path}"); - - var config = configObject.Deserialize(); - if (config == null) - return Fail(fail, $"Unable to deserialize ({configObject.ToJsonString()}) into {typeof(T).FullName}."); - - return config; - } - - private T Fail(bool fail, string message) - where T : class, new() - { - // We would be returning default. - // Check if caller wants us to cry and scream instead. - if (fail) - throw new InvalidOperationException(message); - - _logger.LogWarning("[Config] Tripped load fail state with message: {@Message}", message); - - return new T(); - } +public class ConfigService : IConfigService { + private readonly ILogger _logger; + + /// + /// Constructor + /// + /// + public ConfigService(ILogger logger) { _logger = logger; } + + /// + /// + /// + /// + /// + /// + public T Get(string path, bool fail = false) where T : class, new() { + var jsonPath = + Path.Combine(Server.GameDirectory, IConfigService.ConfigPath); + + if (!File.Exists(jsonPath)) + return Fail(fail, "Config file does not exist"); + + var jsonText = File.ReadAllText(jsonPath); + + var jsonObject = JsonNode.Parse(jsonText); + if (jsonObject == null) + return Fail(fail, $"Unable to parse configuration file at {jsonPath}"); + + var configObject = jsonObject[path]; + if (configObject == null) + return Fail(fail, $"Unable to navigate to config section {path}"); + + var config = configObject.Deserialize(); + if (config == null) + return Fail(fail, + $"Unable to deserialize ({configObject.ToJsonString()}) into {typeof(T).FullName}."); + + return config; + } + + private T Fail(bool fail, string message) where T : class, new() { + // We would be returning default. + // Check if caller wants us to cry and scream instead. + if (fail) throw new InvalidOperationException(message); + + _logger.LogWarning( + "[Config] Tripped load fail state with message: {@Message}", message); + + return new T(); + } } \ No newline at end of file diff --git a/src/TTT/TTT.csproj b/src/TTT/TTT.csproj index ac57023..a561d3a 100644 --- a/src/TTT/TTT.csproj +++ b/src/TTT/TTT.csproj @@ -1,31 +1,31 @@  - - net8.0 - enable - enable - - - - - - - - - - + + net8.0 + enable + enable + - - - - - $(MSBuildThisFileDirectory)/../../build - $(PublishBaseDirectory)/TTT - false - false - true - - - - - + + + + + + + + + + + + + + $(MSBuildThisFileDirectory)/../../build + $(PublishBaseDirectory)/TTT + false + false + true + + + + + \ No newline at end of file diff --git a/src/TTT/TTTPlugin.cs b/src/TTT/TTTPlugin.cs index f9cf6f9..6addcb6 100644 --- a/src/TTT/TTTPlugin.cs +++ b/src/TTT/TTTPlugin.cs @@ -6,68 +6,63 @@ namespace TTT; -public class TTTPlugin : BasePlugin -{ - private readonly IServiceProvider _provider; - private IReadOnlyList? _extensions; - private IServiceScope? _scope; - - /// - /// The TTT plugin. - /// - /// - public TTTPlugin(IServiceProvider provider) - { - _provider = provider; - } +public class TTTPlugin : BasePlugin { + private readonly IServiceProvider _provider; + private IReadOnlyList? _extensions; + private IServiceScope? _scope; - /// - public override string ModuleName => "TTT"; + /// + /// The TTT plugin. + /// + /// + public TTTPlugin(IServiceProvider provider) { _provider = provider; } - /// - public override string ModuleVersion => "1.0.0"; + /// + public override string ModuleName => "TTT"; - /// - public override string ModuleAuthor => "NTM"; + /// + public override string ModuleVersion => "1.0.0"; - /// - public override void Load(bool hotReload) - { - Logger.LogInformation("[TTT] Loading..."); + /// + public override string ModuleAuthor => "NTM"; - _scope = _provider.CreateScope(); - _extensions = _scope.ServiceProvider.GetServices() - .ToImmutableList(); + /// + public override void Load(bool hotReload) { + Logger.LogInformation("[TTT] Loading..."); - Logger.LogInformation("[TTT] Found {@BehaviorCount} behaviors.", _extensions.Count); + _scope = _provider.CreateScope(); + _extensions = _scope.ServiceProvider.GetServices() + .ToImmutableList(); - foreach (var extension in _extensions) - { - // Register all event handlers on the extension object - RegisterAllAttributes(extension); + Logger.LogInformation("[TTT] Found {@BehaviorCount} behaviors.", + _extensions.Count); - // Tell the extension to start it's magic - extension.Start(this); + foreach (var extension in _extensions) { + // Register all event handlers on the extension object + RegisterAllAttributes(extension); - Logger.LogInformation("[TTT] Loaded behavior {@Behavior}", extension.GetType().FullName); - } + // Tell the extension to start it's magic + extension.Start(this); - base.Load(hotReload); + Logger.LogInformation("[TTT] Loaded behavior {@Behavior}", + extension.GetType().FullName); } - /// - public override void Unload(bool hotReload) - { - Logger.LogInformation("[TTT] Shutting down..."); + base.Load(hotReload); + } - if (_extensions != null) - foreach (var extension in _extensions) - extension.Dispose(); + /// + public override void Unload(bool hotReload) { + Logger.LogInformation("[TTT] Shutting down..."); - // Dispose of original extensions scope - // When loading again we will get a new scope to avoid leaking state. - _scope?.Dispose(); + if (_extensions != null) + foreach (var extension in _extensions) + extension.Dispose(); - base.Unload(hotReload); - } + // Dispose of original extensions scope + // When loading again we will get a new scope to avoid leaking state. + _scope?.Dispose(); + + base.Unload(hotReload); + } } \ No newline at end of file diff --git a/src/TTT/TTTServiceCollection.cs b/src/TTT/TTTServiceCollection.cs index 7644954..7b5db9f 100644 --- a/src/TTT/TTTServiceCollection.cs +++ b/src/TTT/TTTServiceCollection.cs @@ -5,18 +5,15 @@ using TTT.Manager; using TTT.Player; using TTT.Roles; -using TTT.Round; namespace TTT; -public class TTTServiceCollection : IPluginServiceCollection -{ - public void ConfigureServices(IServiceCollection serviceCollection) - { - serviceCollection.AddPlayerService(); - serviceCollection.AddTTTRoles(); - serviceCollection.AddDetectiveBehavior(); - serviceCollection.AddLogsService(); - serviceCollection.AddManagerService(); - } +public class TTTServiceCollection : IPluginServiceCollection { + public void ConfigureServices(IServiceCollection serviceCollection) { + serviceCollection.AddPlayerService(); + serviceCollection.AddTTTRoles(); + serviceCollection.AddDetectiveBehavior(); + serviceCollection.AddLogsService(); + serviceCollection.AddManagerService(); + } } \ No newline at end of file