From 282bc688a04b8d64c032a1c94b2d0388fc55f587 Mon Sep 17 00:00:00 2001 From: MSWS Date: Sun, 4 Feb 2024 20:55:48 -0800 Subject: [PATCH 1/8] Add rebel notifications --- mod/Jailbreak.Rebel/RebelManager.cs | 36 +++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index 426976d2..9fadd81f 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -27,6 +27,7 @@ public RebelManager(IRebelNotifications notifs, ILogService logs) public void Start(BasePlugin parent) { parent.RegisterEventHandler(OnPlayerDisconnect); + parent.RegisterEventHandler(OnPlayerDeath); parent.RegisterEventHandler(OnRoundStart); parent.AddTimer(1f, () => @@ -43,6 +44,7 @@ public void Start(BasePlugin parent) } ApplyRebelColor(player); + SendTimeLeft(player); } }, TimerFlags.REPEAT); } @@ -70,6 +72,15 @@ HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) return HookResult.Continue; } + HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) + { + var player = @event.Userid; + if (!player.IsReal()) + return HookResult.Continue; + rebelTimes.Remove(player); + return HookResult.Continue; + } + public ISet GetActiveRebels() { return rebelTimes.Keys.ToHashSet(); @@ -116,11 +127,9 @@ private float GetRebelTimePercentage(CCSPlayerController player) return 0; return (float)(100 - (120 - x) * (Math.Sqrt(120 - x)) / 13f) / 100; } - - private void ApplyRebelColor(CCSPlayerController player) + + private Color GetRebelColor(CCSPlayerController player) { - if (!player.IsReal() || player.Pawn.Value == null) - return; var percent = GetRebelTimePercentage(player); var percentRGB = 255 - (int)Math.Round(percent * 255.0); var color = Color.FromArgb(254, 255, percentRGB, percentRGB); @@ -129,8 +138,27 @@ private void ApplyRebelColor(CCSPlayerController player) color = Color.FromArgb(254, 255, 255, 255); } + return color; + } + + private void ApplyRebelColor(CCSPlayerController player) + { + if (!player.IsReal() || player.Pawn.Value == null) + return; + var color = GetRebelColor(player); + player.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; player.Pawn.Value.Render = color; Utilities.SetStateChanged(player.Pawn.Value, "CBaseModelEntity", "m_clrRender"); } + + private void SendTimeLeft(CCSPlayerController player) + { + var timeLeft = GetRebelTimeLeft(player); + var formattedTime = TimeSpan.FromSeconds(timeLeft).ToString(@"mm\:ss"); + var color = GetRebelColor(player); + var formattedColor = $""; + + player.PrintToCenterHtml($"You are a rebel for {formattedColor}{formattedTime} more seconds."); + } } \ No newline at end of file From a291ef22da2138487ff0bc4d26302483cb9b62ba Mon Sep 17 00:00:00 2001 From: MSWS Date: Sun, 4 Feb 2024 20:55:48 -0800 Subject: [PATCH 2/8] Add rebel notifications --- mod/Jailbreak.Rebel/RebelManager.cs | 36 +++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index 426976d2..9fadd81f 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -27,6 +27,7 @@ public RebelManager(IRebelNotifications notifs, ILogService logs) public void Start(BasePlugin parent) { parent.RegisterEventHandler(OnPlayerDisconnect); + parent.RegisterEventHandler(OnPlayerDeath); parent.RegisterEventHandler(OnRoundStart); parent.AddTimer(1f, () => @@ -43,6 +44,7 @@ public void Start(BasePlugin parent) } ApplyRebelColor(player); + SendTimeLeft(player); } }, TimerFlags.REPEAT); } @@ -70,6 +72,15 @@ HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) return HookResult.Continue; } + HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) + { + var player = @event.Userid; + if (!player.IsReal()) + return HookResult.Continue; + rebelTimes.Remove(player); + return HookResult.Continue; + } + public ISet GetActiveRebels() { return rebelTimes.Keys.ToHashSet(); @@ -116,11 +127,9 @@ private float GetRebelTimePercentage(CCSPlayerController player) return 0; return (float)(100 - (120 - x) * (Math.Sqrt(120 - x)) / 13f) / 100; } - - private void ApplyRebelColor(CCSPlayerController player) + + private Color GetRebelColor(CCSPlayerController player) { - if (!player.IsReal() || player.Pawn.Value == null) - return; var percent = GetRebelTimePercentage(player); var percentRGB = 255 - (int)Math.Round(percent * 255.0); var color = Color.FromArgb(254, 255, percentRGB, percentRGB); @@ -129,8 +138,27 @@ private void ApplyRebelColor(CCSPlayerController player) color = Color.FromArgb(254, 255, 255, 255); } + return color; + } + + private void ApplyRebelColor(CCSPlayerController player) + { + if (!player.IsReal() || player.Pawn.Value == null) + return; + var color = GetRebelColor(player); + player.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; player.Pawn.Value.Render = color; Utilities.SetStateChanged(player.Pawn.Value, "CBaseModelEntity", "m_clrRender"); } + + private void SendTimeLeft(CCSPlayerController player) + { + var timeLeft = GetRebelTimeLeft(player); + var formattedTime = TimeSpan.FromSeconds(timeLeft).ToString(@"mm\:ss"); + var color = GetRebelColor(player); + var formattedColor = $""; + + player.PrintToCenterHtml($"You are a rebel for {formattedColor}{formattedTime} more seconds."); + } } \ No newline at end of file From 5deb951da5124ed760d6ae2e414431dd75494fa0 Mon Sep 17 00:00:00 2001 From: Isaac Date: Sun, 4 Feb 2024 23:46:19 -0800 Subject: [PATCH 3/8] Feat/debug (#19) * Initial stuff for debug * More classes! * Base implementation --- Jailbreak.sln | 7 + .../Generic/GenericCommandNotifications.cs | 34 ++++ mod/Jailbreak.Debug/DebugCommand.cs | 46 ++++++ mod/Jailbreak.Debug/DebugServiceExtension.cs | 12 ++ mod/Jailbreak.Debug/Jailbreak.Debug.csproj | 14 ++ .../Subcommands/AbstractCommand.cs | 145 ++++++++++++++++++ mod/Jailbreak.Debug/Subcommands/MarkRebel.cs | 45 ++++++ .../Subcommands/WrappedInfo.cs | 29 ++++ mod/Jailbreak.Logs/LogsServiceExtension.cs | 2 +- mod/Jailbreak.Rebel/RebelManager.cs | 2 +- .../Logistics/LanguageConfig.cs | 4 + .../Views/IGenericCommandNotifications.cs | 9 ++ .../Mod/Rebel/IRebelService.cs | 2 +- src/Jailbreak/Jailbreak.csproj | 1 + src/Jailbreak/JailbreakServiceCollection.cs | 6 +- 15 files changed, 354 insertions(+), 4 deletions(-) create mode 100644 lang/Jailbreak.English/Generic/GenericCommandNotifications.cs create mode 100644 mod/Jailbreak.Debug/DebugCommand.cs create mode 100644 mod/Jailbreak.Debug/DebugServiceExtension.cs create mode 100644 mod/Jailbreak.Debug/Jailbreak.Debug.csproj create mode 100644 mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs create mode 100644 mod/Jailbreak.Debug/Subcommands/MarkRebel.cs create mode 100644 mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs create mode 100644 public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs diff --git a/Jailbreak.sln b/Jailbreak.sln index 4e9a7f23..6098dfce 100644 --- a/Jailbreak.sln +++ b/Jailbreak.sln @@ -26,6 +26,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jailbreak.Rebel", "mod\Jail EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jailbreak.Logs", "mod\Jailbreak.Logs\Jailbreak.Logs.csproj", "{CE6EC648-E7F9-4CE7-B28F-8C7995830F35}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jailbreak.Debug", "mod\Jailbreak.Debug\Jailbreak.Debug.csproj", "{4F10E2B5-E8BB-4253-9BE6-9187575ADB13}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -68,6 +70,10 @@ Global {CE6EC648-E7F9-4CE7-B28F-8C7995830F35}.Debug|Any CPU.Build.0 = Debug|Any CPU {CE6EC648-E7F9-4CE7-B28F-8C7995830F35}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE6EC648-E7F9-4CE7-B28F-8C7995830F35}.Release|Any CPU.Build.0 = Release|Any CPU + {4F10E2B5-E8BB-4253-9BE6-9187575ADB13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F10E2B5-E8BB-4253-9BE6-9187575ADB13}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F10E2B5-E8BB-4253-9BE6-9187575ADB13}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F10E2B5-E8BB-4253-9BE6-9187575ADB13}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {9135CCC9-66C5-4A9C-AE3C-91475B5F0437} = {177DA48D-8306-4102-918D-992569878581} @@ -79,5 +85,6 @@ Global {FC2D6F50-BCFF-41E6-A965-6C73CC01C3BF} = {CDCDE44E-01D2-4B76-99DA-A57E1E956038} {CB2391A1-6CDD-496F-B8D6-674FD6268038} = {36BA84C0-291C-4930-A7C6-97CDF8F7F0D7} {CE6EC648-E7F9-4CE7-B28F-8C7995830F35} = {36BA84C0-291C-4930-A7C6-97CDF8F7F0D7} + {4F10E2B5-E8BB-4253-9BE6-9187575ADB13} = {36BA84C0-291C-4930-A7C6-97CDF8F7F0D7} EndGlobalSection EndGlobal diff --git a/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs new file mode 100644 index 00000000..f246b231 --- /dev/null +++ b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs @@ -0,0 +1,34 @@ +using CounterStrikeSharp.API.Modules.Utils; +using Jailbreak.Formatting.Base; +using Jailbreak.Formatting.Core; +using Jailbreak.Formatting.Logistics; +using Jailbreak.Formatting.Objects; +using Jailbreak.Formatting.Views; + +namespace Jailbreak.English.Generic; + +public class GenericCommandNotifications : IGenericCommandNotifications, ILanguage +{ + public static FormatObject PREFIX = + new HiddenFormatObject($" {ChatColors.Darkred}[{ChatColors.LightRed}JB{ChatColors.Darkred}]") + { + // Hide in panorama and center text + Plain = false, + Panorama = false, + Chat = true, + }; + + public IView PlayerNotFound(string query) + { + return new SimpleView(writer => + writer + .Line(PREFIX, $"Player '{query}' not found!")); + } + + public IView PlayerFoundMultiple(string query) + { + return new SimpleView(writer => + writer + .Line(PREFIX, $"Multiple players found for '{query}'!")); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/DebugCommand.cs b/mod/Jailbreak.Debug/DebugCommand.cs new file mode 100644 index 00000000..32532b9a --- /dev/null +++ b/mod/Jailbreak.Debug/DebugCommand.cs @@ -0,0 +1,46 @@ +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Admin; +using CounterStrikeSharp.API.Modules.Commands; +using Jailbreak.Debug.Subcommands; +using Jailbreak.Formatting.Views; +using Jailbreak.Public.Behaviors; + +namespace Jailbreak.Debug; + +// css_debug [subcommand] [args] -> subcommand [args] +public class DebugCommand : IPluginBehavior +{ + private readonly Dictionary commands = new(); + + public DebugCommand(IServiceProvider serviceProvider) + { + commands.Add("markrebel", new MarkRebel(serviceProvider)); + } + + [RequiresPermissions("@css/root")] + public void Command_Debug(CCSPlayerController? executor, CommandInfo info) + { + if (executor == null) + { + return; + } + + if (info.ArgCount == 1) + { + foreach (var command in commands) + { + info.ReplyToCommand(command.Key); + } + + return; + } + + if (!commands.TryGetValue(info.GetArg(1), out var subcommand)) + { + info.ReplyToCommand("Invalid subcommand"); + return; + } + + subcommand.OnCommand(executor, new WrappedInfo(info)); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/DebugServiceExtension.cs b/mod/Jailbreak.Debug/DebugServiceExtension.cs new file mode 100644 index 00000000..5f1ed04e --- /dev/null +++ b/mod/Jailbreak.Debug/DebugServiceExtension.cs @@ -0,0 +1,12 @@ +using Jailbreak.Public.Extensions; +using Microsoft.Extensions.DependencyInjection; + +namespace Jailbreak.Debug; + +public static class DebugServiceExtension +{ + public static void AddJailbreakDebug(this IServiceCollection services) + { + services.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Jailbreak.Debug.csproj b/mod/Jailbreak.Debug/Jailbreak.Debug.csproj new file mode 100644 index 00000000..e549f3ef --- /dev/null +++ b/mod/Jailbreak.Debug/Jailbreak.Debug.csproj @@ -0,0 +1,14 @@ + + + + net7.0 + enable + enable + + + + + + + + diff --git a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs new file mode 100644 index 00000000..010ec189 --- /dev/null +++ b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs @@ -0,0 +1,145 @@ +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Admin; +using CounterStrikeSharp.API.Modules.Commands; +using CounterStrikeSharp.API.Modules.Commands.Targeting; +using Jailbreak.Formatting.Extensions; +using Jailbreak.Formatting.Views; +using Microsoft.Extensions.DependencyInjection; + +namespace Jailbreak.Debug.Subcommands; + +public abstract class AbstractCommand +{ + protected IServiceProvider services; + private IGenericCommandNotifications lang; + + protected AbstractCommand(IServiceProvider services) + { + this.services = services; + lang = services.GetRequiredService(); + } + + public abstract void OnCommand(CCSPlayerController? executor, WrappedInfo info); + + protected TargetResult? GetTarget(WrappedInfo command, int argIndex = 1, + Func? predicate = null) + { + return GetTarget(command.info, argIndex + 1, predicate); + } + + protected TargetResult? GetVulnerableTarget(WrappedInfo command, int argIndex = 1, + Func? predicate = null) + { + return GetVulnerableTarget(command.info, argIndex + 1, predicate); + } + + protected TargetResult? GetTarget(CommandInfo command, int argIndex = 1, + Func? predicate = null) + { + var matches = command.GetArgTargetResult(argIndex); + + matches.Players = matches.Players.Where(player => + player is { IsValid: true, Connected: PlayerConnectedState.PlayerConnected }).ToList(); + if (predicate != null) + matches.Players = matches.Players.Where(predicate).ToList(); + + if (!matches.Any()) + { + if (command.CallingPlayer != null) + lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + return null; + } + + if (matches.Count() > 1 && command.GetArg(argIndex).StartsWith('@')) + return matches; + + if (matches.Count() == 1 || !command.GetArg(argIndex).StartsWith('@')) + return matches; + + if (command.CallingPlayer != null) + lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + return null; + } + + internal TargetResult? GetVulnerableTarget(CommandInfo command, int argIndex = 1, + Func? predicate = null) + { + return GetTarget(command, argIndex, + (p) => command.CallingPlayer == null || + command.CallingPlayer.CanTarget(p) && (predicate == null || predicate(p))); + } + + internal TargetResult? GetSingleTarget(CommandInfo command, int argIndex = 1) + { + var matches = command.GetArgTargetResult(argIndex); + + if (!matches.Any()) + { + if (command.CallingPlayer != null) + lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + return null; + } + + if (matches.Count() > 1) + { + if (command.CallingPlayer != null) + lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + return null; + } + + return matches; + } + + internal string GetTargetLabel(CommandInfo info, int argIndex = 1) + { + switch (info.GetArg(argIndex)) + { + case "@all": + return "all players"; + case "@bots": + return "all bots"; + case "@humans": + return "all humans"; + case "@alive": + return "alive players"; + case "@dead": + return "dead players"; + case "@!me": + return "all except self"; + case "@me": + return info.CallingPlayer == null ? "Console" : info.CallingPlayer.PlayerName; + case "@ct": + return "all CTs"; + case "@t": + return "all Ts"; + case "@spec": + return "all spectators"; + default: + var player = info.GetArgTargetResult(argIndex).FirstOrDefault(); + if (player != null) + return player.PlayerName; + return "unknown"; + } + } + + + internal string GetTargetLabels(CommandInfo info, int argIndex = 1) + { + string label = GetTargetLabel(info, argIndex); + if (label.ToLower().EndsWith("s")) + return label + "'"; + return label + "'s"; + } +} + +public static class CommandExtensions + +{ + internal static bool CanTarget(this CCSPlayerController controller, CCSPlayerController target) + { + if (!target.IsValid) return false; + if (target.Connected != PlayerConnectedState.PlayerConnected) return false; + if (target.IsBot || target.IsHLTV) return true; + return AdminManager.CanPlayerTarget(controller, target); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs new file mode 100644 index 00000000..7e735a43 --- /dev/null +++ b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs @@ -0,0 +1,45 @@ +using CounterStrikeSharp.API; +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Commands; +using Jailbreak.Formatting.Views; +using Jailbreak.Public.Mod.Rebel; +using Microsoft.Extensions.DependencyInjection; + +namespace Jailbreak.Debug.Subcommands; + +// css_markrebel [player] +public class MarkRebel : AbstractCommand +{ + public MarkRebel(IServiceProvider services) : base(services) + { + } + + public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) + { + if (info.ArgCount == 1) + { + info.ReplyToCommand("Specify target?"); + return; + } + + var target = GetVulnerableTarget(info); + if (target == null) + return; + + var duration = 120; + if(info.ArgCount == 3) + { + if (!int.TryParse(info.GetArg(2), out duration)) + { + info.ReplyToCommand("Invalid duration"); + return; + } + } + + foreach (var player in target.Players) + { + services.GetRequiredService().MarkRebel(player, duration); + } + info.ReplyToCommand($"Marked {target.Players.Count()} players as rebels for {duration} seconds"); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs new file mode 100644 index 00000000..f64af2de --- /dev/null +++ b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs @@ -0,0 +1,29 @@ +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Commands; + +namespace Jailbreak.Debug.Subcommands; + +public class WrappedInfo +{ + public readonly CommandInfo info; + + public WrappedInfo(CommandInfo info) + { + this.info = info; + } + + public CCSPlayerController? CallingPlayer => info.CallingPlayer; + + public IntPtr Handle => info.Handle; + + public int ArgCount => info.ArgCount - 1; + + public string ArgString => info.ArgString[(info.ArgString.IndexOf(' ') + 1)..]; + + public string GetCommandString => info.GetCommandString[(info.GetCommandString.IndexOf(' ') + 1)..]; + + public string ArgByIndex(int index) => info.ArgByIndex(index + 1); + public string GetArg(int index) => info.GetArg(index + 1); + + public void ReplyToCommand(string message, bool console = false) => info.ReplyToCommand(message, console); +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsServiceExtension.cs b/mod/Jailbreak.Logs/LogsServiceExtension.cs index 815ad70d..4c626273 100644 --- a/mod/Jailbreak.Logs/LogsServiceExtension.cs +++ b/mod/Jailbreak.Logs/LogsServiceExtension.cs @@ -6,7 +6,7 @@ namespace Jailbreak.Logs; public static class LogsServiceExtension { - public static void AddLogsService(this IServiceCollection services) + public static void AddJailbreakLogs(this IServiceCollection services) { services.AddPluginBehavior(); diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index 9fadd81f..e971b2c5 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -96,7 +96,7 @@ public long GetRebelTimeLeft(CCSPlayerController player) return 0; } - public bool MarkRebel(CCSPlayerController player, long time) + public bool MarkRebel(CCSPlayerController player, long time = 120) { if (!rebelTimes.ContainsKey(player)) { diff --git a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs index bc07c36a..3848bfc8 100644 --- a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs +++ b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs @@ -15,6 +15,10 @@ public LanguageConfig(IServiceCollection collection) _collection = collection; } + public void WithGenericCommand() + where TGenericCommand : class, ILanguage, IGenericCommandNotifications + => _collection.AddSingleton(); + public void WithRatio() where TRatio : class, ILanguage, IRatioNotifications => _collection.AddSingleton(); diff --git a/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs b/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs new file mode 100644 index 00000000..e7250481 --- /dev/null +++ b/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs @@ -0,0 +1,9 @@ +using Jailbreak.Formatting.Base; + +namespace Jailbreak.Formatting.Views; + +public interface IGenericCommandNotifications +{ + public IView PlayerNotFound(string query); + public IView PlayerFoundMultiple(string query); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs b/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs index 87363d8c..61be0744 100644 --- a/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs +++ b/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs @@ -13,7 +13,7 @@ bool IsRebel(CCSPlayerController player) long GetRebelTimeLeft(CCSPlayerController player); - bool MarkRebel(CCSPlayerController player, long time); + bool MarkRebel(CCSPlayerController player, long time = 120); void UnmarkRebel(CCSPlayerController player); } \ No newline at end of file diff --git a/src/Jailbreak/Jailbreak.csproj b/src/Jailbreak/Jailbreak.csproj index c4f3890a..2a615055 100644 --- a/src/Jailbreak/Jailbreak.csproj +++ b/src/Jailbreak/Jailbreak.csproj @@ -33,6 +33,7 @@ + diff --git a/src/Jailbreak/JailbreakServiceCollection.cs b/src/Jailbreak/JailbreakServiceCollection.cs index 99a8ef80..d1046809 100644 --- a/src/Jailbreak/JailbreakServiceCollection.cs +++ b/src/Jailbreak/JailbreakServiceCollection.cs @@ -3,6 +3,8 @@ using CounterStrikeSharp.API.Core; using Jailbreak.Config; +using Jailbreak.Debug; +using Jailbreak.English.Generic; using Jailbreak.English.Rebel; using Jailbreak.English.Teams; using Jailbreak.English.Warden; @@ -33,14 +35,16 @@ public void ConfigureServices(IServiceCollection serviceCollection) serviceCollection.AddTransient(); serviceCollection.AddJailbreakGeneric(); - serviceCollection.AddLogsService(); + serviceCollection.AddJailbreakLogs(); serviceCollection.AddJailbreakWarden(); serviceCollection.AddJailbreakTeams(); serviceCollection.AddJailbreakRebel(); + serviceCollection.AddJailbreakDebug(); // Add in english localization serviceCollection.AddLanguage(config => { + config.WithGenericCommand(); config.WithRatio(); config.WithWarden(); config.WithRebel(); From 29749982e9580287a497095a5b980197becdb617 Mon Sep 17 00:00:00 2001 From: Isaac Date: Mon, 5 Feb 2024 00:15:40 -0800 Subject: [PATCH 4/8] Feat/debug (#20) * Initial stuff for debug * More classes! * Base implementation * Verified working --- mod/Jailbreak.Debug/DebugCommand.cs | 3 ++ .../Subcommands/AbstractCommand.cs | 15 +++++--- mod/Jailbreak.Debug/Subcommands/MarkRebel.cs | 2 +- mod/Jailbreak.Debug/Subcommands/Pardon.cs | 36 +++++++++++++++++++ mod/Jailbreak.Logs/LogsListeners.cs | 2 +- mod/Jailbreak.Rebel/RebelManager.cs | 23 ++++++++++-- 6 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 mod/Jailbreak.Debug/Subcommands/Pardon.cs diff --git a/mod/Jailbreak.Debug/DebugCommand.cs b/mod/Jailbreak.Debug/DebugCommand.cs index 32532b9a..f0208769 100644 --- a/mod/Jailbreak.Debug/DebugCommand.cs +++ b/mod/Jailbreak.Debug/DebugCommand.cs @@ -1,4 +1,5 @@ using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; using CounterStrikeSharp.API.Modules.Commands; using Jailbreak.Debug.Subcommands; @@ -15,9 +16,11 @@ public class DebugCommand : IPluginBehavior public DebugCommand(IServiceProvider serviceProvider) { commands.Add("markrebel", new MarkRebel(serviceProvider)); + commands.Add("pardon", new Pardon(serviceProvider)); } [RequiresPermissions("@css/root")] + [ConsoleCommand("css_debug", "Debug command for Jailbreak.")] public void Command_Debug(CCSPlayerController? executor, CommandInfo info) { if (executor == null) diff --git a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs index 010ec189..c42a3c56 100644 --- a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs +++ b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs @@ -69,7 +69,7 @@ protected AbstractCommand(IServiceProvider services) command.CallingPlayer.CanTarget(p) && (predicate == null || predicate(p))); } - internal TargetResult? GetSingleTarget(CommandInfo command, int argIndex = 1) + protected TargetResult? GetSingleTarget(CommandInfo command, int argIndex = 1) { var matches = command.GetArgTargetResult(argIndex); @@ -90,7 +90,11 @@ protected AbstractCommand(IServiceProvider services) return matches; } - internal string GetTargetLabel(CommandInfo info, int argIndex = 1) + protected string GetTargetLabel(WrappedInfo info, int argIndex = 1) + { + return GetTargetLabel(info.info, argIndex + 1); + } + protected string GetTargetLabel(CommandInfo info, int argIndex = 1) { switch (info.GetArg(argIndex)) { @@ -122,8 +126,11 @@ internal string GetTargetLabel(CommandInfo info, int argIndex = 1) } } - - internal string GetTargetLabels(CommandInfo info, int argIndex = 1) + protected string GetTargetLabels(WrappedInfo info, int argIndex = 1) + { + return GetTargetLabels(info.info, argIndex + 1); + } + protected string GetTargetLabels(CommandInfo info, int argIndex = 1) { string label = GetTargetLabel(info, argIndex); if (label.ToLower().EndsWith("s")) diff --git a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs index 7e735a43..b884ad5b 100644 --- a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs +++ b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs @@ -40,6 +40,6 @@ public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) { services.GetRequiredService().MarkRebel(player, duration); } - info.ReplyToCommand($"Marked {target.Players.Count()} players as rebels for {duration} seconds"); + info.ReplyToCommand($"Marked {GetTargetLabel(info)} as rebels for {duration} seconds."); } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/Pardon.cs b/mod/Jailbreak.Debug/Subcommands/Pardon.cs new file mode 100644 index 00000000..ebdfa46d --- /dev/null +++ b/mod/Jailbreak.Debug/Subcommands/Pardon.cs @@ -0,0 +1,36 @@ +using CounterStrikeSharp.API; +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Commands; +using Jailbreak.Formatting.Views; +using Jailbreak.Public.Mod.Rebel; +using Microsoft.Extensions.DependencyInjection; + +namespace Jailbreak.Debug.Subcommands; + +// css_markrebel [player] +public class Pardon : AbstractCommand +{ + public Pardon(IServiceProvider services) : base(services) + { + } + + public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) + { + if (info.ArgCount == 1) + { + info.ReplyToCommand("Specify target?"); + return; + } + + var target = GetVulnerableTarget(info); + if (target == null) + return; + + foreach (var player in target.Players) + { + services.GetRequiredService().UnmarkRebel(player); + } + + info.ReplyToCommand($"Pardoned {GetTargetLabel(info)}"); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsListeners.cs b/mod/Jailbreak.Logs/LogsListeners.cs index 6305e041..50fc0f5e 100644 --- a/mod/Jailbreak.Logs/LogsListeners.cs +++ b/mod/Jailbreak.Logs/LogsListeners.cs @@ -61,7 +61,7 @@ private HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) var attacker = @event.Attacker; bool isWorld = attacker == null || !attacker.IsReal(); - int health = @event.Health; + int health = @event.DmgHealth; if (isWorld) { diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index e971b2c5..61d6203d 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -29,6 +29,7 @@ public void Start(BasePlugin parent) parent.RegisterEventHandler(OnPlayerDisconnect); parent.RegisterEventHandler(OnPlayerDeath); parent.RegisterEventHandler(OnRoundStart); + parent.RegisterListener(OnTick); parent.AddTimer(1f, () => { @@ -49,6 +50,22 @@ public void Start(BasePlugin parent) }, TimerFlags.REPEAT); } + private void OnTick() + { + foreach (var player in GetActiveRebels()) + { + if (!player.IsReal()) + continue; + + if (GetRebelTimeLeft(player) <= 0) + { + continue; + } + + SendTimeLeft(player); + } + } + HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { rebelTimes.Clear(); @@ -127,7 +144,7 @@ private float GetRebelTimePercentage(CCSPlayerController player) return 0; return (float)(100 - (120 - x) * (Math.Sqrt(120 - x)) / 13f) / 100; } - + private Color GetRebelColor(CCSPlayerController player) { var percent = GetRebelTimePercentage(player); @@ -158,7 +175,7 @@ private void SendTimeLeft(CCSPlayerController player) var formattedTime = TimeSpan.FromSeconds(timeLeft).ToString(@"mm\:ss"); var color = GetRebelColor(player); var formattedColor = $""; - - player.PrintToCenterHtml($"You are a rebel for {formattedColor}{formattedTime} more seconds."); + + player.PrintToCenterHtml($"You are {formattedColor}rebelling"); } } \ No newline at end of file From 211ca83ddf4d148c6c8cb5a60cd29b609088afbc Mon Sep 17 00:00:00 2001 From: Mooshua <43320783+Mooshua@users.noreply.github.com> Date: Mon, 5 Feb 2024 15:12:54 -0800 Subject: [PATCH 5/8] Prevent some crashes when touching disconnected clients (#22) * Make global state eviction slightly more verbose * All format operations will check for a valid client before continuing --- mod/Jailbreak.Teams/Queue/QueueBehavior.cs | 14 ++++++- .../Extensions/ViewExtensions.cs | 37 +++++++++++++------ .../Behaviors/GlobalStateTracker.cs | 12 ++++++ 3 files changed, 49 insertions(+), 14 deletions(-) diff --git a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs index 9133a528..e9c42416 100644 --- a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs +++ b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs @@ -46,6 +46,9 @@ public void Start(BasePlugin parent) public bool TryEnterQueue(CCSPlayerController player) { + if (!player.IsReal()) + return false; + if (player.GetTeam() == CsTeam.CounterTerrorist) return false; @@ -59,6 +62,9 @@ public bool TryEnterQueue(CCSPlayerController player) public bool TryExitQueue(CCSPlayerController player) { + if (!player.IsReal()) + return false; + var state = _state.Get(player); state.InQueue = false; state.IsGuard = false; @@ -68,7 +74,9 @@ public bool TryExitQueue(CCSPlayerController player) public bool TryPop(int count) { - var queue = Queue.ToList(); + var queue = Queue + .Where(player => player.IsReal()) + .ToList(); if (queue.Count <= count) { @@ -91,9 +99,11 @@ public bool TryPop(int count) public bool TryPush(int count) { var players = Utilities.GetPlayers() + .Where(player => player.IsReal()) .Where(player => player.GetTeam() == CsTeam.CounterTerrorist) .Shuffle(Random.Shared) .ToList(); + _logger.LogInformation("[Queue] Push requested {@Count} out of {@GuardCount}", count, players.Count); for (int i = 0; i < Math.Min(count, players.Count); i++) @@ -176,7 +186,7 @@ public HookResult OnPlayerSpawn(EventPlayerSpawn ev, GameEventInfo info) var player = ev.Userid; if (!player.IsReal()) return HookResult.Continue; - + var state = _state.Get(ev.Userid); if (player.GetTeam() == CsTeam.CounterTerrorist && !state.IsGuard) diff --git a/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs index 981f483a..36e3997c 100644 --- a/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs +++ b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs @@ -3,6 +3,7 @@ using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; +using Jailbreak.Public.Extensions; namespace Jailbreak.Formatting.Extensions; @@ -22,40 +23,52 @@ public static FormatWriter ToWriter(this IView view) public static IView ToPlayerConsole(this IView view, CCSPlayerController player) { - var writer = view.ToWriter(); + if (player.IsReal()) + { + var writer = view.ToWriter(); - foreach (string writerLine in writer.Plain) - player.PrintToConsole(writerLine); + foreach (string writerLine in writer.Plain) + player.PrintToConsole(writerLine); + } return view; } public static IView ToPlayerChat(this IView view, CCSPlayerController player) { - var writer = view.ToWriter(); + if (player.IsReal()) + { + var writer = view.ToWriter(); - foreach (string writerLine in writer.Chat) - player.PrintToChat(writerLine); + foreach (string writerLine in writer.Chat) + player.PrintToChat(writerLine); + } return view; } public static IView ToPlayerCenter(this IView view, CCSPlayerController player) { - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Plain); + if (player.IsReal()) + { + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Plain); - player.PrintToCenter(merged); + player.PrintToCenter(merged); + } return view; } public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) { - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Panorama); + if (player.IsReal()) + { + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Panorama); - player.PrintToCenterHtml(merged); + player.PrintToCenterHtml(merged); + } return view; } diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs index 5eeeb7cb..c5c25789 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs @@ -23,4 +23,16 @@ public HookResult OnDisconnect(EventPlayerDisconnect ev, GameEventInfo info) Reset(ev.Userid); return HookResult.Continue; } + + /// + /// Reset all global states when a new game starts + /// + /// + /// + /// + public HookResult OnGameEnd(EventGameEnd ev, GameEventInfo info) + { + ResetAll(); + return HookResult.Continue; + } } From 9579c32ed07cb268450eba979c9098bb6057e141 Mon Sep 17 00:00:00 2001 From: Isaac Date: Mon, 5 Feb 2024 16:31:45 -0800 Subject: [PATCH 6/8] Cleanup (#23) * Format * Enforce variable naming scheme * Fix namespaces and nullabilities * Resolve all warnings * Update Github Actions --- .github/workflows/nightly.yml | 15 +- README.md | 3 + .../Generic/GenericCommandNotifications.cs | 8 +- .../Jailbreak.English.csproj | 2 +- .../Rebel/RebelNotifications.cs | 20 +- .../Teams/RatioNotifications.cs | 86 ++-- .../Warden/WardenNotifications.cs | 89 ++-- mod/Jailbreak.Debug/DebugCommand.cs | 27 +- mod/Jailbreak.Debug/DebugServiceExtension.cs | 8 +- mod/Jailbreak.Debug/Jailbreak.Debug.csproj | 4 +- .../Subcommands/AbstractCommand.cs | 38 +- mod/Jailbreak.Debug/Subcommands/MarkRebel.cs | 16 +- mod/Jailbreak.Debug/Subcommands/Pardon.cs | 12 +- .../Subcommands/WrappedInfo.cs | 48 +- mod/Jailbreak.Logs/Jailbreak.Logs.csproj | 4 +- mod/Jailbreak.Logs/LogsCommand.cs | 6 +- mod/Jailbreak.Logs/LogsListeners.cs | 38 +- mod/Jailbreak.Logs/LogsManager.cs | 85 ++-- mod/Jailbreak.Logs/LogsServiceExtension.cs | 14 +- mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj | 6 +- mod/Jailbreak.Rebel/RebelListener.cs | 12 +- mod/Jailbreak.Rebel/RebelManager.cs | 116 ++--- mod/Jailbreak.Rebel/RebelServiceExtension.cs | 14 +- mod/Jailbreak.Teams/Jailbreak.Teams.csproj | 6 +- mod/Jailbreak.Teams/Queue/QueueBehavior.cs | 453 +++++++++--------- mod/Jailbreak.Teams/Queue/QueueState.cs | 17 +- mod/Jailbreak.Teams/Ratio/RatioBehavior.cs | 208 ++++---- mod/Jailbreak.Teams/Ratio/RatioConfig.cs | 14 +- mod/Jailbreak.Teams/TeamsServiceExtension.cs | 15 +- .../Commands/WardenCommandsBehavior.cs | 148 +++--- .../WardenFormatWriterExtensions.cs | 1 - mod/Jailbreak.Warden/Global/WardenBehavior.cs | 270 +++++------ mod/Jailbreak.Warden/Jailbreak.Warden.csproj | 4 +- .../Markers/WardenMarkerBehavior.cs | 34 +- .../Paint/WardenPaintBehavior.cs | 79 ++- .../Selection/QueueFavorState.cs | 22 +- mod/Jailbreak.Warden/Selection/QueueState.cs | 6 +- .../Selection/WardenSelectionBehavior.cs | 336 +++++++------ .../WardenServiceExtension.cs | 23 +- public/Jailbreak.Formatting/Base/IView.cs | 6 +- .../Jailbreak.Formatting/Base/SimpleView.cs | 38 +- .../Jailbreak.Formatting/Core/FormatObject.cs | 35 +- .../Jailbreak.Formatting/Core/FormatWriter.cs | 31 +- .../Extensions/ViewExtensions.cs | 130 +++-- .../Jailbreak.Formatting.csproj | 2 +- .../Jailbreak.Formatting/Languages/English.cs | 3 +- .../Logistics/IDialect.cs | 7 +- .../Logistics/ILanguage.cs | 9 +- .../Logistics/LanguageConfig.cs | 50 +- .../Logistics/RegisterLanguageExtensions.cs | 18 +- .../Objects/HiddenFormatObject.cs | 68 +-- .../Objects/PlayerFormatObject.cs | 31 +- .../Objects/StringFormatObject.cs | 49 +- .../Views/IRebelNotifications.cs | 2 +- .../Views/ITeamsNotifications.cs | 19 +- .../Views/IWardenNotifications.cs | 55 ++- .../Behaviors/IPluginBehavior.cs | 26 +- .../Configuration/IConfigService.cs | 27 +- .../Extensions/EnumerableExtensions.cs | 36 +- .../Extensions/PlayerExtensions.cs | 35 +- .../Extensions/ServerExtensions.cs | 13 +- .../Extensions/ServiceCollectionExtensions.cs | 71 ++- .../Extensions/StringExtensions.cs | 12 +- .../Extensions/VectorExtensions.cs | 8 +- .../Jailbreak.Public/Generic/ICoroutines.cs | 8 +- .../Jailbreak.Public/Generic/IPlayerState.cs | 12 +- .../Generic/IPlayerStateFactory.cs | 16 +- .../Jailbreak.Public/Jailbreak.Public.csproj | 6 +- .../Jailbreak.Public/Mod/Draw/BeamCircle.cs | 53 +- public/Jailbreak.Public/Mod/Draw/BeamLine.cs | 57 +-- .../Jailbreak.Public/Mod/Draw/BeamedShape.cs | 20 +- .../Mod/Draw/DrawableShape.cs | 29 +- .../Mod/Rebel/IRebelService.cs | 2 +- .../Jailbreak.Public/Mod/Teams/IGuardQueue.cs | 71 ++- .../Mod/Warden/IWardenSelectionService.cs | 18 +- .../Mod/Warden/IWardenService.cs | 30 +- .../Jailbreak.Public/Utils/TemporaryConvar.cs | 31 +- .../Coroutines/CoroutineManager.cs | 42 +- .../GenericServiceExtension.cs | 23 +- .../Jailbreak.Generic.csproj | 2 +- .../Behaviors/AliveStateTracker.cs | 22 +- .../PlayerState/Behaviors/BaseStateTracker.cs | 38 +- .../Behaviors/GlobalStateTracker.cs | 8 +- .../Behaviors/RoundStateTracker.cs | 24 +- .../PlayerState/ITrackedPlayerState.cs | 6 +- .../PlayerState/PlayerStateFactory.cs | 59 +-- .../PlayerState/PlayerStateImpl.cs | 31 +- src/Jailbreak/Config/ConfigService.cs | 114 ++--- src/Jailbreak/Jailbreak.cs | 101 ++-- src/Jailbreak/Jailbreak.csproj | 16 +- src/Jailbreak/JailbreakServiceCollection.cs | 54 +-- 91 files changed, 1940 insertions(+), 2041 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index ff9058e1..fbe2cec8 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -11,21 +11,18 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Insert Job Version run: sed -i "s/{GIT_VERSION}/${{github.run_number}}/g" src/Jailbreak/Jailbreak.cs - name: Setup .NET SDK - uses: actions/setup-dotnet@v3 + uses: actions/setup-dotnet@v4 with: dotnet-version: 8.0.x - - - name: Restore dependencies - run: dotnet restore - - name: Build - run: dotnet build src/Jailbreak/Jailbreak.csproj --no-restore - - name: Publish - run: dotnet publish src/Jailbreak/Jailbreak.csproj --no-build --no-restore + - run: | + dotnet restore + dotnet build src/Jailbreak/Jailbreak.csproj --no-restore + dotnet publish src/Jailbreak/Jailbreak.csproj --no-build --no-restore - uses: actions/upload-artifact@v4.0.0 with: diff --git a/README.md b/README.md index e2faad22..5274d75d 100644 --- a/README.md +++ b/README.md @@ -15,13 +15,16 @@ The classic Jail gamemode, ported to Counter-Strike 2. - [ ] Error reporting - [x] Configuration system - Note: Passable, but in a terrible state. Needs TLC. + - [x] Logging - **👮 Guards** - [x] Warden Selection + - [x] Warden Laser and Paint - [ ] Special Days - [x] Ratio Enforcement - [ ] Bans/Punishments - **🎃 Prisoners** - [ ] Last Request + - [x] Rebel System - **🛕 Maps** - [ ] Custom Entities - [ ] Custom I/O diff --git a/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs index f246b231..b19293d6 100644 --- a/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs +++ b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs @@ -9,26 +9,26 @@ namespace Jailbreak.English.Generic; public class GenericCommandNotifications : IGenericCommandNotifications, ILanguage { - public static FormatObject PREFIX = + public static FormatObject Prefix = new HiddenFormatObject($" {ChatColors.Darkred}[{ChatColors.LightRed}JB{ChatColors.Darkred}]") { // Hide in panorama and center text Plain = false, Panorama = false, - Chat = true, + Chat = true }; public IView PlayerNotFound(string query) { return new SimpleView(writer => writer - .Line(PREFIX, $"Player '{query}' not found!")); + .Line(Prefix, $"Player '{query}' not found!")); } public IView PlayerFoundMultiple(string query) { return new SimpleView(writer => writer - .Line(PREFIX, $"Multiple players found for '{query}'!")); + .Line(Prefix, $"Multiple players found for '{query}'!")); } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Jailbreak.English.csproj b/lang/Jailbreak.English/Jailbreak.English.csproj index 883695e7..5b7c3e08 100644 --- a/lang/Jailbreak.English/Jailbreak.English.csproj +++ b/lang/Jailbreak.English/Jailbreak.English.csproj @@ -7,7 +7,7 @@ - + diff --git a/lang/Jailbreak.English/Rebel/RebelNotifications.cs b/lang/Jailbreak.English/Rebel/RebelNotifications.cs index 53ffd2ad..347ddfb7 100644 --- a/lang/Jailbreak.English/Rebel/RebelNotifications.cs +++ b/lang/Jailbreak.English/Rebel/RebelNotifications.cs @@ -9,14 +9,16 @@ namespace Jailbreak.English.Rebel; public class RebelNotifications : IRebelNotifications, ILanguage { - public static FormatObject PREFIX = new HiddenFormatObject( $" {ChatColors.Darkred}[{ChatColors.LightRed}Rebel{ChatColors.Darkred}]" ) - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true, - }; - public IView NO_LONGER_REBEL => new SimpleView(writer => + public static FormatObject Prefix = + new HiddenFormatObject($" {ChatColors.Darkred}[{ChatColors.LightRed}Rebel{ChatColors.Darkred}]") + { + // Hide in panorama and center text + Plain = false, + Panorama = false, + Chat = true + }; + + public IView NoLongerRebel => new SimpleView(writer => writer - .Line(PREFIX, "You are no longer a rebel.")); + .Line(Prefix, "You are no longer a rebel.")); } \ No newline at end of file diff --git a/lang/Jailbreak.English/Teams/RatioNotifications.cs b/lang/Jailbreak.English/Teams/RatioNotifications.cs index 5747b526..95f4d4b5 100644 --- a/lang/Jailbreak.English/Teams/RatioNotifications.cs +++ b/lang/Jailbreak.English/Teams/RatioNotifications.cs @@ -1,5 +1,4 @@ using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Logistics; @@ -10,45 +9,46 @@ namespace Jailbreak.English.Teams; public class RatioNotifications : IRatioNotifications, ILanguage { - public static FormatObject PREFIX = new HiddenFormatObject( $" {ChatColors.LightRed}[{ChatColors.Red}JB{ChatColors.LightRed}]" ) - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true, - }; - - public IView NOT_ENOUGH_GUARDS => new SimpleView(writer => - writer - .Line(PREFIX, "There's not enough guards in the queue!")); - - public IView PLEASE_JOIN_GUARD_QUEUE => new SimpleView(writer => - writer - .Line(PREFIX, "Type !guard to become a guard!")); - - public IView JOINED_GUARD_QUEUE => new SimpleView(writer => - writer - .Line(PREFIX, "You've joined the guard queue!")); - - public IView ALREADY_A_GUARD => new SimpleView(writer => - writer - .Line(PREFIX, "You're already a guard!")); - - public IView YOU_WERE_AUTOBALANCED_PRISONER => new SimpleView(writer => - writer - .Line(PREFIX, "You were autobalanced to the prisoner team!")); - - public IView ATTEMPT_TO_JOIN_FROM_TEAM_MENU => new SimpleView(writer => - writer - .Line(PREFIX, "You were swapped back to the prisoner team!") - .Line(PREFIX, "Please use !guard to join the guard team.")); - - public IView LEFT_GUARD => new SimpleView(writer => - writer - .Line(PREFIX, "You are no longer a guard.") - .Line(PREFIX, "Please use !guard if you want to re-join the guard team.")); - - public IView YOU_WERE_AUTOBALANCED_GUARD => new SimpleView(writer => - writer - .Line(PREFIX, "You are now a guard!")); -} + public static FormatObject Prefix = + new HiddenFormatObject($" {ChatColors.LightRed}[{ChatColors.Red}JB{ChatColors.LightRed}]") + { + // Hide in panorama and center text + Plain = false, + Panorama = false, + Chat = true + }; + + public IView NotEnoughGuards => new SimpleView(writer => + writer + .Line(Prefix, "There's not enough guards in the queue!")); + + public IView PleaseJoinGuardQueue => new SimpleView(writer => + writer + .Line(Prefix, "Type !guard to become a guard!")); + + public IView JoinedGuardQueue => new SimpleView(writer => + writer + .Line(Prefix, "You've joined the guard queue!")); + + public IView AlreadyAGuard => new SimpleView(writer => + writer + .Line(Prefix, "You're already a guard!")); + + public IView YouWereAutobalancedPrisoner => new SimpleView(writer => + writer + .Line(Prefix, "You were autobalanced to the prisoner team!")); + + public IView AttemptToJoinFromTeamMenu => new SimpleView(writer => + writer + .Line(Prefix, "You were swapped back to the prisoner team!") + .Line(Prefix, "Please use !guard to join the guard team.")); + + public IView LeftGuard => new SimpleView(writer => + writer + .Line(Prefix, "You are no longer a guard.") + .Line(Prefix, "Please use !guard if you want to re-join the guard team.")); + + public IView YouWereAutobalancedGuard => new SimpleView(writer => + writer + .Line(Prefix, "You are now a guard!")); +} \ No newline at end of file diff --git a/lang/Jailbreak.English/Warden/WardenNotifications.cs b/lang/Jailbreak.English/Warden/WardenNotifications.cs index 332120b5..bc54cbcf 100644 --- a/lang/Jailbreak.English/Warden/WardenNotifications.cs +++ b/lang/Jailbreak.English/Warden/WardenNotifications.cs @@ -1,6 +1,5 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Logistics; @@ -11,57 +10,57 @@ namespace Jailbreak.English.Warden; public class WardenNotifications : IWardenNotifications, ILanguage { - public static FormatObject PREFIX = new HiddenFormatObject( $" {ChatColors.Lime}[{ChatColors.Green}WARDEN{ChatColors.Lime}]" ) - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true, - }; + public static FormatObject Prefix = + new HiddenFormatObject($" {ChatColors.Lime}[{ChatColors.Green}WARDEN{ChatColors.Lime}]") + { + // Hide in panorama and center text + Plain = false, + Panorama = false, + Chat = true + }; - public IView PICKING_SHORTLY => new SimpleView(writer => - writer - .Line(PREFIX, "Picking a warden shortly") - .Line(PREFIX, "To enter the warden queue, type !warden in chat.")); + public IView PickingShortly => new SimpleView(writer => + writer + .Line(Prefix, "Picking a warden shortly") + .Line(Prefix, "To enter the warden queue, type !warden in chat.")); - public IView NO_WARDENS => new SimpleView(writer => - writer - .Line(PREFIX, "No wardens in queue! The next player to run !warden will become a warden.")); + public IView NoWardens => new SimpleView(writer => + writer + .Line(Prefix, "No wardens in queue! The next player to run !warden will become a warden.")); - public IView WARDEN_LEFT => new SimpleView(writer => - writer.Line(PREFIX, "The warden has left the game!")); + public IView WardenLeft => new SimpleView(writer => + writer.Line(Prefix, "The warden has left the game!")); - public IView WARDEN_DIED => new SimpleView(writer => - writer.Line(PREFIX, "The warden has died!")); + public IView WardenDied => new SimpleView(writer => + writer.Line(Prefix, "The warden has died!")); - public IView BECOME_NEXT_WARDEN => new SimpleView(writer => - writer.Line(PREFIX, "Type !warden to become the next warden")); + public IView BecomeNextWarden => new SimpleView(writer => + writer.Line(Prefix, "Type !warden to become the next warden")); - public IView JOIN_RAFFLE => new SimpleView(writer => - writer.Line(PREFIX, "You've joined the warden raffle!")); + public IView JoinRaffle => new SimpleView(writer => + writer.Line(Prefix, "You've joined the warden raffle!")); - public IView LEAVE_RAFFLE => new SimpleView(writer => - writer.Line(PREFIX, "You've left the warden raffle!")); + public IView LeaveRaffle => new SimpleView(writer => + writer.Line(Prefix, "You've left the warden raffle!")); - public IView PASS_WARDEN(CCSPlayerController player) - { - return new SimpleView(writer => - writer.Line(PREFIX, player, "has resigned from being warden!")); - } + public IView PassWarden(CCSPlayerController player) + { + return new SimpleView(writer => + writer.Line(Prefix, player, "has resigned from being warden!")); + } - public IView NEW_WARDEN(CCSPlayerController player) - { - return new SimpleView(writer => - writer.Line(PREFIX, player, "is now the warden!")); - } + public IView NewWarden(CCSPlayerController player) + { + return new SimpleView(writer => + writer.Line(Prefix, player, "is now the warden!")); + } - public IView CURRENT_WARDEN(CCSPlayerController? player) - { - if (player is not null) - return new SimpleView(writer => - writer.Line(PREFIX, "The current warden is", player)); - else - return new SimpleView(writer => - writer.Line(PREFIX, "There is currently no warden!")); - } -} + public IView CurrentWarden(CCSPlayerController? player) + { + if (player is not null) + return new SimpleView(writer => + writer.Line(Prefix, "The current warden is", player)); + return new SimpleView(writer => + writer.Line(Prefix, "There is currently no warden!")); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Debug/DebugCommand.cs b/mod/Jailbreak.Debug/DebugCommand.cs index f0208769..2b953cbc 100644 --- a/mod/Jailbreak.Debug/DebugCommand.cs +++ b/mod/Jailbreak.Debug/DebugCommand.cs @@ -3,7 +3,6 @@ using CounterStrikeSharp.API.Modules.Admin; using CounterStrikeSharp.API.Modules.Commands; using Jailbreak.Debug.Subcommands; -using Jailbreak.Formatting.Views; using Jailbreak.Public.Behaviors; namespace Jailbreak.Debug; @@ -11,39 +10,33 @@ namespace Jailbreak.Debug; // css_debug [subcommand] [args] -> subcommand [args] public class DebugCommand : IPluginBehavior { - private readonly Dictionary commands = new(); - + private readonly Dictionary _commands = new(); + public DebugCommand(IServiceProvider serviceProvider) { - commands.Add("markrebel", new MarkRebel(serviceProvider)); - commands.Add("pardon", new Pardon(serviceProvider)); + _commands.Add("markrebel", new MarkRebel(serviceProvider)); + _commands.Add("pardon", new Pardon(serviceProvider)); } - + [RequiresPermissions("@css/root")] [ConsoleCommand("css_debug", "Debug command for Jailbreak.")] public void Command_Debug(CCSPlayerController? executor, CommandInfo info) { - if (executor == null) - { - return; - } + if (executor == null) return; if (info.ArgCount == 1) { - foreach (var command in commands) - { - info.ReplyToCommand(command.Key); - } + foreach (var command in _commands) info.ReplyToCommand(command.Key); return; } - - if (!commands.TryGetValue(info.GetArg(1), out var subcommand)) + + if (!_commands.TryGetValue(info.GetArg(1), out var subcommand)) { info.ReplyToCommand("Invalid subcommand"); return; } - + subcommand.OnCommand(executor, new WrappedInfo(info)); } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/DebugServiceExtension.cs b/mod/Jailbreak.Debug/DebugServiceExtension.cs index 5f1ed04e..0c6f4bc7 100644 --- a/mod/Jailbreak.Debug/DebugServiceExtension.cs +++ b/mod/Jailbreak.Debug/DebugServiceExtension.cs @@ -5,8 +5,8 @@ namespace Jailbreak.Debug; public static class DebugServiceExtension { - public static void AddJailbreakDebug(this IServiceCollection services) - { - services.AddPluginBehavior(); - } + public static void AddJailbreakDebug(this IServiceCollection services) + { + services.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Jailbreak.Debug.csproj b/mod/Jailbreak.Debug/Jailbreak.Debug.csproj index e549f3ef..7997b564 100644 --- a/mod/Jailbreak.Debug/Jailbreak.Debug.csproj +++ b/mod/Jailbreak.Debug/Jailbreak.Debug.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs index c42a3c56..a5117c36 100644 --- a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs +++ b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs @@ -10,27 +10,27 @@ namespace Jailbreak.Debug.Subcommands; public abstract class AbstractCommand { - protected IServiceProvider services; - private IGenericCommandNotifications lang; - + private readonly IGenericCommandNotifications _lang; + protected IServiceProvider Services; + protected AbstractCommand(IServiceProvider services) { - this.services = services; - lang = services.GetRequiredService(); + Services = services; + _lang = services.GetRequiredService(); } - + public abstract void OnCommand(CCSPlayerController? executor, WrappedInfo info); protected TargetResult? GetTarget(WrappedInfo command, int argIndex = 1, Func? predicate = null) { - return GetTarget(command.info, argIndex + 1, predicate); + return GetTarget(command.Info, argIndex + 1, predicate); } - + protected TargetResult? GetVulnerableTarget(WrappedInfo command, int argIndex = 1, Func? predicate = null) { - return GetVulnerableTarget(command.info, argIndex + 1, predicate); + return GetVulnerableTarget(command.Info, argIndex + 1, predicate); } protected TargetResult? GetTarget(CommandInfo command, int argIndex = 1, @@ -46,7 +46,7 @@ protected AbstractCommand(IServiceProvider services) if (!matches.Any()) { if (command.CallingPlayer != null) - lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + _lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); return null; } @@ -57,7 +57,7 @@ protected AbstractCommand(IServiceProvider services) return matches; if (command.CallingPlayer != null) - lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + _lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); return null; } @@ -65,8 +65,8 @@ protected AbstractCommand(IServiceProvider services) Func? predicate = null) { return GetTarget(command, argIndex, - (p) => command.CallingPlayer == null || - command.CallingPlayer.CanTarget(p) && (predicate == null || predicate(p))); + p => command.CallingPlayer == null || + (command.CallingPlayer.CanTarget(p) && (predicate == null || predicate(p)))); } protected TargetResult? GetSingleTarget(CommandInfo command, int argIndex = 1) @@ -76,14 +76,14 @@ protected AbstractCommand(IServiceProvider services) if (!matches.Any()) { if (command.CallingPlayer != null) - lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + _lang.PlayerNotFound(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); return null; } if (matches.Count() > 1) { if (command.CallingPlayer != null) - lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); + _lang.PlayerFoundMultiple(command.GetArg(argIndex)).ToPlayerChat(command.CallingPlayer); return null; } @@ -92,8 +92,9 @@ protected AbstractCommand(IServiceProvider services) protected string GetTargetLabel(WrappedInfo info, int argIndex = 1) { - return GetTargetLabel(info.info, argIndex + 1); + return GetTargetLabel(info.Info, argIndex + 1); } + protected string GetTargetLabel(CommandInfo info, int argIndex = 1) { switch (info.GetArg(argIndex)) @@ -128,11 +129,12 @@ protected string GetTargetLabel(CommandInfo info, int argIndex = 1) protected string GetTargetLabels(WrappedInfo info, int argIndex = 1) { - return GetTargetLabels(info.info, argIndex + 1); + return GetTargetLabels(info.Info, argIndex + 1); } + protected string GetTargetLabels(CommandInfo info, int argIndex = 1) { - string label = GetTargetLabel(info, argIndex); + var label = GetTargetLabel(info, argIndex); if (label.ToLower().EndsWith("s")) return label + "'"; return label + "'s"; diff --git a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs index b884ad5b..6376b1d5 100644 --- a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs +++ b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs @@ -1,7 +1,4 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Commands; -using Jailbreak.Formatting.Views; +using CounterStrikeSharp.API.Core; using Jailbreak.Public.Mod.Rebel; using Microsoft.Extensions.DependencyInjection; @@ -27,19 +24,14 @@ public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) return; var duration = 120; - if(info.ArgCount == 3) - { + if (info.ArgCount == 3) if (!int.TryParse(info.GetArg(2), out duration)) { info.ReplyToCommand("Invalid duration"); return; } - } - - foreach (var player in target.Players) - { - services.GetRequiredService().MarkRebel(player, duration); - } + + foreach (var player in target.Players) Services.GetRequiredService().MarkRebel(player, duration); info.ReplyToCommand($"Marked {GetTargetLabel(info)} as rebels for {duration} seconds."); } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/Pardon.cs b/mod/Jailbreak.Debug/Subcommands/Pardon.cs index ebdfa46d..4626607d 100644 --- a/mod/Jailbreak.Debug/Subcommands/Pardon.cs +++ b/mod/Jailbreak.Debug/Subcommands/Pardon.cs @@ -1,7 +1,4 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Commands; -using Jailbreak.Formatting.Views; +using CounterStrikeSharp.API.Core; using Jailbreak.Public.Mod.Rebel; using Microsoft.Extensions.DependencyInjection; @@ -25,11 +22,8 @@ public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) var target = GetVulnerableTarget(info); if (target == null) return; - - foreach (var player in target.Players) - { - services.GetRequiredService().UnmarkRebel(player); - } + + foreach (var player in target.Players) Services.GetRequiredService().UnmarkRebel(player); info.ReplyToCommand($"Pardoned {GetTargetLabel(info)}"); } diff --git a/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs index f64af2de..cf3bea1b 100644 --- a/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs +++ b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs @@ -3,27 +3,37 @@ namespace Jailbreak.Debug.Subcommands; -public class WrappedInfo +public class WrappedInfo { - public readonly CommandInfo info; - + public readonly CommandInfo Info; + public WrappedInfo(CommandInfo info) { - this.info = info; + Info = info; + } + + public CCSPlayerController? CallingPlayer => Info.CallingPlayer; + + public IntPtr Handle => Info.Handle; + + public int ArgCount => Info.ArgCount - 1; + + public string ArgString => Info.ArgString[(Info.ArgString.IndexOf(' ') + 1)..]; + + public string GetCommandString => Info.GetCommandString[(Info.GetCommandString.IndexOf(' ') + 1)..]; + + public string ArgByIndex(int index) + { + return Info.ArgByIndex(index + 1); + } + + public string GetArg(int index) + { + return Info.GetArg(index + 1); + } + + public void ReplyToCommand(string message, bool console = false) + { + Info.ReplyToCommand(message, console); } - - public CCSPlayerController? CallingPlayer => info.CallingPlayer; - - public IntPtr Handle => info.Handle; - - public int ArgCount => info.ArgCount - 1; - - public string ArgString => info.ArgString[(info.ArgString.IndexOf(' ') + 1)..]; - - public string GetCommandString => info.GetCommandString[(info.GetCommandString.IndexOf(' ') + 1)..]; - - public string ArgByIndex(int index) => info.ArgByIndex(index + 1); - public string GetArg(int index) => info.GetArg(index + 1); - - public void ReplyToCommand(string message, bool console = false) => info.ReplyToCommand(message, console); } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Jailbreak.Logs.csproj b/mod/Jailbreak.Logs/Jailbreak.Logs.csproj index 233a12cd..d6145537 100644 --- a/mod/Jailbreak.Logs/Jailbreak.Logs.csproj +++ b/mod/Jailbreak.Logs/Jailbreak.Logs.csproj @@ -7,7 +7,7 @@ - - + + diff --git a/mod/Jailbreak.Logs/LogsCommand.cs b/mod/Jailbreak.Logs/LogsCommand.cs index cd356112..44421fae 100644 --- a/mod/Jailbreak.Logs/LogsCommand.cs +++ b/mod/Jailbreak.Logs/LogsCommand.cs @@ -9,17 +9,17 @@ namespace Jailbreak.Logs; public class LogsCommand : IPluginBehavior { - private ILogService logs; + private readonly ILogService _logs; public LogsCommand(ILogService logs) { - this.logs = logs; + _logs = logs; } [ConsoleCommand("css_logs")] [RequiresPermissionsOr("@css/ban", "@css/generic", "@css/kick")] public void Command_Logs(CCSPlayerController? executor, CommandInfo info) { - logs.PrintLogs(executor); + _logs.PrintLogs(executor); } } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsListeners.cs b/mod/Jailbreak.Logs/LogsListeners.cs index 50fc0f5e..cbffd7eb 100644 --- a/mod/Jailbreak.Logs/LogsListeners.cs +++ b/mod/Jailbreak.Logs/LogsListeners.cs @@ -8,11 +8,11 @@ namespace Jailbreak.Logs; public class LogsListeners : IPluginBehavior { - private ILogService logs; + private readonly ILogService _logs; public LogsListeners(ILogService logs) { - this.logs = logs; + _logs = logs; } public void Start(BasePlugin parent) @@ -27,17 +27,17 @@ private HookResult OnButtonPressed(CEntityIOOutput output, string name, CEntityI { if (!activator.IsValid) return HookResult.Continue; - int index = (int)activator.Index; - CCSPlayerPawn? pawn = Utilities.GetEntityFromIndex(index); + var index = (int)activator.Index; + var pawn = Utilities.GetEntityFromIndex(index); if (!pawn.IsValid) return HookResult.Continue; if (!pawn.OriginalController.IsValid) return HookResult.Continue; - CBaseEntity? ent = Utilities.GetEntityFromIndex((int)caller.Index); + var ent = Utilities.GetEntityFromIndex((int)caller.Index); if (!ent.IsValid) return HookResult.Continue; - logs.AddLogMessage( - $"{logs.FormatPlayer(pawn.OriginalController.Value!)} pressed a button {ent.Entity?.Name ?? "Unlabeled"} -> {output?.Connections?.TargetDesc ?? "None"}"); + _logs.AddLogMessage( + $"{_logs.FormatPlayer(pawn.OriginalController.Value!)} pressed a button {ent.Entity?.Name ?? "Unlabeled"} -> {output.Connections?.TargetDesc ?? "None"}"); return HookResult.Continue; } @@ -48,7 +48,7 @@ private HookResult OnGrenadeThrown(EventGrenadeThrown @event, GameEventInfo info return HookResult.Continue; var grenade = @event.Weapon; - logs.AddLogMessage($"{logs.FormatPlayer(player)} threw a {grenade}"); + _logs.AddLogMessage($"{_logs.FormatPlayer(player)} threw a {grenade}"); return HookResult.Continue; } @@ -60,31 +60,23 @@ private HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) return HookResult.Continue; var attacker = @event.Attacker; - bool isWorld = attacker == null || !attacker.IsReal(); - int health = @event.DmgHealth; + var isWorld = attacker == null || !attacker.IsReal(); + var health = @event.DmgHealth; if (isWorld) { if (health > 0) - { - logs.AddLogMessage($"The world hurt {logs.FormatPlayer(player)} for {health} damage"); - } + _logs.AddLogMessage($"The world hurt {_logs.FormatPlayer(player)} for {health} damage"); else - { - logs.AddLogMessage($"The world killed {logs.FormatPlayer(player)}"); - } + _logs.AddLogMessage($"The world killed {_logs.FormatPlayer(player)}"); } else { if (health > 0) - { - logs.AddLogMessage( - $"{logs.FormatPlayer(attacker!)} hurt {logs.FormatPlayer(player)} for {health} damage"); - } + _logs.AddLogMessage( + $"{_logs.FormatPlayer(attacker!)} hurt {_logs.FormatPlayer(player)} for {health} damage"); else - { - logs.AddLogMessage($"{logs.FormatPlayer(attacker!)} killed {logs.FormatPlayer(player)}"); - } + _logs.AddLogMessage($"{_logs.FormatPlayer(attacker!)} killed {_logs.FormatPlayer(player)}"); } return HookResult.Continue; diff --git a/mod/Jailbreak.Logs/LogsManager.cs b/mod/Jailbreak.Logs/LogsManager.cs index 382b005d..d2406a96 100644 --- a/mod/Jailbreak.Logs/LogsManager.cs +++ b/mod/Jailbreak.Logs/LogsManager.cs @@ -13,51 +13,21 @@ namespace Jailbreak.Logs; public class LogsManager : IPluginBehavior, ILogService { private readonly List _logMessages = new(); - private long startTime; - private IWardenService wardenService; - private IRebelService rebelService; - private IServiceProvider _serviceProvider; + private readonly IServiceProvider _serviceProvider; + private IRebelService? _rebelService; + private long _startTime; + private IWardenService? _wardenService; public LogsManager(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } - public void Start(BasePlugin parent) - { - parent.RegisterEventHandler(OnRoundStart); - parent.RegisterEventHandler(OnRoundEnd); - wardenService = _serviceProvider.GetRequiredService(); - rebelService = _serviceProvider.GetRequiredService(); - } - - private HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - foreach (var player in Utilities.GetPlayers()) - { - if(!player.IsReal()) - continue; - foreach (var log in _logMessages) - { - player.PrintToConsole(log); - } - } - - return HookResult.Continue; - } - - private HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - startTime = DateTimeOffset.Now.ToUnixTimeSeconds(); - ClearLogMessages(); - return HookResult.Continue; - } - public void AddLogMessage(string message) { // format to [MM:SS] message - string prefix = $"[{TimeSpan.FromSeconds(DateTimeOffset.Now.ToUnixTimeSeconds() - startTime):mm\\:ss}] "; + var prefix = $"[{TimeSpan.FromSeconds(DateTimeOffset.Now.ToUnixTimeSeconds() - _startTime):mm\\:ss}] "; _logMessages.Add(prefix + message); } @@ -73,11 +43,13 @@ public void ClearLogMessages() public string FormatPlayer(CCSPlayerController player) { - if (wardenService.IsWarden(player)) + if(_rebelService == null || _wardenService == null) + throw new InvalidOperationException("Services not initialized"); + if (_wardenService.IsWarden(player)) return $"{player.PlayerName} (WARDEN)"; if (player.GetTeam() == CsTeam.CounterTerrorist) return $"{player.PlayerName} (CT)"; - if (rebelService.IsRebel(player)) + if (_rebelService.IsRebel(player)) return $"{player.PlayerName} (REBEL)"; return $"{player.PlayerName} (Prisoner)"; } @@ -86,16 +58,38 @@ public string FormatPlayer(CCSPlayerController player) public void PrintLogs(CCSPlayerController? player) { if (player == null) + PrintLogs(Server.PrintToConsole); + else if (player.IsReal()) PrintLogs(player.PrintToConsole); + } + + public void Start(BasePlugin parent) + { + parent.RegisterEventHandler(OnRoundStart); + parent.RegisterEventHandler(OnRoundEnd); + _wardenService = _serviceProvider.GetRequiredService(); + _rebelService = _serviceProvider.GetRequiredService(); + } + + private HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) + { + foreach (var player in Utilities.GetPlayers()) { - printLogs(Server.PrintToConsole); - } - else if (player.IsReal()) - { - printLogs(player.PrintToConsole); + if (!player.IsReal()) + continue; + foreach (var log in _logMessages) player.PrintToConsole(log); } + + return HookResult.Continue; } - private void printLogs(Delegate printFunction) + private HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) + { + _startTime = DateTimeOffset.Now.ToUnixTimeSeconds(); + ClearLogMessages(); + return HookResult.Continue; + } + + private void PrintLogs(Delegate printFunction) { if (!GetLogMessages().Any()) { @@ -106,10 +100,7 @@ private void printLogs(Delegate printFunction) printFunction.DynamicInvoke("********************************"); printFunction.DynamicInvoke("***** BEGIN JAILBREAK LOGS *****"); printFunction.DynamicInvoke("********************************"); - foreach (string log in GetLogMessages()) - { - printFunction.DynamicInvoke(log); - } + foreach (var log in GetLogMessages()) printFunction.DynamicInvoke(log); printFunction.DynamicInvoke("********************************"); printFunction.DynamicInvoke("****** END JAILBREAK LOGS ******"); diff --git a/mod/Jailbreak.Logs/LogsServiceExtension.cs b/mod/Jailbreak.Logs/LogsServiceExtension.cs index 4c626273..3f05d495 100644 --- a/mod/Jailbreak.Logs/LogsServiceExtension.cs +++ b/mod/Jailbreak.Logs/LogsServiceExtension.cs @@ -6,11 +6,11 @@ namespace Jailbreak.Logs; public static class LogsServiceExtension { - public static void AddJailbreakLogs(this IServiceCollection services) - { - services.AddPluginBehavior(); - - services.AddPluginBehavior(); - services.AddPluginBehavior(); - } + public static void AddJailbreakLogs(this IServiceCollection services) + { + services.AddPluginBehavior(); + + services.AddPluginBehavior(); + services.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj b/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj index 128ff34e..edb468c5 100644 --- a/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj +++ b/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj @@ -7,8 +7,8 @@ - - + + - + diff --git a/mod/Jailbreak.Rebel/RebelListener.cs b/mod/Jailbreak.Rebel/RebelListener.cs index d5a955d0..da14056c 100644 --- a/mod/Jailbreak.Rebel/RebelListener.cs +++ b/mod/Jailbreak.Rebel/RebelListener.cs @@ -4,23 +4,23 @@ using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Rebel; -namespace Jailbreak.Teams; +namespace Jailbreak.Rebel; public class RebelListener : IPluginBehavior { - private IRebelService _rebelService; - + private readonly IRebelService _rebelService; + public RebelListener(IRebelService rebelService) { _rebelService = rebelService; } - + public void Start(BasePlugin parent) { parent.RegisterEventHandler(OnPlayerHurt); } - HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) + private HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) { var player = @event.Userid; if (!player.IsReal()) @@ -35,7 +35,7 @@ HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) if (attacker.GetTeam() != CsTeam.Terrorist) return HookResult.Continue; - _rebelService.MarkRebel(attacker, 120); + _rebelService.MarkRebel(attacker); return HookResult.Continue; } } \ No newline at end of file diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index 61d6203d..6e8afc38 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -1,7 +1,6 @@ using System.Drawing; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Timers; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; @@ -10,18 +9,18 @@ using Jailbreak.Public.Mod.Logs; using Jailbreak.Public.Mod.Rebel; -namespace Jailbreak.Teams; +namespace Jailbreak.Rebel; public class RebelManager : IPluginBehavior, IRebelService { - private Dictionary rebelTimes = new(); - private IRebelNotifications notifs; - private ILogService logs; + private readonly ILogService _logs; + private readonly IRebelNotifications _notifs; + private readonly Dictionary _rebelTimes = new(); public RebelManager(IRebelNotifications notifs, ILogService logs) { - this.notifs = notifs; - this.logs = logs; + _notifs = notifs; + _logs = logs; } public void Start(BasePlugin parent) @@ -50,6 +49,36 @@ public void Start(BasePlugin parent) }, TimerFlags.REPEAT); } + public ISet GetActiveRebels() + { + return _rebelTimes.Keys.ToHashSet(); + } + + public long GetRebelTimeLeft(CCSPlayerController player) + { + if (_rebelTimes.TryGetValue(player, out var time)) return time - DateTimeOffset.Now.ToUnixTimeSeconds(); + + return 0; + } + + public bool MarkRebel(CCSPlayerController player, long time = 120) + { + if (!_rebelTimes.ContainsKey(player)) _logs.AddLogMessage(player.PlayerName + " is now a rebel."); + + _rebelTimes[player] = DateTimeOffset.Now.ToUnixTimeSeconds() + time; + ApplyRebelColor(player); + return true; + } + + public void UnmarkRebel(CCSPlayerController player) + { + _notifs.NoLongerRebel.ToPlayerChat(player); + _logs.AddLogMessage(player.PlayerName + " is no longer a rebel."); + + _rebelTimes.Remove(player); + ApplyRebelColor(player); + } + private void OnTick() { foreach (var player in GetActiveRebels()) @@ -57,18 +86,15 @@ private void OnTick() if (!player.IsReal()) continue; - if (GetRebelTimeLeft(player) <= 0) - { - continue; - } + if (GetRebelTimeLeft(player) <= 0) continue; SendTimeLeft(player); } } - HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) + private HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { - rebelTimes.Clear(); + _rebelTimes.Clear(); foreach (var player in Utilities.GetPlayers()) { if (!player.IsReal()) @@ -79,81 +105,39 @@ HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) return HookResult.Continue; } - HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) + private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) { - if (rebelTimes.ContainsKey(@event.Userid)) - { - rebelTimes.Remove(@event.Userid); - } + if (_rebelTimes.ContainsKey(@event.Userid)) _rebelTimes.Remove(@event.Userid); return HookResult.Continue; } - HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) + private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { var player = @event.Userid; if (!player.IsReal()) return HookResult.Continue; - rebelTimes.Remove(player); + _rebelTimes.Remove(player); return HookResult.Continue; } - public ISet GetActiveRebels() - { - return rebelTimes.Keys.ToHashSet(); - } - - public long GetRebelTimeLeft(CCSPlayerController player) - { - if (rebelTimes.TryGetValue(player, out long time)) - { - return time - DateTimeOffset.Now.ToUnixTimeSeconds(); - } - - return 0; - } - - public bool MarkRebel(CCSPlayerController player, long time = 120) - { - if (!rebelTimes.ContainsKey(player)) - { - logs.AddLogMessage(player.PlayerName + " is now a rebel."); - } - - rebelTimes[player] = DateTimeOffset.Now.ToUnixTimeSeconds() + time; - ApplyRebelColor(player); - return true; - } - - public void UnmarkRebel(CCSPlayerController player) - { - notifs.NO_LONGER_REBEL.ToPlayerChat(player); - logs.AddLogMessage(player.PlayerName + " is no longer a rebel."); - - rebelTimes.Remove(player); - ApplyRebelColor(player); - } - // https://www.desmos.com/calculator/g2v6vvg7ax private float GetRebelTimePercentage(CCSPlayerController player) { - long x = GetRebelTimeLeft(player); + var x = GetRebelTimeLeft(player); if (x > 120) return 1; if (x <= 0) return 0; - return (float)(100 - (120 - x) * (Math.Sqrt(120 - x)) / 13f) / 100; + return (float)(100 - (120 - x) * Math.Sqrt(120 - x) / 13f) / 100; } private Color GetRebelColor(CCSPlayerController player) { var percent = GetRebelTimePercentage(player); - var percentRGB = 255 - (int)Math.Round(percent * 255.0); - var color = Color.FromArgb(254, 255, percentRGB, percentRGB); - if (percent <= 0) - { - color = Color.FromArgb(254, 255, 255, 255); - } + var percentRgb = 255 - (int)Math.Round(percent * 255.0); + var color = Color.FromArgb(254, 255, percentRgb, percentRgb); + if (percent <= 0) color = Color.FromArgb(254, 255, 255, 255); return color; } @@ -171,8 +155,8 @@ private void ApplyRebelColor(CCSPlayerController player) private void SendTimeLeft(CCSPlayerController player) { - var timeLeft = GetRebelTimeLeft(player); - var formattedTime = TimeSpan.FromSeconds(timeLeft).ToString(@"mm\:ss"); + // var timeLeft = GetRebelTimeLeft(player); + // var formattedTime = TimeSpan.FromSeconds(timeLeft).ToString(@"mm\:ss"); var color = GetRebelColor(player); var formattedColor = $""; diff --git a/mod/Jailbreak.Rebel/RebelServiceExtension.cs b/mod/Jailbreak.Rebel/RebelServiceExtension.cs index 835a7e41..c5424e50 100644 --- a/mod/Jailbreak.Rebel/RebelServiceExtension.cs +++ b/mod/Jailbreak.Rebel/RebelServiceExtension.cs @@ -1,16 +1,14 @@ using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Rebel; -using Jailbreak.Public.Mod.Teams; -using Jailbreak.Teams; using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Rebel; public static class RebelServiceExtension { - public static void AddJailbreakRebel(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } -} + public static void AddJailbreakRebel(this IServiceCollection collection) + { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Teams/Jailbreak.Teams.csproj b/mod/Jailbreak.Teams/Jailbreak.Teams.csproj index 7f2b8a0c..7997b564 100644 --- a/mod/Jailbreak.Teams/Jailbreak.Teams.csproj +++ b/mod/Jailbreak.Teams/Jailbreak.Teams.csproj @@ -7,8 +7,8 @@ - - + + - + diff --git a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs index e9c42416..64762765 100644 --- a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs +++ b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs @@ -3,255 +3,251 @@ using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; using Jailbreak.Public.Behaviors; -using Jailbreak.Formatting.Extensions; -using Jailbreak.Formatting.Views; using Jailbreak.Public.Extensions; using Jailbreak.Public.Generic; using Jailbreak.Public.Mod.Teams; - using Microsoft.Extensions.Logging; -using Microsoft.VisualBasic.CompilerServices; - -using Serilog; namespace Jailbreak.Teams.Queue; public class QueueBehavior : IGuardQueue, IPluginBehavior { - private int _counter; - private IPlayerState _state; - private ILogger _logger; - - private IRatioNotifications _notifications; - + private int _counter; + private readonly ILogger _logger; - public QueueBehavior(IPlayerStateFactory factory, IRatioNotifications notifications, ILogger logger) - { - _logger = logger; - _notifications = notifications; - _counter = 0; - _state = factory.Global(); - } + private readonly IRatioNotifications _notifications; + private readonly IPlayerState _state; - public void Start(BasePlugin parent) - { - // Listen for the player requesting to join a team. - // Thanks, destoer! - parent.AddCommandListener("jointeam", OnRequestToJoinTeam); - } - - public bool TryEnterQueue(CCSPlayerController player) - { - if (!player.IsReal()) - return false; - - if (player.GetTeam() == CsTeam.CounterTerrorist) - return false; - - var state = _state.Get(player); - state.Position = ++_counter; - state.InQueue = true; - state.IsGuard = false; - - return true; - } - - public bool TryExitQueue(CCSPlayerController player) - { - if (!player.IsReal()) - return false; - - var state = _state.Get(player); - state.InQueue = false; - state.IsGuard = false; - - return true; - } - - public bool TryPop(int count) - { - var queue = Queue - .Where(player => player.IsReal()) - .ToList(); - - if (queue.Count <= count) - { - _notifications.NOT_ENOUGH_GUARDS.ToAllChat(); - _notifications.PLEASE_JOIN_GUARD_QUEUE.ToAllChat().ToAllCenter(); - } - - _logger.LogInformation("[Queue] Pop requested {@Count} out of {@InQueue}", count, queue.Count); - - for (int i = 0; i < Math.Min(queue.Count, count); i++) - { - _logger.LogInformation("[Queue] Popping player {@Name}", queue[i].PlayerName); - - ForceGuard( queue[i] ); - } - - return true; - } - - public bool TryPush(int count) - { - var players = Utilities.GetPlayers() - .Where(player => player.IsReal()) - .Where(player => player.GetTeam() == CsTeam.CounterTerrorist) - .Shuffle(Random.Shared) - .ToList(); - - _logger.LogInformation("[Queue] Push requested {@Count} out of {@GuardCount}", count, players.Count); - - for (int i = 0; i < Math.Min(count, players.Count); i++) - { - var toSwap = players[i]; - _logger.LogInformation("[Queue] Pushing {@Name}", toSwap.PlayerName); - var state = _state.Get(toSwap); - - state.IsGuard = false; - toSwap.ChangeTeam(CsTeam.Terrorist); - toSwap.Respawn(); - - TryEnterQueue(toSwap); - - _notifications.YOU_WERE_AUTOBALANCED_PRISONER.ToPlayerCenter(toSwap); - } - - return true; - } - - public void ForceGuard(CCSPlayerController player) - { - // Set IsGuard so they won't be swapped back. - _state.Get(player).IsGuard = true; - - _notifications.YOU_WERE_AUTOBALANCED_GUARD - .ToPlayerChat(player) - .ToPlayerCenter(player); - - player.ChangeTeam(CsTeam.CounterTerrorist); - player.Respawn(); - } - - /// - /// Block players from joining the CT team using the "m" menu. - /// - /// - /// - /// - public HookResult OnRequestToJoinTeam(CCSPlayerController? invoked, CommandInfo command) - { - if(invoked == null || !invoked.IsReal()) - return HookResult.Continue; - - var state = _state.Get(invoked); - - // Invalid command? Stop here to be safe. - if (command.ArgCount < 2) - return HookResult.Stop; - - if (!int.TryParse(command.ArgByIndex(1), out int team)) - return HookResult.Stop; - - if (Utilities.GetPlayers().Find(c => c.GetTeam() == CsTeam.CounterTerrorist) == null) - return HookResult.Continue; // If no CTs, let anyone on CT team - - // Player is attempting to join CT and is not a guard? - // If so, stop them!! - if ((CsTeam)team == CsTeam.CounterTerrorist && !state.IsGuard) - { - _notifications.ATTEMPT_TO_JOIN_FROM_TEAM_MENU - .ToPlayerChat(invoked) - .ToPlayerCenter(invoked); - - return HookResult.Stop; - } - // All else: A-OK. - return HookResult.Continue; - } - - /// - /// Remove guards from the team if they are not a guard in the queue state - /// - /// - /// - /// - [GameEventHandler] - public HookResult OnPlayerSpawn(EventPlayerSpawn ev, GameEventInfo info) - { - var player = ev.Userid; - if (!player.IsReal()) - return HookResult.Continue; - - var state = _state.Get(ev.Userid); - - if (player.GetTeam() == CsTeam.CounterTerrorist && !state.IsGuard) - { - _notifications.ATTEMPT_TO_JOIN_FROM_TEAM_MENU - .ToPlayerChat(player) - .ToPlayerCenter(player); - - player.ChangeTeam(CsTeam.Terrorist); - player.Respawn(); - } - - return HookResult.Continue; - } - - /// - /// Remove guard state if they switch to the terrorist team. - /// - /// - /// - /// - [GameEventHandler] - public HookResult OnPlayerTeam(EventPlayerTeam ev, GameEventInfo info) - { - var state = _state.Get(ev.Userid); - var player = ev.Userid; - - if ((CsTeam)ev.Team != CsTeam.CounterTerrorist && state.IsGuard) - { - if (this.TryExitQueue(player)) - _notifications.LEFT_GUARD - .ToPlayerCenter(player) - .ToPlayerChat(player); - } - - return HookResult.Continue; - } - private void HandleQueueRequest(CCSPlayerController player) + public QueueBehavior(IPlayerStateFactory factory, IRatioNotifications notifications, ILogger logger) + { + _logger = logger; + _notifications = notifications; + _counter = 0; + _state = factory.Global(); + } + + public bool TryEnterQueue(CCSPlayerController player) + { + if (!player.IsReal()) + return false; + + if (player.GetTeam() == CsTeam.CounterTerrorist) + return false; + + var state = _state.Get(player); + state.Position = ++_counter; + state.InQueue = true; + state.IsGuard = false; + + return true; + } + + public bool TryExitQueue(CCSPlayerController player) + { + if (!player.IsReal()) + return false; + + var state = _state.Get(player); + state.InQueue = false; + state.IsGuard = false; + + return true; + } + + public bool TryPop(int count) + { + var queue = Queue.Where(p=>p.IsReal()).ToList(); + + if (queue.Count <= count) + { + _notifications.NotEnoughGuards.ToAllChat(); + _notifications.PleaseJoinGuardQueue.ToAllChat().ToAllCenter(); + } + + _logger.LogInformation("[Queue] Pop requested {@Count} out of {@InQueue}", count, queue.Count); + + for (var i = 0; i < Math.Min(queue.Count, count); i++) + { + _logger.LogInformation("[Queue] Popping player {@Name}", queue[i].PlayerName); + + ForceGuard(queue[i]); + } + + return true; + } + + public bool TryPush(int count) + { + var players = Utilities.GetPlayers() + .Where(p => p.IsReal() && p.GetTeam() == CsTeam.CounterTerrorist) + .Shuffle(Random.Shared) + .ToList(); + _logger.LogInformation("[Queue] Push requested {@Count} out of {@GuardCount}", count, players.Count); + + for (var i = 0; i < Math.Min(count, players.Count); i++) + { + var toSwap = players[i]; + _logger.LogInformation("[Queue] Pushing {@Name}", toSwap.PlayerName); + var state = _state.Get(toSwap); + + state.IsGuard = false; + toSwap.ChangeTeam(CsTeam.Terrorist); + toSwap.Respawn(); + + TryEnterQueue(toSwap); + + _notifications.YouWereAutobalancedPrisoner.ToPlayerCenter(toSwap); + } + + return true; + } + + public void ForceGuard(CCSPlayerController player) { - if (TryEnterQueue(player)) - _notifications.JOINED_GUARD_QUEUE - .ToPlayerCenter(player) - .ToPlayerChat(player); - else - player.PrintToCenter("An error occured adding you to the queue."); + // Set IsGuard so they won't be swapped back. + _state.Get(player).IsGuard = true; + + _notifications.YouWereAutobalancedGuard + .ToPlayerChat(player) + .ToPlayerCenter(player); + player.ChangeTeam(CsTeam.CounterTerrorist); + player.Respawn(); + } + + public int GetQueuePosition(CCSPlayerController player) + { + return Queue.ToList() + .FindIndex(controller => controller.Slot == player.Slot); + } + + + public IEnumerable Queue + => Utilities.GetPlayers() + .Select(player => (Player: player, State: _state.Get(player))) + .Where(tuple => tuple.State.InQueue) // Exclude not in queue + .Where(tuple => !tuple.State.IsGuard) // Exclude current guards + .OrderBy(tuple => tuple.State.Position) // Order by counter value when joined queue + .Select(tuple => tuple.Player); + + public void Start(BasePlugin parent) + { + // Listen for the player requesting to join a team. + // Thanks, destoer! + parent.AddCommandListener("jointeam", OnRequestToJoinTeam); + } + + /// + /// Block players from joining the CT team using the "m" menu. + /// + /// + /// + /// + public HookResult OnRequestToJoinTeam(CCSPlayerController? invoked, CommandInfo command) + { + if (invoked == null || !invoked.IsReal()) + return HookResult.Continue; + + var state = _state.Get(invoked); + + // Invalid command? Stop here to be safe. + if (command.ArgCount < 2) + return HookResult.Stop; + + if (!int.TryParse(command.ArgByIndex(1), out var team)) + return HookResult.Stop; + + if (Utilities.GetPlayers().Find(c => c.GetTeam() == CsTeam.CounterTerrorist) == null) + return HookResult.Continue; // If no CTs, let anyone on CT team + + // Player is attempting to join CT and is not a guard? + // If so, stop them!! + if ((CsTeam)team == CsTeam.CounterTerrorist && !state.IsGuard) + { + _notifications.AttemptToJoinFromTeamMenu + .ToPlayerChat(invoked) + .ToPlayerCenter(invoked); + + return HookResult.Stop; + } + + // All else: A-OK. + return HookResult.Continue; + } + + /// + /// Remove guards from the team if they are not a guard in the queue state + /// + /// + /// + /// + [GameEventHandler] + public HookResult OnPlayerSpawn(EventPlayerSpawn ev, GameEventInfo info) + { + var player = ev.Userid; + if (!player.IsReal()) + return HookResult.Continue; + + var state = _state.Get(ev.Userid); + + if (player.GetTeam() == CsTeam.CounterTerrorist && !state.IsGuard) + { + _notifications.AttemptToJoinFromTeamMenu + .ToPlayerChat(player) + .ToPlayerCenter(player); + + player.ChangeTeam(CsTeam.Terrorist); + player.Respawn(); + } + + return HookResult.Continue; + } + + /// + /// Remove guard state if they switch to the terrorist team. + /// + /// + /// + /// + [GameEventHandler] + public HookResult OnPlayerTeam(EventPlayerTeam ev, GameEventInfo info) + { + var state = _state.Get(ev.Userid); + var player = ev.Userid; + + if ((CsTeam)ev.Team != CsTeam.CounterTerrorist && state.IsGuard) + if (TryExitQueue(player)) + _notifications.LeftGuard + .ToPlayerCenter(player) + .ToPlayerChat(player); + + return HookResult.Continue; + } + + private void HandleQueueRequest(CCSPlayerController player) + { + if (TryEnterQueue(player)) + _notifications.JoinedGuardQueue + .ToPlayerCenter(player) + .ToPlayerChat(player); + else + player.PrintToCenter("An error occured adding you to the queue."); } private void HandleLeaveRequest(CCSPlayerController player) { if (TryExitQueue(player)) - _notifications.LEFT_GUARD - .ToPlayerCenter(player) - .ToPlayerChat(player); + _notifications.LeftGuard + .ToPlayerCenter(player) + .ToPlayerChat(player); else player.PrintToCenter("An error occured removing you from the queue."); } - public int GetQueuePosition(CCSPlayerController player) - { - return Queue.ToList() - .FindIndex(controller => controller.Slot == player.Slot); - } - [ConsoleCommand("css_guard", "Joins the guard queue")] [ConsoleCommand("css_g", "Joins the guard queue")] [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] @@ -270,13 +266,4 @@ public void Command_Leave(CCSPlayerController? player, CommandInfo command) return; HandleLeaveRequest(player); } - - - public IEnumerable Queue - => Utilities.GetPlayers() - .Select(player => (Player: player, State: _state.Get(player))) - .Where(tuple => tuple.State.InQueue) // Exclude not in queue - .Where(tuple => !tuple.State.IsGuard) // Exclude current guards - .OrderBy(tuple => tuple.State.Position) // Order by counter value when joined queue - .Select(tuple => tuple.Player); -} +} \ No newline at end of file diff --git a/mod/Jailbreak.Teams/Queue/QueueState.cs b/mod/Jailbreak.Teams/Queue/QueueState.cs index 006087ea..71f76235 100644 --- a/mod/Jailbreak.Teams/Queue/QueueState.cs +++ b/mod/Jailbreak.Teams/Queue/QueueState.cs @@ -2,25 +2,20 @@ public class QueueState { - - public QueueState() - { - } - /// - /// The counter value when the player entered the queue - /// Lower = join CT sooner + /// The counter value when the player entered the queue + /// Lower = join CT sooner /// public int Position { get; set; } /// - /// True when this player is currently in the queue + /// True when this player is currently in the queue /// public bool InQueue { get; set; } /// - /// This player is allowed to be on the CT team. - /// If this is false, they will be swapped back to prisoner. + /// This player is allowed to be on the CT team. + /// If this is false, they will be swapped back to prisoner. /// public bool IsGuard { get; set; } -} +} \ No newline at end of file diff --git a/mod/Jailbreak.Teams/Ratio/RatioBehavior.cs b/mod/Jailbreak.Teams/Ratio/RatioBehavior.cs index 1d399f79..657e9ab1 100644 --- a/mod/Jailbreak.Teams/Ratio/RatioBehavior.cs +++ b/mod/Jailbreak.Teams/Ratio/RatioBehavior.cs @@ -1,120 +1,116 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Cvars; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Teams; using Jailbreak.Public.Utils; - using Microsoft.Extensions.Logging; -using Serilog; - namespace Jailbreak.Teams.Ratio; public class RatioBehavior : IPluginBehavior { - private IGuardQueue _guardQueue; - private ILogger _logger; - - public enum RatioActionType - { - Add, - Remove, - None, - } - - public struct RatioAction - { - public RatioActionType Type { get; init; } - public int Count { get; init; } - - public RatioAction(int count = 0, RatioActionType type = RatioActionType.None) - { - Count = count; - Type = type; - } - } - - private RatioConfig _config; - - public RatioBehavior(RatioConfig config, IGuardQueue guardQueue, ILogger logger) - { - _config = config; - _guardQueue = guardQueue; - _logger = logger; - } - - /// - /// Evaluate whether the provided CT/T ratio needs - /// - /// - /// - /// - public RatioAction Evaluate(int ct, int t) - { - // No divide by zero errors today... - // Make value 0.01 so the decision will always be to add Ts - // 1 / 0.01 = 100, etc... - var normalized_ct = (ct == 0 ? 0.01 : (double)ct); - double ts_per_ct = t / (double)normalized_ct; - int target = (int)( (ct + t) / _config.Target ) + 1; - - _logger.LogTrace("[Ratio] Evaluating ratio of {@Ct}ct to {@T}t: {@TsPerCt}t/ct ratio, {@Target} target.", ct ,t ,ts_per_ct, target); - - if (_config.Maximum <= ts_per_ct) - { - // There are too many Ts per CT! - // Get more guards on the team - _logger.LogTrace("[Ratio] Decision: Not enough CTs: {@Maximum} <= {@TsPerCt}", _config.Maximum, ts_per_ct); - return new(target - ct, RatioActionType.Add); - } - - if (ts_per_ct <= _config.Minimum) - { - // There are too many guards per T! - _logger.LogTrace("[Ratio] Decision: Too many CTs: {@TsPerCt} <= {@Minimum}", ts_per_ct, _config.Minimum); - return new(ct - target, RatioActionType.Remove); - } - - _logger.LogTrace("[Ratio] Decision: Goldilocks: {@Maximum} (max) <= {@TsPerCt} (t/ct) <= {@Minimum} (min)", _config.Maximum, ts_per_ct, _config.Minimum); - // Take no action - return new(); - } - - /// - /// When a round starts, balance out the teams - /// - [GameEventHandler(HookMode.Pre)] - public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) - { - var counterTerrorists = Utilities.GetPlayers().Count(player => player.GetTeam() == CsTeam.CounterTerrorist); - var terrorists = Utilities.GetPlayers().Count(player => player.GetTeam() == CsTeam.Terrorist); - - var action = Evaluate(counterTerrorists, terrorists); - - // Prevent the round from ending while we make ratio adjustments - using (var _ = new TemporaryConvar("mp_ignore_round_win_conditions", true)) - { - var success = action.Type switch - { - RatioActionType.Add => _guardQueue.TryPop(action.Count), - RatioActionType.Remove => _guardQueue.TryPush(action.Count), - _ => true - }; - - if (!success) - Server.PrintToChatAll($"[BUG] Ratio enforcement failed :^( [RatioAction: {action.Type} @ {action.Count}]"); - } - - return HookResult.Continue; - } - - public void Dispose() - { - - } -} + public enum RatioActionType + { + Add, + Remove, + None + } + + private readonly RatioConfig _config; + private readonly IGuardQueue _guardQueue; + private readonly ILogger _logger; + + public RatioBehavior(RatioConfig config, IGuardQueue guardQueue, ILogger logger) + { + _config = config; + _guardQueue = guardQueue; + _logger = logger; + } + + public void Dispose() + { + } + + /// + /// Evaluate whether the provided CT/T ratio needs + /// + /// + /// + /// + public RatioAction Evaluate(int ct, int t) + { + // No divide by zero errors today... + // Make value 0.01 so the decision will always be to add Ts + // 1 / 0.01 = 100, etc... + var normalizedCt = ct == 0 ? 0.01 : ct; + var tsPerCt = t / normalizedCt; + var target = (int)((ct + t) / _config.Target) + 1; + + _logger.LogTrace("[Ratio] Evaluating ratio of {@Ct}ct to {@T}t: {@TsPerCt}t/ct ratio, {@Target} target.", ct, t, + tsPerCt, target); + + if (_config.Maximum <= tsPerCt) + { + // There are too many Ts per CT! + // Get more guards on the team + _logger.LogTrace("[Ratio] Decision: Not enough CTs: {@Maximum} <= {@TsPerCt}", _config.Maximum, tsPerCt); + return new RatioAction(target - ct, RatioActionType.Add); + } + + if (tsPerCt <= _config.Minimum) + { + // There are too many guards per T! + _logger.LogTrace("[Ratio] Decision: Too many CTs: {@TsPerCt} <= {@Minimum}", tsPerCt, _config.Minimum); + return new RatioAction(ct - target, RatioActionType.Remove); + } + + _logger.LogTrace("[Ratio] Decision: Goldilocks: {@Maximum} (max) <= {@TsPerCt} (t/ct) <= {@Minimum} (min)", + _config.Maximum, tsPerCt, _config.Minimum); + // Take no action + return new RatioAction(); + } + + /// + /// When a round starts, balance out the teams + /// + [GameEventHandler(HookMode.Pre)] + public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) + { + var counterTerrorists = Utilities.GetPlayers().Count(player => player.GetTeam() == CsTeam.CounterTerrorist); + var terrorists = Utilities.GetPlayers().Count(player => player.GetTeam() == CsTeam.Terrorist); + + var action = Evaluate(counterTerrorists, terrorists); + + // Prevent the round from ending while we make ratio adjustments + using (var _ = new TemporaryConvar("mp_ignore_round_win_conditions", true)) + { + var success = action.Type switch + { + RatioActionType.Add => _guardQueue.TryPop(action.Count), + RatioActionType.Remove => _guardQueue.TryPush(action.Count), + _ => true + }; + + if (!success) + Server.PrintToChatAll( + $"[BUG] Ratio enforcement failed :^( [RatioAction: {action.Type} @ {action.Count}]"); + } + + return HookResult.Continue; + } + + public struct RatioAction + { + public RatioActionType Type { get; init; } + public int Count { get; init; } + + public RatioAction(int count = 0, RatioActionType type = RatioActionType.None) + { + Count = count; + Type = type; + } + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Teams/Ratio/RatioConfig.cs b/mod/Jailbreak.Teams/Ratio/RatioConfig.cs index 23c01dbe..6bd6f942 100644 --- a/mod/Jailbreak.Teams/Ratio/RatioConfig.cs +++ b/mod/Jailbreak.Teams/Ratio/RatioConfig.cs @@ -3,20 +3,20 @@ public class RatioConfig { /// - /// The minimum amount of Ts per every CT. - /// When this is passed, CTs will be added until Target is reached. + /// The minimum amount of Ts per every CT. + /// When this is passed, CTs will be added until Target is reached. /// public double Minimum { get; set; } = 2.5; /// - /// The maximum amount of Ts per every CT. - /// When this is passed, CTs will be removed until Target is reached. + /// The maximum amount of Ts per every CT. + /// When this is passed, CTs will be removed until Target is reached. /// public double Maximum { get; set; } = 4; /// - /// When the ratio is autobalanced, the amount of guards - /// should be total_players / target. + /// When the ratio is autobalanced, the amount of guards + /// should be total_players / target. /// public double Target { get; set; } = 4; -} +} \ No newline at end of file diff --git a/mod/Jailbreak.Teams/TeamsServiceExtension.cs b/mod/Jailbreak.Teams/TeamsServiceExtension.cs index bbc83303..21fbab08 100644 --- a/mod/Jailbreak.Teams/TeamsServiceExtension.cs +++ b/mod/Jailbreak.Teams/TeamsServiceExtension.cs @@ -2,18 +2,17 @@ using Jailbreak.Public.Mod.Teams; using Jailbreak.Teams.Queue; using Jailbreak.Teams.Ratio; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Teams; public static class TeamsServiceExtension { - public static void AddJailbreakTeams(this IServiceCollection collection) - { - collection.AddConfig("ratio"); + public static void AddJailbreakTeams(this IServiceCollection collection) + { + collection.AddConfig("ratio"); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } -} + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs index 4d82827c..690df9f5 100644 --- a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs @@ -3,7 +3,6 @@ using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; using Jailbreak.Public.Behaviors; @@ -14,76 +13,77 @@ namespace Jailbreak.Warden.Commands; public class WardenCommandsBehavior : IPluginBehavior { - private IWardenSelectionService _queue; - private IWardenService _warden; - private IWardenNotifications _notifications; - - public WardenCommandsBehavior(IWardenSelectionService queue, IWardenService warden, IWardenNotifications notifications) - { - _queue = queue; - _warden = warden; - _notifications = notifications; - } - - - [ConsoleCommand("css_pass", "Pass warden onto another player")] - [ConsoleCommand("css_uw", "Pass warden onto another player")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Pass(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - - var isCt = player.GetTeam() == CsTeam.CounterTerrorist; - - if (_warden.IsWarden(player)) - { - // Handle warden pass - _notifications.PASS_WARDEN(player) - .ToAllChat() - .ToAllCenter(); - - _notifications.BECOME_NEXT_WARDEN.ToAllChat(); - - if (!_warden.TryRemoveWarden()) - Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); - } - } - - [ConsoleCommand("css_warden", "Become a warden, Join the warden queue, or see information about the current warden.")] - [ConsoleCommand("css_w", "Become a warden, Join the warden queue, or see information about the current warden.")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Warden(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - - var isCt = player.GetTeam() == CsTeam.CounterTerrorist; - - // Is a CT and queue is open - if (isCt && _queue.Active) - { - if (!_queue.InQueue(player)) { - if (_queue.TryEnter(player)) - _notifications.JOIN_RAFFLE.ToPlayerChat(player); - return; - } - - if (_queue.InQueue(player)) - if (_queue.TryExit(player)) - _notifications.LEAVE_RAFFLE.ToPlayerChat(player); - - return; - } - - // Is a CT and there is no warden - if (isCt && !_warden.HasWarden) - _warden.TrySetWarden(player); - - _notifications.CURRENT_WARDEN(_warden.Warden).ToPlayerChat(player); - } - - public void Dispose() - { - } -} + private readonly IWardenNotifications _notifications; + private readonly IWardenSelectionService _queue; + private readonly IWardenService _warden; + + public WardenCommandsBehavior(IWardenSelectionService queue, IWardenService warden, + IWardenNotifications notifications) + { + _queue = queue; + _warden = warden; + _notifications = notifications; + } + + public void Dispose() + { + } + + + [ConsoleCommand("css_pass", "Pass warden onto another player")] + [ConsoleCommand("css_uw", "Pass warden onto another player")] + [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] + public void Command_Pass(CCSPlayerController? player, CommandInfo command) + { + if (player == null) + return; + + if (_warden.IsWarden(player)) + { + // Handle warden pass + _notifications.PassWarden(player) + .ToAllChat() + .ToAllCenter(); + + _notifications.BecomeNextWarden.ToAllChat(); + + if (!_warden.TryRemoveWarden()) + Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); + } + } + + [ConsoleCommand("css_warden", + "Become a warden, Join the warden queue, or see information about the current warden.")] + [ConsoleCommand("css_w", "Become a warden, Join the warden queue, or see information about the current warden.")] + [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] + public void Command_Warden(CCSPlayerController? player, CommandInfo command) + { + if (player == null) + return; + + var isCt = player.GetTeam() == CsTeam.CounterTerrorist; + + // Is a CT and queue is open + if (isCt && _queue.Active) + { + if (!_queue.InQueue(player)) + { + if (_queue.TryEnter(player)) + _notifications.JoinRaffle.ToPlayerChat(player); + return; + } + + if (_queue.InQueue(player)) + if (_queue.TryExit(player)) + _notifications.LeaveRaffle.ToPlayerChat(player); + + return; + } + + // Is a CT and there is no warden + if (isCt && !_warden.HasWarden) + _warden.TrySetWarden(player); + + _notifications.CurrentWarden(_warden.Warden).ToPlayerChat(player); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs b/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs index 2e6a4e31..7a0d872d 100644 --- a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs +++ b/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs @@ -2,5 +2,4 @@ public class WardenFormatWriterExtensions { - } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Global/WardenBehavior.cs b/mod/Jailbreak.Warden/Global/WardenBehavior.cs index ad5cc0bf..a59b17af 100644 --- a/mod/Jailbreak.Warden/Global/WardenBehavior.cs +++ b/mod/Jailbreak.Warden/Global/WardenBehavior.cs @@ -1,149 +1,149 @@ using System.Drawing; -using System.Reflection; - using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Utils; - -using Jailbreak.Public.Behaviors; -using Jailbreak.Public.Extensions; -using Jailbreak.Public.Mod.Warden; -using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; +using Jailbreak.Public.Behaviors; +using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Logs; +using Jailbreak.Public.Mod.Warden; using Microsoft.Extensions.Logging; -using Serilog; - namespace Jailbreak.Warden.Global; public class WardenBehavior : IPluginBehavior, IWardenService { - private ILogger _logger; - private ILogService logs; - - private IWardenNotifications _notifications; - - private bool _hasWarden; - private CCSPlayerController? _warden; - - public WardenBehavior(ILogger logger, IWardenNotifications notifications, ILogService logs) - { - _logger = logger; - _notifications = notifications; - this.logs = logs; - } - - /// - /// Get the current warden, if there is one. - /// - public CCSPlayerController? Warden => _warden; - - /// - /// Whether or not a warden is currently assigned - /// - public bool HasWarden => _hasWarden; - - public bool TrySetWarden(CCSPlayerController controller) - { - if (_hasWarden) - return false; - - // Verify player is a CT - if (controller.GetTeam() != CsTeam.CounterTerrorist) - return false; - if (!controller.PawnIsAlive) - return false; - - _hasWarden = true; - _warden = controller; - - if (_warden.Pawn.Value != null) - { - _warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; - _warden.Pawn.Value.Render = Color.Blue; - Utilities.SetStateChanged(_warden.Pawn.Value, "CBaseModelEntity", "m_clrRender"); - } - - _notifications.NEW_WARDEN(_warden) - .ToAllChat() - .ToAllCenter(); - - logs.AddLogMessage($"{_warden.PlayerName} is now the warden."); - return true; - } - - public bool TryRemoveWarden() - { - if (!_hasWarden) - return false; - - _hasWarden = false; - - if (_warden != null && _warden.Pawn.Value != null) - { - _warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; - _warden.Pawn.Value.Render = Color.FromArgb(254, 255, 255, 255); - Utilities.SetStateChanged(_warden.Pawn.Value, "CBaseModelEntity", "m_clrRender"); - logs.AddLogMessage($"{_warden.PlayerName} is no longer the warden."); - } - - _warden = null; - - return true; - } - - [GameEventHandler] - public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) - { - if (!_hasWarden) - return HookResult.Continue; - - if (ev.Userid.UserId == _warden.UserId) - { - if (!this.TryRemoveWarden()) - _logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); - - // Warden died! - _notifications.WARDEN_DIED - .ToAllChat() - .ToAllCenter(); - - _notifications.BECOME_NEXT_WARDEN.ToAllChat(); - } - - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) - { - this.TryRemoveWarden(); - - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, GameEventInfo info) - { - if (!_hasWarden) - return HookResult.Continue; - - if (ev.Userid.UserId == _warden.UserId) - { - if (!this.TryRemoveWarden()) - _logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); - - - _notifications.WARDEN_LEFT - .ToAllChat() - .ToAllCenter(); - - _notifications.BECOME_NEXT_WARDEN.ToAllChat(); - } - - return HookResult.Continue; - } -} + private readonly ILogger _logger; + + private readonly IWardenNotifications _notifications; + private readonly ILogService _logs; + + public WardenBehavior(ILogger logger, IWardenNotifications notifications, ILogService logs) + { + _logger = logger; + _notifications = notifications; + _logs = logs; + } + + /// + /// Get the current warden, if there is one. + /// + public CCSPlayerController? Warden { get; private set; } + + /// + /// Whether or not a warden is currently assigned + /// + public bool HasWarden { get; private set; } + + public bool TrySetWarden(CCSPlayerController controller) + { + if (HasWarden) + return false; + + // Verify player is a CT + if (controller.GetTeam() != CsTeam.CounterTerrorist) + return false; + if (!controller.PawnIsAlive) + return false; + + HasWarden = true; + Warden = controller; + + if (Warden.Pawn.Value != null) + { + Warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; + Warden.Pawn.Value.Render = Color.Blue; + Utilities.SetStateChanged(Warden.Pawn.Value, "CBaseModelEntity", "m_clrRender"); + } + + _notifications.NewWarden(Warden) + .ToAllChat() + .ToAllCenter(); + + _logs.AddLogMessage($"{Warden.PlayerName} is now the warden."); + return true; + } + + public bool TryRemoveWarden() + { + if (!HasWarden) + return false; + + HasWarden = false; + + if (Warden != null && Warden.Pawn.Value != null) + { + Warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; + Warden.Pawn.Value.Render = Color.FromArgb(254, 255, 255, 255); + Utilities.SetStateChanged(Warden.Pawn.Value, "CBaseModelEntity", "m_clrRender"); + _logs.AddLogMessage($"{Warden.PlayerName} is no longer the warden."); + } + + Warden = null; + + return true; + } + + [GameEventHandler] + public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) + { + if (!HasWarden) + return HookResult.Continue; + + var player = ev.Userid; + if (!player.IsReal()) + return HookResult.Continue; + + if (!((IWardenService)this).IsWarden(player)) + return HookResult.Continue; + + if (!TryRemoveWarden()) + _logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); + + // Warden died! + _notifications.WardenDied + .ToAllChat() + .ToAllCenter(); + + _notifications.BecomeNextWarden.ToAllChat(); + + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) + { + TryRemoveWarden(); + + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, GameEventInfo info) + { + if (!HasWarden) + return HookResult.Continue; + + var player = ev.Userid; + + if (!player.IsReal()) + return HookResult.Continue; + + if (!((IWardenService)this).IsWarden(ev.Userid)) + return HookResult.Continue; + + if (!TryRemoveWarden()) + _logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); + + + _notifications.WardenLeft + .ToAllChat() + .ToAllCenter(); + + _notifications.BecomeNextWarden.ToAllChat(); + + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Jailbreak.Warden.csproj b/mod/Jailbreak.Warden/Jailbreak.Warden.csproj index e549f3ef..7997b564 100644 --- a/mod/Jailbreak.Warden/Jailbreak.Warden.csproj +++ b/mod/Jailbreak.Warden/Jailbreak.Warden.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs index c4919994..be1190f0 100644 --- a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs +++ b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs @@ -11,14 +11,14 @@ namespace Jailbreak.Warden.Markers; public class WardenMarkerBehavior : IPluginBehavior { + private const float MinRadius = 60f, MaxRadius = 360f; private readonly IWardenService _warden; private BeamCircle? _marker; - private Vector? currentPos; - private const float MIN_RADIUS = 60f, MAX_RADIUS = 360f; - private float radius = MIN_RADIUS; - private long placementTime = 0; + private Vector? _currentPos; + private long _placementTime; + private float _radius = MinRadius; public WardenMarkerBehavior(IWardenService warden) { @@ -38,40 +38,40 @@ public HookResult OnPing(EventPlayerPing @event, GameEventInfo info) if (!_warden.IsWarden(player)) return HookResult.Handled; - Vector vec = new Vector(@event.X, @event.Y, @event.Z); + var vec = new Vector(@event.X, @event.Y, @event.Z); - if (currentPos != null) + if (_currentPos != null) { - float distance = currentPos.Distance(vec); - long timeElapsed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - placementTime; + var distance = _currentPos.Distance(vec); + var timeElapsed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - _placementTime; if (timeElapsed < 500) { - if (distance <= MAX_RADIUS * 1.5) + if (distance <= MaxRadius * 1.5) { - distance = Math.Clamp(distance, MIN_RADIUS, MAX_RADIUS); + distance = Math.Clamp(distance, MinRadius, MaxRadius); _marker?.SetRadius(distance); _marker?.Update(); - radius = distance; + _radius = distance; return HookResult.Handled; } } - else if (distance <= radius) + else if (distance <= _radius) { _marker?.Remove(); return HookResult.Handled; } } - radius = MIN_RADIUS; - currentPos = vec; - placementTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + _radius = MinRadius; + _currentPos = vec; + _placementTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); _marker?.Move(vec); - _marker?.SetRadius(radius); + _marker?.SetRadius(_radius); _marker?.Update(); return HookResult.Handled; } - HookResult CommandListener_PlayerPing(CCSPlayerController? player, CommandInfo info) + private HookResult CommandListener_PlayerPing(CCSPlayerController? player, CommandInfo info) { return _warden.IsWarden(player) ? HookResult.Continue : HookResult.Handled; } diff --git a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs index d66c558a..c14cd943 100644 --- a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs +++ b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs @@ -1,7 +1,5 @@ -using System.Drawing; -using CounterStrikeSharp.API; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Timers; using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; @@ -12,9 +10,9 @@ namespace Jailbreak.Warden.Paint; public class WardenPaintBehavior : IPluginBehavior { - private IWardenService _warden; - private BasePlugin parent; private Vector? _lastPosition; + private readonly IWardenService _warden; + private BasePlugin? _parent; public WardenPaintBehavior(IWardenService warden) { @@ -23,7 +21,7 @@ public WardenPaintBehavior(IWardenService warden) public void Start(BasePlugin parent) { - this.parent = parent; + _parent = parent; parent.RegisterListener(Paint); } @@ -36,76 +34,73 @@ private void Paint() if (warden == null || !warden.IsReal()) return; - if ((warden.Buttons & PlayerButtons.Use) == 0) - { - return; - } + if ((warden.Buttons & PlayerButtons.Use) == 0) return; - Vector? position = FindFloorIntersection(warden); + var position = FindFloorIntersection(warden); if (position == null) return; var start = _lastPosition ?? position; start = start.Clone(); - if (_lastPosition != null && position.DistanceSquared(_lastPosition) < 25 * 25) - { - return; - } + if (_lastPosition != null && position.DistanceSquared(_lastPosition) < 25 * 25) return; _lastPosition = position; - if (start.DistanceSquared(position) > 150 * 150) - { - start = position; - } + if (start.DistanceSquared(position) > 150 * 150) start = position; - new BeamLine(parent, start.Clone(), position.Clone()).Draw(10f); + if(_parent == null) + throw new NullReferenceException("Parent plugin is null"); + + new BeamLine(_parent, start.Clone(), position.Clone()).Draw(10f); } private Vector? FindFloorIntersection(CCSPlayerController player) { if (player.Pawn.Value == null || player.PlayerPawn.Value == null) return null; - CBasePlayerPawn pawn = player.Pawn.Value; - CCSPlayerPawn playerPawn = player.PlayerPawn.Value; - if (!pawn.IsValid || !playerPawn.IsValid || pawn.CameraServices == null) + var pawn = player.Pawn.Value; + var playerPawn = player.PlayerPawn.Value; + if (pawn == null || !pawn.IsValid || !playerPawn.IsValid || pawn.CameraServices == null) + return null; + if(pawn.AbsOrigin == null) return null; - CPlayer_CameraServices camera = pawn.CameraServices; - Vector cameraOrigin = new Vector(pawn?.AbsOrigin?.X, pawn?.AbsOrigin?.Y, - pawn.AbsOrigin.Z + camera.OldPlayerViewOffsetZ); - QAngle eye_angle = player.PlayerPawn.Value.EyeAngles; + var camera = pawn.CameraServices; + var cameraOrigin = new Vector(pawn.AbsOrigin!.X, pawn.AbsOrigin!.Y, + pawn.AbsOrigin!.Z + camera.OldPlayerViewOffsetZ); + var eyeAngle = player.PlayerPawn.Value.EyeAngles; - double pitch = (Math.PI / 180) * eye_angle.X; - double yaw = (Math.PI / 180) * eye_angle.Y; + var pitch = Math.PI / 180 * eyeAngle.X; + var yaw = Math.PI / 180 * eyeAngle.Y; // get direction vector from angles - Vector eye_vector = new Vector((float)(Math.Cos(yaw) * Math.Cos(pitch)), - (float)(Math.Sin(yaw) * Math.Cos(pitch)), (float)(-Math.Sin(pitch))); + var eyeVector = new Vector((float)(Math.Cos(yaw) * Math.Cos(pitch)), + (float)(Math.Sin(yaw) * Math.Cos(pitch)), (float)-Math.Sin(pitch)); - return FindFloorIntersection(cameraOrigin, eye_vector, new Vector(eye_angle.X, eye_angle.Y, eye_angle.Z), + return FindFloorIntersection(cameraOrigin, eyeVector, new Vector(eyeAngle.X, eyeAngle.Y, eyeAngle.Z), pawn.AbsOrigin.Z); } private Vector? FindFloorIntersection(Vector start, Vector worldAngles, Vector rotationAngles, float z) { - float pitch = rotationAngles.X; // 90 = straight down, -90 = straight up, 0 = straight ahead + var pitch = rotationAngles.X; // 90 = straight down, -90 = straight up, 0 = straight ahead // normalize so 0 = straight down, 180 = straight up, 90 = straight ahead pitch = 90 - pitch; if (pitch >= 90) return null; - float angle_a = ToRadians(90); - float side_b = start.Z - z; - float angle_c = ToRadians(pitch); + + // var angleA = ToRadians(90); + var sideB = start.Z - z; + var angleC = ToRadians(pitch); - float angle_b = 180 - 90 - pitch; - float side_a = side_b * MathF.Sin(ToRadians(90)) / MathF.Sin(ToRadians(angle_b)); - float side_c = MathF.Sqrt(side_b * side_b + side_a * side_a - 2 * side_b * side_a * MathF.Cos(angle_c)); + var angleB = 180 - 90 - pitch; + var sideA = sideB * MathF.Sin(ToRadians(90)) / MathF.Sin(ToRadians(angleB)); + var sideC = MathF.Sqrt(sideB * sideB + sideA * sideA - 2 * sideB * sideA * MathF.Cos(angleC)); - Vector destination = start.Clone(); - destination.X += worldAngles.X * side_c; - destination.Y += worldAngles.Y * side_c; + var destination = start.Clone(); + destination.X += worldAngles.X * sideC; + destination.Y += worldAngles.Y * sideC; destination.Z = z; return destination; } diff --git a/mod/Jailbreak.Warden/Selection/QueueFavorState.cs b/mod/Jailbreak.Warden/Selection/QueueFavorState.cs index fc8b4b82..3f1036ac 100644 --- a/mod/Jailbreak.Warden/Selection/QueueFavorState.cs +++ b/mod/Jailbreak.Warden/Selection/QueueFavorState.cs @@ -2,18 +2,16 @@ public class QueueFavorState { + public const int BaseTickets = 2; - public const int BASE_TICKETS = 2; + public int RoundsWithoutWarden { get; set; } = 0; - public int RoundsWithoutWarden { get; set; } = 0; + public int Favor { get; set; } = 0; - public int Favor { get; set; } = 0; - - public int GetTickets() - { - return BASE_TICKETS - + Favor - + RoundsWithoutWarden; - } - -} + public int GetTickets() + { + return BaseTickets + + Favor + + RoundsWithoutWarden; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Selection/QueueState.cs b/mod/Jailbreak.Warden/Selection/QueueState.cs index ef885e29..e36f121c 100644 --- a/mod/Jailbreak.Warden/Selection/QueueState.cs +++ b/mod/Jailbreak.Warden/Selection/QueueState.cs @@ -2,10 +2,8 @@ public class QueueState { - /// - /// Whether or not this player is currently in the queue + /// Whether or not this player is currently in the queue /// public bool InQueue { get; set; } = false; - -} +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs b/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs index 804bdb36..ed4c7931 100644 --- a/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs +++ b/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs @@ -1,191 +1,181 @@ -using System; -using System.Linq; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Timers; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Generic; using Jailbreak.Public.Mod.Warden; - using Microsoft.Extensions.Logging; -using Serilog; - -using Timer = CounterStrikeSharp.API.Modules.Timers.Timer; - namespace Jailbreak.Warden.Selection; /// -/// Behavior responsible for choosing the next warden +/// Behavior responsible for choosing the next warden /// public class WardenSelectionBehavior : IPluginBehavior, IWardenSelectionService { - /// - /// A state dict that handles the player's current queue - /// enrollment and favor. Uses the Round reset mode. - /// - private IPlayerState _queue; - - private IPlayerState _favor; - - private ILogger _logger; - - /// - /// Whether or not to use the queue. - /// When true, the queue should be skipped and turn to first-come-first-serve. - /// - private bool _queueInactive; - - private IWardenService _warden; - - private IWardenNotifications _notifications; - - private ICoroutines _coroutines; - - public WardenSelectionBehavior(IPlayerStateFactory factory, IWardenService warden, IWardenNotifications notifications, ILogger logger, ICoroutines coroutines) - { - _warden = warden; - _notifications = notifications; - _logger = logger; - _coroutines = coroutines; - _queue = factory.Round(); - _favor = factory.Global(); - - _queueInactive = true; - } - - public void Start(BasePlugin parent) - { - - } - - public void Dispose() - { - - } - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) - { - // Enable the warden queue - _queueInactive = false; - - _notifications.PICKING_SHORTLY.ToAllChat(); - - // Start a timer to pick the warden in 7 seconds - ScheduleChooseWarden(7.0f); - - return HookResult.Continue; - } - - [MethodImpl(MethodImplOptions.NoOptimization)] - public void ScheduleChooseWarden(float time = 7.0f) - { - _coroutines.Round(OnChooseWarden, time); - } - - /// - /// Timer callback that states it's time to choose the warden. - /// - protected void OnChooseWarden() - { - var eligible = Utilities.GetPlayers() - .Where(player => player.PawnIsAlive) - .Where(player => player.GetTeam() == CsTeam.CounterTerrorist) - .Where(player => _queue.Get(player).InQueue) - .ToList(); - - _logger.LogTrace("[WardenSelectionBehavior] Picking warden from {@Eligible}", eligible); - - if (eligible.Count == 0) - { - _notifications.NO_WARDENS.ToAllChat(); - _queueInactive = true; - - return; - } - - var favors = eligible - .ToDictionary(player => player, player => _favor.Get(player)); - int tickets = favors.Sum(favor => favor.Value.GetTickets()); - int chosen = Random.Shared.Next(tickets); - - _logger.LogTrace("[Warden Raffle] Picking {@Chosen} out of {@Tickets}", chosen, tickets); - - int pointer = 0; - foreach (var (player, favor) in favors) - { - int thisTickets = favor.GetTickets(); - _logger.LogTrace("[Warden Raffle] {@Pointer} -> {@End}: #{@Slot} {@Name}", pointer, pointer + thisTickets, player.Slot, player.PlayerName); - - // If winning ticket belongs to this player, assign them as warden. - if (pointer <= chosen && chosen < (pointer + thisTickets)) - { - _warden.TrySetWarden(player); - favor.RoundsWithoutWarden = 0; - } - else - { - favor.RoundsWithoutWarden++; - } - - pointer += thisTickets; - } - - // Disable the warden raffle for future wardens - // (eg in the event of warden death) - _queueInactive = true; - } - - private bool CanEnterQueue(CCSPlayerController player) - { - if (player.GetTeam() != CsTeam.CounterTerrorist) - return false; - - if (!player.PawnIsAlive) - return false; - - // Cannot enter queue if queue is not running - if (_queueInactive) - return false; - - // Edge case: Is there already a warden? - if (_warden.HasWarden) - return false; - - return true; - } - - public bool TryEnter(CCSPlayerController player) - { - if (!CanEnterQueue(player)) - return false; - - _queue.Get(player).InQueue = true; - return true; - } - - public bool TryExit(CCSPlayerController player) - { - if (!CanEnterQueue(player)) - return false; - - _queue.Get(player).InQueue = false; - return true; - } - - public bool InQueue(CCSPlayerController player) - => _queue.Get(player).InQueue; - - public bool Active => !_queueInactive; - - -} + private readonly ICoroutines _coroutines; + + private readonly IPlayerState _favor; + + private readonly ILogger _logger; + + private readonly IWardenNotifications _notifications; + + /// + /// A state dict that handles the player's current queue + /// enrollment and favor. Uses the Round reset mode. + /// + private readonly IPlayerState _queue; + + /// + /// Whether or not to use the queue. + /// When true, the queue should be skipped and turn to first-come-first-serve. + /// + private bool _queueInactive; + + private readonly IWardenService _warden; + + public WardenSelectionBehavior(IPlayerStateFactory factory, IWardenService warden, + IWardenNotifications notifications, ILogger logger, ICoroutines coroutines) + { + _warden = warden; + _notifications = notifications; + _logger = logger; + _coroutines = coroutines; + _queue = factory.Round(); + _favor = factory.Global(); + + _queueInactive = true; + } + + public void Start(BasePlugin parent) + { + } + + public void Dispose() + { + } + + public bool TryEnter(CCSPlayerController player) + { + if (!CanEnterQueue(player)) + return false; + + _queue.Get(player).InQueue = true; + return true; + } + + public bool TryExit(CCSPlayerController player) + { + if (!CanEnterQueue(player)) + return false; + + _queue.Get(player).InQueue = false; + return true; + } + + public bool InQueue(CCSPlayerController player) + { + return _queue.Get(player).InQueue; + } + + public bool Active => !_queueInactive; + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) + { + // Enable the warden queue + _queueInactive = false; + + _notifications.PickingShortly.ToAllChat(); + + // Start a timer to pick the warden in 7 seconds + ScheduleChooseWarden(); + + return HookResult.Continue; + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void ScheduleChooseWarden(float time = 7.0f) + { + _coroutines.Round(OnChooseWarden, time); + } + + /// + /// Timer callback that states it's time to choose the warden. + /// + protected void OnChooseWarden() + { + var eligible = Utilities.GetPlayers() + .Where(player => player.PawnIsAlive) + .Where(player => player.GetTeam() == CsTeam.CounterTerrorist) + .Where(player => _queue.Get(player).InQueue) + .ToList(); + + _logger.LogTrace("[WardenSelectionBehavior] Picking warden from {@Eligible}", eligible); + + if (eligible.Count == 0) + { + _notifications.NoWardens.ToAllChat(); + _queueInactive = true; + + return; + } + + var favors = eligible + .ToDictionary(player => player, player => _favor.Get(player)); + var tickets = favors.Sum(favor => favor.Value.GetTickets()); + var chosen = Random.Shared.Next(tickets); + + _logger.LogTrace("[Warden Raffle] Picking {@Chosen} out of {@Tickets}", chosen, tickets); + + var pointer = 0; + foreach (var (player, favor) in favors) + { + var thisTickets = favor.GetTickets(); + _logger.LogTrace("[Warden Raffle] {@Pointer} -> {@End}: #{@Slot} {@Name}", pointer, pointer + thisTickets, + player.Slot, player.PlayerName); + + // If winning ticket belongs to this player, assign them as warden. + if (pointer <= chosen && chosen < pointer + thisTickets) + { + _warden.TrySetWarden(player); + favor.RoundsWithoutWarden = 0; + } + else + { + favor.RoundsWithoutWarden++; + } + + pointer += thisTickets; + } + + // Disable the warden raffle for future wardens + // (eg in the event of warden death) + _queueInactive = true; + } + + private bool CanEnterQueue(CCSPlayerController player) + { + if (player.GetTeam() != CsTeam.CounterTerrorist) + return false; + + if (!player.PawnIsAlive) + return false; + + // Cannot enter queue if queue is not running + if (_queueInactive) + return false; + + // Edge case: Is there already a warden? + if (_warden.HasWarden) + return false; + + return true; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/WardenServiceExtension.cs b/mod/Jailbreak.Warden/WardenServiceExtension.cs index 2344a1da..9f7a0fc5 100644 --- a/mod/Jailbreak.Warden/WardenServiceExtension.cs +++ b/mod/Jailbreak.Warden/WardenServiceExtension.cs @@ -1,26 +1,23 @@ -using CounterStrikeSharp.API.Core; - -using Jailbreak.Public.Extensions; +using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Warden; using Jailbreak.Warden.Commands; using Jailbreak.Warden.Global; using Jailbreak.Warden.Markers; using Jailbreak.Warden.Paint; using Jailbreak.Warden.Selection; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Warden; public static class WardenServiceExtension { - public static void AddJailbreakWarden(this IServiceCollection serviceCollection) - { - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); + public static void AddJailbreakWarden(this IServiceCollection serviceCollection) + { + serviceCollection.AddPluginBehavior(); + serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - } -} + serviceCollection.AddPluginBehavior(); + serviceCollection.AddPluginBehavior(); + serviceCollection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Base/IView.cs b/public/Jailbreak.Formatting/Base/IView.cs index 9568bafe..ae3ce208 100644 --- a/public/Jailbreak.Formatting/Base/IView.cs +++ b/public/Jailbreak.Formatting/Base/IView.cs @@ -4,7 +4,5 @@ namespace Jailbreak.Formatting.Base; public interface IView { - - void Render(FormatWriter writer); - -} + void Render(FormatWriter writer); +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Base/SimpleView.cs b/public/Jailbreak.Formatting/Base/SimpleView.cs index 6cf13644..d2c3bb98 100644 --- a/public/Jailbreak.Formatting/Base/SimpleView.cs +++ b/public/Jailbreak.Formatting/Base/SimpleView.cs @@ -4,27 +4,23 @@ namespace Jailbreak.Formatting.Base; public class SimpleView : IView { + private readonly Action _handler; - private Action _handler; + public SimpleView(Action handler) + { + _handler = handler; + } - public SimpleView(Action handler) - { - _handler = handler; - } + public SimpleView(params string[] lines) + { + _handler = writer => + { + foreach (var line in lines) writer.Line(line); + }; + } - public SimpleView(params string[] lines) - { - _handler = (writer) => - { - foreach (string line in lines) - { - writer.Line(line); - } - }; - } - - public void Render(FormatWriter writer) - { - _handler(writer); - } -} + public void Render(FormatWriter writer) + { + _handler(writer); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Core/FormatObject.cs b/public/Jailbreak.Formatting/Core/FormatObject.cs index 49f31096..daef6232 100644 --- a/public/Jailbreak.Formatting/Core/FormatObject.cs +++ b/public/Jailbreak.Formatting/Core/FormatObject.cs @@ -1,5 +1,4 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Objects; using Jailbreak.Public.Extensions; @@ -7,33 +6,43 @@ namespace Jailbreak.Formatting.Core; 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() - => ToPlain(); + { + return ToPlain(); + } /// - /// Output this format object in a panorama-compatible format. + /// Output this format object in a panorama-compatible format. /// /// public virtual string ToPanorama() - => ToPlain().Sanitize(); + { + return ToPlain().Sanitize(); + } /// - /// Output plaintext + /// Output plaintext /// /// public abstract string ToPlain(); - public static implicit operator FormatObject(string value) - => new StringFormatObject(value); + public static implicit operator FormatObject(string value) + { + return new StringFormatObject(value); + } - public static implicit operator FormatObject(CCSPlayerController value) - => new PlayerFormatObject(value); + public static implicit operator FormatObject(CCSPlayerController value) + { + return new PlayerFormatObject(value); + } - public static FormatObject FromObject(object value) => new StringFormatObject(value.ToString()); -} + public static FormatObject FromObject(object value) + { + return new StringFormatObject(value.ToString() ?? "null"); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Core/FormatWriter.cs b/public/Jailbreak.Formatting/Core/FormatWriter.cs index feccfc30..760bcdc5 100644 --- a/public/Jailbreak.Formatting/Core/FormatWriter.cs +++ b/public/Jailbreak.Formatting/Core/FormatWriter.cs @@ -2,27 +2,24 @@ public class FormatWriter { + private readonly List _lines = new(); - private List< FormatObject[] > _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 Plain + => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToPlain()))); - 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 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/Jailbreak.Formatting/Extensions/ViewExtensions.cs b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs index 36e3997c..b023531d 100644 --- a/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs +++ b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs @@ -1,6 +1,5 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Public.Extensions; @@ -9,90 +8,89 @@ namespace Jailbreak.Formatting.Extensions; public static class ViewExtensions { + public static FormatWriter ToWriter(this IView view) + { + var writer = new FormatWriter(); - public static FormatWriter ToWriter(this IView view) - { - var writer = new FormatWriter(); - - view.Render(writer); + view.Render(writer); - return writer; - } + return writer; + } - #region Individual + public static IView ToAllConsole(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); - public static IView ToPlayerConsole(this IView view, CCSPlayerController player) - { - if (player.IsReal()) - { - var writer = view.ToWriter(); + return view; + } - foreach (string writerLine in writer.Plain) - player.PrintToConsole(writerLine); - } + public static IView ToAllChat(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); - return view; - } + return view; + } - public static IView ToPlayerChat(this IView view, CCSPlayerController player) - { - if (player.IsReal()) - { - var writer = view.ToWriter(); + public static IView ToAllCenter(this IView view) + { + Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); - foreach (string writerLine in writer.Chat) - player.PrintToChat(writerLine); - } + return view; + } - return view; - } + #region Individual - public static IView ToPlayerCenter(this IView view, CCSPlayerController player) - { - if (player.IsReal()) - { - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Plain); + public static IView ToPlayerConsole(this IView view, CCSPlayerController player) + { + if(!player.IsReal()) + return view; + + var writer = view.ToWriter(); - player.PrintToCenter(merged); - } + foreach (var writerLine in writer.Plain) + player.PrintToConsole(writerLine); - return view; - } + return view; + } - public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) - { - if (player.IsReal()) - { - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Panorama); + public static IView ToPlayerChat(this IView view, CCSPlayerController player) + { + if(!player.IsReal()) + return view; + + var writer = view.ToWriter(); - player.PrintToCenterHtml(merged); - } + foreach (var writerLine in writer.Chat) + player.PrintToChat(writerLine); - return view; - } + return view; + } - #endregion + public static IView ToPlayerCenter(this IView view, CCSPlayerController player) + { + if(!player.IsReal()) + return view; + + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Plain); - public static IView ToAllConsole(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); + player.PrintToCenter(merged); - return view; - } + return view; + } - public static IView ToAllChat(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); + public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) + { + if(!player.IsReal()) + return view; + + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Panorama); - return view; - } + player.PrintToCenterHtml(merged); - public static IView ToAllCenter(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); + return view; + } - return view; - } -} + #endregion +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj b/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj index dfa47427..3097d794 100644 --- a/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj +++ b/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj @@ -7,7 +7,7 @@ - + diff --git a/public/Jailbreak.Formatting/Languages/English.cs b/public/Jailbreak.Formatting/Languages/English.cs index 0fa55e13..a016d8ec 100644 --- a/public/Jailbreak.Formatting/Languages/English.cs +++ b/public/Jailbreak.Formatting/Languages/English.cs @@ -4,5 +4,4 @@ namespace Jailbreak.Formatting.Languages; public class English : IDialect { - -} +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Logistics/IDialect.cs b/public/Jailbreak.Formatting/Logistics/IDialect.cs index a10560c4..2d43dd0a 100644 --- a/public/Jailbreak.Formatting/Logistics/IDialect.cs +++ b/public/Jailbreak.Formatting/Logistics/IDialect.cs @@ -1,10 +1,9 @@ namespace Jailbreak.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 diff --git a/public/Jailbreak.Formatting/Logistics/ILanguage.cs b/public/Jailbreak.Formatting/Logistics/ILanguage.cs index a6483688..752d747c 100644 --- a/public/Jailbreak.Formatting/Logistics/ILanguage.cs +++ b/public/Jailbreak.Formatting/Logistics/ILanguage.cs @@ -1,12 +1,11 @@ namespace Jailbreak.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 + where TDialect : IDialect { - -} +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs index 3848bfc8..e96df713 100644 --- a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs +++ b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs @@ -1,33 +1,39 @@ using Jailbreak.Formatting.Views; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Formatting.Logistics; public class LanguageConfig - where TDialect: IDialect + where TDialect : IDialect { + private readonly IServiceCollection _collection; + + public LanguageConfig(IServiceCollection collection) + { + _collection = collection; + } - private IServiceCollection _collection; + public void WithGenericCommand() + where TGenericCommand : class, ILanguage, IGenericCommandNotifications + { + _collection.AddSingleton(); + } - public LanguageConfig(IServiceCollection collection) - { - _collection = collection; - } + public void WithRatio() + where TRatio : class, ILanguage, IRatioNotifications + { + _collection.AddSingleton(); + } - public void WithGenericCommand() - where TGenericCommand : class, ILanguage, IGenericCommandNotifications - => _collection.AddSingleton(); - - public void WithRatio() - where TRatio : class, ILanguage, IRatioNotifications - => _collection.AddSingleton(); + public void WithWarden() + where TWarden : class, ILanguage, IWardenNotifications + { + _collection.AddSingleton(); + } - public void WithWarden() - where TWarden : class, ILanguage, IWardenNotifications - => _collection.AddSingleton(); - - public void WithRebel() - where TRebel : class, ILanguage, IRebelNotifications - => _collection.AddSingleton(); -} + public void WithRebel() + where TRebel : class, ILanguage, IRebelNotifications + { + _collection.AddSingleton(); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs b/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs index b2174095..ecc2afd6 100644 --- a/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs +++ b/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs @@ -4,13 +4,13 @@ namespace Jailbreak.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 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/Jailbreak.Formatting/Objects/HiddenFormatObject.cs b/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs index a9cac122..7f271b2e 100644 --- a/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs @@ -4,37 +4,37 @@ namespace Jailbreak.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 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/Jailbreak.Formatting/Objects/PlayerFormatObject.cs b/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs index 3dadab23..08b04f0e 100644 --- a/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs @@ -1,6 +1,5 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Core; using Jailbreak.Public.Extensions; @@ -8,19 +7,25 @@ namespace Jailbreak.Formatting.Objects; public class PlayerFormatObject : FormatObject { - private CCSPlayerController _player; + private readonly CCSPlayerController _player; - public PlayerFormatObject(CCSPlayerController player) - { - _player = player; - } + public PlayerFormatObject(CCSPlayerController player) + { + _player = player; + } - public override string ToChat() - => $"{ChatColors.Yellow}{_player.PlayerName}"; + public override string ToChat() + { + return $"{ChatColors.Yellow}{_player.PlayerName}"; + } - public override string ToPanorama() - => _player.PlayerName.Sanitize(); + public override string ToPanorama() + { + return _player.PlayerName.Sanitize(); + } - public override string ToPlain() - => _player.PlayerName; -} + public override string ToPlain() + { + return _player.PlayerName; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/StringFormatObject.cs b/public/Jailbreak.Formatting/Objects/StringFormatObject.cs index 64900bba..c19c7037 100644 --- a/public/Jailbreak.Formatting/Objects/StringFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/StringFormatObject.cs @@ -1,28 +1,31 @@ -using CounterStrikeSharp.API.Modules.Utils; - -using Jailbreak.Formatting.Core; +using Jailbreak.Formatting.Core; namespace Jailbreak.Formatting.Objects; public class StringFormatObject : FormatObject { - private string _value; - private char _chatColor; - - public StringFormatObject(string value, char chatColor = '\x01') - { - _value = value; - _chatColor = chatColor; - } - - public string Value => _value; - - public override string ToChat() - => $"{_chatColor}{Value}"; - - public override string ToPanorama() - => Value; - - public override string ToPlain() - => Value; -} + private readonly char _chatColor; + + public StringFormatObject(string value, char chatColor = '\x01') + { + Value = value; + _chatColor = chatColor; + } + + public string Value { get; } + + public override string ToChat() + { + return $"{_chatColor}{Value}"; + } + + public override string ToPanorama() + { + return Value; + } + + public override string ToPlain() + { + return Value; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IRebelNotifications.cs b/public/Jailbreak.Formatting/Views/IRebelNotifications.cs index 4631baec..53ec2027 100644 --- a/public/Jailbreak.Formatting/Views/IRebelNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IRebelNotifications.cs @@ -4,5 +4,5 @@ namespace Jailbreak.Formatting.Views; public interface IRebelNotifications { - public IView NO_LONGER_REBEL { get; } + public IView NoLongerRebel { get; } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs b/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs index f30e63d5..e687431d 100644 --- a/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs @@ -4,21 +4,20 @@ namespace Jailbreak.Formatting.Views; public interface IRatioNotifications { - public IView NOT_ENOUGH_GUARDS { get; } + public IView NotEnoughGuards { get; } - public IView PLEASE_JOIN_GUARD_QUEUE { get; } + public IView PleaseJoinGuardQueue { get; } - public IView JOINED_GUARD_QUEUE { get; } + public IView JoinedGuardQueue { get; } - public IView ALREADY_A_GUARD { get; } + public IView AlreadyAGuard { get; } - public IView YOU_WERE_AUTOBALANCED_PRISONER { get; } + public IView YouWereAutobalancedPrisoner { get; } - public IView YOU_WERE_AUTOBALANCED_GUARD { get; } + public IView YouWereAutobalancedGuard { get; } - public IView ATTEMPT_TO_JOIN_FROM_TEAM_MENU { get; } + public IView AttemptToJoinFromTeamMenu { get; } - public IView LEFT_GUARD { get; } - -} + public IView LeftGuard { get; } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IWardenNotifications.cs b/public/Jailbreak.Formatting/Views/IWardenNotifications.cs index 189b41be..5ccbffcd 100644 --- a/public/Jailbreak.Formatting/Views/IWardenNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IWardenNotifications.cs @@ -1,38 +1,37 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Base; namespace Jailbreak.Formatting.Views; public interface IWardenNotifications { - public IView PICKING_SHORTLY { get; } - public IView NO_WARDENS { get; } - public IView WARDEN_LEFT { get; } - public IView WARDEN_DIED { get; } - public IView BECOME_NEXT_WARDEN { get; } - public IView JOIN_RAFFLE { get; } - public IView LEAVE_RAFFLE { get; } + public IView PickingShortly { get; } + public IView NoWardens { get; } + public IView WardenLeft { get; } + public IView WardenDied { get; } + public IView BecomeNextWarden { get; } + public IView JoinRaffle { get; } + public IView LeaveRaffle { get; } - /// - /// Create a view for when the specified player passes warden - /// - /// - /// - public IView PASS_WARDEN(CCSPlayerController player); + /// + /// Create a view for when the specified player passes warden + /// + /// + /// + public IView PassWarden(CCSPlayerController player); - /// - /// Create a view for when this player becomes a new warden - /// - /// - /// - public IView NEW_WARDEN(CCSPlayerController player); + /// + /// Create a view for when this player becomes a new warden + /// + /// + /// + public IView NewWarden(CCSPlayerController player); - /// - /// Format a response to a request about the current warden. - /// When player is null, instead respond stating that there is no warden. - /// - /// - /// - public IView CURRENT_WARDEN(CCSPlayerController? player); -} + /// + /// Format a response to a request about the current warden. + /// When player is null, instead respond stating that there is no warden. + /// + /// + /// + public IView CurrentWarden(CCSPlayerController? player); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs b/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs index 137eb709..a1125ec0 100644 --- a/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs +++ b/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs @@ -3,22 +3,18 @@ namespace Jailbreak.Public.Behaviors; /// -/// A plugin extension class that is +/// A plugin extension class that is /// public interface IPluginBehavior : IDisposable { + void IDisposable.Dispose() + { + } - /// - /// Tells the plugin that it will be starting imminently - /// - void Start(BasePlugin parent) - { - - } - - void IDisposable.Dispose() - { - - } - -} + /// + /// Tells the plugin that it will be starting imminently + /// + void Start(BasePlugin parent) + { + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Configuration/IConfigService.cs b/public/Jailbreak.Public/Configuration/IConfigService.cs index 7b690ec9..5380d3d6 100644 --- a/public/Jailbreak.Public/Configuration/IConfigService.cs +++ b/public/Jailbreak.Public/Configuration/IConfigService.cs @@ -1,19 +1,16 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; - -namespace Jailbreak.Public.Configuration; +namespace Jailbreak.Public.Configuration; public interface IConfigService { - public const string CONFIG_PATH = "jailbreak.json"; + 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/Jailbreak.Public/Extensions/EnumerableExtensions.cs b/public/Jailbreak.Public/Extensions/EnumerableExtensions.cs index 1e109586..5741f73c 100644 --- a/public/Jailbreak.Public/Extensions/EnumerableExtensions.cs +++ b/public/Jailbreak.Public/Extensions/EnumerableExtensions.cs @@ -2,23 +2,21 @@ public static class EnumerableExtensions { - public static IEnumerable Shuffle(this IEnumerable source, Random rng) - { - // From https://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm - // Yay stackoverflow :D + public static IEnumerable Shuffle(this IEnumerable source, Random rng) + { + // From https://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm + // Yay stackoverflow :D - T[] elements = source.ToArray(); - // Note i > 0 to avoid final pointless iteration - for (int i = elements.Length-1; i > 0; i--) - { - // Swap element "i" with a random earlier element it (or itself) - int swapIndex = rng.Next(i + 1); - (elements[i], elements[swapIndex]) = (elements[swapIndex], elements[i]); - } - // Lazily yield (avoiding aliasing issues etc) - foreach (T element in elements) - { - yield return element; - } - } -} + var elements = source.ToArray(); + // Note i > 0 to avoid final pointless iteration + for (var i = elements.Length - 1; i > 0; i--) + { + // Swap element "i" with a random earlier element it (or itself) + var swapIndex = rng.Next(i + 1); + (elements[i], elements[swapIndex]) = (elements[swapIndex], elements[i]); + } + + // Lazily yield (avoiding aliasing issues etc) + foreach (var element in elements) yield return element; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/PlayerExtensions.cs b/public/Jailbreak.Public/Extensions/PlayerExtensions.cs index 3e55bc6a..1837f5eb 100644 --- a/public/Jailbreak.Public/Extensions/PlayerExtensions.cs +++ b/public/Jailbreak.Public/Extensions/PlayerExtensions.cs @@ -5,25 +5,24 @@ namespace Jailbreak.Public.Extensions; public static class PlayerExtensions { - public static CsTeam GetTeam(this CCSPlayerController controller) - { - return (CsTeam)controller.TeamNum; - } + public static CsTeam GetTeam(this CCSPlayerController controller) + { + return (CsTeam)controller.TeamNum; + } - 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; + 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.IsBot || player.IsHLTV) - return false; + if (player.Connected != PlayerConnectedState.PlayerConnected) + return false; - return true; - } + if (player.IsBot || player.IsHLTV) + return false; -} + return true; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/ServerExtensions.cs b/public/Jailbreak.Public/Extensions/ServerExtensions.cs index cd058274..90466bc7 100644 --- a/public/Jailbreak.Public/Extensions/ServerExtensions.cs +++ b/public/Jailbreak.Public/Extensions/ServerExtensions.cs @@ -1,13 +1,12 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Modules.Memory; +using CounterStrikeSharp.API.Modules.Memory; using CounterStrikeSharp.API.Modules.Utils; namespace Jailbreak.Public.Extensions; public static class ServerExtensions { - public static void PrintToCenterAll(string message) - { - VirtualFunctions.ClientPrintAll(HudDestination.Center, message, 0, 0, 0, 0); - } -} + public static void PrintToCenterAll(string message) + { + VirtualFunctions.ClientPrintAll(HudDestination.Center, message, 0, 0, 0, 0); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs b/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs index ea3f949c..7712a260 100644 --- a/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs +++ b/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs @@ -1,6 +1,5 @@ using Jailbreak.Public.Behaviors; using Jailbreak.Public.Configuration; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Public.Extensions; @@ -8,57 +7,57 @@ namespace Jailbreak.Public.Extensions; 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(); + 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(); - - collection.AddTransient(provider => provider.GetRequiredService()); - collection.AddTransient(provider => provider.GetRequiredService()); - } + 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()); + } /// - /// 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. - - // 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, /*failOnDefault*/ false)); - } -} + 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)); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/StringExtensions.cs b/public/Jailbreak.Public/Extensions/StringExtensions.cs index cce35f8a..f86de3d5 100644 --- a/public/Jailbreak.Public/Extensions/StringExtensions.cs +++ b/public/Jailbreak.Public/Extensions/StringExtensions.cs @@ -2,9 +2,9 @@ public static class StringExtensions { - public static string Sanitize(this string unknown) - { - return unknown - .Replace("<", "<"); - } -} + public static string Sanitize(this string unknown) + { + return unknown + .Replace("<", "<"); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/VectorExtensions.cs b/public/Jailbreak.Public/Extensions/VectorExtensions.cs index 158b738d..b522920b 100644 --- a/public/Jailbreak.Public/Extensions/VectorExtensions.cs +++ b/public/Jailbreak.Public/Extensions/VectorExtensions.cs @@ -42,15 +42,15 @@ public static Vector Normalize(this Vector vector) public static float Distance(this Vector vector, Vector other) { - return (float)System.Math.Sqrt(vector.DistanceSquared(other)); + return (float)Math.Sqrt(vector.DistanceSquared(other)); } public static float DistanceSquared(this Vector vector, Vector other) { return (float)( - System.Math.Pow(vector.X - other.X, 2) + - System.Math.Pow(vector.Y - other.Y, 2) + - System.Math.Pow(vector.Z - other.Z, 2) + 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/Jailbreak.Public/Generic/ICoroutines.cs b/public/Jailbreak.Public/Generic/ICoroutines.cs index b6b1cd7b..1cdadad3 100644 --- a/public/Jailbreak.Public/Generic/ICoroutines.cs +++ b/public/Jailbreak.Public/Generic/ICoroutines.cs @@ -2,13 +2,11 @@ public interface ICoroutines { - /// - /// Invoke a coroutine within the current round. - /// Do not allow this coroutine to pass onto other rounds. + /// Invoke a coroutine within the current round. + /// Do not allow this coroutine to pass onto other rounds. /// /// /// void Round(Action callback, float time = 10.0f); - -} +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Generic/IPlayerState.cs b/public/Jailbreak.Public/Generic/IPlayerState.cs index fa903c76..c55954b6 100644 --- a/public/Jailbreak.Public/Generic/IPlayerState.cs +++ b/public/Jailbreak.Public/Generic/IPlayerState.cs @@ -3,14 +3,12 @@ namespace Jailbreak.Public.Generic; /// -/// A player state dictionary that automatically deletes stale states -/// and translates between different client formats. +/// A player state dictionary that automatically deletes stale states +/// and translates between different client formats. /// /// public interface IPlayerState - where TState: class, new() + where TState : class, new() { - - TState Get(CCSPlayerController controller); - -} + TState Get(CCSPlayerController controller); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs b/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs index 7e9872fc..263d1d15 100644 --- a/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs +++ b/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs @@ -2,29 +2,27 @@ public interface IPlayerStateFactory { - /// - /// This state lasts from when the player connect to until the player disconnects. + /// This state lasts from when the player connect to until the player disconnects. /// /// /// IPlayerState Global() - where T : class, new(); + where T : class, new(); /// - /// This state resets when the player dies + /// This state resets when the player dies /// /// /// IPlayerState Alive() - where T : class, new(); + where T : class, new(); /// - /// This state resets when the round ends or begins. + /// This state resets when the round ends or begins. /// /// /// IPlayerState Round() - where T : class, new(); - -} + where T : class, new(); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Jailbreak.Public.csproj b/public/Jailbreak.Public/Jailbreak.Public.csproj index 2dd2d587..83079e55 100644 --- a/public/Jailbreak.Public/Jailbreak.Public.csproj +++ b/public/Jailbreak.Public/Jailbreak.Public.csproj @@ -7,12 +7,12 @@ - - + + - + diff --git a/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs b/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs index 7bc034b8..58fbb7ed 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs @@ -1,5 +1,3 @@ -using System.Drawing; -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; @@ -7,50 +5,51 @@ namespace Jailbreak.Public.Mod.Draw; public class BeamCircle : BeamedShape { + private readonly BeamLine?[] _lines; + private Vector[] _offsets; + private float _radius; - private BeamLine?[] lines; - private Vector[] offsets; - private float radius; - - public BeamCircle(BasePlugin plugin, Vector position, float radius, int resolution) : base(plugin, position, resolution) + public BeamCircle(BasePlugin plugin, Vector position, float radius, int resolution) : base(plugin, position, + resolution) { - this.radius = radius; - this.lines = new BeamLine[resolution]; + _radius = radius; + _lines = new BeamLine[resolution]; - offsets = generateOffsets(); + _offsets = GenerateOffsets(); } - private float degToRadian(float d) + private float DegToRadian(float d) { return (float)(d * (Math.PI / 180)); } - private Vector[] generateOffsets() + private Vector[] GenerateOffsets() { - var offsets = new Vector[lines.Length]; - var angle = 360f / lines.Length; - for (var i = 0; i < lines.Length; i++) + var offsets = new Vector[_lines.Length]; + var angle = 360f / _lines.Length; + for (var i = 0; i < _lines.Length; i++) { - var x = radius * MathF.Cos(degToRadian(angle * i)); - var y = radius * MathF.Sin(degToRadian(angle * i)); + var x = _radius * MathF.Cos(DegToRadian(angle * i)); + var y = _radius * MathF.Sin(DegToRadian(angle * i)); offsets[i] = new Vector(x, y, 0); } + return offsets; } public override void Draw() { - for (var i = 0; i < lines.Length; i++) + for (var i = 0; i < _lines.Length; i++) { - var line = lines[i]; - var start = position + offsets[i]; - var end = position + offsets[(i + 1) % offsets.Length]; + var line = _lines[i]; + var start = Position + _offsets[i]; + var end = Position + _offsets[(i + 1) % _offsets.Length]; if (line == null) { - line = new BeamLine(plugin, start, end); - line.SetColor(color); + line = new BeamLine(Plugin, start, end); + line.SetColor(Color); line.Draw(); - lines[i] = line; + _lines[i] = line; } else { @@ -59,10 +58,10 @@ public override void Draw() } } } - + public void SetRadius(float radius) { - this.radius = radius; - offsets = generateOffsets(); + _radius = radius; + _offsets = GenerateOffsets(); } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Draw/BeamLine.cs b/public/Jailbreak.Public/Mod/Draw/BeamLine.cs index 3a073e34..7587ee30 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamLine.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamLine.cs @@ -7,63 +7,64 @@ namespace Jailbreak.Public.Mod.Draw; public class BeamLine : DrawableShape, IColorable { - private Vector end; - private Color color = Color.White; - private CEnvBeam? beam; - private float width = 1f; + private CEnvBeam? _beam; + private Color _color = Color.White; + private Vector _end; + private float _width = 1f; public BeamLine(BasePlugin plugin, Vector position, Vector end) : base(plugin, position) { - this.end = end; + _end = end; + } + + public void SetColor(Color color) + { + _color = color; + } + + public Color GetColor() + { + return _color; } public void Move(Vector start, Vector end) { - this.position = start; - this.end = end; + Position = start; + _end = end; } public override void Draw() { - Remove(); + Remove(); var beam = Utilities.CreateEntityByName("env_beam"); if (beam == null) return; beam.RenderMode = RenderMode_t.kRenderTransColor; - beam.Width = width; + beam.Width = _width; beam.Render = GetColor(); - beam.Teleport(position, new QAngle(), new Vector()); - beam.EndPos.X = end.X; - beam.EndPos.Y = end.Y; - beam.EndPos.Z = end.Z; - this.beam = beam; + beam.Teleport(Position, new QAngle(), new Vector()); + beam.EndPos.X = _end.X; + beam.EndPos.Y = _end.Y; + beam.EndPos.Z = _end.Z; + _beam = beam; Utilities.SetStateChanged(beam, "CBeam", "m_vecEndPos"); } public override void Remove() { - beam?.Remove(); - beam = null; - } - - public void SetColor(Color color) - { - this.color = color; - } - - public Color GetColor() - { - return color; + KillTimer?.Kill(); + _beam?.Remove(); + _beam = null; } public void SetWidth(float width) { - this.width = width; + _width = width; } public float GetWidth() { - return width; + return _width; } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs b/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs index ddde4ac2..431864f9 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs @@ -5,37 +5,37 @@ namespace Jailbreak.Public.Mod.Draw; /// -/// Represents a shape that is drawn using many beam segments +/// Represents a shape that is drawn using many beam segments /// public abstract class BeamedShape : DrawableShape, IColorable { - protected BeamLine?[] beams; - protected Color color = Color.White; - protected int resolution; + protected BeamLine?[] Beams; + protected Color Color = Color.White; + protected int Resolution; protected BeamedShape(BasePlugin plugin, Vector position, int resolution) : base(plugin, position) { - beams = new BeamLine[resolution]; + Beams = new BeamLine[resolution]; } // TODO: Add support for rotation across arbitrary axis public Color GetColor() { - return color; + return Color; } public void SetColor(Color color) { - this.color = color; + Color = color; } public override void Remove() { - for(int i = 0; i < beams.Length; i++) + for (var i = 0; i < Beams.Length; i++) { - beams[i]?.Remove(); - beams[i] = null; + Beams[i]?.Remove(); + Beams[i] = null; } } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs b/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs index 27fb36d2..b027a6f9 100644 --- a/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs +++ b/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs @@ -1,4 +1,3 @@ -using System.Drawing; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Timers; using CounterStrikeSharp.API.Modules.Utils; @@ -7,42 +6,46 @@ namespace Jailbreak.Public.Mod.Draw; /// -/// Represents a drawable shape +/// Represents a drawable shape /// public abstract class DrawableShape { + protected Timer? KillTimer; // Internal timer used to remove the shape after a certain amount of time - protected BasePlugin plugin; - protected Vector position; // Represents the origin of the shape - // Note that this can mean different things for different shapes - protected DateTime startTime = DateTime.Now; + protected BasePlugin Plugin; + + protected Vector Position; // Represents the origin of the shape - private Timer? killTimer; // Internal timer used to remove the shape after a certain amount of time + // Note that this can mean different things for different shapes + protected DateTime StartTime = DateTime.Now; public DrawableShape(BasePlugin plugin, Vector position) { - this.plugin = plugin; - this.position = position; + Plugin = plugin; + Position = position; } public abstract void Draw(); - public virtual void Update() { + public virtual void Update() + { Remove(); Draw(); } - public virtual void Tick() { } + public virtual void Tick() + { + } public void Draw(float lifetime) { Draw(); - killTimer = plugin.AddTimer(lifetime, Remove, TimerFlags.STOP_ON_MAPCHANGE); + KillTimer = Plugin.AddTimer(lifetime, Remove, TimerFlags.STOP_ON_MAPCHANGE); } public virtual void Move(Vector position) { - this.position = position; + Position = position; } public abstract void Remove(); diff --git a/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs b/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs index 61be0744..90ae68e3 100644 --- a/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs +++ b/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs @@ -14,6 +14,6 @@ bool IsRebel(CCSPlayerController player) long GetRebelTimeLeft(CCSPlayerController player); bool MarkRebel(CCSPlayerController player, long time = 120); - + void UnmarkRebel(CCSPlayerController player); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Teams/IGuardQueue.cs b/public/Jailbreak.Public/Mod/Teams/IGuardQueue.cs index cb374beb..b1ab47f2 100644 --- a/public/Jailbreak.Public/Mod/Teams/IGuardQueue.cs +++ b/public/Jailbreak.Public/Mod/Teams/IGuardQueue.cs @@ -4,43 +4,42 @@ namespace Jailbreak.Public.Mod.Teams; public interface IGuardQueue { - - - bool TryEnterQueue(CCSPlayerController player); - - bool TryExitQueue(CCSPlayerController player); - - /// - /// Pop the provided amount of players from the queue - /// and put them on the CT team - /// - /// - /// - bool TryPop(int count); - - /// - /// Pull the provided amount of players from the CT team - /// and put them back in the queue. - /// - /// - /// - bool TryPush(int count); - /// - /// Force the player to join CT, without being pushed back to T. + /// Get all players in the queue /// - /// - void ForceGuard(CCSPlayerController player); + IEnumerable Queue { get; } - /// - /// Get this player's position in the queue - /// - /// - /// - int GetQueuePosition(CCSPlayerController player); - /// - /// Get all players in the queue - /// - IEnumerable Queue { get; } -} + bool TryEnterQueue(CCSPlayerController player); + + bool TryExitQueue(CCSPlayerController player); + + /// + /// Pop the provided amount of players from the queue + /// and put them on the CT team + /// + /// + /// + bool TryPop(int count); + + /// + /// Pull the provided amount of players from the CT team + /// and put them back in the queue. + /// + /// + /// + bool TryPush(int count); + + /// + /// Force the player to join CT, without being pushed back to T. + /// + /// + void ForceGuard(CCSPlayerController player); + + /// + /// Get this player's position in the queue + /// + /// + /// + int GetQueuePosition(CCSPlayerController player); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs b/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs index 4f5a88a4..b25730f7 100644 --- a/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs +++ b/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs @@ -5,26 +5,26 @@ namespace Jailbreak.Public.Mod.Warden; public interface IWardenSelectionService { /// - /// Enter this player into the warden queue + /// Whether or not the warden queue is currently in use + /// + bool Active { get; } + + /// + /// Enter this player into the warden queue /// /// bool TryEnter(CCSPlayerController player); /// - /// Remove this player from the warden queue + /// Remove this player from the warden queue /// /// bool TryExit(CCSPlayerController player); /// - /// Determine whether this player is in the queue or not + /// Determine whether this player is in the queue or not /// /// /// bool InQueue(CCSPlayerController player); - - /// - /// Whether or not the warden queue is currently in use - /// - bool Active {get;} -} +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Warden/IWardenService.cs b/public/Jailbreak.Public/Mod/Warden/IWardenService.cs index 249fae1a..9f7eafde 100644 --- a/public/Jailbreak.Public/Mod/Warden/IWardenService.cs +++ b/public/Jailbreak.Public/Mod/Warden/IWardenService.cs @@ -5,23 +5,21 @@ namespace Jailbreak.Public.Mod.Warden; public interface IWardenService { + public CCSPlayerController? Warden { get; } - CCSPlayerController? Warden { get; } + /// + /// Whether or not a warden is currently assigned + /// + public bool HasWarden { get; } - /// - /// Whether or not a warden is currently assigned - /// - bool HasWarden { get; } + public bool IsWarden(CCSPlayerController? player) + { + if (player == null || !player.IsReal()) + return false; + return HasWarden && Warden != null && Warden.Slot == player.Slot; + } - bool IsWarden(CCSPlayerController? player) - { - if (player == null || !player.IsReal()) - return false; - return HasWarden && Warden != null && Warden.Slot == player.Slot; - } + public bool TrySetWarden(CCSPlayerController warden); - bool TrySetWarden(CCSPlayerController warden); - - bool TryRemoveWarden(); - -} + public bool TryRemoveWarden(); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Utils/TemporaryConvar.cs b/public/Jailbreak.Public/Utils/TemporaryConvar.cs index 5ddb543d..265d418a 100644 --- a/public/Jailbreak.Public/Utils/TemporaryConvar.cs +++ b/public/Jailbreak.Public/Utils/TemporaryConvar.cs @@ -4,20 +4,21 @@ namespace Jailbreak.Public.Utils; public class TemporaryConvar : IDisposable { - private T _previousValue; - private ConVar _handle; - public TemporaryConvar(string name, T value) - { - _handle = ConVar.Find(name); - if (_handle == null) - throw new InvalidOperationException($"ConVar {name} does not exist!"); + private readonly ConVar _handle; + private readonly T _previousValue; - _previousValue = _handle.GetPrimitiveValue(); - _handle.SetValue(value); - } + public TemporaryConvar(string name, T value) + { + _handle = ConVar.Find(name) ?? throw new InvalidOperationException(); + if (_handle == null) + throw new InvalidOperationException($"ConVar {name} does not exist!"); - public void Dispose() - { - _handle.SetValue(_previousValue); - } -} + _previousValue = _handle.GetPrimitiveValue(); + _handle.SetValue(value); + } + + public void Dispose() + { + _handle.SetValue(_previousValue); + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs b/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs index 4011ea4e..4bffc03d 100644 --- a/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs +++ b/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs @@ -1,32 +1,32 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Timers; - using Jailbreak.Public.Behaviors; using Jailbreak.Public.Generic; - using Timer = CounterStrikeSharp.API.Modules.Timers.Timer; namespace Jailbreak.Generic.Coroutines; public class CoroutineManager : ICoroutines, IPluginBehavior { - private List _destroyOnRoundEnd = new(); - - private Timer New(Action callback, float time = 10) - => new(time, callback, TimerFlags.STOP_ON_MAPCHANGE); - - public void Round(Action callback, float time = 10) - { - var timer = New(callback, time); - _destroyOnRoundEnd.Add(timer); - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) - { - _destroyOnRoundEnd.ForEach(timer => timer.Kill()); - - return HookResult.Continue; - } -} + private readonly List _destroyOnRoundEnd = new(); + + public void Round(Action callback, float time = 10) + { + var timer = New(callback, time); + _destroyOnRoundEnd.Add(timer); + } + + private Timer New(Action callback, float time = 10) + { + return new Timer(time, callback, TimerFlags.STOP_ON_MAPCHANGE); + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) + { + _destroyOnRoundEnd.ForEach(timer => timer.Kill()); + + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/GenericServiceExtension.cs b/src/Jailbreak.Generic/GenericServiceExtension.cs index 7b32a053..28fe83c5 100644 --- a/src/Jailbreak.Generic/GenericServiceExtension.cs +++ b/src/Jailbreak.Generic/GenericServiceExtension.cs @@ -1,25 +1,22 @@ -using CounterStrikeSharp.API.Core; - -using Jailbreak.Generic.Coroutines; +using Jailbreak.Generic.Coroutines; using Jailbreak.Generic.PlayerState; using Jailbreak.Generic.PlayerState.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Generic; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Generic; public static class GenericServiceExtension { - public static void AddJailbreakGeneric(this IServiceCollection serviceCollection) - { - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); + public static void AddJailbreakGeneric(this IServiceCollection serviceCollection) + { + serviceCollection.AddPluginBehavior(); + serviceCollection.AddPluginBehavior(); + serviceCollection.AddPluginBehavior(); - serviceCollection.AddTransient(); + serviceCollection.AddTransient(); - serviceCollection.AddPluginBehavior(); - } -} + serviceCollection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/Jailbreak.Generic.csproj b/src/Jailbreak.Generic/Jailbreak.Generic.csproj index d809758e..29f7e134 100644 --- a/src/Jailbreak.Generic/Jailbreak.Generic.csproj +++ b/src/Jailbreak.Generic/Jailbreak.Generic.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs index e386c828..7a77e8c3 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs @@ -1,22 +1,20 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; - using Jailbreak.Public.Behaviors; namespace Jailbreak.Generic.PlayerState.Behaviors; public class AliveStateTracker : BaseStateTracker, IPluginBehavior { - public void Start(BasePlugin parent) - { - - } + public void Start(BasePlugin parent) + { + } - [GameEventHandler] - public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) - { - Reset(ev.Userid); + [GameEventHandler] + public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) + { + Reset(ev.Userid); - return HookResult.Continue; - } -} + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs index 9112588f..40c4e01e 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs @@ -4,25 +4,27 @@ namespace Jailbreak.Generic.PlayerState.Behaviors; public class BaseStateTracker : IDisposable { - private List _trackedPlayerStates = new(); + private readonly List _trackedPlayerStates = new(); - protected void Reset(CCSPlayerController controller) - { - foreach (ITrackedPlayerState trackedPlayerState in _trackedPlayerStates) - trackedPlayerState.Reset(controller); - } + public void Dispose() + { + ResetAll(); + } - protected void ResetAll() - { - foreach (ITrackedPlayerState trackedPlayerState in _trackedPlayerStates) - trackedPlayerState.Drop(); - } + protected void Reset(CCSPlayerController controller) + { + foreach (var trackedPlayerState in _trackedPlayerStates) + trackedPlayerState.Reset(controller); + } - public void Track(ITrackedPlayerState state) - { - _trackedPlayerStates.Add(state); - } + protected void ResetAll() + { + foreach (var trackedPlayerState in _trackedPlayerStates) + trackedPlayerState.Drop(); + } - public void Dispose() - => ResetAll(); -} + public void Track(ITrackedPlayerState state) + { + _trackedPlayerStates.Add(state); + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs index c5c25789..718043c7 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs @@ -1,16 +1,14 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; - using Jailbreak.Public.Behaviors; namespace Jailbreak.Generic.PlayerState.Behaviors; public class GlobalStateTracker : BaseStateTracker, IPluginBehavior { - public void Start(BasePlugin parent) - { - - } + public void Start(BasePlugin parent) + { + } /// /// Disconnect handler to reset states on user leave diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs index 7c624fa2..8d9a74ea 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs @@ -1,24 +1,20 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; - using Jailbreak.Public.Behaviors; -using Serilog; - namespace Jailbreak.Generic.PlayerState.Behaviors; public class RoundStateTracker : BaseStateTracker, IPluginBehavior { - public void Start(BasePlugin parent) - { - - } + public void Start(BasePlugin parent) + { + } - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) - { - ResetAll(); + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) + { + ResetAll(); - return HookResult.Continue; - } -} + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs b/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs index 8b4dca2c..05bbd37d 100644 --- a/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs +++ b/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs @@ -5,13 +5,13 @@ namespace Jailbreak.Generic.PlayerState; public interface ITrackedPlayerState { /// - /// Reset a state for a specific player + /// Reset a state for a specific player /// /// void Reset(CCSPlayerController controller); /// - /// Reset states for all players + /// Reset states for all players /// void Drop(); -} +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs b/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs index 8a38f352..2d92ca4f 100644 --- a/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs +++ b/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs @@ -5,42 +5,43 @@ namespace Jailbreak.Generic.PlayerState; public class PlayerStateFactory : IPlayerStateFactory { - private GlobalStateTracker _global; - private AliveStateTracker _alive; - private RoundStateTracker _round; + private readonly AliveStateTracker _alive; + private readonly GlobalStateTracker _global; + private readonly RoundStateTracker _round; - public PlayerStateFactory(GlobalStateTracker global, AliveStateTracker alive, RoundStateTracker round) - { - _global = global; - _alive = alive; - _round = round; - } + public PlayerStateFactory(GlobalStateTracker global, AliveStateTracker alive, RoundStateTracker round) + { + _global = global; + _alive = alive; + _round = round; + } - public IPlayerState Global() where T : class, new() - { - var state = new PlayerStateImpl(); + public IPlayerState Global() where T : class, new() + { + var state = new PlayerStateImpl(); - _global.Track(state); + _global.Track(state); - return state; - } + return state; + } - public IPlayerState Alive() where T : class, new() - { - var state = new PlayerStateImpl(); + public IPlayerState Alive() where T : class, new() + { + var state = new PlayerStateImpl(); - _global.Track(state); - _alive.Track(state); + _global.Track(state); + _alive.Track(state); - return state; } + return state; + } - public IPlayerState Round() where T : class, new() - { - var state = new PlayerStateImpl(); + public IPlayerState Round() where T : class, new() + { + var state = new PlayerStateImpl(); - _global.Track(state); - _round.Track(state); + _global.Track(state); + _round.Track(state); - return state; - } -} + return state; + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs b/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs index 75d57cdf..0dd1c4d2 100644 --- a/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs +++ b/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs @@ -1,25 +1,28 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Public.Generic; namespace Jailbreak.Generic.PlayerState; public class PlayerStateImpl : IPlayerState, ITrackedPlayerState - where TState : class, new() + where TState : class, new() { - private Dictionary _states = new(); + private readonly Dictionary _states = new(); - public TState Get(CCSPlayerController controller) - { - // If the state doesn't exist, create it :^) - _states.TryAdd(controller.Slot, new TState()); + public TState Get(CCSPlayerController controller) + { + // If the state doesn't exist, create it :^) + _states.TryAdd(controller.Slot, new TState()); - return _states[controller.Slot]; - } + return _states[controller.Slot]; + } - public void Reset(CCSPlayerController controller) - => _states.Remove(controller.Slot); + public void Reset(CCSPlayerController controller) + { + _states.Remove(controller.Slot); + } - public void Drop() - => _states.Clear(); -} + public void Drop() + { + _states.Clear(); + } +} \ No newline at end of file diff --git a/src/Jailbreak/Config/ConfigService.cs b/src/Jailbreak/Config/ConfigService.cs index 446531d9..fb25a63b 100644 --- a/src/Jailbreak/Config/ConfigService.cs +++ b/src/Jailbreak/Config/ConfigService.cs @@ -1,66 +1,68 @@ using System.Text.Json; using System.Text.Json.Nodes; - using CounterStrikeSharp.API; - using Jailbreak.Public.Configuration; - using Microsoft.Extensions.Logging; - namespace Jailbreak.Config; +/// +/// A service to load and parse configuration files. +/// public class ConfigService : IConfigService { - private ILogger _logger; - - public ConfigService(ILogger logger) - { - _logger = logger; - } - - 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 T Get(string path, bool fail = false) - where T : class, new() - { - var jsonPath = Path.Combine(Server.GameDirectory, IConfigService.CONFIG_PATH); - - if (!File.Exists(jsonPath)) - return Fail(fail, "Config file does not exist"); - - var jsonText = File.ReadAllText(jsonPath); - - var jsonObject = JsonObject.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 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/Jailbreak/Jailbreak.cs b/src/Jailbreak/Jailbreak.cs index a6af5aba..1bd605e4 100644 --- a/src/Jailbreak/Jailbreak.cs +++ b/src/Jailbreak/Jailbreak.cs @@ -1,70 +1,77 @@ using System.Collections.Immutable; -using System.Reflection; - -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; - using Jailbreak.Public.Behaviors; - using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Serilog; - namespace Jailbreak; +/// +/// The classic Jail gamemode, ported to Counter-Strike 2. +/// public class Jailbreak : BasePlugin { - public override string ModuleName => "Jailbreak"; - public override string ModuleVersion => "0.3.0.{GIT_VERSION}"; - public override string ModuleAuthor => "EdgeGamers Development"; + private IReadOnlyList? _extensions; + + private readonly IServiceProvider _provider; + private IServiceScope? _scope; + + /// + /// The Jailbreak plugin. + /// + /// + public Jailbreak(IServiceProvider provider) + { + _provider = provider; + } + + /// + public override string ModuleName => "Jailbreak"; - private IServiceProvider _provider; - private IServiceScope _scope; - private IReadOnlyList _extensions; + /// + public override string ModuleVersion => "1.0.0.{GIT_VERSION}"; - public Jailbreak(IServiceProvider provider) - { - _provider = provider; - } + /// + public override string ModuleAuthor => "EdgeGamers Development"; - public override void Load(bool hotReload) - { - Logger.LogInformation("[Jailbreak] Loading..."); + /// + public override void Load(bool hotReload) + { + Logger.LogInformation("[Jailbreak] Loading..."); - _scope = _provider.CreateScope(); - _extensions = _scope.ServiceProvider.GetServices() - .ToImmutableList(); + _scope = _provider.CreateScope(); + _extensions = _scope.ServiceProvider.GetServices() + .ToImmutableList(); - Logger.LogInformation("[Jailbreak] Found {@BehaviorCount} behaviors.", _extensions.Count); + Logger.LogInformation("[Jailbreak] Found {@BehaviorCount} behaviors.", _extensions.Count); - foreach (IPluginBehavior 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("[Jailbreak] Loaded behavior {@Behavior}", extension.GetType().FullName); - } + Logger.LogInformation("[Jailbreak] Loaded behavior {@Behavior}", extension.GetType().FullName); + } - base.Load(hotReload); - } + base.Load(hotReload); + } - public override void Unload(bool hotReload) - { - Logger.LogInformation("[Jailbreak] Shutting down..."); + /// + public override void Unload(bool hotReload) + { + Logger.LogInformation("[Jailbreak] Shutting down..."); - foreach (IPluginBehavior 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/Jailbreak/Jailbreak.csproj b/src/Jailbreak/Jailbreak.csproj index 2a615055..75360569 100644 --- a/src/Jailbreak/Jailbreak.csproj +++ b/src/Jailbreak/Jailbreak.csproj @@ -32,14 +32,14 @@ - - - - - - - - + + + + + + + + diff --git a/src/Jailbreak/JailbreakServiceCollection.cs b/src/Jailbreak/JailbreakServiceCollection.cs index d1046809..0c2e225a 100644 --- a/src/Jailbreak/JailbreakServiceCollection.cs +++ b/src/Jailbreak/JailbreakServiceCollection.cs @@ -1,14 +1,10 @@ -using System.Reflection; - -using CounterStrikeSharp.API.Core; - +using CounterStrikeSharp.API.Core; using Jailbreak.Config; using Jailbreak.Debug; using Jailbreak.English.Generic; using Jailbreak.English.Rebel; using Jailbreak.English.Teams; using Jailbreak.English.Warden; -using Jailbreak.Formatting.Languages; using Jailbreak.Formatting.Logistics; using Jailbreak.Generic; using Jailbreak.Logs; @@ -16,38 +12,36 @@ using Jailbreak.Rebel; using Jailbreak.Teams; using Jailbreak.Warden; - using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; namespace Jailbreak; /// -/// Class that auto-registers all jailbreak services and classes. +/// Class that auto-registers all jailbreak services and classes. /// public class JailbreakServiceCollection : IPluginServiceCollection { - /// - public void ConfigureServices(IServiceCollection serviceCollection) - { - // Do we want to make this scoped? - // Not sure how this will behave with multiple rounds and whatnot. - serviceCollection.AddTransient(); + /// + public void ConfigureServices(IServiceCollection serviceCollection) + { + // Do we want to make this scoped? + // Not sure how this will behave with multiple rounds and whatnot. + serviceCollection.AddTransient(); - serviceCollection.AddJailbreakGeneric(); - serviceCollection.AddJailbreakLogs(); - serviceCollection.AddJailbreakWarden(); - serviceCollection.AddJailbreakTeams(); - serviceCollection.AddJailbreakRebel(); - serviceCollection.AddJailbreakDebug(); + serviceCollection.AddJailbreakGeneric(); + serviceCollection.AddJailbreakLogs(); + serviceCollection.AddJailbreakWarden(); + serviceCollection.AddJailbreakTeams(); + serviceCollection.AddJailbreakRebel(); + serviceCollection.AddJailbreakDebug(); - // Add in english localization - serviceCollection.AddLanguage(config => - { - config.WithGenericCommand(); - config.WithRatio(); - config.WithWarden(); - config.WithRebel(); - }); - } -} + // Add in english localization + serviceCollection.AddLanguage(config => + { + config.WithGenericCommand(); + config.WithRatio(); + config.WithWarden(); + config.WithRebel(); + }); + } +} \ No newline at end of file From be712655ba7edef0deb7d57af814a624d8f6ab6c Mon Sep 17 00:00:00 2001 From: MSWS Date: Mon, 5 Feb 2024 16:52:25 -0800 Subject: [PATCH 7/8] Fix merge issues --- mod/Jailbreak.Rebel/RebelManager.cs | 40 ------------------- .../Logistics/LanguageConfig.cs | 6 --- 2 files changed, 46 deletions(-) diff --git a/mod/Jailbreak.Rebel/RebelManager.cs b/mod/Jailbreak.Rebel/RebelManager.cs index 458d0391..d25efb5c 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -49,23 +49,6 @@ public void Start(BasePlugin parent) }, TimerFlags.REPEAT); } - - private void OnTick() - { - foreach (var player in GetActiveRebels()) - { - if (!player.IsReal()) - continue; - - if (GetRebelTimeLeft(player) <= 0) - { - continue; - } - - SendTimeLeft(player); - } - } - public ISet GetActiveRebels() { return _rebelTimes.Keys.ToHashSet(); @@ -87,16 +70,6 @@ public bool MarkRebel(CCSPlayerController player, long time = 120) return true; } - - HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - rebelTimes.Remove(player); - return HookResult.Continue; - } - public void UnmarkRebel(CCSPlayerController player) { _notifs.NoLongerRebel.ToPlayerChat(player); @@ -169,19 +142,6 @@ private Color GetRebelColor(CCSPlayerController player) return color; } - private Color GetRebelColor(CCSPlayerController player) - { - var percent = GetRebelTimePercentage(player); - var percentRGB = 255 - (int)Math.Round(percent * 255.0); - var color = Color.FromArgb(254, 255, percentRGB, percentRGB); - if (percent <= 0) - { - color = Color.FromArgb(254, 255, 255, 255); - } - - return color; - } - private void ApplyRebelColor(CCSPlayerController player) { if (!player.IsReal() || player.Pawn.Value == null) diff --git a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs index 582bc3e0..e96df713 100644 --- a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs +++ b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs @@ -31,12 +31,6 @@ public void WithWarden() _collection.AddSingleton(); } - public void WithGenericCommand() - where TGenericCommand : class, ILanguage, IGenericCommandNotifications - { - _collection.AddSingleton(); - } - public void WithRebel() where TRebel : class, ILanguage, IRebelNotifications { From 70c0a7f95760adfaa4f6ae88a5a31c86fd2a45a4 Mon Sep 17 00:00:00 2001 From: Mooshua <43320783+mooshua@users.noreply.github.com> Date: Tue, 6 Feb 2024 11:32:35 -0800 Subject: [PATCH 8/8] Work on CI/CD for releases & nightlies, add GitVersion --- .github/release_template.md | 18 ++++++++++++++ .github/workflows/nightly.yml | 19 ++++++++------- .github/workflows/release.yml | 43 ++++++++++++++++++++++++++++++++++ src/Jailbreak/Jailbreak.cs | 4 ++-- src/Jailbreak/Jailbreak.csproj | 40 ++++++++++++++++++++++++++++++- 5 files changed, 112 insertions(+), 12 deletions(-) create mode 100644 .github/release_template.md create mode 100644 .github/workflows/release.yml diff --git a/.github/release_template.md b/.github/release_template.md new file mode 100644 index 00000000..05903d2e --- /dev/null +++ b/.github/release_template.md @@ -0,0 +1,18 @@ +[![EdgeGamers](https://cdn.edgm.io/images/brand/ego_text_blue.webp)](https://edgm.rs/)⠀⠀[![Discord](https://img.shields.io/discord/161245089774043136?style=for-the-badge&logo=discord&logoColor=%23ffffff&label=Join%20Our%20Discord&color=%235865F2 +)](https://edgm.rs/discord)⠀⠀[![Commits](https://img.shields.io/badge/COMMITS-gray?style=for-the-badge&logo=git&logoColor=%23fff&color=f05032)](https://github.com/edgegamers/Jailbreak/commits/1.0.0) + +## Major Changes +- **⚙️ Server** +- **👮 Guards** +- **🎃 Prisoners** +- **🛕 Maps** + +## Installing + +To install Jailbreak, download the `jailbreak.zip` file below and extract it into your CounterStrikeSharp `plugins` directory. +Jailbreak is ready-to-run out of the box without any additional configuration. + +## Known Issues + +*No known issues yet!* +To report a bug or issue with this release, please [open an issue](https://github.com/edgegamers/Jailbreak/issues) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index fbe2cec8..f4ff3466 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -7,34 +7,35 @@ on: [push, pull_request] jobs: build: - runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 - - name: Insert Job Version - run: sed -i "s/{GIT_VERSION}/${{github.run_number}}/g" src/Jailbreak/Jailbreak.cs - + with: + fetch-depth: 0 + fetch-tags: true + show-progress: true, + - name: Setup .NET SDK uses: actions/setup-dotnet@v4 with: dotnet-version: 8.0.x + - run: | dotnet restore dotnet build src/Jailbreak/Jailbreak.csproj --no-restore dotnet publish src/Jailbreak/Jailbreak.csproj --no-build --no-restore - + - uses: actions/upload-artifact@v4.0.0 with: name: jailbreak-nightly - path: build + path: build/Jailbreak # If build didn't put any artifacts in the build folder, consider it an error if-no-files-found: error post_webhook: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/dev' - + steps: - name: POST Webhook run: | @@ -42,4 +43,4 @@ jobs: --fail \ -F token=${{ secrets.GITLAB_SECRET_TOKEN }} \ -F ref=dev \ - https://gitlab.edgegamers.io/api/v4/projects/2594/trigger/pipeline \ No newline at end of file + https://gitlab.edgegamers.io/api/v4/projects/2594/trigger/pipeline diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..11c0b5b6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,43 @@ +name: Release + +on: + push: + branches-ignore: + - "*" + tags: + - "*" + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true + show-progress: true, + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - run: | + dotnet restore + dotnet build src/Jailbreak/Jailbreak.csproj --no-restore + dotnet publish src/Jailbreak/Jailbreak.csproj --no-build --no-restore + + - uses: actions/upload-artifact@v4.0.0 + with: + name: jailbreak + path: build/Jailbreak + # If build didn't put any artifacts in the build folder, consider it an error + if-no-files-found: error + + - name: Release + uses: softprops/action-gh-release@v1 + with: + draft: true + fail_on_unmatched_files: true + files: build/Jailbreak.zip + body_path: .github/release_template.md diff --git a/src/Jailbreak/Jailbreak.cs b/src/Jailbreak/Jailbreak.cs index 1bd605e4..90934284 100644 --- a/src/Jailbreak/Jailbreak.cs +++ b/src/Jailbreak/Jailbreak.cs @@ -29,7 +29,7 @@ public Jailbreak(IServiceProvider provider) public override string ModuleName => "Jailbreak"; /// - public override string ModuleVersion => "1.0.0.{GIT_VERSION}"; + public override string ModuleVersion => $"{GitVersionInformation.SemVer} ({GitVersionInformation.ShortSha})"; /// public override string ModuleAuthor => "EdgeGamers Development"; @@ -74,4 +74,4 @@ public override void Unload(bool hotReload) base.Unload(hotReload); } -} \ No newline at end of file +} diff --git a/src/Jailbreak/Jailbreak.csproj b/src/Jailbreak/Jailbreak.csproj index 2a615055..945c2eeb 100644 --- a/src/Jailbreak/Jailbreak.csproj +++ b/src/Jailbreak/Jailbreak.csproj @@ -18,10 +18,34 @@ true + + + + true + true + + false + false + false + + false + true + + $(GitVersion_ToolArgments) /verbosity Normal + $(GitVersion_ToolArgments) /overrideconfig mode=ContinuousDelivery + $(GitVersion_ToolArgments) /overrideconfig assembly-file-versioning-format="{SemVer}" + $(GitVersion_ToolArgments) /overrideconfig assembly-versioning-format="{Major}.{Minor}.{Patch}.{CommitsSinceVersionSource}" + $(GitVersion_ToolArgments) /overrideconfig assembly-informational-format="{FullSemVer}{EscapedBranchName}" + $(GitVersion_ToolArgments) /overrideconfig commit-message-incrementing=Disabled + $(GitVersion_ToolArgments) /overrideconfig increment=Patch + + - $(MSBuildThisFileDirectory)/../../build/Jailbreak + $(MSBuildThisFileDirectory)/../../build + $(PublishBaseDirectory)/Jailbreak + false false true @@ -42,4 +66,18 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + +