From c4055bb903fad9654a0d9ac99df72beb6d77566b Mon Sep 17 00:00:00 2001 From: MSWS Date: Sat, 20 Jul 2024 15:02:49 -0700 Subject: [PATCH] Revert "Cleanup (#9)" This reverts commit 5946b4cd9b52300f449e9bf2f33650f7608946b4. --- TTT.sln | 7 + TTT.sln.DotSettings | 95 ---- a | 1 + .gitignore => gitignore | 24 +- mod/TTT.Detective/DetectiveConfig.cs | 6 +- mod/TTT.Detective/DetectiveManager.cs | 186 ++++---- .../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 | 88 ++-- 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 | 235 ++++----- mod/TTT.Manager/ManagerServiceExtension.cs | 16 +- mod/TTT.Manager/MuteManager.cs | 143 +++--- mod/TTT.Manager/TTT.Manager.csproj | 2 +- mod/TTT.Manager/TraitorRoom.cs | 47 +- mod/TTT.Player/AntiBlockManager.cs | 81 ++-- 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 | 444 ++++++++++-------- 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 | 164 ++++--- mod/TTT.Round/RoundBehavior.cs | 226 ++++----- 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 | 22 +- .../TTT.Public/Mod/Traitor/ITraitorService.cs | 5 +- public/TTT.Public/Player/GamePlayer.cs | 177 ++++--- 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 +- 93 files changed, 2792 insertions(+), 2275 deletions(-) delete mode 100644 TTT.sln.DotSettings create mode 100644 a rename .gitignore => gitignore (88%) diff --git a/TTT.sln b/TTT.sln index f66b749..8d65e6e 100644 --- a/TTT.sln +++ b/TTT.sln @@ -11,6 +11,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mod", "mod", "{14FF3D75-F9C EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TTT", "src\TTT\TTT.csproj", "{A917B0F5-762F-4C4A-9F50-02BA4A0C6B63}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TTT.Generic", "src\TTT.Generic\TTT.Generic.csproj", "{953B2EA0-EFFC-475D-85CA-F7E5224BBFE1}" +EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TTT.Public", "public\TTT.Public\TTT.Public.csproj", "{8B006910-4BE0-491C-9F28-C60443E3251D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TTT.Detective", "mod\TTT.Detective\TTT.Detective.csproj", "{B6A65935-2233-4C74-A7EA-C2D64967CE52}" @@ -42,6 +44,10 @@ Global {A917B0F5-762F-4C4A-9F50-02BA4A0C6B63}.Debug|Any CPU.Build.0 = Debug|Any CPU {A917B0F5-762F-4C4A-9F50-02BA4A0C6B63}.Release|Any CPU.ActiveCfg = Release|Any CPU {A917B0F5-762F-4C4A-9F50-02BA4A0C6B63}.Release|Any CPU.Build.0 = Release|Any CPU + {953B2EA0-EFFC-475D-85CA-F7E5224BBFE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {953B2EA0-EFFC-475D-85CA-F7E5224BBFE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {953B2EA0-EFFC-475D-85CA-F7E5224BBFE1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {953B2EA0-EFFC-475D-85CA-F7E5224BBFE1}.Release|Any CPU.Build.0 = Release|Any CPU {8B006910-4BE0-491C-9F28-C60443E3251D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B006910-4BE0-491C-9F28-C60443E3251D}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B006910-4BE0-491C-9F28-C60443E3251D}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -81,6 +87,7 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {A917B0F5-762F-4C4A-9F50-02BA4A0C6B63} = {C7CCF187-9F99-4091-B092-6397C35BE9F1} + {953B2EA0-EFFC-475D-85CA-F7E5224BBFE1} = {C7CCF187-9F99-4091-B092-6397C35BE9F1} {8B006910-4BE0-491C-9F28-C60443E3251D} = {C84CEB1F-0132-43EF-9A5F-12C7AA08B8E7} {B6A65935-2233-4C74-A7EA-C2D64967CE52} = {14FF3D75-F9CF-4A32-9F59-83765EA68874} {0E7A451E-D56F-4D96-9B5C-5F1B0A6B0656} = {14FF3D75-F9CF-4A32-9F59-83765EA68874} diff --git a/TTT.sln.DotSettings b/TTT.sln.DotSettings deleted file mode 100644 index f239129..0000000 --- a/TTT.sln.DotSettings +++ /dev/null @@ -1,95 +0,0 @@ - - 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 new file mode 100644 index 0000000..7898192 --- /dev/null +++ b/a @@ -0,0 +1 @@ +a diff --git a/.gitignore b/gitignore similarity index 88% rename from .gitignore rename to gitignore index aad3b71..d3bf8e7 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/mod/TTT.Detective/DetectiveConfig.cs b/mod/TTT.Detective/DetectiveConfig.cs index f91d36d..04a1344 100644 --- a/mod/TTT.Detective/DetectiveConfig.cs +++ b/mod/TTT.Detective/DetectiveConfig.cs @@ -1,5 +1,7 @@ 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 535bc7a..f22acc3 100644 --- a/mod/TTT.Detective/DetectiveManager.cs +++ b/mod/TTT.Detective/DetectiveManager.cs @@ -1,7 +1,9 @@ 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; @@ -11,109 +13,135 @@ 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.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(); } - if (info.BitsDamageType is not 256) return HookResult.Continue; - if (attacker == null) return HookResult.Continue; + public HookResult OnZeus(DynamicHook hook) + { + var ent = hook.GetParam(0); - info.Damage = 0; + var playerWhoWasDamaged = player(ent); - var targetRole = roleService.GetPlayer(playerWhoWasDamaged); + if (playerWhoWasDamaged == null) return HookResult.Continue; - Server.NextFrame(() => { - attacker.PrintToChat(StringUtils.FormatTTT( - $"You tased player {playerWhoWasDamaged.PlayerName} they are a {targetRole.PlayerRole().FormatRoleFull()}")); - }); + var info = hook.GetParam(1); - return HookResult.Stop; - } + CCSPlayerController? attacker = null; + if (info.Attacker.Value != null) + { + var playerWhoAttacked = info.Attacker.Value.As(); - private void OnPlayerUse(CCSPlayerController player) { IdentifyBody(player); } + attacker = playerWhoAttacked.Controller.Value.As(); - private void IdentifyBody(CCSPlayerController caller) { - if (roleService.GetPlayer(caller).PlayerRole() != Role.Detective) return; + } - var entity = caller.GetClientRagdollAimTarget(); + if (info.BitsDamageType is not 256) return HookResult.Continue; + if (attacker == null) return HookResult.Continue; - if (entity == null || !entity.PawnIsAlive) return; + info.Damage = 0; - var player = roleService.GetPlayer(entity); + var targetRole = roleService.GetPlayer(playerWhoWasDamaged); - if (player.IsFound()) return; - - var killerEntity = player.Killer(); - - string message; - - var plr = player.Player(); - if (plr == null) return; + Server.NextFrame(() => + { + attacker.PrintToChat( + StringUtils.FormatTTT( + $"You tased player {playerWhoWasDamaged.PlayerName} they are a {targetRole.PlayerRole().FormatRoleFull()}")); + }); + + return HookResult.Stop; + } - 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)); + + private void OnPlayerUse(CCSPlayerController player) + { + IdentifyBody(player); + } - player.SetFound(true); + private void IdentifyBody(CCSPlayerController caller) + { + //add states - Server.NextFrame(() => { Server.PrintToChatAll(message); }); - } + if (roleService.GetPlayer(caller).PlayerRole() != Role.Detective) return; - //to be moved to a utility class - public static CCSPlayerController? player(CEntityInstance? instance) { - if (instance == null) return null; + var entity = caller.GetClientRagdollAimTarget(); - if (instance.DesignerName != "player") return null; + if (entity == null) return; + + if (entity.PawnIsAlive) return; + + var player = roleService.GetPlayer(entity); - // grab the pawn index - var player_index = (int)instance.Index; + if (player.IsFound()) return; + + var killerEntity= player.Killer(); + + string message; - // grab player controller from pawn - var player_pawn = Utilities.GetEntityFromIndex(player_index); + var plr = player.Player(); + if (plr == null) return; - // pawn valid - if (player_pawn == null || !player_pawn.IsValid) return null; + 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)); - // controller valid - if (player_pawn.OriginalController is not { IsValid: true }) return null; - // any further validity is up to the caller - return player_pawn.OriginalController.Value; - } + 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; + } } \ No newline at end of file diff --git a/mod/TTT.Detective/DetectiveServiceExtension.cs b/mod/TTT.Detective/DetectiveServiceExtension.cs index a3ba82e..e13d267 100644 --- a/mod/TTT.Detective/DetectiveServiceExtension.cs +++ b/mod/TTT.Detective/DetectiveServiceExtension.cs @@ -4,8 +4,10 @@ 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 961cd21..cf4da7c 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 d16c827..f53703b 100644 --- a/mod/TTT.Logs/LogBehavior.cs +++ b/mod/TTT.Logs/LogBehavior.cs @@ -1,6 +1,9 @@ -using CounterStrikeSharp.API; +using System.Collections.Generic; +using System.Linq; +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; @@ -8,50 +11,73 @@ namespace TTT.Logs; -public class LogBehavior : ILogService, IPluginBehavior { - private readonly Dictionary logs = new(); - private int currentRound = 1; +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 int GetCurrentRound() { return currentRound; } + 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 void AddLog(Action action) { logs[currentRound].AddLog(action); } + public bool PrintToPlayer(CCSPlayerController player, int round) + { + if (!_logs.ContainsKey(round)) return false; + player.PrintToConsole(GetLogs(round).FormattedLogs()); + return true; + } - public bool PrintLogs(int round) { - if (logs.ContainsKey(round)) return false; - foreach (var player in Utilities.GetPlayers()) PrintToPlayer(player, round); + public bool PrintToConsole(int round) + { + if (!_logs.ContainsKey(round)) return false; + Server.PrintToConsole(GetLogs(round).FormattedLogs()); + return true; + } - 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 __) { - // TODO: This looks wrong, should be ++currentRound - CreateRound(currentRound++); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd _, GameEventInfo __) { - PrintLogs(currentRound); - return HookResult.Continue; - } + public IRoundLogs GetLogs(int round) + { + return _logs[round]; + } + + public void CreateRound(int round) + { + _logs.Add(round, new RoundLog(round)); + } } \ No newline at end of file diff --git a/mod/TTT.Logs/LogServiceExtension.cs b/mod/TTT.Logs/LogServiceExtension.cs index 55dc6b2..f7b3feb 100644 --- a/mod/TTT.Logs/LogServiceExtension.cs +++ b/mod/TTT.Logs/LogServiceExtension.cs @@ -1,13 +1,16 @@ 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 a808031..5e5458a 100644 --- a/mod/TTT.Logs/LogsCommand.cs +++ b/mod/TTT.Logs/LogsCommand.cs @@ -8,44 +8,56 @@ 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) { } - - [ConsoleCommand("css_logs", "Prints logs to console")] - 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 roundId = service.GetCurrentRound(); - - if (info.ArgCount == 2) { - if (!int.TryParse(info.GetArg(1), out roundId) || roundId <= 0) { - info.ReplyToCommand( - StringUtils.FormatTTT("Invalid round id, /logs ")); - return; - } + public void Start(BasePlugin plugin) + { + } - - 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; + + [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")); } - - 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 787e454..a59382e 100644 --- a/mod/TTT.Logs/LogsListener.cs +++ b/mod/TTT.Logs/LogsListener.cs @@ -1,4 +1,5 @@ -using CounterStrikeSharp.API.Core; +using System; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using TTT.Public.Action; using TTT.Public.Behaviors; @@ -9,52 +10,49 @@ 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; +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; } - - 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 a190563..dcecb1e 100644 --- a/mod/TTT.Logs/RoundLog.cs +++ b/mod/TTT.Logs/RoundLog.cs @@ -1,29 +1,45 @@ -using System.Text; +using System.Collections.Generic; +using System.Text; +using TTT.Public.Action; 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 fc5f91b..ca14336 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 5b5b51f..c34d37c 100644 --- a/mod/TTT.Manager/ChatManager.cs +++ b/mod/TTT.Manager/ChatManager.cs @@ -1,42 +1,52 @@ -using CounterStrikeSharp.API.Core; +using System; +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 18ef35c..1866918 100644 --- a/mod/TTT.Manager/InfoManager.cs +++ b/mod/TTT.Manager/InfoManager.cs @@ -1,141 +1,154 @@ -using CounterStrikeSharp.API; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +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(IPlayerService playerService, IRoleService manager) - : IPluginBehavior { - private readonly IRoundService manager = manager.GetRoundService(); - - private readonly - Dictionary> - playerLookAtRole = new(); - - private readonly Dictionary> - spectatorLookAtRole = new(); - - public void Start(BasePlugin plugin) { - plugin.RegisterListener(OnTick); - plugin.AddTimer(0.1f, OnTickAll, TimerFlags.REPEAT); - } +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 void Reset() { - playerLookAtRole.Clear(); - spectatorLookAtRole.Clear(); - } + public void Reset() + { + _playerLookAtRole.Clear(); + _spectatorLookAtRole.Clear(); + } + + public void RegisterLookAtRole(CCSPlayerController player, Tuple role) + { + _playerLookAtRole.TryAdd(player, role); + } - public void RegisterLookAtRole(CCSPlayerController player, - Tuple role) { - playerLookAtRole.TryAdd(player, role); - } + public void RemoveLookAtRole(CCSPlayerController player) + { + _playerLookAtRole.Remove(player); + } - public void RemoveLookAtRole(CCSPlayerController player) { - playerLookAtRole.Remove(player); - } + public void OnTick() + { + foreach (var gamePlayer in _playerService.Players()) + { + if (_manager.GetRoundStatus() != RoundStatus.Started) return; - public void OnTick() { - if (manager.GetRoundStatus() != RoundStatus.Started) return; - foreach (var gamePlayer in playerService.Players()) { - var player = gamePlayer.Player(); + var player = gamePlayer.Player(); - if (player == null) continue; - if (!player.IsReal()) continue; + if (player == null) continue; + if (!player.IsReal()) continue; - var playerRole = gamePlayer.PlayerRole(); + var playerRole = gamePlayer.PlayerRole(); - if (playerRole == Role.Unassigned) continue; + if (playerRole == Role.Unassigned) continue; - if (!player.PawnIsAlive) continue; + if (!player.PawnIsAlive) continue; - if (!playerLookAtRole.TryGetValue(player, out var value)) { - player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}"); - continue; - } + if (!_playerLookAtRole.TryGetValue(player, out var value)) + { + Server.NextFrame(() => + player.PrintToCenterHtml( + $"Your Role: {playerRole.GetCenterRole()}")); + continue; + } - if (!value.Item1.IsReal()) continue; + if (!value.Item1.IsReal()) continue; - if (!value.Item1.PawnIsAlive) - HandleDeadTarget(player, playerRole, value.Item1, value.Item2); - else - HandleAliveTarget(player, playerRole, value.Item1, value.Item2); + if (!value.Item1.PawnIsAlive) HandleDeadTarget(player, playerRole, value.Item1, value.Item2); + else HandleAliveTarget(player, playerRole, value.Item1, value.Item2); + } } - } - - public void - HandleDeadTarget(CCSPlayerController player, Role playerRole, - CCSPlayerController target, Role targetRole) { - 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: - player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}"); - return; - case Role.Traitor when playerRole == Role.Traitor: - player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}"); - return; - default: + + public void HandleDeadTarget(CCSPlayerController player, Role playerRole, CCSPlayerController target, Role targetRole) + { Server.NextFrame(() => player.PrintToCenterHtml( - $"Your Role: {playerRole.GetCenterRole()}
" - + $"{target.PlayerName}'s Role: {Role.Unassigned.GetCenterRole()}")); - break; + $"Your Role: {playerRole.GetCenterRole()}
" + + $"{target.PlayerName}'s Corpse
" + + $"{target.PlayerName}'s Role: {targetRole.GetCenterRole()}")); } - } - - public void OnTickAll() { - var players = playerService.Players() - .Select(plr => plr.Player()) - .Where(p => p != null && p.IsReal()) - .ToList(); - playerLookAtRole.Clear(); - - foreach (var player in players) { - if (player == null) continue; - if (!player.IsReal()) continue; - - var target = player.GetClientPlayerAimTarget(); - - if (target == null || !target.IsReal()) continue; - if (!target.IsReal()) continue; - - RegisterLookAtRole(player, - new Tuple(target, - playerService.GetPlayer(target).PlayerRole())); + 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; + + 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 == null || !player.IsReal() || !target.IsReal()) - return HookResult.Continue; - - spectatorLookAtRole.TryAdd(player, - new Tuple(target.PlayerName, - playerService.GetPlayer(target).PlayerRole())); - return HookResult.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; + } } \ No newline at end of file diff --git a/mod/TTT.Manager/ManagerServiceExtension.cs b/mod/TTT.Manager/ManagerServiceExtension.cs index cdafe34..73c6d15 100644 --- a/mod/TTT.Manager/ManagerServiceExtension.cs +++ b/mod/TTT.Manager/ManagerServiceExtension.cs @@ -4,11 +4,13 @@ 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 8eccd38..e602e1c 100644 --- a/mod/TTT.Manager/MuteManager.cs +++ b/mod/TTT.Manager/MuteManager.cs @@ -1,4 +1,5 @@ -using CounterStrikeSharp.API; +using System.Linq; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; @@ -9,69 +10,95 @@ namespace TTT.Manager; -public class MuteManager : IMuteService, IPluginBehavior { - public void Mute(CCSPlayerController player) { - if (BypassMute(player)) return; - - 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.Team is CsTeam.Terrorist or CsTeam.CounterTerrorist)) - UnMute(player); - } +public class MuteManager : IMuteService, IPluginBehavior +{ + public void Start(BasePlugin plugin) + { + plugin.RegisterListener(OnPlayerSpeak); + } - public void MuteAll() { - foreach (var player in Utilities.GetPlayers() - .Where(player - => player.Team is CsTeam.Terrorist or CsTeam.CounterTerrorist)) - Mute(player); - } + [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; + } - public void Start(BasePlugin plugin) { - plugin.RegisterListener(OnPlayerSpeak); - } + 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); + } + } - [GameEventHandler] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { - if (@event.Userid == null) return HookResult.Continue; - Mute(@event.Userid); - return HookResult.Continue; - } + 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); + } + } - [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; - private void OnPlayerSpeak(int playerSlot) { - var player = Utilities.GetPlayerFromSlot(playerSlot); - if (player == null || !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; + } - if (!player.PawnIsAlive && !BypassMute(player)) { - // Normal players can't speak when dead - Mute(player); - player.PrintToCenter("You are dead and muted!"); - return; + 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; } - if (IsMuted(player)) 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"); - } + 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 72ebcba..d0b8182 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 7032376..2ef1705 100644 --- a/mod/TTT.Manager/TraitorRoom.cs +++ b/mod/TTT.Manager/TraitorRoom.cs @@ -6,22 +6,39 @@ 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(); - public void OpenTraitorRoom(CCSPlayerController player) { - if ((player.Buttons & PlayerButtons.Use) == 0) return; + if (traitorRoom == null) + { + Server.NextFrame(() => player.PrintToCenter("No door has been found!")); + return; + } - var traitorRoom = player.GetClientPlayerTraitorRoom(); + if (traitorRoom.Globalname is not "traitor_door") + { + Server.NextFrame(() => player.PrintToCenter("Door is not a traitor room!")); + return; + } - if (traitorRoom?.Globalname != "traitor_door") return; - - traitorRoom.AcceptInput("Open"); - } + 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 54e9a8b..14dc7d3 100644 --- a/mod/TTT.Player/AntiBlockManager.cs +++ b/mod/TTT.Player/AntiBlockManager.cs @@ -11,55 +11,62 @@ namespace TTT.Player; -public class AntiBlockManager : IPluginBehavior { - private readonly WIN_LINUX OnCollisionRulesChangedOffset = new(173, 172); +public class AntiBlockManager : IPluginBehavior +{ + public void Start(BasePlugin plugin) + { + } + + [GameEventHandler] + private HookResult Event_PlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) + { + if (!@event.Userid.IsValid) return HookResult.Continue; + + var player = @event.Userid; - public void Start(BasePlugin plugin) { } + if (!player.IsReal()) return HookResult.Continue; - [GameEventHandler] - private HookResult Event_PlayerSpawn(EventPlayerSpawn @event, - GameEventInfo info) { - var player = @event.Userid; - if (player == null || !player.IsValid) return HookResult.Continue; - if (!player.IsReal()) return HookResult.Continue; - if (!player.PlayerPawn.IsValid) return HookResult.Continue; + if (!player.PlayerPawn.IsValid) return HookResult.Continue; - var pawn = player.PlayerPawn; - if (pawn.Value == null) return HookResult.Continue; + var pawn = player.PlayerPawn; - PlayerSpawnNextFrame(player, pawn.Value!); - return HookResult.Continue; - } + Server.NextFrame(() => PlayerSpawnNextFrame(player, pawn)); + + return HookResult.Continue; + } - private void PlayerSpawnNextFrame(CCSPlayerController player, - CCSPlayerPawn pawn) { - pawn.Collision.CollisionGroup = - (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; + private readonly WIN_LINUX OnCollisionRulesChangedOffset = new(173, 172); - pawn.Collision.CollisionAttribute.CollisionGroup = - (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; + private void PlayerSpawnNextFrame(CCSPlayerController player, CHandle pawn) + { + pawn.Value.Collision.CollisionGroup = (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; - var collisionRulesChanged = new VirtualFunctionVoid(pawn.Handle, - OnCollisionRulesChangedOffset.Get()); + pawn.Value.Collision.CollisionAttribute.CollisionGroup = (byte)CollisionGroup.COLLISION_GROUP_DISSOLVING; - collisionRulesChanged.Invoke(pawn.Handle); - } + var collisionRulesChanged = + new VirtualFunctionVoid(pawn.Value.Handle, OnCollisionRulesChangedOffset.Get()); - public class WIN_LINUX { - public WIN_LINUX(T windows, T linux) { - Windows = windows; - Linux = linux; + collisionRulesChanged.Invoke(pawn.Value.Handle); } + + public class WIN_LINUX + { + [JsonPropertyName("Windows")] public T Windows { get; private set; } - [JsonPropertyName("Windows")] - public T Windows { get; } + [JsonPropertyName("Linux")] public T Linux { get; private set; } - [JsonPropertyName("Linux")] - public T Linux { get; } + public WIN_LINUX(T windows, T linux) + { + Windows = windows; + Linux = linux; + } - public T Get() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Windows; - return Linux; + public T Get() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return Windows; + else + return Linux; + } } - } } \ No newline at end of file diff --git a/mod/TTT.Player/CreditManager.cs b/mod/TTT.Player/CreditManager.cs index bf5b46b..b694b93 100644 --- a/mod/TTT.Player/CreditManager.cs +++ b/mod/TTT.Player/CreditManager.cs @@ -1,40 +1,49 @@ 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 void Start(BasePlugin plugin) { } +public class CreditManager(IPlayerService playerService) : IPluginBehavior +{ - - [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; + public void Start(BasePlugin plugin) + { + } - - if (attackerPlayer.PlayerRole() != Role.Traitor - && victimPlayer.PlayerRole() == Role.Traitor) { - attackerPlayer.AddCredits(500); - 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; } - 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 a58d35e..c5b9517 100644 --- a/mod/TTT.Player/KarmaManager.cs +++ b/mod/TTT.Player/KarmaManager.cs @@ -7,29 +7,37 @@ 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(); - - if (killerRole == killedRole) { - gpKiller.RemoveKarma(5); - return HookResult.Continue; +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(); - if (killedRole == Role.Traitor) gpKiller.AddKarma(2); - return HookResult.Continue; - } -} \ No newline at end of file + if (killerRole == killedRole) + { + gpKiller.RemoveKarma(5); + return HookResult.Continue; + } + + if (killedRole == Role.Traitor) + { + gpKiller.AddKarma(2); + } + return HookResult.Continue; + } +} diff --git a/mod/TTT.Player/PlayerBehavior.cs b/mod/TTT.Player/PlayerBehavior.cs index 61a03ee..9785918 100644 --- a/mod/TTT.Player/PlayerBehavior.cs +++ b/mod/TTT.Player/PlayerBehavior.cs @@ -1,4 +1,7 @@ -using CounterStrikeSharp.API.Core; +using System; +using System.Collections.Generic; +using System.Linq; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using TTT.Public.Behaviors; using TTT.Public.Mod.Role; @@ -7,69 +10,82 @@ namespace TTT.Player; -public class PlayerBehavior : IPlayerService, IPluginBehavior { - private readonly Dictionary _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 List Players() { return _players.Values.ToList(); } - - public GamePlayer GetPlayer(CCSPlayerController player) { - return _players[player]; - } - - public void RemovePlayer(CCSPlayerController player) { - _players.Remove(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 void Clr() { - foreach (var player in Players()) { - player.SetKiller(null); - player.SetPlayerRole(Role.Unassigned); - player.ResetCredits(); - player.ModifyKarma(); - player.SetFound(false); - player.SetDead(); + public List Players() + { + return _players.Values.ToList(); } - } - public void Start(BasePlugin plugin) { } + public GamePlayer GetPlayer(CCSPlayerController player) + { + return _players[player]; + } - [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 void RemovePlayer(CCSPlayerController player) + { + _players.Remove(player); + } - public Dictionary GetPlayers() { - return _players; - } + public void Clr() + { + foreach (var player in Players()) + { + player.SetKiller(null); + player.SetPlayerRole(Role.Unassigned); + player.ResetCredits(); + player.ModifyKarma(); + player.SetFound(false); + player.SetDead(); + } + } } \ No newline at end of file diff --git a/mod/TTT.Player/PlayerConfig.cs b/mod/TTT.Player/PlayerConfig.cs index fdea2c6..51d41de 100644 --- a/mod/TTT.Player/PlayerConfig.cs +++ b/mod/TTT.Player/PlayerConfig.cs @@ -1,8 +1,9 @@ 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 322892f..048c288 100644 --- a/mod/TTT.Player/PlayerServiceExtension.cs +++ b/mod/TTT.Player/PlayerServiceExtension.cs @@ -5,11 +5,13 @@ namespace TTT.Player; -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 +public static class PlayerServiceExtension +{ + public static void AddPlayerService(this IServiceCollection collection) + { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } +} diff --git a/mod/TTT.Player/TTT.Player.csproj b/mod/TTT.Player/TTT.Player.csproj index fc5f91b..ce5ec60 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 ad15978..c396b49 100644 --- a/mod/TTT.Roles/Commands/RolesCommand.cs +++ b/mod/TTT.Roles/Commands/RolesCommand.cs @@ -1,9 +1,12 @@ 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; @@ -11,44 +14,49 @@ 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 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 RolesCommand(IPlayerService roleService, IRoleService roundService) + { + _roleService = roleService; + _roundService = roundService.GetRoundService(); } - - if (_roundService.GetRoundStatus() != RoundStatus.Started) { - command.ReplyToCommand( - StringUtils.FormatTTT("The round has not started yet.")); - return; + + public void Start(BasePlugin plugin) + { + } - - 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))); + + [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.")); } - - 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 7dc4efd..986e14f 100644 --- a/mod/TTT.Roles/ModelHandler.cs +++ b/mod/TTT.Roles/ModelHandler.cs @@ -3,34 +3,36 @@ 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(_ => { - 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(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); + }); + } } \ No newline at end of file diff --git a/mod/TTT.Roles/RoleBehavior.cs b/mod/TTT.Roles/RoleBehavior.cs index b48ae0e..be4a477 100644 --- a/mod/TTT.Roles/RoleBehavior.cs +++ b/mod/TTT.Roles/RoleBehavior.cs @@ -4,6 +4,7 @@ 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; @@ -14,253 +15,286 @@ namespace TTT.Roles; -public class RoleBehavior : IRoleService, IPluginBehavior { - private const int MaxDetectives = 3; - private readonly IPlayerService service; +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 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); + */ + } - private int _innocentsLeft; - private readonly IRoundService _roundService; - private int _traitorsLeft; + public IRoundService GetRoundService() + { + return _roundService; + } + + [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 RoleBehavior(IPlayerService playerService) { - _roundService = new RoundBehavior(this); - service = playerService; - } + [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; + } - public void Start(BasePlugin parent) { - ModelHandler.RegisterListener(parent); - _roundService.Start(parent); - } + [GameEventHandler(HookMode.Pre)] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) + { + info.DontBroadcast = true; - public IRoundService GetRoundService() { return _roundService; } + var playerWhoWasDamaged = @event.Userid; + var attacker = @event.Attacker; + + + + + if (playerWhoWasDamaged == null) return HookResult.Continue; - public void AddRoles() { - var eligible = Utilities.GetPlayers() - .Where(player => player.IsReal()) - .Where(player => player.Team is not (CsTeam.Spectator or CsTeam.None)) - .ToList(); + SetColor(playerWhoWasDamaged); + + playerWhoWasDamaged.ModifyScoreBoard(); - var traitorCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 3)); - var detectiveCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 8)); + service.GetPlayer(playerWhoWasDamaged).SetKiller(attacker); + + if (IsTraitor(playerWhoWasDamaged)) _traitorsLeft--; - _traitorsLeft = traitorCount; - _innocentsLeft = eligible.Count - traitorCount; + if (IsDetective(playerWhoWasDamaged) || IsInnocent(playerWhoWasDamaged)) _innocentsLeft--; - if (detectiveCount > MaxDetectives) detectiveCount = MaxDetectives; + if (_traitorsLeft == 0 || _innocentsLeft == 0) Server.NextFrame(() => _roundService.ForceEnd()); - for (var i = 0; i < traitorCount; i++) { - var chosen = eligible[Random.Shared.Next(eligible.Count)]; - eligible.Remove(chosen); - AddTraitor(chosen); - } + Server.NextFrame(() => + { + Server.PrintToChatAll( + StringUtils.FormatTTT($"{GetRole(playerWhoWasDamaged).FormatStringFullAfter(" has been found.")}")); - for (var i = 0; i < detectiveCount; i++) { - var chosen = eligible[Random.Shared.Next(eligible.Count)]; - eligible.Remove(chosen); - AddDetective(chosen); - } + if (attacker == playerWhoWasDamaged || attacker == null) return; - AddInnocents(eligible.ToArray()); - } - - public ISet GetTraitors() { - return GetByRole(Role.Traitor); - } - - public ISet GetDetectives() { - return GetByRole(Role.Detective); - } - - public ISet GetInnocents() { - return GetByRole(Role.Innocent); - } - - public ISet GetByRole(Role role) { - return service.Players() - .Where(player => player.PlayerRole() == role) - .Select(player => player.Player()) - .Where(p => p != null) - .ToHashSet()!; - } - - public Role GetRole(CCSPlayerController player) { - return service.GetPlayer(player).PlayerRole(); - } - - public void AddTraitor(params CCSPlayerController[] players) { - foreach (var player in players) { - service.GetPlayer(player).SetPlayerRole(Role.Traitor); - player.SwitchTeam(CsTeam.Terrorist); - player.PrintToCenter( - Role.Traitor.FormatStringFullBefore("You are now a")); - player.PrintToChat(Role.Traitor.FormatStringFullBefore("You are now a")); - ModelHandler.SetModel(player, ModelHandler.ModelPathTmPhoenix); - } - } - - public void AddDetective(params CCSPlayerController[] players) { - foreach (var player in players) { - service.GetPlayer(player).SetPlayerRole(Role.Detective); - player.SwitchTeam(CsTeam.CounterTerrorist); - player.PrintToCenter( - Role.Detective.FormatStringFullBefore("You are now a")); - player.GiveNamedItem(CsItem.Taser); - ModelHandler.SetModel(player, ModelHandler.ModelPathCtmSas); - } - } - - public void AddInnocents(params CCSPlayerController[] 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.SetModel(player, ModelHandler.ModelPathTmPhoenix); - } - } - - 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 - 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(); - player.GiveNamedItem("weapon_glock"); - player.GiveNamedItem("weapon_knife"); - service.GetPlayer(player).ModifyKarma(); - } + attacker.ModifyScoreBoard(); - return HookResult.Continue; - } + playerWhoWasDamaged.PrintToChat(StringUtils.FormatTTT( + $"You were killed by {GetRole(attacker).FormatStringFullAfter(" " + attacker.PlayerName)}.")); + attacker.PrintToChat(StringUtils.FormatTTT( + $"You killed {GetRole(playerWhoWasDamaged).FormatStringFullAfter(" " + playerWhoWasDamaged.PlayerName)}.")); + }); - [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; + } - return HookResult.Continue; - } + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) + { + var players = Utilities.GetPlayers() + .Where(player => player.IsValid).Where(player => player.IsReal()).ToList(); - [GameEventHandler(HookMode.Pre)] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { - info.DontBroadcast = true; + foreach (var player in players) player.PrintToCenter(GetWinner().FormatStringFullAfter("s has won!")); - var playerWhoWasDamaged = @event.Userid; - var attacker = @event.Attacker; + Server.NextFrame(Clear); - if (playerWhoWasDamaged == null) return HookResult.Continue; + return HookResult.Continue; + } - SetColor(playerWhoWasDamaged); - playerWhoWasDamaged.ModifyScoreBoard(); + [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; + } - service.GetPlayer(playerWhoWasDamaged).SetKiller(attacker); + public void AddRoles() + { + var eligible = Utilities.GetPlayers() + .Where(player => player.IsReal()) + .Where(player => player.Team is not (CsTeam.Spectator or CsTeam.None)) + .ToList(); - if (IsTraitor(playerWhoWasDamaged)) _traitorsLeft--; - if (IsDetective(playerWhoWasDamaged) || IsInnocent(playerWhoWasDamaged)) - _innocentsLeft--; + var traitorCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 3)); + var detectiveCount = (int)Math.Floor(Convert.ToDouble(eligible.Count / 8)); - if (_traitorsLeft == 0 || _innocentsLeft == 0) - Server.NextFrame(() => _roundService.ForceEnd()); + _traitorsLeft = traitorCount; + _innocentsLeft = eligible.Count - traitorCount; - Server.NextFrame(() => { - Server.PrintToChatAll(StringUtils.FormatTTT( - $"{GetRole(playerWhoWasDamaged).FormatStringFullAfter(" has been found.")}")); + if (detectiveCount > MaxDetectives) detectiveCount = MaxDetectives; - if (attacker == playerWhoWasDamaged || attacker == null) return; + for (var i = 0; i < traitorCount; i++) + { + var chosen = eligible[Random.Shared.Next(eligible.Count)]; + eligible.Remove(chosen); + AddTraitor(chosen); + } - attacker.ModifyScoreBoard(); + for (var i = 0; i < detectiveCount; i++) + { + var chosen = eligible[Random.Shared.Next(eligible.Count)]; + eligible.Remove(chosen); + AddDetective(chosen); + } - playerWhoWasDamaged.PrintToChat(StringUtils.FormatTTT( - $"You were killed by {GetRole(attacker).FormatStringFullAfter(" " + attacker.PlayerName)}.")); - attacker.PrintToChat(StringUtils.FormatTTT( - $"You killed {GetRole(playerWhoWasDamaged).FormatStringFullAfter(" " + playerWhoWasDamaged.PlayerName)}.")); - }); + AddInnocents(eligible); + } - return HookResult.Continue; - } + public ISet GetTraitors() + { + return service.Players().Where(player => player.PlayerRole() == Role.Traitor).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 GetDetectives() + { + return service.Players().Where(player => player.PlayerRole() == Role.Detective).Select(player => player.Player()) + .ToHashSet(); + } - foreach (var player in players) - player.PrintToCenter(GetWinner().FormatStringFullAfter("s has won!")); + public ISet GetInnocents() + { + return service.Players().Where(player => player.PlayerRole() == Role.Innocent).Select(player => player.Player()) + .ToHashSet(); + } - Server.NextFrame(Clear); - return HookResult.Continue; - } + public Role GetRole(CCSPlayerController player) + { + return service.GetPlayer(player).PlayerRole(); + } - [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 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); + } - return HookResult.Continue; - } + 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 bool IsInnocent(CCSPlayerController player) { - return service.GetPlayer(player).PlayerRole() == Role.Innocent; - } + 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); + } + } - private Role GetWinner() { - return _traitorsLeft == 0 ? Role.Traitor : Role.Innocent; - } + public bool IsDetective(CCSPlayerController player) + { + return service.GetPlayer(player).PlayerRole() == Role.Detective; + } - public void SetColor(CCSPlayerController player) { - if (!player.IsReal()) return; + public bool IsTraitor(CCSPlayerController player) + { + return service.GetPlayer(player).PlayerRole() == Role.Traitor; + } - var pawn = player.PlayerPawn.Value; + public void Clear() + { + service.Clr(); + foreach (var key in service.Players()) + { + key.SetPlayerRole(Role.Unassigned); + if (key.Player() == null) continue; + RemoveColor(key.Player()); + } + } - if (pawn == null || !pawn.IsValid) return; + public bool IsInnocent(CCSPlayerController player) + { + return service.GetPlayer(player).PlayerRole() == Role.Innocent; + } - pawn.RenderMode = RenderMode_t.kRenderTransColor; - pawn.Render = GetRole(player).GetColor(); + private Role GetWinner() + { + return _traitorsLeft == 0 ? Role.Traitor : Role.Innocent; + } - Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); - } + public void SetColor(CCSPlayerController player) + { + if (!player.IsReal()) return; - public void RemoveColor(CCSPlayerController player) { - if (!player.IsReal()) return; + var pawn = player.PlayerPawn.Value; + + if (pawn == null || !pawn.IsValid) return; - var pawn = player.PlayerPawn.Value; + 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; - if (pawn == null || !pawn.IsValid) return; + var pawn = player.PlayerPawn.Value; + + 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 f367211..74619c4 100644 --- a/mod/TTT.Roles/RoleConfig.cs +++ b/mod/TTT.Roles/RoleConfig.cs @@ -1,8 +1,10 @@ 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 4bbd158..af20a73 100644 --- a/mod/TTT.Roles/RoleServiceExtension.cs +++ b/mod/TTT.Roles/RoleServiceExtension.cs @@ -5,9 +5,11 @@ 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 3f3c06d..489cca3 100644 --- a/mod/TTT.Roles/RoleTester.cs +++ b/mod/TTT.Roles/RoleTester.cs @@ -1,30 +1,22 @@ -using CounterStrikeSharp.API.Modules.Cvars; +using CounterStrikeSharp.API; +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 _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."); +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."); + + } \ No newline at end of file diff --git a/mod/TTT.Roles/TTT.Roles.csproj b/mod/TTT.Roles/TTT.Roles.csproj index 0d7766e..dfd9e59 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 718c8a0..2da0707 100644 --- a/mod/TTT.Roles/TraitorRoom.cs +++ b/mod/TTT.Roles/TraitorRoom.cs @@ -1,3 +1,8 @@ -namespace TTT.Roles; +using CounterStrikeSharp.API.Core; -public class TraitorRoom { } \ No newline at end of file +namespace TTT.Roles; + +public class TraitorRoom +{ + +} \ No newline at end of file diff --git a/mod/TTT.Round/Round.cs b/mod/TTT.Round/Round.cs index 2dd3296..be705f7 100644 --- a/mod/TTT.Round/Round.cs +++ b/mod/TTT.Round/Round.cs @@ -1,90 +1,106 @@ 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.Formatting; using TTT.Public.Mod.Role; +using TTT.Public.Formatting; namespace TTT.Round; -public class Round(IRoleService roleService, RoundConfig? config, int roundId) { - private readonly RoundConfig? config = config; - private float graceTime = 20 * 64; - - 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 float GraceTime() { return graceTime; } +public class Round +{ + private readonly IRoleService _roleService; + private readonly RoundConfig? _config; + private float _graceTime = 20 * 64; + private readonly int _roundId; - 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(); - } + public Round(IRoleService roleService, RoundConfig? config, int roundId) + { + _roleService = roleService; + _config = config; + _graceTime = 20 * 64; + _roundId = roundId; + } - private void SendInnocentMessage() { - foreach (var player in roleService.GetInnocents()) - Server.NextFrame(() - => player.PrintToChat( - StringUtils.FormatTTT("You are now an innocent"))); - } + 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"); + }); + } + } - private void SendTraitorMessage() { - var traitors = roleService.GetTraitors(); + public float GraceTime() + { + return _graceTime; + } - 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)); - } + 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 SendDetectiveMessage() { - var detectives = roleService.GetDetectives(); + 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 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)); - } + 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)); + } + } } - } -} \ No newline at end of file +} diff --git a/mod/TTT.Round/RoundBehavior.cs b/mod/TTT.Round/RoundBehavior.cs index 963e6b1..a227f9d 100644 --- a/mod/TTT.Round/RoundBehavior.cs +++ b/mod/TTT.Round/RoundBehavior.cs @@ -5,131 +5,137 @@ 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 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 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); } - this.roundStatus = roundStatus; - } + public RoundStatus GetRoundStatus() + { + return _roundStatus; + } - public void TickWaiting() { - if (round == null) { - round = new Round(roleService, null, roundId); - return; + 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; } - if (roundStatus != RoundStatus.Waiting) 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); + + } - round.Tick(); + 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"); + } - if (round.GraceTime() != 0) return; + 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(); + } + } - 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 BlockDamage(DynamicHook hook) + { + if (hook.GetParam(0).DesignerName is not "player") return HookResult.Continue; + return _roundStatus != RoundStatus.Waiting ? HookResult.Continue : HookResult.Stop; } - SetRoundStatus(RoundStatus.Started); - } - - public void ForceStart() { - foreach (var player in Utilities.GetPlayers().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 + 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; + } +} diff --git a/mod/TTT.Round/RoundConfig.cs b/mod/TTT.Round/RoundConfig.cs index a229469..a8e77f6 100644 --- a/mod/TTT.Round/RoundConfig.cs +++ b/mod/TTT.Round/RoundConfig.cs @@ -1,6 +1,7 @@ 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 588fedb..b41b37b 100644 --- a/mod/TTT.Round/RoundServiceExtension.cs +++ b/mod/TTT.Round/RoundServiceExtension.cs @@ -1,7 +1,12 @@ 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 f28455f..33298b6 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 a056d1b..31fb7ca 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 e5bd4f7..2d15db0 100644 --- a/public/TTT.Formatting/Base/IView.cs +++ b/public/TTT.Formatting/Base/IView.cs @@ -2,6 +2,7 @@ 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 28a8fae..b3382f8 100644 --- a/public/TTT.Formatting/Base/SimpleView.cs +++ b/public/TTT.Formatting/Base/SimpleView.cs @@ -1,49 +1,70 @@ using System.Collections; + using TTT.Formatting.Core; namespace TTT.Formatting.Base; -public class SimpleView : IView, IEnumerable> { - public static Newline NEWLINE = new(); +public class SimpleView : IView, IEnumerable> +{ + public struct Newline + { + + } + + public static Newline NEWLINE = new Newline(); + + private List> _lines = new(); - private readonly List> _lines = new(); + public SimpleView() + { - public IEnumerator> GetEnumerator() { - return _lines.GetEnumerator(); - } + } - IEnumerator IEnumerable.GetEnumerator() { return 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()); - public void Render(FormatWriter writer) { - foreach (var formatObjects in _lines) writer.Line(formatObjects.ToArray()); - } + _lines[_lines.Count - 1].Add(item); + } - /// - /// 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()); + /// + /// Add multiple items at a time to this SimpleView + /// + /// + public void Add(params FormatObject[] line) + { + if (_lines.Count == 0) + _lines.Add(new List()); - _lines[_lines.Count - 1].Add(item); - } + _lines[_lines.Count - 1].AddRange(line); + } - /// - /// Add multiple items at a time to this SimpleView - /// - /// - public void Add(params FormatObject[] line) { - if (_lines.Count == 0) _lines.Add(new List()); + /// + /// Add a new line to this SimpleView + /// + /// + public void Add(Newline newline) + { + _lines.Add(new List()); + } - _lines[_lines.Count - 1].AddRange(line); - } + public void Render(FormatWriter writer) + { + foreach (var formatObjects in _lines) + writer.Line(formatObjects.ToArray()); + } - /// - /// Add a new line to this SimpleView - /// - /// - public void Add(Newline newline) { _lines.Add(new List()); } + public IEnumerator> GetEnumerator() + => _lines.GetEnumerator(); - public struct Newline { } -} \ No newline at end of file + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/public/TTT.Formatting/Core/FormatObject.cs b/public/TTT.Formatting/Core/FormatObject.cs index d39b5c0..956333d 100644 --- a/public/TTT.Formatting/Core/FormatObject.cs +++ b/public/TTT.Formatting/Core/FormatObject.cs @@ -4,41 +4,53 @@ 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() { return ToPlain(); } -} \ No newline at end of file + public override string ToString() + => ToPlain(); +} diff --git a/public/TTT.Formatting/Core/FormatWriter.cs b/public/TTT.Formatting/Core/FormatWriter.cs index d4034c4..78f66d7 100644 --- a/public/TTT.Formatting/Core/FormatWriter.cs +++ b/public/TTT.Formatting/Core/FormatWriter.cs @@ -1,26 +1,25 @@ 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 8d17538..f03bfb6 100644 --- a/public/TTT.Formatting/Extensions/ViewExtensions.cs +++ b/public/TTT.Formatting/Extensions/ViewExtensions.cs @@ -1,93 +1,110 @@ 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 (var s in writer.Plain) Server.PrintToConsole(s); + foreach (string s in writer.Plain) + { + Server.PrintToConsole(s); + } - return view; - } + return view; + } - public static IView ToAllConsole(this IView view) { - Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); + #region Individual - return view; - } + public static IView ToPlayerConsole(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(); - return view; - } + foreach (var writerLine in writer.Plain) + player.PrintToConsole(writerLine); - public static IView ToAllCenter(this IView view) { - Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); + return view; + } - return view; - } + public static IView ToPlayerChat(this IView view, CCSPlayerController player) + { + if (!player.IsReal() || player.IsBot) + return view; - #region Individual + var writer = view.ToWriter(); - public static IView ToPlayerConsole(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(); + return view; + } - foreach (var writerLine in writer.Plain) player.PrintToConsole(writerLine); + 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); - public static IView - ToPlayerChat(this IView view, CCSPlayerController player) { - if (!player.IsReal() || player.IsBot) return view; + player.PrintToCenter(merged); - var writer = view.ToWriter(); + return view; + } - foreach (var writerLine in writer.Chat) player.PrintToChat(writerLine); + public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) + { + if (!player.IsReal() || player.IsBot) + return view; - return view; - } + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Panorama); - public static IView ToPlayerCenter(this IView view, - CCSPlayerController player) { - if (!player.IsReal() || player.IsBot) return view; + player.PrintToCenterHtml(merged); - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Plain); + return view; + } - player.PrintToCenter(merged); + #endregion - return view; - } + public static IView ToAllConsole(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); - public static IView ToPlayerCenterHtml(this IView view, - CCSPlayerController player) { - if (!player.IsReal() || player.IsBot) return view; + return view; + } - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Panorama); + public static IView ToAllChat(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); - player.PrintToCenterHtml(merged); + return view; + } - return view; - } + public static IView ToAllCenter(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); - #endregion -} \ No newline at end of file + return view; + } +} diff --git a/public/TTT.Formatting/Languages/English.cs b/public/TTT.Formatting/Languages/English.cs index 7b5d539..727c519 100644 --- a/public/TTT.Formatting/Languages/English.cs +++ b/public/TTT.Formatting/Languages/English.cs @@ -2,4 +2,6 @@ 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 76a77f3..52b81ef 100644 --- a/public/TTT.Formatting/Logistics/IDialect.cs +++ b/public/TTT.Formatting/Logistics/IDialect.cs @@ -1,7 +1,9 @@ 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 40b1479..d19e0d2 100644 --- a/public/TTT.Formatting/Logistics/ILanguage.cs +++ b/public/TTT.Formatting/Logistics/ILanguage.cs @@ -1,8 +1,11 @@ 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 040be1b..11c25ae 100644 --- a/public/TTT.Formatting/Logistics/LanguageConfig.cs +++ b/public/TTT.Formatting/Logistics/LanguageConfig.cs @@ -1,11 +1,18 @@ -using Microsoft.Extensions.DependencyInjection; +using TTT.Formatting.Views; + +using Microsoft.Extensions.DependencyInjection; namespace TTT.Formatting.Logistics; -public class LanguageConfig where TDialect : IDialect { - private IServiceCollection _collection; +public class LanguageConfig + where TDialect: IDialect +{ + + private IServiceCollection _collection; + + public LanguageConfig(IServiceCollection collection) + { + _collection = 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 72ded0f..d2606f8 100644 --- a/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs +++ b/public/TTT.Formatting/Logistics/RegisterLanguageExtensions.cs @@ -2,11 +2,15 @@ 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 d6fe3f1..ef4f112 100644 --- a/public/TTT.Formatting/Objects/HiddenFormatObject.cs +++ b/public/TTT.Formatting/Objects/HiddenFormatObject.cs @@ -2,29 +2,39 @@ 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 acea79d..2f06eac 100644 --- a/public/TTT.Formatting/Objects/IntegerFormatObject.cs +++ b/public/TTT.Formatting/Objects/IntegerFormatObject.cs @@ -1,20 +1,32 @@ -using TTT.Formatting.Core; +using CounterStrikeSharp.API.Modules.Utils; +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 c03bd4b..846fdcb 100644 --- a/public/TTT.Formatting/Objects/PlayerFormatObject.cs +++ b/public/TTT.Formatting/Objects/PlayerFormatObject.cs @@ -5,16 +5,27 @@ 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; } -} \ No newline at end of file + public override string ToPlain() + { + return _name; + } +} diff --git a/public/TTT.Formatting/Objects/StringFormatObject.cs b/public/TTT.Formatting/Objects/StringFormatObject.cs index 511d9fc..7c85915 100644 --- a/public/TTT.Formatting/Objects/StringFormatObject.cs +++ b/public/TTT.Formatting/Objects/StringFormatObject.cs @@ -2,19 +2,30 @@ 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 da6f8d9..647c812 100644 --- a/public/TTT.Formatting/Objects/TreeFormatObject.cs +++ b/public/TTT.Formatting/Objects/TreeFormatObject.cs @@ -1,67 +1,86 @@ 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 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 +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(); + } +} diff --git a/public/TTT.Formatting/TTT.Formatting.csproj b/public/TTT.Formatting/TTT.Formatting.csproj index 77467aa..0d44a15 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 94be705..35826a6 100644 --- a/public/TTT.Formatting/Views/IRoleNotifications.cs +++ b/public/TTT.Formatting/Views/IRoleNotifications.cs @@ -3,8 +3,9 @@ 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 160d780..842b0c9 100644 --- a/public/TTT.Public/Action/DamageAction.cs +++ b/public/TTT.Public/Action/DamageAction.cs @@ -4,32 +4,38 @@ 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; } + public override CCSPlayerController Actor() + { + return _actor.Item1; + } + + private string GetActorName() + { + return _actor?.Item2.FormatStringFullAfter(" " + _actor?.Item1.PlayerName) ?? "World"; + } - 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."; - } + 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 87bac54..4c4fa32 100644 --- a/public/TTT.Public/Action/DeathAction.cs +++ b/public/TTT.Public/Action/DeathAction.cs @@ -4,17 +4,24 @@ 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 11ae959..a32097a 100644 --- a/public/TTT.Public/Action/IAction.cs +++ b/public/TTT.Public/Action/IAction.cs @@ -3,11 +3,13 @@ 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 b5084bb..b383450 100644 --- a/public/TTT.Public/Action/KillAction.cs +++ b/public/TTT.Public/Action/KillAction.cs @@ -4,24 +4,28 @@ 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 63994d4..f4cbdfb 100644 --- a/public/TTT.Public/Action/MiscAction.cs +++ b/public/TTT.Public/Action/MiscAction.cs @@ -2,18 +2,24 @@ 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 d852bdb..0d946ea 100644 --- a/public/TTT.Public/Action/ShopAction.cs +++ b/public/TTT.Public/Action/ShopAction.cs @@ -1,3 +1,5 @@ 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 b070b6b..ada7b0a 100644 --- a/public/TTT.Public/Behaviors/IPluginBehavior.cs +++ b/public/TTT.Public/Behaviors/IPluginBehavior.cs @@ -3,13 +3,18 @@ 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 7eccf1a..45f07c0 100644 --- a/public/TTT.Public/Configuration/IConfigService.cs +++ b/public/TTT.Public/Configuration/IConfigService.cs @@ -1,14 +1,16 @@ 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 e337c5c..39e8a51 100644 --- a/public/TTT.Public/Database/DatabaseService.cs +++ b/public/TTT.Public/Database/DatabaseService.cs @@ -2,55 +2,66 @@ using MySqlConnector; using TTT.Player; using TTT.Public.Mod.Role; +using TTT.Public.Player; namespace TTT.Public.Database; -public class DatabaseService { - private readonly MySqlConnection _connector; +public class DatabaseService +{ + private 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 63fd3fd..5183f40 100644 --- a/public/TTT.Public/Extensions/EntityIOExtensions.cs +++ b/public/TTT.Public/Extensions/EntityIOExtensions.cs @@ -3,22 +3,26 @@ 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; - } -} \ No newline at end of file + return controller?.IsReal() == true; + } +} diff --git a/public/TTT.Public/Extensions/PlayerExtensions.cs b/public/TTT.Public/Extensions/PlayerExtensions.cs index 22480b0..c73f338 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 cd3dd0c..d7f9902 100644 --- a/public/TTT.Public/Extensions/ScoreboardExtension.cs +++ b/public/TTT.Public/Extensions/ScoreboardExtension.cs @@ -5,97 +5,104 @@ 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); - } + 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); + } - public static void ModifyKarma(this GamePlayer gamePlayer) { - var player = gamePlayer.Player(); - if (player == null) return; - setScore(gamePlayer); - } + 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"); + } - private static void setScore(GamePlayer gamePlayer) { - var player = gamePlayer.Player(); - if (player == null) return; + 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"); + } - if (player.Score == gamePlayer.Karma()) return; - player.Score = gamePlayer.Karma(); - } + 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 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 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 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"); - } + 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 3f76c60..4bda151 100644 --- a/public/TTT.Public/Extensions/ServerExtensions.cs +++ b/public/TTT.Public/Extensions/ServerExtensions.cs @@ -5,27 +5,26 @@ 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()!; - } -} \ No newline at end of file + /// + /// 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()!; + } +} diff --git a/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs b/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs index d647b78..1408fee 100644 --- a/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs +++ b/public/TTT.Public/Extensions/ServiceCollectionExtensions.cs @@ -1,66 +1,63 @@ -using Microsoft.Extensions.DependencyInjection; -using TTT.Public.Behaviors; +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 336bbe9..777310e 100644 --- a/public/TTT.Public/Extensions/StringExtensions.cs +++ b/public/TTT.Public/Extensions/StringExtensions.cs @@ -1,7 +1,10 @@ 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 47f0b79..5e80cd3 100644 --- a/public/TTT.Public/Extensions/VectorExtensions.cs +++ b/public/TTT.Public/Extensions/VectorExtensions.cs @@ -2,40 +2,55 @@ 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 5e9c194..ac77113 100644 --- a/public/TTT.Public/Formatting/Format.cs +++ b/public/TTT.Public/Formatting/Format.cs @@ -4,65 +4,75 @@ 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 c619439..a0aa8be 100644 --- a/public/TTT.Public/Formatting/StringUtils.cs +++ b/public/TTT.Public/Formatting/StringUtils.cs @@ -2,11 +2,16 @@ 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 ef1a1dc..5f31633 100644 --- a/public/TTT.Public/Mod/Detective/IDetectiveService.cs +++ b/public/TTT.Public/Mod/Detective/IDetectiveService.cs @@ -1,3 +1,5 @@ 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 0725094..8e6f727 100644 --- a/public/TTT.Public/Mod/Logs/ILogService.cs +++ b/public/TTT.Public/Mod/Logs/ILogService.cs @@ -1,13 +1,15 @@ 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 35c2fb7..8b07784 100644 --- a/public/TTT.Public/Mod/Logs/IRoundLogs.cs +++ b/public/TTT.Public/Mod/Logs/IRoundLogs.cs @@ -1,8 +1,11 @@ -namespace TTT.Public.Mod.Logs; +using TTT.Public.Action; -public interface IRoundLogs { - IList GetLogs(); - void AddLog(Action.Action action); - void RemoveLog(Action.Action action); - string FormattedLogs(); +namespace TTT.Public.Mod.Logs; + +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 c3faa0c..d61fb7f 100644 --- a/public/TTT.Public/Mod/Manager/IMuteService.cs +++ b/public/TTT.Public/Mod/Manager/IMuteService.cs @@ -2,9 +2,10 @@ 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 521163c..43ed3e2 100644 --- a/public/TTT.Public/Mod/Role/IRoleService.cs +++ b/public/TTT.Public/Mod/Role/IRoleService.cs @@ -1,23 +1,29 @@ 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(params CCSPlayerController[] player); - void AddTraitor(params CCSPlayerController[] player); - void AddInnocents(params CCSPlayerController[] 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 07b39e9..4869e48 100644 --- a/public/TTT.Public/Mod/Round/IRoundService.cs +++ b/public/TTT.Public/Mod/Round/IRoundService.cs @@ -1,15 +1,23 @@ 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 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 2d5f949..9dc1b67 100644 --- a/public/TTT.Public/Mod/Traitor/ITraitorService.cs +++ b/public/TTT.Public/Mod/Traitor/ITraitorService.cs @@ -1,3 +1,6 @@ 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 cf2fab2..c5f2b70 100644 --- a/public/TTT.Public/Player/GamePlayer.cs +++ b/public/TTT.Public/Player/GamePlayer.cs @@ -1,64 +1,127 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using TTT.Public.Mod.Role; +using TTT.Public.Player; namespace TTT.Player; -public class GamePlayer(Role playerRole, long credits, int karma, - int playerId) { - private bool dead; - private bool found; - - // TODO: Use Steam ID - private CCSPlayerController? killer; - - private bool shopOpen; - - public bool IsDead() { return dead; } - - public void SetDead(bool isDead = false) { dead = isDead; } - - public CCSPlayerController? Player() { - return Utilities.GetPlayerFromUserid(playerId); - } - - public Role PlayerRole() { return playerRole; } - - public int Karma() { return karma; } - - public void SetKarma(int karma1) { karma = karma1; } - - public void AddKarma(int karma1) { karma += karma1; } - - public void RemoveKarma(int karma1) { - karma -= karma1; - 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) { this.killer = killer; } - - public void SetShopOpen(bool open) { shopOpen = open; } - - public bool ShopOpen() { return shopOpen; } - - public bool SetFound(bool found) { - this.found = found; - return this.found; - } - - public bool IsFound() { return found; } +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; + } } \ No newline at end of file diff --git a/public/TTT.Public/Player/IPlayerService.cs b/public/TTT.Public/Player/IPlayerService.cs index b474f37..aa51184 100644 --- a/public/TTT.Public/Player/IPlayerService.cs +++ b/public/TTT.Public/Player/IPlayerService.cs @@ -1,14 +1,16 @@ 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 6f57c07..d7028f6 100644 --- a/public/TTT.Public/Shop/AbstractShopItem.cs +++ b/public/TTT.Public/Shop/AbstractShopItem.cs @@ -2,19 +2,23 @@ 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 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 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 bc29f3f..a987316 100644 --- a/public/TTT.Public/Shop/ShopConfig.cs +++ b/public/TTT.Public/Shop/ShopConfig.cs @@ -1,3 +1,8 @@ -namespace TTT.Public.Shop; +using CounterStrikeSharp.API.Core; -public class ShopConfig { } \ No newline at end of file +namespace TTT.Public.Shop; + +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 9fad0d0..4740ad1 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 47b334f..b6fe055 100644 --- a/src/TTT.Generic/TTT.Generic.cs +++ b/src/TTT.Generic/TTT.Generic.cs @@ -1,3 +1,5 @@ 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 1150bae..21737e4 100644 --- a/src/TTT/Config/ConfigService.cs +++ b/src/TTT/Config/ConfigService.cs @@ -1,62 +1,68 @@ -using System.Text.Json; +using System.Text.Json; using System.Text.Json.Nodes; using CounterStrikeSharp.API; -using Microsoft.Extensions.Logging; using TTT.Public.Configuration; +using Microsoft.Extensions.Logging; 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 a561d3a..ac57023 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 6addcb6..f9cf6f9 100644 --- a/src/TTT/TTTPlugin.cs +++ b/src/TTT/TTTPlugin.cs @@ -6,63 +6,68 @@ namespace TTT; -public class TTTPlugin : BasePlugin { - private readonly IServiceProvider _provider; - private IReadOnlyList? _extensions; - private IServiceScope? _scope; +public class TTTPlugin : BasePlugin +{ + private readonly IServiceProvider _provider; + private IReadOnlyList? _extensions; + private IServiceScope? _scope; + + /// + /// The TTT plugin. + /// + /// + public TTTPlugin(IServiceProvider provider) + { + _provider = provider; + } - /// - /// The TTT plugin. - /// - /// - public TTTPlugin(IServiceProvider provider) { _provider = provider; } + /// + public override string ModuleName => "TTT"; - /// - public override string ModuleName => "TTT"; + /// + public override string ModuleVersion => "1.0.0"; - /// - public override string ModuleVersion => "1.0.0"; + /// + public override string ModuleAuthor => "NTM"; - /// - public override string ModuleAuthor => "NTM"; + /// + public override void Load(bool hotReload) + { + Logger.LogInformation("[TTT] Loading..."); - /// - public override void Load(bool hotReload) { - Logger.LogInformation("[TTT] Loading..."); + _scope = _provider.CreateScope(); + _extensions = _scope.ServiceProvider.GetServices() + .ToImmutableList(); - _scope = _provider.CreateScope(); - _extensions = _scope.ServiceProvider.GetServices() - .ToImmutableList(); + Logger.LogInformation("[TTT] Found {@BehaviorCount} behaviors.", _extensions.Count); - Logger.LogInformation("[TTT] Found {@BehaviorCount} behaviors.", - _extensions.Count); + foreach (var extension in _extensions) + { + // Register all event handlers on the extension object + RegisterAllAttributes(extension); - foreach (var extension in _extensions) { - // Register all event handlers on the extension object - RegisterAllAttributes(extension); + // Tell the extension to start it's magic + extension.Start(this); - // Tell the extension to start it's magic - extension.Start(this); + Logger.LogInformation("[TTT] Loaded behavior {@Behavior}", extension.GetType().FullName); + } - Logger.LogInformation("[TTT] Loaded behavior {@Behavior}", - extension.GetType().FullName); + base.Load(hotReload); } - base.Load(hotReload); - } - - /// - public override void Unload(bool hotReload) { - Logger.LogInformation("[TTT] Shutting down..."); + /// + public override void Unload(bool hotReload) + { + Logger.LogInformation("[TTT] Shutting down..."); - if (_extensions != null) - foreach (var extension in _extensions) - extension.Dispose(); + if (_extensions != null) + foreach (var extension in _extensions) + extension.Dispose(); - // Dispose of original extensions scope - // When loading again we will get a new scope to avoid leaking state. - _scope?.Dispose(); + // Dispose of original extensions scope + // When loading again we will get a new scope to avoid leaking state. + _scope?.Dispose(); - base.Unload(hotReload); - } + base.Unload(hotReload); + } } \ No newline at end of file diff --git a/src/TTT/TTTServiceCollection.cs b/src/TTT/TTTServiceCollection.cs index 7b5db9f..7644954 100644 --- a/src/TTT/TTTServiceCollection.cs +++ b/src/TTT/TTTServiceCollection.cs @@ -5,15 +5,18 @@ 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