From ef2e9fe1ea325b82f579c6ccafb4957733cb632c Mon Sep 17 00:00:00 2001 From: Mooshua <43320783+mooshua@users.noreply.github.com> Date: Sat, 8 Jun 2024 19:17:32 -0700 Subject: [PATCH 01/27] Shared API Draft This exposes the current service provider as a plugin capability, allowing other plugins to fetch instantiated IPluginBehaviors. --- public/Jailbreak.Public/API.cs | 16 ++++++++++++++++ src/Jailbreak/Jailbreak.cs | 17 +++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 public/Jailbreak.Public/API.cs diff --git a/public/Jailbreak.Public/API.cs b/public/Jailbreak.Public/API.cs new file mode 100644 index 00000000..8f14661a --- /dev/null +++ b/public/Jailbreak.Public/API.cs @@ -0,0 +1,16 @@ +using CounterStrikeSharp.API.Core.Capabilities; + +namespace Jailbreak.Public; + +/// +/// The entry point to the Jailbreak API +/// +public static class API +{ + /// + /// Grants access to the currently running service provider, if there is one. + /// The service provider can be used to get instantiated IPluginBehaviors and other + /// objects exposed to Jailbreak mods + /// + public static PluginCapability Provider { get; } = new("jailbreak:core"); +} diff --git a/src/Jailbreak/Jailbreak.cs b/src/Jailbreak/Jailbreak.cs index 9b56f59d..75c744d8 100644 --- a/src/Jailbreak/Jailbreak.cs +++ b/src/Jailbreak/Jailbreak.cs @@ -1,5 +1,8 @@ using System.Collections.Immutable; using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core.Capabilities; + +using Jailbreak.Public; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Utils; using Microsoft.Extensions.DependencyInjection; @@ -15,7 +18,7 @@ public class Jailbreak : BasePlugin private IReadOnlyList? _extensions; private readonly IServiceProvider _provider; - private IServiceScope? _scope; + private IServiceScope? _scope = null; /// /// The Jailbreak plugin. @@ -47,7 +50,7 @@ public override void Load(bool hotReload) // manifest.AddResource("soundevents/explosion.vsnd"); // manifest.AddResource("soundevents/jihad.vsnd"); // }); - + // Load Managers FreezeManager.CreateInstance(this); @@ -70,6 +73,15 @@ public override void Load(bool hotReload) Logger.LogInformation("[Jailbreak] Loaded behavior {@Behavior}", extension.GetType().FullName); } + // Expose the scope to other plugins + Capabilities.RegisterPluginCapability(API.Provider, () => + { + if (this._scope == null) + throw new InvalidOperationException("Jailbreak does not have a running scope! Is the jailbreak plugin loaded?"); + + return this._scope.ServiceProvider; + }); + base.Load(hotReload); } @@ -85,6 +97,7 @@ public override void Unload(bool hotReload) // Dispose of original extensions scope // When loading again we will get a new scope to avoid leaking state. _scope?.Dispose(); + _scope = null; base.Unload(hotReload); } From 9ec0cd0a3086273e06e373f799a09f71f7c60d9a Mon Sep 17 00:00:00 2001 From: shook Date: Fri, 5 Jul 2024 11:19:12 -0500 Subject: [PATCH 02/27] Add cooldown to css_guard --- mod/Jailbreak.Teams/Queue/QueueBehavior.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs index bf23c043..8d5b9a24 100644 --- a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs +++ b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs @@ -23,6 +23,8 @@ public class QueueBehavior : IGuardQueue, IPluginBehavior private readonly IPlayerState _state; private BasePlugin _parent; + private readonly Dictionary _lastCommandUsage = new(); + public QueueBehavior(IPlayerStateFactory factory, IRatioNotifications notifications, ILogger logger) { _logger = logger; @@ -39,6 +41,16 @@ public bool TryEnterQueue(CCSPlayerController player) if (player.GetTeam() == CsTeam.CounterTerrorist) return false; + if (_lastCommandUsage.TryGetValue(player, out var lastUsage)) + { + var timeNextUsage = lastUsage.AddSeconds(10); + if (timeNextUsage > DateTime.Now) + { + _generics.CommandOnCooldown(timeNextUsage).ToPlayerChat(player); + return false; + } + } + var state = _state.Get(player); state.Position = ++_counter; state.InQueue = true; From 24eed96f81843e4b30d83e1165e59e847100ee28 Mon Sep 17 00:00:00 2001 From: shook Date: Tue, 9 Jul 2024 14:56:17 -0500 Subject: [PATCH 03/27] Add Support for Logging Weapons Drops --- .../Listeners/LogEntityParentListeners.cs | 56 +++++++++++++++++++ .../Extensions/WeaponExtensions.cs | 51 +++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs create mode 100644 public/Jailbreak.Public/Extensions/WeaponExtensions.cs diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs new file mode 100644 index 00000000..140330d3 --- /dev/null +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -0,0 +1,56 @@ +using CounterStrikeSharp.API; +using CounterStrikeSharp.API.Core; +using Jailbreak.Formatting.Views; +using Jailbreak.Public.Extensions; + +namespace Jailbreak.Logs.Listeners; + +public class LogEntityParentListeners +{ + private readonly IRichLogService _logs; + private BasePlugin parent; + private static readonly string[] weaponStrings = { + "weapon_ak47", "weapon_aug", "weapon_awp", "weapon_bizon", "weapon_cz75a", "weapon_deagle", "weapon_famas", "weapon_fiveseven", "weapon_g3sg1", "weapon_galilar", + "weapon_glock", "weapon_hkp2000", "weapon_m249", "weapon_m4a1", "weapon_m4a1_silencer", "weapon_m4a4", "weapon_mac10", "weapon_mag7", "weapon_mp5sd", "weapon_mp7", + "weapon_mp9", "weapon_negev", "weapon_nova", "weapon_p250", "weapon_p90", "weapon_revolver", "weapon_sawedoff", "weapon_scar20", "weapon_sg553", "weapon_sg556", + "weapon_ssg08", "weapon_taser", "weapon_tec9", "weapon_ump45", "weapon_usp_silencer", "weapon_xm1014" }; + + public LogEntityParentListeners(IRichLogService logs) + { + _logs = logs; + } + + public void Start(BasePlugin parent) + { + this.parent = parent; + + parent.RegisterListener(OnEntityParentChanged); + } + public void Dispose() + { + parent.RemoveListener("OnEntityParentChanged", OnEntityParentChanged); + } + public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) + { + if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; + + var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); + if (weaponEntity == null) return; + + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); + if (weaponOwner == null) return; + + if (!newParent.IsValid) //a.k.a parent is world + { + _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); + } + + if (newParent.IsValid) + { + var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); + if (weaponPickerUpper == null) return; + + _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); + } + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/WeaponExtensions.cs b/public/Jailbreak.Public/Extensions/WeaponExtensions.cs new file mode 100644 index 00000000..ae478adc --- /dev/null +++ b/public/Jailbreak.Public/Extensions/WeaponExtensions.cs @@ -0,0 +1,51 @@ +using CounterStrikeSharp.API.Core; + +namespace Jailbreak.Public.Extensions; + +public static class WeaponExtensions +{ + public static string ToFriendlyString(this CCSWeaponBase weaponEntity) + { + var designerName = weaponEntity.DesignerName; + switch (designerName) + { + case "weapon_ak47": return "AK47"; + case "weapon_aug": return "AUG"; + case "weapon_awp": return "AWP"; + case "weapon_bizon": return "Bizon"; + case "weapon_cz75a": return "CZ75"; + case "weapon_deagle": return "Desert Eagle"; + case "weapon_famas": return "Famas"; + case "weapon_fiveseven": return "Five Seven"; + case "weapon_g3sg1": return "G3SG1"; + case "weapon_galilar": return "Galil"; + case "weapon_glock": return "Glock 18"; + case "weapon_hkp2000": return "HPK2000"; + case "weapon_m249": return "M249"; + case "weapon_m4a1": return "M4A1"; + case "weapon_m4a1_silencer": return "M4A1S"; + case "weapon_m4a4": return "M4A4"; + case "weapon_mac10": return "MAC10"; + case "weapon_mag7": return "MAG7"; + case "weapon_mp5sd": return "MP5SD"; + case "weapon_mp7": return "MP7"; + case "weapon_mp9": return "MP9"; + case "weapon_negev": return "Negev"; + case "weapon_nova": return "Nova"; + case "weapon_p250": return "P250"; + case "weapon_p90": return "P90"; + case "weapon_revolver": return "Revolver"; + case "weapon_sawedoff": return "Sawed Off"; + case "weapon_scar20": return "Scar20"; + case "weapon_sg553": return "SG553"; + case "weapon_sg556": return "SG556"; + case "weapon_ssg08": return "SSG08"; + case "weapon_taser": return "Zeus"; + case "weapon_tec9": return "Tec9"; + case "weapon_ump45": return "UMP45"; + case "weapon_usp_silencer": return "USPS"; + case "weapon_xm1014": return "XM1014"; + default: return "UNKNOWN: Pleace Contact Tech"; + } + } +} \ No newline at end of file From 6fa852beb4a934de90e56cfcedbd893f954b8bcc Mon Sep 17 00:00:00 2001 From: ntm <35658945+ntm5@users.noreply.github.com> Date: Wed, 10 Jul 2024 00:52:56 +0200 Subject: [PATCH 04/27] Remove redudant variable --- mod/Jailbreak.LastGuard/LastGuard.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index 34389520..87f22fbf 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -65,12 +65,12 @@ public int CalculateHealth() public void StartLastGuard(CCSPlayerController lastGuard) { - var ctPlayerPawn = lastGuard.PlayerPawn.Value; + var guardPlayerPawn = lastGuard.PlayerPawn.Value; if (ctPlayerPawn == null || !ctPlayerPawn.IsValid) return; - var ctHealth = ctPlayerPawn.Health; - var ctCalcHealth = CalculateHealth(); + var guardHealth = ctPlayerPawn.Health; + var guardCalcHealth = CalculateHealth(); ctPlayerPawn.Health = ctHealth > ctCalcHealth ? 125 : ctCalcHealth; Utilities.SetStateChanged(ctPlayerPawn, "CBaseEntity", "m_iHealth"); @@ -81,10 +81,9 @@ public void StartLastGuard(CCSPlayerController lastGuard) var aliveTerrorists = Utilities.GetPlayers() .Where(p => p.IsReal() && p is { PawnIsAlive: true, Team: CsTeam.Terrorist }).ToList(); - var guardHp = lastGuard.PlayerPawn?.Value?.Health ?? 0; var prisonerHp = aliveTerrorists.Sum(prisoner => prisoner.PlayerPawn?.Value?.Health ?? 0); - notifications.LG_STARTED(guardHp, prisonerHp).ToAllCenter().ToAllChat(); + notifications.LG_STARTED(guardHealth, prisonerHp).ToAllCenter().ToAllChat(); if (string.IsNullOrEmpty(config.LastGuardWeapon)) return; @@ -93,4 +92,4 @@ public void StartLastGuard(CCSPlayerController lastGuard) player.GiveNamedItem(config.LastGuardWeapon); } } -} \ No newline at end of file +} From d334dd98265786549133069dec31e83b5e798497 Mon Sep 17 00:00:00 2001 From: ntm <35658945+ntm5@users.noreply.github.com> Date: Wed, 10 Jul 2024 00:56:26 +0200 Subject: [PATCH 05/27] Fix namings --- mod/Jailbreak.LastGuard/LastGuard.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index 87f22fbf..694da38e 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -67,13 +67,13 @@ public void StartLastGuard(CCSPlayerController lastGuard) { var guardPlayerPawn = lastGuard.PlayerPawn.Value; - if (ctPlayerPawn == null || !ctPlayerPawn.IsValid) return; + if (guardPlayerPawn == null || !guardPlayerPawn.IsValid) return; - var guardHealth = ctPlayerPawn.Health; + var guardHealth = guardPlayerPawn.Health; var guardCalcHealth = CalculateHealth(); - ctPlayerPawn.Health = ctHealth > ctCalcHealth ? 125 : ctCalcHealth; - Utilities.SetStateChanged(ctPlayerPawn, "CBaseEntity", "m_iHealth"); + ctPlayerPawn.Health = guardHealth > guardCalcHealth ? 125 : guardHealth; + Utilities.SetStateChanged(guardPlayerPawn, "CBaseEntity", "m_iHealth"); // foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) // player.ExecuteClientCommand("play sounds/lastct"); From d9b49566c26a39dede42314e62681c565563c44d Mon Sep 17 00:00:00 2001 From: ntm <35658945+ntm5@users.noreply.github.com> Date: Wed, 10 Jul 2024 00:58:04 +0200 Subject: [PATCH 06/27] Actually fix var names --- mod/Jailbreak.LastGuard/LastGuard.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index 694da38e..af4b31fd 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -72,7 +72,7 @@ public void StartLastGuard(CCSPlayerController lastGuard) var guardHealth = guardPlayerPawn.Health; var guardCalcHealth = CalculateHealth(); - ctPlayerPawn.Health = guardHealth > guardCalcHealth ? 125 : guardHealth; + guardPlayerPawn.Health = guardHealth > guardCalcHealth ? 125 : guardHealth; Utilities.SetStateChanged(guardPlayerPawn, "CBaseEntity", "m_iHealth"); // foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) From e0ab07f27bbfd9145ab1fa3db6b5f9fc2e480c49 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 10:04:54 -0500 Subject: [PATCH 07/27] Revert "Add cooldown to css_guard" This reverts commit 9ec0cd0a3086273e06e373f799a09f71f7c60d9a. --- mod/Jailbreak.Teams/Queue/QueueBehavior.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs index 8d5b9a24..bf23c043 100644 --- a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs +++ b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs @@ -23,8 +23,6 @@ public class QueueBehavior : IGuardQueue, IPluginBehavior private readonly IPlayerState _state; private BasePlugin _parent; - private readonly Dictionary _lastCommandUsage = new(); - public QueueBehavior(IPlayerStateFactory factory, IRatioNotifications notifications, ILogger logger) { _logger = logger; @@ -41,16 +39,6 @@ public bool TryEnterQueue(CCSPlayerController player) if (player.GetTeam() == CsTeam.CounterTerrorist) return false; - if (_lastCommandUsage.TryGetValue(player, out var lastUsage)) - { - var timeNextUsage = lastUsage.AddSeconds(10); - if (timeNextUsage > DateTime.Now) - { - _generics.CommandOnCooldown(timeNextUsage).ToPlayerChat(player); - return false; - } - } - var state = _state.Get(player); state.Position = ++_counter; state.InQueue = true; From 40c7e45a4df471966047b6ae6c0ac8a530b55656 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 10:10:12 -0500 Subject: [PATCH 08/27] Early Return --- .../Listeners/LogEntityParentListeners.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 140330d3..21e251e4 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -43,14 +43,12 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc if (!newParent.IsValid) //a.k.a parent is world { _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); + return; } - if (newParent.IsValid) - { - var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); - if (weaponPickerUpper == null) return; + var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); + if (weaponPickerUpper == null) return; - _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); - } + _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From 15798834ad95dd9a75abd6a8a3f742b6c89fb90b Mon Sep 17 00:00:00 2001 From: ntm <35658945+ntm5@users.noreply.github.com> Date: Thu, 11 Jul 2024 00:59:49 +0200 Subject: [PATCH 09/27] Set health to calculated health no matter what --- mod/Jailbreak.LastGuard/LastGuard.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index af4b31fd..e668746f 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -69,10 +69,9 @@ public void StartLastGuard(CCSPlayerController lastGuard) if (guardPlayerPawn == null || !guardPlayerPawn.IsValid) return; - var guardHealth = guardPlayerPawn.Health; var guardCalcHealth = CalculateHealth(); - guardPlayerPawn.Health = guardHealth > guardCalcHealth ? 125 : guardHealth; + guardPlayerPawn.Health = guardCalcHealth; Utilities.SetStateChanged(guardPlayerPawn, "CBaseEntity", "m_iHealth"); // foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) @@ -83,7 +82,7 @@ public void StartLastGuard(CCSPlayerController lastGuard) var prisonerHp = aliveTerrorists.Sum(prisoner => prisoner.PlayerPawn?.Value?.Health ?? 0); - notifications.LG_STARTED(guardHealth, prisonerHp).ToAllCenter().ToAllChat(); + notifications.LG_STARTED(guardCalcHealth, prisonerHp).ToAllCenter().ToAllChat(); if (string.IsNullOrEmpty(config.LastGuardWeapon)) return; From 3a4fbe9fa088fdb20c99cb0c82eb8b25e1a4cc4c Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 20:23:18 -0500 Subject: [PATCH 10/27] implement plugin behavior --- mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 21e251e4..d05b2c7e 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -1,11 +1,12 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using Jailbreak.Formatting.Views; +using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; namespace Jailbreak.Logs.Listeners; -public class LogEntityParentListeners +public class LogEntityParentListeners : IPluginBehavior { private readonly IRichLogService _logs; private BasePlugin parent; From 17fb91b69089f105a2757176a15febfe7a22e7a7 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 20:37:26 -0500 Subject: [PATCH 11/27] Debug --- .../Listeners/LogEntityParentListeners.cs | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index d05b2c7e..c426b7dc 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -26,6 +26,7 @@ public void Start(BasePlugin parent) this.parent = parent; parent.RegisterListener(OnEntityParentChanged); + Server.PrintToChatAll("Listener Registered"); } public void Dispose() { @@ -33,23 +34,35 @@ public void Dispose() } public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) { + Server.PrintToChatAll("Function Called"); if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null) return; - - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); - if (weaponOwner == null) return; - - if (!newParent.IsValid) //a.k.a parent is world + if (weaponEntity == null) + { + Server.PrintToChatAll("weaponEntity null"); + return; + } + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Get().Index); + if (weaponOwner == null) + { + Server.PrintToChatAll("weaponOwner null"); + return; + } + if (!newParent.IsValid) //a.k.a parent is world { + Server.PrintToChatAll("log drop"); _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); return; } var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); - if (weaponPickerUpper == null) return; - + if (weaponPickerUpper == null) + { + Server.PrintToChatAll("weaponPickerUpper null"); + return; + } + Server.PrintToChatAll("Log pickup"); _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From e52de1264deaad0697c6d232d1baae3f2c0b4362 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 20:38:51 -0500 Subject: [PATCH 12/27] Revert "Debug" This reverts commit 17fb91b69089f105a2757176a15febfe7a22e7a7. --- .../Listeners/LogEntityParentListeners.cs | 29 +++++-------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index c426b7dc..d05b2c7e 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -26,7 +26,6 @@ public void Start(BasePlugin parent) this.parent = parent; parent.RegisterListener(OnEntityParentChanged); - Server.PrintToChatAll("Listener Registered"); } public void Dispose() { @@ -34,35 +33,23 @@ public void Dispose() } public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) { - Server.PrintToChatAll("Function Called"); if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null) - { - Server.PrintToChatAll("weaponEntity null"); - return; - } - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Get().Index); - if (weaponOwner == null) - { - Server.PrintToChatAll("weaponOwner null"); - return; - } - if (!newParent.IsValid) //a.k.a parent is world + if (weaponEntity == null) return; + + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); + if (weaponOwner == null) return; + + if (!newParent.IsValid) //a.k.a parent is world { - Server.PrintToChatAll("log drop"); _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); return; } var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); - if (weaponPickerUpper == null) - { - Server.PrintToChatAll("weaponPickerUpper null"); - return; - } - Server.PrintToChatAll("Log pickup"); + if (weaponPickerUpper == null) return; + _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From 2221464e0609f56320ad32e7bf733ad84e7fb471 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 20:40:42 -0500 Subject: [PATCH 13/27] debug --- .../Listeners/LogEntityParentListeners.cs | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index d05b2c7e..5b57a725 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -26,6 +26,7 @@ public void Start(BasePlugin parent) this.parent = parent; parent.RegisterListener(OnEntityParentChanged); + Server.PrintToChatAll("Debug 1"); } public void Dispose() { @@ -36,20 +37,32 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null) return; + if (weaponEntity == null) + { + Server.PrintToChatAll("Debug 2"); + return; + } - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); - if (weaponOwner == null) return; + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Get().Index); + if (weaponOwner == null) { + Server.PrintToChatAll("Debug 3"); + return; + } if (!newParent.IsValid) //a.k.a parent is world { _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); + Server.PrintToChatAll("Debug 4"); return; } var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); - if (weaponPickerUpper == null) return; - + if (weaponPickerUpper == null) + { + Server.PrintToChatAll("Debug 5"); + return; + } + Server.PrintToChatAll("Debug 6"); _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From 9a0b73f62a410ab2313f5d3eaaa8d69ef3b538b4 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 20:51:31 -0500 Subject: [PATCH 14/27] Actually register properly --- mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs | 5 +++-- mod/Jailbreak.Logs/LogsServiceExtension.cs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 5b57a725..fd2811a7 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -28,12 +28,13 @@ public void Start(BasePlugin parent) parent.RegisterListener(OnEntityParentChanged); Server.PrintToChatAll("Debug 1"); } - public void Dispose() + /*public void Dispose() { parent.RemoveListener("OnEntityParentChanged", OnEntityParentChanged); - } + }*/ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) { + Server.PrintToChatAll("Debug 7"); if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); diff --git a/mod/Jailbreak.Logs/LogsServiceExtension.cs b/mod/Jailbreak.Logs/LogsServiceExtension.cs index 6918ea04..8aece7b5 100644 --- a/mod/Jailbreak.Logs/LogsServiceExtension.cs +++ b/mod/Jailbreak.Logs/LogsServiceExtension.cs @@ -18,9 +18,10 @@ public static void AddJailbreakLogs(this IServiceCollection services) services.AddPluginBehavior(); services.AddPluginBehavior(); + services.AddPluginBehavior(); - // PlayerTagHelper is a lower-level class that avoids dependency loops. - services.AddTransient(); + // PlayerTagHelper is a lower-level class that avoids dependency loops. + services.AddTransient(); services.AddTransient(); } } From 0bda3d046748c345957cb897e5f54441cf496a93 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 21:10:34 -0500 Subject: [PATCH 15/27] fix errors --- .../Listeners/LogEntityParentListeners.cs | 24 ++++--------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index fd2811a7..217f791b 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -26,7 +26,6 @@ public void Start(BasePlugin parent) this.parent = parent; parent.RegisterListener(OnEntityParentChanged); - Server.PrintToChatAll("Debug 1"); } /*public void Dispose() { @@ -34,36 +33,23 @@ public void Start(BasePlugin parent) }*/ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) { - Server.PrintToChatAll("Debug 7"); if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null) - { - Server.PrintToChatAll("Debug 2"); - return; - } + if (weaponEntity == null || weaponEntity.PrevOwner == null) return; - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Get().Index); - if (weaponOwner == null) { - Server.PrintToChatAll("Debug 3"); - return; - } + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); + if (weaponOwner == null) return; if (!newParent.IsValid) //a.k.a parent is world { _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); - Server.PrintToChatAll("Debug 4"); return; } var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); - if (weaponPickerUpper == null) - { - Server.PrintToChatAll("Debug 5"); - return; - } - Server.PrintToChatAll("Debug 6"); + if (weaponPickerUpper == null) return; + _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From 874e2bf3ee4ccefd559da4cf03e7dbfa0da17dc8 Mon Sep 17 00:00:00 2001 From: shook Date: Wed, 10 Jul 2024 21:30:29 -0500 Subject: [PATCH 16/27] more debugging --- mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 217f791b..741c5d1a 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -38,8 +38,10 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); if (weaponEntity == null || weaponEntity.PrevOwner == null) return; - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); + var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); if (weaponOwner == null) return; + Server.PrintToChatAll($"{weaponOwner.PlayerName}"); + Server.PrintToChatAll($"{(int)weaponEntity.PrevOwner.Index}"); if (!newParent.IsValid) //a.k.a parent is world { @@ -47,7 +49,7 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc return; } - var weaponPickerUpper = Utilities.GetEntityFromIndex((int)(newParent.Index)); + var weaponPickerUpper = Utilities.GetEntityFromIndex((int)newParent.Index); if (weaponPickerUpper == null) return; _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); From ab2ba89a04e9262384668419ee9c970d1f6ae73d Mon Sep 17 00:00:00 2001 From: MSWS Date: Wed, 10 Jul 2024 19:42:02 -0700 Subject: [PATCH 17/27] Start applying same styling on new logs --- .../Listeners/LogEntityParentListeners.cs | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 741c5d1a..3a82e1d7 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -1,31 +1,25 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; namespace Jailbreak.Logs.Listeners; -public class LogEntityParentListeners : IPluginBehavior -{ - private readonly IRichLogService _logs; - private BasePlugin parent; - private static readonly string[] weaponStrings = { +public class LogEntityParentListeners(IRichLogService logs) : IPluginBehavior { + private BasePlugin parent = null!; + private static readonly string[] WEAPON_STRINGS = { "weapon_ak47", "weapon_aug", "weapon_awp", "weapon_bizon", "weapon_cz75a", "weapon_deagle", "weapon_famas", "weapon_fiveseven", "weapon_g3sg1", "weapon_galilar", "weapon_glock", "weapon_hkp2000", "weapon_m249", "weapon_m4a1", "weapon_m4a1_silencer", "weapon_m4a4", "weapon_mac10", "weapon_mag7", "weapon_mp5sd", "weapon_mp7", "weapon_mp9", "weapon_negev", "weapon_nova", "weapon_p250", "weapon_p90", "weapon_revolver", "weapon_sawedoff", "weapon_scar20", "weapon_sg553", "weapon_sg556", "weapon_ssg08", "weapon_taser", "weapon_tec9", "weapon_ump45", "weapon_usp_silencer", "weapon_xm1014" }; - public LogEntityParentListeners(IRichLogService logs) + public void Start(BasePlugin _parent) { - _logs = logs; - } - - public void Start(BasePlugin parent) - { - this.parent = parent; + parent = _parent; - parent.RegisterListener(OnEntityParentChanged); + _parent.RegisterListener(OnEntityParentChanged); } /*public void Dispose() { @@ -33,7 +27,7 @@ public void Start(BasePlugin parent) }*/ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) { - if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; + if (!affectedEntity.IsValid || !WEAPON_STRINGS.Contains(affectedEntity.DesignerName)) return; var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); if (weaponEntity == null || weaponEntity.PrevOwner == null) return; @@ -45,13 +39,13 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc if (!newParent.IsValid) //a.k.a parent is world { - _logs.Append(_logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); + logs.Append(logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); return; } var weaponPickerUpper = Utilities.GetEntityFromIndex((int)newParent.Index); if (weaponPickerUpper == null) return; - _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); + logs.Append(logs.Player(weaponPickerUpper), "picked up", logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); } } \ No newline at end of file From f2cda40e9bb5794fa7327021e5ff552f8ee7f821 Mon Sep 17 00:00:00 2001 From: MSWS Date: Wed, 10 Jul 2024 19:47:20 -0700 Subject: [PATCH 18/27] Fix build --- mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 3a82e1d7..20d9ff37 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -1,7 +1,6 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using Jailbreak.Formatting.Views; -using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; From c23b87455291a7ffc54e864bbfd1e8f25b875555 Mon Sep 17 00:00:00 2001 From: MSWS Date: Wed, 10 Jul 2024 19:48:50 -0700 Subject: [PATCH 19/27] Re-apply formatting --- .../Listeners/LogEntityParentListeners.cs | 84 +++++++++++-------- 1 file changed, 51 insertions(+), 33 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 20d9ff37..07e8e029 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -7,44 +7,62 @@ namespace Jailbreak.Logs.Listeners; public class LogEntityParentListeners(IRichLogService logs) : IPluginBehavior { - private BasePlugin parent = null!; - private static readonly string[] WEAPON_STRINGS = { - "weapon_ak47", "weapon_aug", "weapon_awp", "weapon_bizon", "weapon_cz75a", "weapon_deagle", "weapon_famas", "weapon_fiveseven", "weapon_g3sg1", "weapon_galilar", - "weapon_glock", "weapon_hkp2000", "weapon_m249", "weapon_m4a1", "weapon_m4a1_silencer", "weapon_m4a4", "weapon_mac10", "weapon_mag7", "weapon_mp5sd", "weapon_mp7", - "weapon_mp9", "weapon_negev", "weapon_nova", "weapon_p250", "weapon_p90", "weapon_revolver", "weapon_sawedoff", "weapon_scar20", "weapon_sg553", "weapon_sg556", - "weapon_ssg08", "weapon_taser", "weapon_tec9", "weapon_ump45", "weapon_usp_silencer", "weapon_xm1014" }; - - public void Start(BasePlugin _parent) - { - parent = _parent; + private BasePlugin parent = null!; - _parent.RegisterListener(OnEntityParentChanged); - } - /*public void Dispose() - { - parent.RemoveListener("OnEntityParentChanged", OnEntityParentChanged); - }*/ - public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) - { - if (!affectedEntity.IsValid || !WEAPON_STRINGS.Contains(affectedEntity.DesignerName)) return; + private static readonly string[] WEAPON_STRINGS = [ + "weapon_ak47", "weapon_aug", "weapon_awp", "weapon_bizon", "weapon_cz75a", + "weapon_deagle", "weapon_famas", "weapon_fiveseven", "weapon_g3sg1", + "weapon_galilar", "weapon_glock", "weapon_hkp2000", "weapon_m249", + "weapon_m4a1", "weapon_m4a1_silencer", "weapon_m4a4", "weapon_mac10", + "weapon_mag7", "weapon_mp5sd", "weapon_mp7", "weapon_mp9", "weapon_negev", + "weapon_nova", "weapon_p250", "weapon_p90", "weapon_revolver", + "weapon_sawedoff", "weapon_scar20", "weapon_sg553", "weapon_sg556", + "weapon_ssg08", "weapon_taser", "weapon_tec9", "weapon_ump45", + "weapon_usp_silencer", "weapon_xm1014" + ]; - var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null || weaponEntity.PrevOwner == null) return; + public void Start(BasePlugin _parent) { + parent = _parent; - var weaponOwner = Utilities.GetEntityFromIndex((int)weaponEntity.PrevOwner.Index); - if (weaponOwner == null) return; - Server.PrintToChatAll($"{weaponOwner.PlayerName}"); - Server.PrintToChatAll($"{(int)weaponEntity.PrevOwner.Index}"); + _parent + .RegisterListener< + CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( + OnEntityParentChanged); + } - if (!newParent.IsValid) //a.k.a parent is world - { - logs.Append(logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); - return; - } + /*public void Dispose() + { + parent.RemoveListener("OnEntityParentChanged", OnEntityParentChanged); + }*/ + public void OnEntityParentChanged(CEntityInstance affectedEntity, + CEntityInstance newParent) { + if (!affectedEntity.IsValid + || !WEAPON_STRINGS.Contains(affectedEntity.DesignerName)) + return; - var weaponPickerUpper = Utilities.GetEntityFromIndex((int)newParent.Index); - if (weaponPickerUpper == null) return; + var weaponEntity = + Utilities.GetEntityFromIndex((int)affectedEntity.Index); + if (weaponEntity == null || weaponEntity.PrevOwner == null) return; - logs.Append(logs.Player(weaponPickerUpper), "picked up", logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); + var weaponOwner = + Utilities.GetEntityFromIndex( + (int)weaponEntity.PrevOwner.Index); + if (weaponOwner == null) return; + Server.PrintToChatAll($"{weaponOwner.PlayerName}"); + Server.PrintToChatAll($"{(int)weaponEntity.PrevOwner.Index}"); + + if (!newParent.IsValid) //a.k.a parent is world + { + logs.Append(logs.Player(weaponOwner), + $"dropped their {weaponEntity.ToFriendlyString}"); + return; } + + var weaponPickerUpper = + Utilities.GetEntityFromIndex((int)newParent.Index); + if (weaponPickerUpper == null) return; + + logs.Append(logs.Player(weaponPickerUpper), "picked up", + logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); + } } \ No newline at end of file From 25ad1db32c1a361d203e36c86e3d938ce3be92d5 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 10 Jul 2024 20:04:05 -0700 Subject: [PATCH 20/27] Cleanup/july (#213) Cleanup --- Formatting.DotSettings | 82 +++ Jailbreak.sln.DotSettings | 9 + .../Generic/GenericCommandNotifications.cs | 89 ++- .../Jailbreak.English.csproj | 6 +- .../LastGuard/LastGuardNotifications.cs | 41 +- .../LastRequest/LastRequestMessages.cs | 146 ++-- .../LastRequest/RaceLRMessages.cs | 46 +- lang/Jailbreak.English/Logs/LogMessages.cs | 44 +- lang/Jailbreak.English/Mute/PeaceMessages.cs | 121 ++-- .../Rebel/JihadC4Notifications.cs | 35 +- .../Rebel/RebelNotifications.cs | 24 +- .../Warden/RollCommandNotifications.cs | 24 +- .../Warden/SpecialTreatmentNotifications.cs | 54 +- .../Warden/WardenNotifications.cs | 182 ++--- mod/Jailbreak.Debug/DebugCommand.cs | 57 +- mod/Jailbreak.Debug/DebugServiceExtension.cs | 10 +- mod/Jailbreak.Debug/Jailbreak.Debug.csproj | 12 +- .../Subcommands/AbstractCommand.cs | 246 ++++--- mod/Jailbreak.Debug/Subcommands/LastGuard.cs | 39 +- .../Subcommands/LastRequest.cs | 138 ++-- mod/Jailbreak.Debug/Subcommands/MarkRebel.cs | 42 +- mod/Jailbreak.Debug/Subcommands/MarkST.cs | 37 +- mod/Jailbreak.Debug/Subcommands/Pardon.cs | 28 +- .../Subcommands/WrappedInfo.cs | 32 +- mod/Jailbreak.LastGuard/LastGuard.cs | 12 +- mod/Jailbreak.LastGuard/LastGuardConfig.cs | 7 +- .../LastGuardServiceExtension.cs | 12 +- mod/Jailbreak.LastRequest/EndRaceCommand.cs | 39 +- .../Jailbreak.LastRequest.csproj | 8 +- .../LastRequestCommand.cs | 217 +++--- .../LastRequestConfig.cs | 5 +- .../LastRequestExtension.cs | 21 +- .../LastRequestFactory.cs | 63 +- .../LastRequestManager.cs | 440 ++++++------ .../LastRequestMenuSelector.cs | 45 +- .../LastRequestPlayerSelector.cs | 67 +- .../LastRequests/Coinflip.cs | 152 ++--- .../LastRequests/GunToss.cs | 52 +- .../LastRequests/KnifeFight.cs | 34 +- .../LastRequests/MagForMag.cs | 230 +++---- .../LastRequests/NoScope.cs | 148 ++-- .../LastRequests/Race.cs | 183 +++-- .../LastRequests/RockPaperScissors.cs | 197 +++--- .../LastRequests/ShotForShot.cs | 224 +++--- .../LastRequests/TeleportingRequest.cs | 32 +- .../LastRequests/WeaponizedRequest.cs | 64 +- mod/Jailbreak.Logs/Jailbreak.Logs.csproj | 8 +- .../Listeners/LogDamageListeners.cs | 107 ++- .../Listeners/LogEntityListeners.cs | 71 +- .../Listeners/LogEntityParentListeners.cs | 6 +- mod/Jailbreak.Logs/LogsCommand.cs | 14 +- mod/Jailbreak.Logs/LogsManager.cs | 140 ++-- mod/Jailbreak.Logs/LogsServiceExtension.cs | 24 +- mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs | 72 +- mod/Jailbreak.Mute/Jailbreak.Mute.csproj | 8 +- mod/Jailbreak.Mute/MuteServiceExtension.cs | 10 +- mod/Jailbreak.Mute/MuteSystem.cs | 369 +++++----- mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj | 8 +- .../JihadC4/JihadC4Behavior.cs | 345 +++++----- mod/Jailbreak.Rebel/RebelListener.cs | 37 +- mod/Jailbreak.Rebel/RebelManager.cs | 249 +++---- mod/Jailbreak.Rebel/RebelServiceExtension.cs | 16 +- .../Commands/PeaceCommandsBehavior.cs | 65 +- .../Commands/RollCommandBehavior.cs | 76 +-- .../SpecialTreatmentCommandsBehavior.cs | 95 ++- .../Commands/WardenCommandsBehavior.cs | 260 +++---- .../WardenFormatWriterExtensions.cs | 4 +- mod/Jailbreak.Warden/Global/WardenBehavior.cs | 645 ++++++++---------- mod/Jailbreak.Warden/Jailbreak.Warden.csproj | 8 +- .../Markers/WardenMarkerBehavior.cs | 99 ++- .../Paint/WardenPaintBehavior.cs | 195 +++--- .../Selection/QueueFavorState.cs | 16 +- mod/Jailbreak.Warden/Selection/QueueState.cs | 11 +- .../Selection/WardenSelectionBehavior.cs | 248 +++---- .../SpecialTreatmentBehavior.cs | 123 ++-- mod/Jailbreak.Warden/WardenConfig.cs | 11 +- .../WardenServiceExtension.cs | 34 +- public/Jailbreak.Formatting/Base/IView.cs | 5 +- .../Jailbreak.Formatting/Base/SimpleView.cs | 89 +-- .../Jailbreak.Formatting/Core/FormatObject.cs | 88 ++- .../Jailbreak.Formatting/Core/FormatWriter.cs | 31 +- .../Extensions/ViewExtensions.cs | 129 ++-- .../Jailbreak.Formatting.csproj | 6 +- .../Jailbreak.Formatting/Languages/English.cs | 4 +- .../Logistics/IDialect.cs | 8 +- .../Logistics/ILanguage.cs | 9 +- .../Logistics/LanguageConfig.cs | 139 ++-- .../Logistics/RegisterLanguageExtensions.cs | 16 +- .../Objects/HiddenFormatObject.cs | 60 +- .../Objects/IntegerFormatObject.cs | 32 +- .../Objects/PlayerFormatObject.cs | 27 +- .../Objects/StringFormatObject.cs | 29 +- .../Objects/TreeFormatObject.cs | 139 ++-- .../Views/IGenericCommandNotifications.cs | 13 +- .../Views/IJihadC4Notifications.cs | 20 +- .../Views/ILastGuardNotifications.cs | 6 +- .../Views/ILastRequestMessages.cs | 23 +- .../Views/ILogMessages.cs | 41 +- .../Views/IPeaceMessages.cs | 31 +- .../Views/IRaceLRMessages.cs | 7 +- .../Views/IRebelNotifications.cs | 7 +- .../Views/IRollCommandNotications.cs | 5 +- .../Views/ISpecialDayNotifications.cs | 17 +- .../Views/ISpecialTreatmentNotifications.cs | 15 +- .../Views/ITeamsNotifications.cs | 21 +- .../Views/IWardenNotifications.cs | 79 +-- .../Views/Logging/IRichLogService.cs | 12 +- .../Views/Logging/IRichPlayerTag.cs | 20 +- public/Jailbreak.Public/API.cs | 20 +- .../Behaviors/IPluginBehavior.cs | 19 +- .../Configuration/IConfigService.cs | 22 +- .../Extensions/EntityIOExtensions.cs | 30 +- .../Extensions/PlayerExtensions.cs | 166 ++--- .../Extensions/ServerExtensions.cs | 45 +- .../Extensions/ServiceCollectionExtensions.cs | 104 +-- .../Extensions/StringExtensions.cs | 11 +- .../Extensions/VectorExtensions.cs | 77 +-- .../Jailbreak.Public/Generic/ICoroutines.cs | 17 +- .../Jailbreak.Public/Generic/IPlayerState.cs | 10 +- .../Generic/IPlayerStateFactory.cs | 42 +- .../Jailbreak.Public/Jailbreak.Public.csproj | 6 +- .../Mod/Damage/IBlockAllDamage.cs | 39 +- .../Jailbreak.Public/Mod/Draw/BeamCircle.cs | 101 ++- public/Jailbreak.Public/Mod/Draw/BeamLine.cs | 98 ++- .../Jailbreak.Public/Mod/Draw/BeamedShape.cs | 37 +- .../Mod/Draw/DrawableShape.cs | 47 +- .../Jailbreak.Public/Mod/Draw/IColorable.cs | 7 +- .../Mod/LastGuard/ILastGuardService.cs | 7 +- .../Mod/LastRequest/AbstractLastRequest.cs | 36 +- .../Mod/LastRequest/Enums/LRResult.cs | 8 +- .../Mod/LastRequest/Enums/LRState.cs | 8 +- .../Mod/LastRequest/Enums/LRType.cs | 103 ++- .../Mod/LastRequest/ILastRequestFactory.cs | 9 +- .../Mod/LastRequest/ILastRequestManager.cs | 32 +- .../Jailbreak.Public/Mod/Logs/ILogService.cs | 13 +- .../Jailbreak.Public/Mod/Logs/IPlayerTag.cs | 17 +- .../Jailbreak.Public/Mod/Mute/IMuteService.cs | 15 +- .../Jailbreak.Public/Mod/Mute/MuteReason.cs | 8 +- .../Mod/Rebel/IJihadC4Service.cs | 40 +- .../Mod/Rebel/IRebelService.cs | 18 +- .../Mod/Warden/ISpecialTreatmentService.cs | 40 +- .../Mod/Warden/IWardenSelectionService.cs | 43 +- .../Mod/Warden/IWardenService.cs | 27 +- .../Jailbreak.Public/Utils/FreezeManager.cs | 70 +- .../Jailbreak.Public/Utils/TemporaryConvar.cs | 27 +- .../Coroutines/CoroutineManager.cs | 32 +- .../GenericServiceExtension.cs | 19 +- .../Jailbreak.Generic.csproj | 6 +- .../Behaviors/AliveStateTracker.cs | 21 +- .../PlayerState/Behaviors/BaseStateTracker.cs | 35 +- .../Behaviors/GlobalStateTracker.cs | 51 +- .../Behaviors/RoundStateTracker.cs | 18 +- .../PlayerState/ITrackedPlayerState.cs | 21 +- .../PlayerState/PlayerStateFactory.cs | 42 +- .../PlayerState/PlayerStateImpl.cs | 28 +- src/Jailbreak/Config/ConfigService.cs | 109 ++- src/Jailbreak/Jailbreak.cs | 137 ++-- src/Jailbreak/Jailbreak.csproj | 37 +- src/Jailbreak/JailbreakServiceCollection.cs | 69 +- 159 files changed, 4674 insertions(+), 5668 deletions(-) create mode 100644 Formatting.DotSettings create mode 100644 Jailbreak.sln.DotSettings diff --git a/Formatting.DotSettings b/Formatting.DotSettings new file mode 100644 index 00000000..01c99f3b --- /dev/null +++ b/Formatting.DotSettings @@ -0,0 +1,82 @@ + + Built-in: Full Cleanup + public private override virtual file new abstract internal protected sealed static readonly extern unsafe volatile async required + Remove + 0 + END_OF_LINE + END_OF_LINE + False + False + True + END_OF_LINE + END_OF_LINE + TOGETHER_SAME_LINE + False + True + True + True + True + True + True + INDENT + 2 + END_OF_LINE + True + True + True + True + True + True + END_OF_LINE + False + False + False + False + False + False + False + False + False + 10 + 5 + 5 + 10 + 5 + COMPACT + END_OF_LINE + True + True + NEVER + NEVER + False + False + NEVER + False + False + NEVER + True + True + True + False + 2 + END_OF_LINE + False + True + True + False + CHOP_IF_LONG + CHOP_IF_LONG + WRAP_IF_LONG + 80 + WRAP_IF_LONG + True + API + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, ProtectedInternal, Internal, PrivateProtected" Description="Non-Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, Public, FileLocal" Description="Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> \ No newline at end of file diff --git a/Jailbreak.sln.DotSettings b/Jailbreak.sln.DotSettings new file mode 100644 index 00000000..6b68132e --- /dev/null +++ b/Jailbreak.sln.DotSettings @@ -0,0 +1,9 @@ + + IO + LR + ST + + + + + \ No newline at end of file diff --git a/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs index d4ced81a..2bcad41c 100644 --- a/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs +++ b/lang/Jailbreak.English/Generic/GenericCommandNotifications.cs @@ -7,57 +7,50 @@ 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 class GenericCommandNotifications : IGenericCommandNotifications, + ILanguage { + private static readonly 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 - { PREFIX, $"{ChatColors.Red}Player '{ChatColors.LightBlue}{query}{ChatColors.Red}' not found." }; - } + public IView PlayerNotFound(string query) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}Player '{ChatColors.LightBlue}{query}{ChatColors.Red}' not found." + }; + } - public IView PlayerFoundMultiple(string query) - { - return new SimpleView - { - PREFIX, - $"{ChatColors.Red}Multiple players found for '{ChatColors.LightBlue}{query}{ChatColors.Red}'." - }; - } + public IView PlayerFoundMultiple(string query) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}Multiple players found for '{ChatColors.LightBlue}{query}{ChatColors.Red}'." + }; + } - public IView CommandOnCooldown(DateTime cooldownEndsAt) - { - var seconds = (int)(cooldownEndsAt - DateTime.Now).TotalSeconds; - return new SimpleView - { - PREFIX, $"{ChatColors.Grey}Command is on cooldown for", seconds, - $"{ChatColors.Grey}seconds!" - }; - } + public IView CommandOnCooldown(DateTime cooldownEndsAt) { + var seconds = (int)(cooldownEndsAt - DateTime.Now).TotalSeconds; + return new SimpleView { + PREFIX, + $"{ChatColors.Grey}Command is on cooldown for", + seconds, + $"{ChatColors.Grey}seconds!" + }; + } - public IView InvalidParameter(string parameter, string expected) - { - return new SimpleView - { - PREFIX, - $"{ChatColors.Red}Invalid parameter '{ChatColors.LightBlue}{parameter}{ChatColors.Red}', expected a(n) {ChatColors.White}{expected}{ChatColors.Red}." - }; - } + public IView InvalidParameter(string parameter, string expected) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}Invalid parameter '{ChatColors.LightBlue}{parameter}{ChatColors.Red}', expected a(n) {ChatColors.White}{expected}{ChatColors.Red}." + }; + } - public IView NoPermissionMessage(string permission) - { - return new SimpleView - { - PREFIX, - $"{ChatColors.Red}This command requires the {ChatColors.White}{permission}{ChatColors.Red} permission." - }; - } + public IView NoPermissionMessage(string permission) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}This command requires the {ChatColors.White}{permission}{ChatColors.Red} permission." + }; + } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Jailbreak.English.csproj b/lang/Jailbreak.English/Jailbreak.English.csproj index ff208cf1..814dac54 100644 --- a/lang/Jailbreak.English/Jailbreak.English.csproj +++ b/lang/Jailbreak.English/Jailbreak.English.csproj @@ -7,11 +7,7 @@ - - - - - + diff --git a/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs b/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs index 4b09748f..31cf64aa 100644 --- a/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs +++ b/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs @@ -1,30 +1,29 @@ using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Base; -using Jailbreak.Formatting.Logistics; -using Jailbreak.Formatting.Views; using Jailbreak.Formatting.Core; +using Jailbreak.Formatting.Logistics; using Jailbreak.Formatting.Objects; +using Jailbreak.Formatting.Views; namespace Jailbreak.English.LastGuard; -public class LastGuardNotifications : ILastGuardNotifications, ILanguage -{ - public static FormatObject PREFIX = - new HiddenFormatObject($" {ChatColors.DarkRed}[{ChatColors.LightRed}Last Guard{ChatColors.DarkRed}]") - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true - }; +public class LastGuardNotifications : ILastGuardNotifications, + ILanguage { + public static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.DarkRed}[{ChatColors.LightRed}Last Guard{ChatColors.DarkRed}]") { + // Hide in panorama and center text + Plain = false, Panorama = false, Chat = true + }; - public IView LG_STARTED(int ctHealth, int tHealth) - { - return new SimpleView() - { - PREFIX, - $"{ChatColors.Red}Last Guard has been activated! Last guard has", ctHealth, - $"{ChatColors.Red}health and Ts have", tHealth, $"{ChatColors.Red}health." - }; - } + public IView LG_STARTED(int ctHealth, int tHealth) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}Last Guard has been activated! Last guard has", + ctHealth, + $"{ChatColors.Red}health and Ts have", + tHealth, + $"{ChatColors.Red}health." + }; + } } \ No newline at end of file diff --git a/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs b/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs index f4e59ee7..a25e4aca 100644 --- a/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs +++ b/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs @@ -10,90 +10,90 @@ namespace Jailbreak.English.LastRequest; -public class LastRequestMessages : ILastRequestMessages, ILanguage -{ - public static FormatObject PREFIX = - new HiddenFormatObject($" {ChatColors.DarkRed}[{ChatColors.LightRed}LR{ChatColors.DarkRed}]") - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true - }; +public class LastRequestMessages : ILastRequestMessages, + ILanguage { + public static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.DarkRed}[{ChatColors.LightRed}LR{ChatColors.DarkRed}]") { + // Hide in panorama and center text + Plain = false, Panorama = false, Chat = true + }; - public IView LastRequestEnabled() => new SimpleView() - { - { - PREFIX, - $"Last Request has been enabled. {ChatColors.Grey}Type {ChatColors.LightBlue}!lr{ChatColors.Grey} to start a last request." - } + public IView LastRequestEnabled() { + return new SimpleView { + { + PREFIX, + $"Last Request has been enabled. {ChatColors.Grey}Type {ChatColors.LightBlue}!lr{ChatColors.Grey} to start a last request." + } }; + } - public IView LastRequestDisabled() => new SimpleView() - { - { PREFIX, $"{ChatColors.Grey}Last Request has been {ChatColors.Red}disabled{ChatColors.Grey}." } + public IView LastRequestDisabled() { + return new SimpleView { + { + PREFIX, + $"{ChatColors.Grey}Last Request has been {ChatColors.Red}disabled{ChatColors.Grey}." + } }; + } - public IView LastRequestNotEnabled() => new SimpleView() - { - { PREFIX, $"{ChatColors.Red}Last Request is not enabled." } + public IView LastRequestNotEnabled() { + return new SimpleView { + { PREFIX, $"{ChatColors.Red}Last Request is not enabled." } }; + } - public IView InvalidLastRequest(string query) - { - return new SimpleView() - { - PREFIX, - "Invalid Last Request: ", - query - }; - } + public IView InvalidLastRequest(string query) { + return new SimpleView { PREFIX, "Invalid Last Request: ", query }; + } - public IView InvalidPlayerChoice(CCSPlayerController player, string reason) - { - return new SimpleView() - { - PREFIX, - "Invalid player choice: ", - player, - " Reason: ", - reason - }; - } + public IView InvalidPlayerChoice(CCSPlayerController player, string reason) { + return new SimpleView { + PREFIX, + "Invalid player choice: ", + player, + " Reason: ", + reason + }; + } - public IView InformLastRequest(AbstractLastRequest lr) - { - return new SimpleView() - { - PREFIX, - lr.prisoner, "is preparing a", lr.type.ToFriendlyString(), - "Last Request against", lr.guard - }; - } + public IView InformLastRequest(AbstractLastRequest lr) { + return new SimpleView { + PREFIX, + lr.Prisoner, + "is preparing a", + lr.Type.ToFriendlyString(), + "Last Request against", + lr.Guard + }; + } - public IView AnnounceLastRequest(AbstractLastRequest lr) - { - return new SimpleView() - { - PREFIX, - lr.prisoner, "is doing a", lr.type.ToFriendlyString(), - "Last Request against", lr.guard - }; - } + public IView AnnounceLastRequest(AbstractLastRequest lr) { + return new SimpleView { + PREFIX, + lr.Prisoner, + "is doing a", + lr.Type.ToFriendlyString(), + "Last Request against", + lr.Guard + }; + } - public IView LastRequestDecided(AbstractLastRequest lr, LRResult result) - { - return new SimpleView() - { - PREFIX, - (result == LRResult.GuardWin ? ChatColors.Blue : ChatColors.Red).ToString(), - result == LRResult.PrisonerWin ? lr.prisoner : lr.guard, - "won the LR." - }; - } + public IView LastRequestDecided(AbstractLastRequest lr, LRResult result) { + return new SimpleView { + PREFIX, + (result == LRResult.GUARD_WIN ? ChatColors.Blue : ChatColors.Red) + .ToString(), + result == LRResult.PRISONER_WIN ? lr.Prisoner : lr.Guard, + "won the LR." + }; + } - public IView DamageBlockedInsideLastRequest => new SimpleView { PREFIX, "You or they are in LR, damage blocked." }; + public IView DamageBlockedInsideLastRequest + => new SimpleView { PREFIX, "You or they are in LR, damage blocked." }; - public IView DamageBlockedNotInSameLR => new SimpleView - { PREFIX, "You are not in the same LR as them, damage blocked." }; + public IView DamageBlockedNotInSameLR + => new SimpleView { + PREFIX, "You are not in the same LR as them, damage blocked." + }; } \ No newline at end of file diff --git a/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs b/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs index 08b0a8d6..7fd52796 100644 --- a/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs +++ b/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs @@ -6,26 +6,32 @@ namespace Jailbreak.English.LastRequest; -public class RaceLRMessages : IRaceLRMessages, ILanguage -{ - public IView END_RACE_INSTRUCTION => new SimpleView() - { - { LastRequestMessages.PREFIX, $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" }, - SimpleView.NEWLINE, - { LastRequestMessages.PREFIX, $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" }, - SimpleView.NEWLINE, - { LastRequestMessages.PREFIX, $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" }, - SimpleView.NEWLINE, +// ReSharper disable ClassNeverInstantiated.Global +public class RaceLRMessages : IRaceLRMessages, + ILanguage { + public IView EndRaceInstruction + => new SimpleView { + { + LastRequestMessages.PREFIX, + $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" + }, + SimpleView.NEWLINE, { + LastRequestMessages.PREFIX, + $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" + }, + SimpleView.NEWLINE, { + LastRequestMessages.PREFIX, + $"Type ${ChatColors.Blue}!endrace${ChatColors.White} to set the end point!" + }, + SimpleView.NEWLINE }; - public IView RACE_STARTING_MESSAGE(CCSPlayerController prisoner) - { - return new SimpleView() - { - { - LastRequestMessages.PREFIX, prisoner, - " is starting a race. Pay attention to where they set the end point!" - } - }; - } + public IView RaceStartingMessage(CCSPlayerController prisoner) { + return new SimpleView { + { + LastRequestMessages.PREFIX, prisoner, + " is starting a race. Pay attention to where they set the end point!" + } + }; + } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Logs/LogMessages.cs b/lang/Jailbreak.English/Logs/LogMessages.cs index 881ca5d8..6161b337 100644 --- a/lang/Jailbreak.English/Logs/LogMessages.cs +++ b/lang/Jailbreak.English/Logs/LogMessages.cs @@ -1,30 +1,26 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Modules.Utils; - -using Jailbreak.Formatting.Base; -using Jailbreak.Formatting.Core; +using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Logistics; -using Jailbreak.Formatting.Objects; using Jailbreak.Formatting.Views; -using Jailbreak.Public.Extensions; namespace Jailbreak.English.Logs; -public class LogMessages : ILogMessages, ILanguage -{ - - public IView BEGIN_JAILBREAK_LOGS => new SimpleView() - { - { "********************************" }, SimpleView.NEWLINE, - { "***** BEGIN JAILBREAK LOGS *****" }, SimpleView.NEWLINE, - { "********************************" } - }; - - public IView END_JAILBREAK_LOGS => new SimpleView() - { - { "********************************" }, SimpleView.NEWLINE, - { "****** END JAILBREAK LOGS ******" }, SimpleView.NEWLINE, - { "********************************" } - }; +public class + LogMessages : ILogMessages, ILanguage { + public IView BeginJailbreakLogs + => new SimpleView { + "********************************", + SimpleView.NEWLINE, + "***** BEGIN JAILBREAK LOGS *****", + SimpleView.NEWLINE, + "********************************" + }; -} + public IView EndJailbreakLogs + => new SimpleView { + "********************************", + SimpleView.NEWLINE, + "****** END JAILBREAK LOGS ******", + SimpleView.NEWLINE, + "********************************" + }; +} \ No newline at end of file diff --git a/lang/Jailbreak.English/Mute/PeaceMessages.cs b/lang/Jailbreak.English/Mute/PeaceMessages.cs index 9f66af34..96a0fcb9 100644 --- a/lang/Jailbreak.English/Mute/PeaceMessages.cs +++ b/lang/Jailbreak.English/Mute/PeaceMessages.cs @@ -1,5 +1,4 @@ -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Utils; +using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Logistics; @@ -8,87 +7,71 @@ namespace Jailbreak.English.Mute; -public class PeaceMessages : IPeaceMessages, ILanguage -{ - private static readonly FormatObject PREFIX = - new HiddenFormatObject( - $" {ChatColors.DarkBlue}[{ChatColors.LightBlue}Voice{ChatColors.DarkBlue}]{ChatColors.Grey} ") - { - Plain = false, - Panorama = false, - Chat = true - }; - - public IView PEACE_ENACTED_BY_ADMIN(int seconds) - { - return new SimpleView() - { - PREFIX, - "An admin has enacted peace for", - seconds, - "seconds." - }; - } +public class PeaceMessages : IPeaceMessages, + ILanguage { + private static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.DarkBlue}[{ChatColors.LightBlue}Voice{ChatColors.DarkBlue}]{ChatColors.Grey} ") { + Plain = false, Panorama = false, Chat = true + }; - public IView WARDEN_ENACTED_PEACE(int seconds) - { - return new SimpleView() - { - PREFIX, - "Warden has enacted peace for", - seconds, - "seconds." - }; - } + public IView PeaceEnactedByAdmin(int seconds) { + return new SimpleView { + PREFIX, "An admin has enacted peace for", seconds, "seconds." + }; + } - public IView GENERAL_PEACE_ENACTED(int seconds) - { - return new SimpleView() - { - PREFIX, - "Peace has been enacted for", - seconds, - "seconds." - }; - } + public IView WardenEnactedPeace(int seconds) { + return new SimpleView { + PREFIX, "Warden has enacted peace for", seconds, "seconds." + }; + } - public IView UNMUTED_GUARDS => new SimpleView() - { - { PREFIX, $"{ChatColors.Blue}Guards {ChatColors.Grey}have been unmuted." } + public IView GeneralPeaceEnacted(int seconds) { + return new SimpleView { + PREFIX, "Peace has been enacted for", seconds, "seconds." }; + } - public IView UNMUTED_PRISONERS => new SimpleView() - { - { PREFIX, $"{ChatColors.LightRed}Prisoners {ChatColors.Grey}have been unmuted." } + public IView UnmutedGuards + => new SimpleView { + { PREFIX, $"{ChatColors.Blue}Guards {ChatColors.Grey}have been unmuted." } }; - public IView MUTE_REMINDER => new SimpleView() - { - { PREFIX, ChatColors.Red, "You are currently muted!" } + public IView UnmutedPrisoners + => new SimpleView { + { + PREFIX, + $"{ChatColors.LightRed}Prisoners {ChatColors.Grey}have been unmuted." + } }; - public IView PEACE_REMINDER => new SimpleView() - { - { - PREFIX, - $"Peace is currently active. {ChatColors.Red}You should only be talking if absolutely necessary!" - } + public IView MuteReminder + => new SimpleView { + { PREFIX, ChatColors.Red, "You are currently muted!" } }; - public IView DEAD_REMINDER => new SimpleView() - { - { - PREFIX, $"{ChatColors.Red}You are dead and cannot speak!" - } + public IView PeaceReminder + => new SimpleView { + { + PREFIX, + $"Peace is currently active. {ChatColors.Red}You should only be talking if absolutely necessary!" + } }; - public IView ADMIN_DEAD_REMINDER => new SimpleView() - { - { PREFIX, "You are dead.", $"{ChatColors.Red}You should only be talking if absolutely necessary!" } + public IView DeadReminder + => new SimpleView { + { PREFIX, $"{ChatColors.Red}You are dead and cannot speak!" } }; - public IView PEACE_ACTIVE => new SimpleView() - { - { PREFIX, "Peace is currently active." } + public IView AdminDeadReminder + => new SimpleView { + { + PREFIX, "You are dead.", + $"{ChatColors.Red}You should only be talking if absolutely necessary!" + } }; + + public IView PeaceActive + => new SimpleView { { PREFIX, "Peace is currently active." } }; } \ No newline at end of file diff --git a/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs b/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs index a398895b..b9a42880 100644 --- a/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs +++ b/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs @@ -1,22 +1,31 @@ -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Utils; +using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Logistics; using Jailbreak.Formatting.Views; namespace Jailbreak.English.Rebel; -public class JihadC4Notifications : IJihadC4Notifications, ILanguage -{ - // public IView JIHAD_C4_DROPPED => new SimpleView { RebelNotifications.PREFIX, "You dropped your Jihad C4!" }; - public IView JIHAD_C4_PICKUP => new SimpleView { RebelNotifications.PREFIX, "You picked up a Jihad C4!" }; - public IView JIHAD_C4_RECEIVED => new SimpleView { RebelNotifications.PREFIX, "You received a Jihad C4!" }; - public IView JIHAD_C4_USAGE1 => new SimpleView { RebelNotifications.PREFIX, $"To detonate it, hold it out and press {ChatColors.Yellow + "E" + ChatColors.Default}." }; - // public IView JIHAD_C4_USAGE2 => new SimpleView { RebelNotifications.PREFIX, $"You can drop the C4 to other players with {ChatColors.Yellow + "G" + ChatColors.Default}." }; +public class JihadC4Notifications : IJihadC4Notifications, + ILanguage { + // public IView JIHAD_C4_DROPPED => new SimpleView { RebelNotifications.PREFIX, "You dropped your Jihad C4!" }; + public IView JihadC4Pickup + => new SimpleView { + RebelNotifications.PREFIX, "You picked up a Jihad C4!" + }; + public IView JihadC4Received + => new SimpleView { RebelNotifications.PREFIX, "You received a Jihad C4!" }; - // public IView PlayerDetonateC4(CCSPlayerController player) - // { - // return new SimpleView { RebelNotifications.PREFIX, $"{player.PlayerName} has detonated a Jihad C4!" }; - // } + public IView JihadC4Usage1 + => new SimpleView { + RebelNotifications.PREFIX, + $"To detonate it, hold it out and press {ChatColors.Yellow + "E" + ChatColors.Default}." + }; + // public IView JIHAD_C4_USAGE2 => new SimpleView { RebelNotifications.PREFIX, $"You can drop the C4 to other players with {ChatColors.Yellow + "G" + ChatColors.Default}." }; + + + // public IView PlayerDetonateC4(CCSPlayerController player) + // { + // return new SimpleView { RebelNotifications.PREFIX, $"{player.PlayerName} has detonated a Jihad C4!" }; + // } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Rebel/RebelNotifications.cs b/lang/Jailbreak.English/Rebel/RebelNotifications.cs index 37d4c1a7..4b47e540 100644 --- a/lang/Jailbreak.English/Rebel/RebelNotifications.cs +++ b/lang/Jailbreak.English/Rebel/RebelNotifications.cs @@ -1,5 +1,4 @@ using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Logistics; @@ -8,16 +7,15 @@ 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 class RebelNotifications : IRebelNotifications, + ILanguage { + public static readonly 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() { PREFIX, "You are no longer a rebel." }; -} + public IView NoLongerRebel + => new SimpleView { PREFIX, "You are no longer a rebel." }; +} \ No newline at end of file diff --git a/lang/Jailbreak.English/Warden/RollCommandNotifications.cs b/lang/Jailbreak.English/Warden/RollCommandNotifications.cs index b1907c76..878f4450 100644 --- a/lang/Jailbreak.English/Warden/RollCommandNotifications.cs +++ b/lang/Jailbreak.English/Warden/RollCommandNotifications.cs @@ -7,18 +7,16 @@ namespace Jailbreak.English.Warden; -public class RollCommandNotifications : IRollCommandNotications, ILanguage -{ - public static FormatObject PREFIX = new HiddenFormatObject($" {ChatColors.Lime}[{ChatColors.Green}Roll{ChatColors.Lime}]") - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true +public class RollCommandNotifications : IRollCommandNotications, + ILanguage { + public static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.Lime}[{ChatColors.Green}Roll{ChatColors.Lime}]") { + // Hide in panorama and center text + Plain = false, Panorama = false, Chat = true }; - - public IView Roll(int roll) - { - return new SimpleView() { PREFIX, $"warden has rolled {roll}!" }; - } + + public IView Roll(int roll) { + return new SimpleView { PREFIX, $"warden has rolled {roll}!" }; + } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs b/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs index 9bc28e30..1b5cd05a 100644 --- a/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs +++ b/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs @@ -8,30 +8,40 @@ namespace Jailbreak.English.Warden; -public class SpecialTreatmentNotifications : ISpecialTreatmentNotifications, ILanguage -{ - public static FormatObject PREFIX = - new HiddenFormatObject($" {ChatColors.Lime}[{ChatColors.Green}ST{ChatColors.Lime}]") - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true, - }; +public class SpecialTreatmentNotifications : ISpecialTreatmentNotifications, + ILanguage { + public static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.Lime}[{ChatColors.Green}ST{ChatColors.Lime}]") { + // Hide in panorama and center text + Plain = false, Panorama = false, Chat = true + }; - public IView GRANTED => - new SimpleView { PREFIX, $"You now have {ChatColors.Green}special treatment{ChatColors.White}!" }; + public IView Granted + => new SimpleView { + PREFIX, + $"You now have {ChatColors.Green}special treatment{ChatColors.White}!" + }; - public IView REVOKED => - new SimpleView { PREFIX, $"Your special treatment was {ChatColors.Red}removed{ChatColors.White}." }; + public IView Revoked + => new SimpleView { + PREFIX, + $"Your special treatment was {ChatColors.Red}removed{ChatColors.White}." + }; - public IView GRANTED_TO(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, $"now has {ChatColors.Grey}Special Treatment{ChatColors.White}!" }; - } + public IView GrantedTo(CCSPlayerController player) { + return new SimpleView { + PREFIX, + player, + $"now has {ChatColors.Grey}Special Treatment{ChatColors.White}!" + }; + } - public IView REVOKED_FROM(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, $"{ChatColors.Red}no longer {ChatColors.Grey}has Special Treatment." }; - } + public IView RevokedFrom(CCSPlayerController player) { + return new SimpleView { + PREFIX, + player, + $"{ChatColors.Red}no longer {ChatColors.Grey}has Special Treatment." + }; + } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Warden/WardenNotifications.cs b/lang/Jailbreak.English/Warden/WardenNotifications.cs index 0305b645..a772cea4 100644 --- a/lang/Jailbreak.English/Warden/WardenNotifications.cs +++ b/lang/Jailbreak.English/Warden/WardenNotifications.cs @@ -8,91 +8,99 @@ namespace Jailbreak.English.Warden; -public class WardenNotifications : IWardenNotifications, ILanguage -{ - public static FormatObject PREFIX = - new HiddenFormatObject($" {ChatColors.Green}[{ChatColors.Olive}WARDEN{ChatColors.Green}]") - { - // Hide in panorama and center text - Plain = false, - Panorama = false, - Chat = true - }; - - public IView PICKING_SHORTLY => - new SimpleView - { - { PREFIX, $"{ChatColors.Grey}Picking a warden shortly..." }, SimpleView.NEWLINE, - { - PREFIX, - $"{ChatColors.Grey}To enter the warden queue, type {ChatColors.Blue}!warden{ChatColors.Grey} in chat." - } - }; - - public IView NO_WARDENS => - new SimpleView - { - PREFIX, - $"No wardens in queue! The next player to run {ChatColors.Blue}!warden{ChatColors.White} will become a warden." - }; - - public IView WARDEN_LEFT => - new SimpleView { PREFIX, "The warden has left the game." }; - - public IView WARDEN_DIED => - new SimpleView - { - PREFIX, - $"{ChatColors.Red}The warden has {ChatColors.DarkRed}died{ChatColors.Red}! CTs must pursue {ChatColors.Blue}!warden{ChatColors.Red}." - }; - - public IView BECOME_NEXT_WARDEN => - new SimpleView - { PREFIX, $"{ChatColors.Grey}Type {ChatColors.Blue}!warden{ChatColors.Grey} to become the next warden" }; - - public IView JOIN_RAFFLE => - new SimpleView - { PREFIX, $"{ChatColors.Grey}You've {ChatColors.Green}joined {ChatColors.Grey}the warden raffle." }; - - public IView LEAVE_RAFFLE => - new SimpleView { PREFIX, $"{ChatColors.Grey}You've {ChatColors.Red}left {ChatColors.Grey}the warden raffle." }; - - public IView NOT_WARDEN => - new SimpleView { PREFIX, $"{ChatColors.LightRed}You are not the warden." }; - - public IView FIRE_COMMAND_FAILED => - new SimpleView { PREFIX, "The fire command has failed to work for some unknown reason..." }; - - public IView PASS_WARDEN(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, "resigned from being warden." }; - } - - public IView FIRE_WARDEN(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, "was fired from being warden." }; - } - - public IView FIRE_WARDEN(CCSPlayerController player, CCSPlayerController admin) - { - return new SimpleView { PREFIX, admin, "fired", player, "from being warden." }; - } - - public IView NEW_WARDEN(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, "is now the warden!" }; - } - - public IView CURRENT_WARDEN(CCSPlayerController? player) - { - if (player is not null) - return new SimpleView { PREFIX, "The warden is", player, "." }; - else - return new SimpleView { PREFIX, "There is no warden." }; - } - - public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player) - { - return new SimpleView { PREFIX, player, "was fired and is no longer the warden." }; - } +public class WardenNotifications : IWardenNotifications, + ILanguage { + public static readonly FormatObject PREFIX = + new HiddenFormatObject( + $" {ChatColors.Green}[{ChatColors.Olive}WARDEN{ChatColors.Green}]") { + // Hide in panorama and center text + Plain = false, Panorama = false, Chat = true + }; + + public IView PICKING_SHORTLY + => new SimpleView { + { PREFIX, $"{ChatColors.Grey}Picking a warden shortly..." }, + SimpleView.NEWLINE, { + PREFIX, + $"{ChatColors.Grey}To enter the warden queue, type {ChatColors.Blue}!warden{ChatColors.Grey} in chat." + } + }; + + public IView NO_WARDENS + => new SimpleView { + PREFIX, + $"No wardens in queue! The next player to run {ChatColors.Blue}!warden{ChatColors.White} will become a warden." + }; + + public IView WARDEN_LEFT + => new SimpleView { PREFIX, "The warden has left the game." }; + + public IView WARDEN_DIED + => new SimpleView { + PREFIX, + $"{ChatColors.Red}The warden has {ChatColors.DarkRed}died{ChatColors.Red}! CTs must pursue {ChatColors.Blue}!warden{ChatColors.Red}." + }; + + public IView BECOME_NEXT_WARDEN + => new SimpleView { + PREFIX, + $"{ChatColors.Grey}Type {ChatColors.Blue}!warden{ChatColors.Grey} to become the next warden" + }; + + public IView JOIN_RAFFLE + => new SimpleView { + PREFIX, + $"{ChatColors.Grey}You've {ChatColors.Green}joined {ChatColors.Grey}the warden raffle." + }; + + public IView LEAVE_RAFFLE + => new SimpleView { + PREFIX, + $"{ChatColors.Grey}You've {ChatColors.Red}left {ChatColors.Grey}the warden raffle." + }; + + public IView NOT_WARDEN + => new SimpleView { + PREFIX, $"{ChatColors.LightRed}You are not the warden." + }; + + public IView FIRE_COMMAND_FAILED + => new SimpleView { + PREFIX, "The fire command has failed to work for some unknown reason..." + }; + + public IView PASS_WARDEN(CCSPlayerController player) { + return new SimpleView { PREFIX, player, "resigned from being warden." }; + } + + public IView FIRE_WARDEN(CCSPlayerController player) { + return new SimpleView { PREFIX, player, "was fired from being warden." }; + } + + public IView FIRE_WARDEN(CCSPlayerController player, + CCSPlayerController admin) { + return new SimpleView { + PREFIX, + admin, + "fired", + player, + "from being warden." + }; + } + + public IView NEW_WARDEN(CCSPlayerController player) { + return new SimpleView { PREFIX, player, "is now the warden!" }; + } + + public IView CURRENT_WARDEN(CCSPlayerController? player) { + if (player is not null) + return new SimpleView { PREFIX, "The warden is", player, "." }; + return new SimpleView { PREFIX, "There is no warden." }; + } + + public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player) { + return new SimpleView { + PREFIX, player, "was fired and is no longer the warden." + }; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/DebugCommand.cs b/mod/Jailbreak.Debug/DebugCommand.cs index c7d1404b..02903a27 100644 --- a/mod/Jailbreak.Debug/DebugCommand.cs +++ b/mod/Jailbreak.Debug/DebugCommand.cs @@ -9,41 +9,36 @@ namespace Jailbreak.Debug; // css_debug [subcommand] [args] -> subcommand [args] /// -/// The debug command allows for Developers to debug and force certain actions/gamestates. +/// The debug command allows for Developers to debug and force certain actions/gamestates. /// -public class DebugCommand(IServiceProvider serviceProvider) : IPluginBehavior -{ - private readonly Dictionary _commands = new(); - private BasePlugin _plugin; +public class DebugCommand(IServiceProvider serviceProvider) : IPluginBehavior { + private readonly Dictionary commands = new(); + private BasePlugin? plugin; - public void Start(BasePlugin parent) - { - _plugin = parent; - _commands.Add("markrebel", new MarkRebel(serviceProvider)); - _commands.Add("pardon", new Pardon(serviceProvider)); - _commands.Add("lr", new Subcommands.LastRequest(serviceProvider, _plugin)); - _commands.Add("st", new MarkST(serviceProvider)); - _commands.Add("lg", new LastGuard(serviceProvider)); - } - - [RequiresPermissions("@css/root")] - [ConsoleCommand("css_debug", "Debug command for Jailbreak.")] - public void Command_Debug(CCSPlayerController? executor, CommandInfo info) - { - if (executor == null) return; + public void Start(BasePlugin basePlugin) { + plugin = basePlugin; + commands.Add("markrebel", new MarkRebel(serviceProvider)); + commands.Add("pardon", new Pardon(serviceProvider)); + commands.Add("lr", new Subcommands.LastRequest(serviceProvider, plugin)); + commands.Add("st", new MarkST(serviceProvider)); + commands.Add("lg", new LastGuard(serviceProvider)); + } - if (info.ArgCount == 1) - { - foreach (var command in _commands) info.ReplyToCommand(command.Key); - return; - } + [RequiresPermissions("@css/root")] + [ConsoleCommand("css_debug", "Debug command for Jailbreak.")] + public void Command_Debug(CCSPlayerController? executor, CommandInfo info) { + if (executor == null) return; - if (!_commands.TryGetValue(info.GetArg(1), out var subcommand)) - { - info.ReplyToCommand("Invalid subcommand"); - return; - } + if (info.ArgCount == 1) { + foreach (var command in commands) info.ReplyToCommand(command.Key); + return; + } - subcommand.OnCommand(executor, new WrappedInfo(info)); + 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 0c6f4bc7..8aa80afc 100644 --- a/mod/Jailbreak.Debug/DebugServiceExtension.cs +++ b/mod/Jailbreak.Debug/DebugServiceExtension.cs @@ -3,10 +3,8 @@ namespace Jailbreak.Debug; -public static class DebugServiceExtension -{ - public static void AddJailbreakDebug(this IServiceCollection services) - { - services.AddPluginBehavior(); - } +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 index 19918a36..97818649 100644 --- a/mod/Jailbreak.Debug/Jailbreak.Debug.csproj +++ b/mod/Jailbreak.Debug/Jailbreak.Debug.csproj @@ -7,14 +7,10 @@ - - - - - - - - + + + + diff --git a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs index a187dbb2..3afa1ae8 100644 --- a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs +++ b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs @@ -8,141 +8,135 @@ namespace Jailbreak.Debug.Subcommands; -public abstract class AbstractCommand(IServiceProvider services) -{ - private readonly IGenericCommandNotifications _lang = services.GetRequiredService(); - protected readonly IServiceProvider Services = services; - - 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); +public abstract class AbstractCommand(IServiceProvider services) { + private readonly IGenericCommandNotifications lang = + services.GetRequiredService(); + + protected readonly IServiceProvider Services = services; + + 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; } - protected TargetResult? GetVulnerableTarget(WrappedInfo command, int argIndex = 1, - Func? predicate = null) - { - return GetVulnerableTarget(command.Info, argIndex + 1, predicate); + 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; + } + + protected 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))); + } + + protected 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; } - 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; + if (matches.Count() > 1) { + if (command.CallingPlayer != null) + lang.PlayerFoundMultiple(command.GetArg(argIndex)) + .ToPlayerChat(command.CallingPlayer); + return null; } - protected 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)))); + return matches; + } + + 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)) { + 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"; } + } - protected 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; - } + protected string GetTargetLabels(WrappedInfo info, int argIndex = 1) { + return GetTargetLabels(info.Info, 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)) - { - 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"; - } - } - - protected string GetTargetLabels(WrappedInfo info, int argIndex = 1) - { - return GetTargetLabels(info.Info, argIndex + 1); - } - - protected string GetTargetLabels(CommandInfo info, int argIndex = 1) - { - var label = GetTargetLabel(info, argIndex); - if (label.ToLower().EndsWith("s")) - return label + "'"; - return label + "'s"; - } + protected string GetTargetLabels(CommandInfo info, int argIndex = 1) { + var 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); - } +public static class CommandExtensions { + public 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/LastGuard.cs b/mod/Jailbreak.Debug/Subcommands/LastGuard.cs index 87e44057..e0b89299 100644 --- a/mod/Jailbreak.Debug/Subcommands/LastGuard.cs +++ b/mod/Jailbreak.Debug/Subcommands/LastGuard.cs @@ -3,35 +3,30 @@ using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.LastGuard; -using Jailbreak.Public.Mod.Rebel; -using Jailbreak.Public.Mod.Warden; -using Jailbreak.Rebel; using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Debug.Subcommands; // css_lastguard -public class LastGuard(IServiceProvider services) : AbstractCommand(services) -{ - public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) - { - var lgService = Services.GetRequiredService(); +public class LastGuard(IServiceProvider services) : AbstractCommand(services) { + public override void OnCommand(CCSPlayerController? executor, + WrappedInfo info) { + var lgService = Services.GetRequiredService(); - var target = Utilities.GetPlayers() - .FirstOrDefault(p => p.IsReal() && p is { Team: CsTeam.CounterTerrorist, PawnIsAlive: true }); + var target = Utilities.GetPlayers() + .FirstOrDefault(p => p.IsReal() && p is { + Team: CsTeam.CounterTerrorist, PawnIsAlive: true + }); - if (info.ArgCount == 2) - { - var targetResult = GetVulnerableTarget(info); - if (targetResult == null) - return; - target = targetResult.First(); - } + if (info.ArgCount == 2) { + var targetResult = GetVulnerableTarget(info); + if (targetResult == null) return; + target = targetResult.First(); + } - if (target == null) - return; + if (target == null) return; - lgService.StartLastGuard(target); - info.ReplyToCommand("Enabled LastGuard for " + target.PlayerName); - } + lgService.StartLastGuard(target); + info.ReplyToCommand("Enabled LastGuard for " + target.PlayerName); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/LastRequest.cs b/mod/Jailbreak.Debug/Subcommands/LastRequest.cs index 9fd9ce33..e1534f32 100644 --- a/mod/Jailbreak.Debug/Subcommands/LastRequest.cs +++ b/mod/Jailbreak.Debug/Subcommands/LastRequest.cs @@ -11,88 +11,78 @@ namespace Jailbreak.Debug.Subcommands; -public class LastRequest : AbstractCommand -{ - private readonly ILastRequestManager _manager; - private readonly LastRequestPlayerSelector _playerSelector; - private readonly LastRequestMenuSelector _menuSelector; - private readonly ILastRequestMessages _messages; +public class LastRequest : AbstractCommand { + private readonly ILastRequestManager manager; + private readonly LastRequestMenuSelector menuSelector; + private readonly ILastRequestMessages messages; + private readonly LastRequestPlayerSelector playerSelector; - private readonly BasePlugin _plugin; + private readonly BasePlugin plugin; - public LastRequest(IServiceProvider services, BasePlugin plugin) : base(services) - { - _plugin = plugin; - _manager = services.GetRequiredService(); - _playerSelector = new LastRequestPlayerSelector(_manager, true); - _menuSelector = new LastRequestMenuSelector(services.GetRequiredService(), - (type) => "css_debug lastrequest " + type); - _messages = services.GetRequiredService(); - } + public LastRequest(IServiceProvider services, BasePlugin plugin) : + base(services) { + this.plugin = plugin; + manager = services.GetRequiredService(); + playerSelector = new LastRequestPlayerSelector(manager, plugin, true); + menuSelector = new LastRequestMenuSelector( + services.GetRequiredService(), + type => "css_debug lastrequest " + type, plugin); + messages = services.GetRequiredService(); + } - // (debug) lastrequest [lr] [player] - public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) - { - if (executor != null && !executor.IsReal()) - return; + // (debug) lastrequest [lr] [player] + public override void OnCommand(CCSPlayerController? executor, + WrappedInfo info) { + if (executor == null || !executor.IsReal()) return; - if (info.ArgCount == 1 && executor != null) - { - MenuManager.OpenCenterHtmlMenu(_plugin, executor, _menuSelector.GetMenu()); - return; - } + if (info.ArgCount == 1) { + MenuManager.OpenCenterHtmlMenu(plugin, executor, menuSelector.GetMenu()); + return; + } - if (info.ArgCount == 2) - { - switch (info.GetArg(1).ToLower()) - { - case "enable": - _manager.EnableLR(); - info.ReplyToCommand("Last Request enabled."); - return; - case "disable": - _manager.DisableLR(); - info.ReplyToCommand("Last Request disabled."); - return; - } - } + if (info.ArgCount == 2) + switch (info.GetArg(1).ToLower()) { + case "enable": + manager.EnableLR(); + info.ReplyToCommand("Last Request enabled."); + return; + case "disable": + manager.DisableLR(); + info.ReplyToCommand("Last Request disabled."); + return; + } - var type = LRTypeExtensions.FromString(info.GetArg(1)); - if (type is null) - { - _messages.InvalidLastRequest(info.GetArg(1)).ToPlayerChat(executor); - return; - } + var type = LRTypeExtensions.FromString(info.GetArg(1)); + if (type is null) { + messages.InvalidLastRequest(info.GetArg(1)).ToPlayerChat(executor); + return; + } - if (info.ArgCount == 2) - { - MenuManager.OpenCenterHtmlMenu(_plugin, executor, - _playerSelector.CreateMenu(executor, (str) => "css_debug lastrequest " + type + " #" + str)); - return; - } + if (info.ArgCount == 2) { + MenuManager.OpenCenterHtmlMenu(plugin, executor, + playerSelector.CreateMenu(executor, + str => "css_debug lastrequest " + type + " #" + str)); + return; + } - var fromPlayer = GetVulnerableTarget(info, 2); - if (fromPlayer == null) - return; + var fromPlayer = GetVulnerableTarget(info, 2); + if (fromPlayer == null) return; - switch (info.ArgCount) - { - case 3 when executor != null: - { - if (executor.Team == CsTeam.Terrorist) - _manager.InitiateLastRequest(executor, fromPlayer.First(), type.Value); - else // They aren't necessarily on different teams, but this is debug so that's OK - _manager.InitiateLastRequest(fromPlayer.First(), executor, type.Value); - return; - } - case 4: - { - var targetPlayer = GetVulnerableTarget(info, 3); - if (targetPlayer == null) - return; - _manager.InitiateLastRequest(fromPlayer.First(), targetPlayer.First(), type.Value); - break; - } - } + switch (info.ArgCount) { + case 3 when executor != null: { + if (executor.Team == CsTeam.Terrorist) + manager.InitiateLastRequest(executor, fromPlayer.First(), type.Value); + else // They aren't necessarily on different teams, but this is debug so that's OK + manager.InitiateLastRequest(fromPlayer.First(), executor, type.Value); + return; + } + case 4: { + var targetPlayer = GetVulnerableTarget(info, 3); + if (targetPlayer == null) return; + manager.InitiateLastRequest(fromPlayer.First(), targetPlayer.First(), + type.Value); + break; + } } + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs index ad7799db..083d8231 100644 --- a/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs +++ b/mod/Jailbreak.Debug/Subcommands/MarkRebel.cs @@ -6,29 +6,27 @@ namespace Jailbreak.Debug.Subcommands; // css_markrebel [player] -public class MarkRebel(IServiceProvider services) : AbstractCommand(services) -{ - public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) - { - if (info.ArgCount == 1) - { - info.ReplyToCommand("Specify target?"); - return; - } +public class MarkRebel(IServiceProvider services) : AbstractCommand(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 target = GetVulnerableTarget(info); + if (target == null) return; - var duration = RebelManager.MAX_REBEL_TIME; - if (info.ArgCount == 3) - if (!int.TryParse(info.GetArg(2), out duration)) - { - info.ReplyToCommand("Invalid duration"); - return; - } + var duration = RebelManager.MAX_REBEL_TIME; + 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 {GetTargetLabel(info)} as rebels for {duration} seconds."); - } + 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/MarkST.cs b/mod/Jailbreak.Debug/Subcommands/MarkST.cs index 49eaf39a..97c942aa 100644 --- a/mod/Jailbreak.Debug/Subcommands/MarkST.cs +++ b/mod/Jailbreak.Debug/Subcommands/MarkST.cs @@ -1,32 +1,27 @@ using CounterStrikeSharp.API.Core; -using Jailbreak.Public.Mod.Rebel; using Jailbreak.Public.Mod.Warden; -using Jailbreak.Rebel; using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Debug.Subcommands; // css_markst [player] -public class MarkST(IServiceProvider services) : AbstractCommand(services) -{ - public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) - { - if (info.ArgCount == 1) - { - info.ReplyToCommand("Specify target?"); - return; - } +public class MarkST(IServiceProvider services) : AbstractCommand(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 target = GetVulnerableTarget(info); + if (target == null) return; - var stService = Services.GetRequiredService(); - foreach (var player in target.Players) - { - stService.SetSpecialTreatment(player, !stService.IsSpecialTreatment(player)); - } + var stService = Services.GetRequiredService(); + foreach (var player in target.Players) + stService.SetSpecialTreatment(player, + !stService.IsSpecialTreatment(player)); - info.ReplyToCommand("Toggled special treatment for " + GetTargetLabel(info) + "."); - } + info.ReplyToCommand("Toggled special treatment for " + GetTargetLabel(info) + + "."); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/Pardon.cs b/mod/Jailbreak.Debug/Subcommands/Pardon.cs index aa5a2efc..6aa146d0 100644 --- a/mod/Jailbreak.Debug/Subcommands/Pardon.cs +++ b/mod/Jailbreak.Debug/Subcommands/Pardon.cs @@ -5,22 +5,20 @@ namespace Jailbreak.Debug.Subcommands; // css_pardon [player] -public class Pardon(IServiceProvider services) : AbstractCommand(services) -{ - public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) - { - if (info.ArgCount == 1) - { - info.ReplyToCommand("Specify target?"); - return; - } +public class Pardon(IServiceProvider services) : AbstractCommand(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 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)}"); - } + info.ReplyToCommand($"Pardoned {GetTargetLabel(info)}"); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs index c8bc6376..37893170 100644 --- a/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs +++ b/mod/Jailbreak.Debug/Subcommands/WrappedInfo.cs @@ -3,32 +3,24 @@ namespace Jailbreak.Debug.Subcommands; -public class WrappedInfo(CommandInfo info) -{ - public readonly CommandInfo Info = info; +public class WrappedInfo(CommandInfo info) { + public readonly CommandInfo Info = info; - public CCSPlayerController? CallingPlayer => Info.CallingPlayer; + public CCSPlayerController? CallingPlayer => Info.CallingPlayer; - public IntPtr Handle => Info.Handle; + public IntPtr Handle => Info.Handle; - public int ArgCount => Info.ArgCount - 1; + public int ArgCount => Info.ArgCount - 1; - public string ArgString => Info.ArgString[(Info.ArgString.IndexOf(' ') + 1)..]; + public string ArgString + => Info.ArgString[(Info.ArgString.IndexOf(' ') + 1)..]; - public string GetCommandString => Info.GetCommandString[(Info.GetCommandString.IndexOf(' ') + 1)..]; + public string GetCommandString + => Info.GetCommandString[(Info.GetCommandString.IndexOf(' ') + 1)..]; - public string ArgByIndex(int index) - { - return Info.ArgByIndex(index + 1); - } + public string ArgByIndex(int index) { return Info.ArgByIndex(index + 1); } - public string GetArg(int index) - { - return Info.GetArg(index + 1); - } + public string GetArg(int index) { return Info.GetArg(index + 1); } - public void ReplyToCommand(string message) - { - Info.ReplyToCommand(message); - } + public void ReplyToCommand(string message) { Info.ReplyToCommand(message); } } \ No newline at end of file diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index e668746f..7654a885 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -14,7 +14,7 @@ namespace Jailbreak.LastGuard; public class LastGuard(LastGuardConfig config, ILastGuardNotifications notifications, ILastRequestManager lrManager) : ILastGuardService, IPluginBehavior { - private bool _canStart; + private bool canStart; [GameEventHandler] public HookResult OnPlayerDeathEvent(EventPlayerDeath @event, GameEventInfo info) @@ -33,22 +33,22 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo private void checkLastGuard(CCSPlayerController? poi) { if (poi == null) return; - if (poi.Team != CsTeam.CounterTerrorist) ; + if (poi.Team != CsTeam.CounterTerrorist) return; var aliveCts = Utilities.GetPlayers() .Count(plr => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }) - 1; - if (aliveCts != 1 || lrManager.IsLREnabled) ; + if (aliveCts != 1 || lrManager.IsLREnabled) return; var lastGuard = Utilities.GetPlayers().First(plr => plr.IsReal() && plr != poi && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }); - if (_canStart) + if (canStart) StartLastGuard(lastGuard); } [GameEventHandler] public HookResult OnRoundStartEvent(EventRoundStart @event, GameEventInfo info) { - _canStart = Utilities.GetPlayers() + canStart = Utilities.GetPlayers() .Count(plr => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }) >= config.MinimumCTs; return HookResult.Continue; @@ -91,4 +91,4 @@ public void StartLastGuard(CCSPlayerController lastGuard) player.GiveNamedItem(config.LastGuardWeapon); } } -} +} \ No newline at end of file diff --git a/mod/Jailbreak.LastGuard/LastGuardConfig.cs b/mod/Jailbreak.LastGuard/LastGuardConfig.cs index 534d7b4f..3ba834f7 100644 --- a/mod/Jailbreak.LastGuard/LastGuardConfig.cs +++ b/mod/Jailbreak.LastGuard/LastGuardConfig.cs @@ -1,7 +1,6 @@ namespace Jailbreak.LastGuard; -public class LastGuardConfig -{ - public string? LastGuardWeapon { get; } = "weapon_glock"; - public int MinimumCTs { get; } = 4; +public class LastGuardConfig { + public string? LastGuardWeapon { get; } = "weapon_glock"; + public int MinimumCTs { get; } = 4; } \ No newline at end of file diff --git a/mod/Jailbreak.LastGuard/LastGuardServiceExtension.cs b/mod/Jailbreak.LastGuard/LastGuardServiceExtension.cs index 00c1e040..7edff0b1 100644 --- a/mod/Jailbreak.LastGuard/LastGuardServiceExtension.cs +++ b/mod/Jailbreak.LastGuard/LastGuardServiceExtension.cs @@ -4,11 +4,9 @@ namespace Jailbreak.LastGuard; -public static class RebelServiceExtension -{ - public static void AddJailbreakLastGuard(this IServiceCollection collection) - { - collection.AddConfig("lastguard"); - collection.AddPluginBehavior(); - } +public static class RebelServiceExtension { + public static void AddJailbreakLastGuard(this IServiceCollection collection) { + collection.AddConfig("lastguard"); + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/EndRaceCommand.cs b/mod/Jailbreak.LastRequest/EndRaceCommand.cs index 2564cc61..958bf106 100644 --- a/mod/Jailbreak.LastRequest/EndRaceCommand.cs +++ b/mod/Jailbreak.LastRequest/EndRaceCommand.cs @@ -1,35 +1,30 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Commands; -using Jailbreak.LastRequest.LastRequests; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest; -public class EndRaceCommand(ILastRequestManager lrManager) : IPluginBehavior -{ - [ConsoleCommand("css_endrace", "Used to set the end point of a race LR")] - [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] - public void Command_EndRace(CCSPlayerController? executor, CommandInfo info) - { - if (executor == null) - return; - var lr = lrManager.GetActiveLR(executor); +public class EndRaceCommand(ILastRequestManager lrManager) : IPluginBehavior { + [ConsoleCommand("css_endrace", "Used to set the end point of a race LR")] + [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] + public void Command_EndRace(CCSPlayerController? executor, CommandInfo info) { + if (executor == null) return; + var lr = lrManager.GetActiveLR(executor); - if (lr is not { type: LRType.Race }) - { - info.ReplyToCommand("You must be in a race LR to use this command."); - return; - } - - if (lr.state != LRState.Pending) - { - info.ReplyToCommand("You must be in the pending state to use this command."); - return; - } + if (lr is not { Type: LRType.RACE }) { + info.ReplyToCommand("You must be in a race LR to use this command."); + return; + } - lr.Execute(); + if (lr.State != LRState.PENDING) { + info.ReplyToCommand( + "You must be in the pending state to use this command."); + return; } + + lr.Execute(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/Jailbreak.LastRequest.csproj b/mod/Jailbreak.LastRequest/Jailbreak.LastRequest.csproj index 70f814b3..f430fd60 100644 --- a/mod/Jailbreak.LastRequest/Jailbreak.LastRequest.csproj +++ b/mod/Jailbreak.LastRequest/Jailbreak.LastRequest.csproj @@ -7,12 +7,8 @@ - - - - - - + + diff --git a/mod/Jailbreak.LastRequest/LastRequestCommand.cs b/mod/Jailbreak.LastRequest/LastRequestCommand.cs index 96aebda0..acaaee77 100644 --- a/mod/Jailbreak.LastRequest/LastRequestCommand.cs +++ b/mod/Jailbreak.LastRequest/LastRequestCommand.cs @@ -1,7 +1,6 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Commands; -using CounterStrikeSharp.API.Modules.Commands.Targeting; using CounterStrikeSharp.API.Modules.Menu; using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Extensions; @@ -10,128 +9,108 @@ using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; -using Microsoft.Extensions.DependencyModel; namespace Jailbreak.LastRequest; -public class LastRequestCommand( - ILastRequestManager manager, - ILastRequestMessages messages, - IGenericCommandNotifications generic, - ILastRequestFactory factory) - : IPluginBehavior -{ - private LastRequestMenuSelector _menuSelector; - private LastRequestPlayerSelector _playerSelector; - private BasePlugin _plugin; - - // css_lr - public void Start(BasePlugin plugin) - { - _plugin = plugin; - _playerSelector = new LastRequestPlayerSelector(manager); - _menuSelector = new LastRequestMenuSelector(factory); +public class LastRequestCommand(ILastRequestManager manager, + ILastRequestMessages messages, IGenericCommandNotifications generic, + ILastRequestFactory factory) : IPluginBehavior { + private LastRequestMenuSelector? menuSelector; + private LastRequestPlayerSelector? playerSelector; + private BasePlugin? plugin; + + // css_lr + public void Start(BasePlugin basePlugin) { + plugin = basePlugin; + playerSelector = new LastRequestPlayerSelector(manager, plugin); + menuSelector = new LastRequestMenuSelector(factory, plugin); + } + + [ConsoleCommand("css_lr", "Start a last request as a prisoner")] + [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] + public void Command_LastRequest(CCSPlayerController? executor, + CommandInfo info) { + if (executor == null || !executor.IsReal()) return; + if (executor.Team != CsTeam.Terrorist) { + info.ReplyToCommand("You must be a terrorist to LR."); + return; } - [ConsoleCommand("css_lr", "Start a last request as a prisoner")] - [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] - public void Command_LastRequest(CCSPlayerController? executor, CommandInfo info) - { - if (executor == null || !executor.IsReal()) - return; - if (executor.Team != CsTeam.Terrorist) - { - info.ReplyToCommand("You must be a terrorist to LR."); - return; - } - - if (!executor.PawnIsAlive) - { - info.ReplyToCommand("You must be alive to LR."); - return; - } - - if (!manager.IsLREnabled) - { - messages.LastRequestNotEnabled().ToPlayerChat(executor); - return; - } - - if (!_playerSelector.WouldHavePlayers()) - { - info.ReplyToCommand("There are no players available to LR."); - return; - } - - if (manager.IsInLR(executor)) - { - info.ReplyToCommand("You are already in an LR!"); - return; - } - - if (info.ArgCount == 1) - { - MenuManager.OpenCenterHtmlMenu(_plugin, executor, _menuSelector.GetMenu()); - return; - } - - // Validate LR - var type = LRTypeExtensions.FromString(info.GetArg(1)); - if (type is null) - { - messages.InvalidLastRequest(info.GetArg(1)).ToPlayerChat(executor); - return; - } - - if (info.ArgCount == 2) - { - MenuManager.OpenCenterHtmlMenu(_plugin, executor, - _playerSelector.CreateMenu(executor, (str) => "css_lr " + type + " #" + str)); - return; - } - - var target = info.GetArgTargetResult(2); - if (target.Players.Count == 0) - { - generic.PlayerNotFound(info.GetArg(2)); - return; - } - - if (target.Players.Count > 1) - { - generic.PlayerFoundMultiple(info.GetArg(2)); - return; - } - - var player = target.Players.First(); - if (player.Team != CsTeam.CounterTerrorist) - { - messages.InvalidPlayerChoice(player, "They're not on CT!"); - return; - } - - if (!player.PawnIsAlive) - { - messages.InvalidPlayerChoice(player, "They're not alive!"); - return; - } - - if (manager.IsInLR(player)) - { - messages.InvalidPlayerChoice(player, "They're already in an LR!"); - return; - } - - //One final check in case they got the menu open in the last round - if (!manager.IsLREnabled) - { - messages.LastRequestNotEnabled().ToPlayerChat(executor); - return; - } - - if (!manager.InitiateLastRequest(executor, player, (LRType)type)) - { - info.ReplyToCommand("An error occurred while initiating the last request. Please try again later."); - } + if (!executor.PawnIsAlive) { + info.ReplyToCommand("You must be alive to LR."); + return; } + + if (!manager.IsLREnabled) { + messages.LastRequestNotEnabled().ToPlayerChat(executor); + return; + } + + if (!playerSelector!.WouldHavePlayers()) { + info.ReplyToCommand("There are no players available to LR."); + return; + } + + if (manager.IsInLR(executor)) { + info.ReplyToCommand("You are already in an LR!"); + return; + } + + if (info.ArgCount == 1) { + MenuManager.OpenCenterHtmlMenu(plugin!, executor, + menuSelector!.GetMenu()); + return; + } + + // Validate LR + var type = LRTypeExtensions.FromString(info.GetArg(1)); + if (type is null) { + messages.InvalidLastRequest(info.GetArg(1)).ToPlayerChat(executor); + return; + } + + if (info.ArgCount == 2) { + MenuManager.OpenCenterHtmlMenu(plugin!, executor, + playerSelector.CreateMenu(executor, + str => "css_lr " + type + " #" + str)); + return; + } + + var target = info.GetArgTargetResult(2); + if (target.Players.Count == 0) { + generic.PlayerNotFound(info.GetArg(2)); + return; + } + + if (target.Players.Count > 1) { + generic.PlayerFoundMultiple(info.GetArg(2)); + return; + } + + var player = target.Players.First(); + if (player.Team != CsTeam.CounterTerrorist) { + messages.InvalidPlayerChoice(player, "They're not on CT!"); + return; + } + + if (!player.PawnIsAlive) { + messages.InvalidPlayerChoice(player, "They're not alive!"); + return; + } + + if (manager.IsInLR(player)) { + messages.InvalidPlayerChoice(player, "They're already in an LR!"); + return; + } + + //One final check in case they got the menu open in the last round + if (!manager.IsLREnabled) { + messages.LastRequestNotEnabled().ToPlayerChat(executor); + return; + } + + if (!manager.InitiateLastRequest(executor, player, (LRType)type)) + info.ReplyToCommand( + "An error occurred while initiating the last request. Please try again later."); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestConfig.cs b/mod/Jailbreak.LastRequest/LastRequestConfig.cs index fd59e8aa..af5ed811 100644 --- a/mod/Jailbreak.LastRequest/LastRequestConfig.cs +++ b/mod/Jailbreak.LastRequest/LastRequestConfig.cs @@ -1,6 +1,5 @@ namespace Jailbreak.LastRequest; -public class LastRequestConfig -{ - public int PrisonersToActiveLR { get; set; } = 2; +public class LastRequestConfig { + public int PrisonersToActiveLR { get; set; } = 2; } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestExtension.cs b/mod/Jailbreak.LastRequest/LastRequestExtension.cs index 055406d5..892f6604 100644 --- a/mod/Jailbreak.LastRequest/LastRequestExtension.cs +++ b/mod/Jailbreak.LastRequest/LastRequestExtension.cs @@ -4,15 +4,14 @@ namespace Jailbreak.LastRequest; -public static class LastRequestExtension -{ - public static void AddJailbreakLastRequest(this IServiceCollection collection) - { - collection.AddConfig("lastrequest"); - - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } +public static class LastRequestExtension { + public static void AddJailbreakLastRequest( + this IServiceCollection collection) { + collection.AddConfig("lastrequest"); + + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestFactory.cs b/mod/Jailbreak.LastRequest/LastRequestFactory.cs index c95dda4e..eadf903a 100644 --- a/mod/Jailbreak.LastRequest/LastRequestFactory.cs +++ b/mod/Jailbreak.LastRequest/LastRequestFactory.cs @@ -7,40 +7,37 @@ namespace Jailbreak.LastRequest; -public class LastRequestFactory(ILastRequestManager manager, IServiceProvider _services) : ILastRequestFactory -{ - private BasePlugin _plugin; +public class LastRequestFactory(ILastRequestManager manager, + IServiceProvider services) : ILastRequestFactory { + private BasePlugin? plugin; - public void Start(BasePlugin parent) - { - _plugin = parent; - } + public void Start(BasePlugin basePlugin) { plugin = basePlugin; } - public AbstractLastRequest CreateLastRequest(CCSPlayerController prisoner, CCSPlayerController guard, LRType type) - { - return type switch - { - LRType.KnifeFight => new KnifeFight(_plugin, manager, prisoner, guard), - LRType.GunToss => new GunToss(_plugin, manager, prisoner, guard), - LRType.NoScope => new NoScope(_plugin, manager, prisoner, guard), - LRType.RockPaperScissors => new RockPaperScissors(_plugin, manager, prisoner, guard), - LRType.Coinflip => new Coinflip(_plugin, manager, prisoner, guard), - LRType.Race => new Race(_plugin, manager, prisoner, guard, _services.GetRequiredService()), - _ => throw new ArgumentException("Invalid last request type: " + type, nameof(type)) - }; - } + public AbstractLastRequest CreateLastRequest(CCSPlayerController prisoner, + CCSPlayerController guard, LRType type) { + return type switch { + LRType.KNIFE_FIGHT => new KnifeFight(plugin!, manager, prisoner, guard), + LRType.GUN_TOSS => new GunToss(plugin!, manager, prisoner, guard), + LRType.NO_SCOPE => new NoScope(plugin!, manager, prisoner, guard), + LRType.ROCK_PAPER_SCISSORS => new RockPaperScissors(plugin!, manager, + prisoner, guard), + LRType.COINFLIP => new Coinflip(plugin!, manager, prisoner, guard), + LRType.RACE => new Race(plugin!, manager, prisoner, guard, + services.GetRequiredService()), + _ => throw new ArgumentException("Invalid last request type: " + type, + nameof(type)) + }; + } - public bool IsValidType(LRType type) - { - return type switch - { - LRType.KnifeFight => true, - LRType.GunToss => true, - LRType.NoScope => true, - LRType.RockPaperScissors => true, - LRType.Coinflip => true, - LRType.Race => true, - _ => false - }; - } + public bool IsValidType(LRType type) { + return type switch { + LRType.KNIFE_FIGHT => true, + LRType.GUN_TOSS => true, + LRType.NO_SCOPE => true, + LRType.ROCK_PAPER_SCISSORS => true, + LRType.COINFLIP => true, + LRType.RACE => true, + _ => false + }; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestManager.cs b/mod/Jailbreak.LastRequest/LastRequestManager.cs index 63d1e530..0e5c19c3 100644 --- a/mod/Jailbreak.LastRequest/LastRequestManager.cs +++ b/mod/Jailbreak.LastRequest/LastRequestManager.cs @@ -1,290 +1,238 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Cvars; -using CounterStrikeSharp.API.Modules.Memory; -using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; using CounterStrikeSharp.API.Modules.Menu; using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; -using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; +using Jailbreak.Public.Mod.Damage; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; -using Jailbreak.Public.Mod.Damage; using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.LastRequest; -public class LastRequestManager( - LastRequestConfig _config, - ILastRequestMessages _messages, - IServiceProvider _provider -) - : ILastRequestManager, IBlockUserDamage -{ - private BasePlugin _parent; - private ILastRequestFactory _factory; - - public bool IsLREnabled { get; set; } - public IList ActiveLRs { get; } = new List(); - - public void Start(BasePlugin parent) - { - _factory = _provider.GetRequiredService(); - _parent = parent; - } +public class LastRequestManager(LastRequestConfig config, + ILastRequestMessages messages, IServiceProvider provider) + : ILastRequestManager, IBlockUserDamage { + private ILastRequestFactory? factory; - [GameEventHandler(HookMode.Pre)] - public HookResult OnTakeDamage(EventPlayerHurt @event, GameEventInfo info) - { - IBlockUserDamage damageHandler = this; - return damageHandler.BlockUserDamage(@event, info); - } + public bool ShouldBlockDamage(CCSPlayerController player, + CCSPlayerController? attacker, EventPlayerHurt @event) { + if (!IsLREnabled) return false; - public bool ShouldBlockDamage(CCSPlayerController player, CCSPlayerController? attacker, EventPlayerHurt @event) - { - if (!IsLREnabled) - return false; - - if (attacker == null || !attacker.IsReal()) - { - return false; - } - - var playerLR = ((ILastRequestManager)this).GetActiveLR(player); - var attackerLR = ((ILastRequestManager)this).GetActiveLR(attacker); - - if (playerLR == null && attackerLR == null) - { - // Neither of them is in an LR - return false; - } - - if ((playerLR == null) != (attackerLR == null)) - { - // One of them is in an LR - _messages.DamageBlockedInsideLastRequest.ToPlayerCenter(attacker); - return true; - } - - // Both of them are in LR - // verify they're in same LR - if (playerLR == null) - return false; - - if (playerLR.prisoner.Equals(attacker) || playerLR.guard.Equals(attacker)) - { - // Same LR, allow damage - return false; - } - - _messages.DamageBlockedNotInSameLR.ToPlayerCenter(attacker); - return true; - } + if (attacker == null || !attacker.IsReal()) return false; - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - if (IsLREnabled) - foreach (var lr in ActiveLRs) - EndLastRequest(lr, LRResult.TimedOut); + var playerLR = ((ILastRequestManager)this).GetActiveLR(player); + var attackerLR = ((ILastRequestManager)this).GetActiveLR(attacker); - IsLREnabled = false; - return HookResult.Continue; - } + if (playerLR == null && attackerLR == null) + // Neither of them is in an LR + return false; - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - foreach (var player in Utilities.GetPlayers()) - { - MenuManager.CloseActiveMenu(player); - } - - if (ServerExtensions.GetGameRules().WarmupPeriod) - return HookResult.Continue; - if (CountAlivePrisoners() > _config.PrisonersToActiveLR) - { - this.IsLREnabled = false; - return HookResult.Continue; - } - - this.IsLREnabled = true; - _messages.LastRequestEnabled().ToAllChat(); - return HookResult.Continue; + if (playerLR == null != (attackerLR == null)) { + // One of them is in an LR + messages.DamageBlockedInsideLastRequest.ToPlayerCenter(attacker); + return true; } - [GameEventHandler(HookMode.Post)] - public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var player = @event.Userid; - if (!player.IsReal() || ServerExtensions.GetGameRules().WarmupPeriod) - return HookResult.Continue; - - if (IsLREnabled) - { - // Handle active LRs - var activeLr = ((ILastRequestManager)this).GetActiveLR(player); - if (activeLr != null && activeLr.state != LRState.Completed) - { - var isPrisoner = activeLr.prisoner.Slot == player.Slot; - EndLastRequest(activeLr, isPrisoner ? LRResult.GuardWin : LRResult.PrisonerWin); - } - - return HookResult.Continue; - } - - if (player.GetTeam() != CsTeam.Terrorist) - return HookResult.Continue; - - if (CountAlivePrisoners() - 1 > _config.PrisonersToActiveLR) - return HookResult.Continue; - - EnableLR(player); - return HookResult.Continue; - } + // Both of them are in LR + // verify they're in same LR + if (playerLR == null) return false; - [GameEventHandler(HookMode.Post)] - public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) - { - var player = @event.Userid; + if (playerLR.Prisoner.Equals(attacker) || playerLR.Guard.Equals(attacker)) + // Same LR, allow damage + return false; - if (player == null) return HookResult.Continue; + messages.DamageBlockedNotInSameLR.ToPlayerCenter(attacker); + return true; + } - if (!player.IsReal() || ServerExtensions.GetGameRules().WarmupPeriod) - return HookResult.Continue; + public bool IsLREnabled { get; set; } - if (IsLREnabled) - return HookResult.Continue; + public IList ActiveLRs { get; } = + new List(); - var activeLr = ((ILastRequestManager)this).GetActiveLR(player); + public void Start(BasePlugin basePlugin) { + factory = provider.GetRequiredService(); + } + + public void DisableLR() { IsLREnabled = false; } + + public void EnableLR(CCSPlayerController? died = null) { + messages.LastRequestEnabled().ToAllChat(); + IsLREnabled = true; + setRoundTime(60); - if (activeLr != null && activeLr.state != LRState.Active) - { - EndLastRequest(activeLr, player.Team == CsTeam.Terrorist ? LRResult.GuardWin : LRResult.PrisonerWin); - return HookResult.Continue; - } + foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) { + // player.ExecuteClientCommand($"play sounds/lr"); + if (player.Team != CsTeam.Terrorist || !player.PawnIsAlive) continue; + if (died != null && player.SteamID == died.SteamID) continue; + player.ExecuteClientCommandFromServer("css_lr"); + } + } - if (player.GetTeam() != CsTeam.Terrorist) - return HookResult.Continue; - if (CountAlivePrisoners() > _config.PrisonersToActiveLR) - return HookResult.Continue; + public bool InitiateLastRequest(CCSPlayerController prisoner, + CCSPlayerController guard, LRType type) { + try { + var lr = factory!.CreateLastRequest(prisoner, guard, type); + lr.Setup(); + ActiveLRs.Add(lr); - EnableLR(); - return HookResult.Continue; - } + if (prisoner.Pawn.Value != null) { + prisoner.Pawn.Value.Health = 100; + prisoner.PlayerPawn.Value!.ArmorValue = 0; + Utilities.SetStateChanged(prisoner.Pawn.Value, "CBaseEntity", + "m_iHealth"); + } - public void DisableLR() - { - IsLREnabled = false; - } - public void EnableLR(CCSPlayerController? died = null) - { - _messages.LastRequestEnabled().ToAllChat(); - IsLREnabled = true; - SetRoundTime(60); - - foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) - { - // player.ExecuteClientCommand($"play sounds/lr"); - if (player.Team != CsTeam.Terrorist || !player.PawnIsAlive) - continue; - if (died != null && player.SteamID == died.SteamID) - continue; - player.ExecuteClientCommandFromServer("css_lr"); - } - } + if (guard.Pawn.Value != null) { + guard.Pawn.Value.Health = 100; + guard.PlayerPawn.Value!.ArmorValue = 0; + Utilities.SetStateChanged(guard.Pawn.Value, "CBaseEntity", "m_iHealth"); + } - private int GetCurrentRoundTime() - { - var gamerules = ServerExtensions.GetGameRules(); - var timeleft = (gamerules.RoundStartTime + gamerules.RoundTime) - Server.CurrentTime; - return (int)timeleft; + messages.InformLastRequest(lr).ToAllChat(); + return true; + } catch (ArgumentException e) { + Console.WriteLine(e); + return false; } + } - private int GetCurrentTimeElapsed() - { - var gamerules = ServerExtensions.GetGameRules(); - var freezeTime = gamerules.FreezeTime; - return (int)((Server.CurrentTime - gamerules.RoundStartTime) - freezeTime); + public bool EndLastRequest(AbstractLastRequest lr, LRResult result) { + if (result is LRResult.GUARD_WIN or LRResult.PRISONER_WIN) { + addRoundTime(30); + messages.LastRequestDecided(lr, result).ToAllChat(); } - private void SetRoundTime(int time) - { - var gamerules = ServerExtensions.GetGameRules(); - gamerules.RoundTime = (int)GetCurrentTimeElapsed() + time; + lr.OnEnd(result); + ActiveLRs.Remove(lr); + return true; + } - Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), "CCSGameRulesProxy", "m_pGameRules"); - } + [GameEventHandler(HookMode.Pre)] + public HookResult OnTakeDamage(EventPlayerHurt @event, GameEventInfo info) { + IBlockUserDamage damageHandler = this; + return damageHandler.BlockUserDamage(@event, info); + } - private void AddRoundTime(int time) - { - var gamerules = ServerExtensions.GetGameRules(); - gamerules.RoundTime += time; + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { + if (IsLREnabled) + foreach (var lr in ActiveLRs) + EndLastRequest(lr, LRResult.TIMED_OUT); - Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), "CCSGameRulesProxy", "m_pGameRules"); - } + IsLREnabled = false; + return HookResult.Continue; + } - private int CountAlivePrisoners() - { - return Utilities.GetPlayers().Count(CountsToLR); - } + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { + foreach (var player in Utilities.GetPlayers()) + MenuManager.CloseActiveMenu(player); - private bool CountsToLR(CCSPlayerController player) - { - if (!player.IsReal()) - return false; - if (!player.PawnIsAlive) - return false; - return player.GetTeam() == CsTeam.Terrorist; - } + if (ServerExtensions.GetGameRules().WarmupPeriod) + return HookResult.Continue; + if (countAlivePrisoners() > config.PrisonersToActiveLR) { + IsLREnabled = false; + return HookResult.Continue; + } - public bool InitiateLastRequest(CCSPlayerController prisoner, CCSPlayerController guard, LRType type) - { - try - { - var lr = _factory.CreateLastRequest(prisoner, guard, type); - lr.Setup(); - ActiveLRs.Add(lr); - - if (prisoner.Pawn.Value != null) - { - prisoner.Pawn.Value.Health = 100; - prisoner.PlayerPawn.Value!.ArmorValue = 0; - Utilities.SetStateChanged(prisoner.Pawn.Value, "CBaseEntity", "m_iHealth"); - } - - - if (guard.Pawn.Value != null) - { - guard.Pawn.Value.Health = 100; - guard.PlayerPawn.Value!.ArmorValue = 0; - Utilities.SetStateChanged(guard.Pawn.Value, "CBaseEntity", "m_iHealth"); - } - - _messages.InformLastRequest(lr).ToAllChat(); - return true; - } - catch (ArgumentException e) - { - Console.WriteLine(e); - return false; - } - } + IsLREnabled = true; + messages.LastRequestEnabled().ToAllChat(); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { + var player = @event.Userid; + if (player == null || !player.IsReal() + || ServerExtensions.GetGameRules().WarmupPeriod) + return HookResult.Continue; + + if (IsLREnabled) { + // Handle active LRs + var activeLr = ((ILastRequestManager)this).GetActiveLR(player); + if (activeLr != null && activeLr.State != LRState.COMPLETED) { + var isPrisoner = activeLr.Prisoner.Slot == player.Slot; + EndLastRequest(activeLr, + isPrisoner ? LRResult.GUARD_WIN : LRResult.PRISONER_WIN); + } + + return HookResult.Continue; + } + + if (player.GetTeam() != CsTeam.Terrorist) return HookResult.Continue; + + if (countAlivePrisoners() - 1 > config.PrisonersToActiveLR) + return HookResult.Continue; + + EnableLR(player); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, + GameEventInfo info) { + var player = @event.Userid; + + if (player == null) return HookResult.Continue; + + if (!player.IsReal() || ServerExtensions.GetGameRules().WarmupPeriod) + return HookResult.Continue; + + if (IsLREnabled) return HookResult.Continue; - public bool EndLastRequest(AbstractLastRequest lr, LRResult result) - { - if (result is LRResult.GuardWin or LRResult.PrisonerWin) - { - AddRoundTime(30); - _messages.LastRequestDecided(lr, result).ToAllChat(); - } - - lr.OnEnd(result); - ActiveLRs.Remove(lr); - return true; - } + var activeLr = ((ILastRequestManager)this).GetActiveLR(player); + + if (activeLr != null && activeLr.State != LRState.ACTIVE) { + EndLastRequest(activeLr, + player.Team == CsTeam.Terrorist ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN); + return HookResult.Continue; + } + + if (player.GetTeam() != CsTeam.Terrorist) return HookResult.Continue; + if (countAlivePrisoners() > config.PrisonersToActiveLR) + return HookResult.Continue; + + EnableLR(); + return HookResult.Continue; + } + + private int getCurrentTimeElapsed() { + var gamerules = ServerExtensions.GetGameRules(); + var freezeTime = gamerules.FreezeTime; + return (int)(Server.CurrentTime - gamerules.RoundStartTime - freezeTime); + } + + private void setRoundTime(int time) { + var gamerules = ServerExtensions.GetGameRules(); + gamerules.RoundTime = getCurrentTimeElapsed() + time; + + Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), + "CCSGameRulesProxy", "m_pGameRules"); + } + + private void addRoundTime(int time) { + var gamerules = ServerExtensions.GetGameRules(); + gamerules.RoundTime += time; + + Utilities.SetStateChanged(ServerExtensions.GetGameRulesProxy(), + "CCSGameRulesProxy", "m_pGameRules"); + } + + private int countAlivePrisoners() { + return Utilities.GetPlayers().Count(prisonerCountsToLR); + } + + private bool prisonerCountsToLR(CCSPlayerController player) { + if (!player.IsReal()) return false; + if (!player.PawnIsAlive) return false; + return player.GetTeam() == CsTeam.Terrorist; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestMenuSelector.cs b/mod/Jailbreak.LastRequest/LastRequestMenuSelector.cs index 472b9f0b..c0cb6484 100644 --- a/mod/Jailbreak.LastRequest/LastRequestMenuSelector.cs +++ b/mod/Jailbreak.LastRequest/LastRequestMenuSelector.cs @@ -1,40 +1,31 @@ using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Entities; using CounterStrikeSharp.API.Modules.Menu; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest; -public class LastRequestMenuSelector -{ - private readonly CenterHtmlMenu _menu; - private readonly Func _command; +public class LastRequestMenuSelector { + private readonly Func command; + private readonly CenterHtmlMenu menu; - public LastRequestMenuSelector(ILastRequestFactory factory) : this(factory, (lr) => "css_lr " + ((int)lr)) - { - } + public LastRequestMenuSelector(ILastRequestFactory factory, BasePlugin plugin) + : this(factory, lr => "css_lr " + (int)lr, plugin) { } - public LastRequestMenuSelector(ILastRequestFactory factory, Func command) - { - _command = command; - _menu = new CenterHtmlMenu("css_lr [LR] [Player]"); - foreach (LRType lr in Enum.GetValues(typeof(LRType))) - { - if (!factory.IsValidType(lr)) - continue; - _menu.AddMenuOption(lr.ToFriendlyString(), (p, o) => OnSelectLR(p, lr)); - } + public LastRequestMenuSelector(ILastRequestFactory factory, + Func command, BasePlugin plugin) { + this.command = command; + menu = new CenterHtmlMenu("css_lr [LR] [Player]", plugin); + foreach (LRType lr in Enum.GetValues(typeof(LRType))) { + if (!factory.IsValidType(lr)) continue; + menu.AddMenuOption(lr.ToFriendlyString(), (p, _) => OnSelectLR(p, lr)); } + } - public CenterHtmlMenu GetMenu() - { - return _menu; - } + public CenterHtmlMenu GetMenu() { return menu; } - private void OnSelectLR(CCSPlayerController player, LRType lr) - { - MenuManager.CloseActiveMenu(player); - player.ExecuteClientCommandFromServer(this._command.Invoke(lr)); - } + private void OnSelectLR(CCSPlayerController player, LRType lr) { + MenuManager.CloseActiveMenu(player); + player.ExecuteClientCommandFromServer(command.Invoke(lr)); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs b/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs index 36f8e191..fb1cf0a6 100644 --- a/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs +++ b/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs @@ -4,47 +4,38 @@ using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; -using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest; -public class LastRequestPlayerSelector -{ - private ILastRequestManager _lrManager; - private bool debug; - - public LastRequestPlayerSelector(ILastRequestManager manager, bool debug = false) - { - _lrManager = manager; - this.debug = debug; +public class LastRequestPlayerSelector(ILastRequestManager manager, + BasePlugin plugin, bool debug = false) { + public CenterHtmlMenu CreateMenu(CCSPlayerController player, + Func command) { + var menu = new CenterHtmlMenu(command.Invoke("[Player]"), plugin); + + foreach (var target in Utilities.GetPlayers()) { + if (!target.IsReal()) continue; + if (!target.PawnIsAlive + || target.Team != CsTeam.CounterTerrorist && !debug) + continue; + menu.AddMenuOption(target.PlayerName, + (_, _) => OnSelect(player, command, target.UserId.ToString()), + !debug && manager.IsInLR(target)); } - public CenterHtmlMenu CreateMenu(CCSPlayerController player, Func command) - { - CenterHtmlMenu menu = new CenterHtmlMenu(command.Invoke("[Player]")); - - foreach (var target in Utilities.GetPlayers()) - { - if (!target.IsReal()) - continue; - if (!target.PawnIsAlive || target.Team != CsTeam.CounterTerrorist && !debug) - continue; - menu.AddMenuOption(target.PlayerName, - (selector, _) => - OnSelect(player, command, target.UserId.ToString()), - !debug && _lrManager.IsInLR(target) - ); - } - - return menu; - } - - public bool WouldHavePlayers() => Utilities.GetPlayers() - .Any(p => p.IsReal() && p is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }); - - private void OnSelect(CCSPlayerController player, Func command, string? value) - { - MenuManager.CloseActiveMenu(player); - player.ExecuteClientCommandFromServer(command.Invoke(value)); - } + return menu; + } + + public bool WouldHavePlayers() { + return Utilities.GetPlayers() + .Any(p => p.IsReal() && p is { + PawnIsAlive: true, Team: CsTeam.CounterTerrorist + }); + } + + private void OnSelect(CCSPlayerController player, + Func command, string? value) { + MenuManager.CloseActiveMenu(player); + player.ExecuteClientCommandFromServer(command.Invoke(value)); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/Coinflip.cs b/mod/Jailbreak.LastRequest/LastRequests/Coinflip.cs index 76789429..0239841e 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/Coinflip.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/Coinflip.cs @@ -1,4 +1,3 @@ -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Menu; using Jailbreak.Public.Mod.LastRequest; @@ -7,96 +6,81 @@ namespace Jailbreak.LastRequest.LastRequests; -public class Coinflip : AbstractLastRequest -{ - private readonly ChatMenu _menu; - private readonly Random _rnd; - private Timer _timeout; +public class Coinflip : AbstractLastRequest { + private readonly string[] events = [ + "A glint of silver flashes through the air...", "The coin does a 180...!", + "Gravity seems so much heavier...", "A quiet clink is heard...", + "An arrow hits the coin!", "The coin is shot in mid-air.", + "The answer is 42", "And yet...", "A sliver of copper falls off...", + "Lucky number 7...", "The coin lands on its side!", + "A bald eagle soars above", + "There wasn't enough room for the two of ya anyways...", + "Woosh woosh woosh", "banana rotate" + ]; - public Coinflip(BasePlugin plugin, ILastRequestManager manager, CCSPlayerController prisoner, - CCSPlayerController guard) : base(plugin, manager, prisoner, guard) - { - _rnd = new Random(); - _menu = new ChatMenu("Heads or Tails?"); - _menu.AddMenuOption("Heads", (_, _) => Decide(true, true)); - _menu.AddMenuOption("Tails", (_, _) => Decide(false, true)); - } + private readonly ChatMenu menu; + private readonly Random rnd; + private Timer? timeout; - public override LRType type => LRType.Coinflip; + public Coinflip(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) : base(plugin, + manager, prisoner, guard) { + rnd = new Random(); + menu = new ChatMenu("Heads or Tails?"); + menu.AddMenuOption("Heads", (_, _) => decide(true, true)); + menu.AddMenuOption("Tails", (_, _) => decide(false, true)); + } - public override void Setup() - { - state = LRState.Pending; - _menu.Title = "Heads or Tails? - " + prisoner.PlayerName + " vs " + guard.PlayerName; - Execute(); - } + public override LRType Type => LRType.COINFLIP; - public override void Execute() - { - state = LRState.Active; - MenuManager.OpenChatMenu(guard, _menu); + public override void Setup() { + State = LRState.PENDING; + menu.Title = "Heads or Tails? - " + Prisoner.PlayerName + " vs " + + Guard.PlayerName; + Execute(); + } - _timeout = plugin.AddTimer(10, () => - { - if (state != LRState.Active) - return; - MenuManager.CloseActiveMenu(guard); - var choice = _rnd.Next(2) == 1; - guard.PrintToChat($"You failed to choose in time, defaulting to {(choice ? "Heads" : "Tails")}"); - Decide(choice, true); - }); - } + public override void Execute() { + State = LRState.ACTIVE; + MenuManager.OpenChatMenu(Guard, menu); - private void Decide(bool heads, bool print) - { - _timeout.Kill(); - if (print) - { - MenuManager.CloseActiveMenu(guard); - PrintToParticipants($"{guard.PlayerName} chose {(heads ? "Heads" : "Tails")}... flipping..."); - state = LRState.Active; - } - plugin.AddTimer(2, () => - { - if (_rnd.Next(4) == 0) - { - PrintToParticipants(events[_rnd.Next(events.Length)]); - plugin.AddTimer(2, () => Decide(heads, false)); - } - else - { - var side = _rnd.Next(2) == 1; - PrintToParticipants($"The coin lands on {(side ? "Heads" : "Tails")}!"); - manager.EndLastRequest(this, side == heads ? LRResult.GuardWin : LRResult.PrisonerWin); - } - }); + timeout = Plugin.AddTimer(10, () => { + if (State != LRState.ACTIVE) return; + MenuManager.CloseActiveMenu(Guard); + var choice = rnd.Next(2) == 1; + Guard.PrintToChat( + $"You failed to choose in time, defaulting to {(choice ? "Heads" : "Tails")}"); + decide(choice, true); + }); + } + + private void decide(bool heads, bool print) { + timeout?.Kill(); + if (print) { + MenuManager.CloseActiveMenu(Guard); + PrintToParticipants( + $"{Guard.PlayerName} chose {(heads ? "Heads" : "Tails")}... flipping..."); + State = LRState.ACTIVE; } - private readonly string[] events = - { - "A glint of silver flashes through the air...", - "The coin does a 180...!", - "Gravity seems so much heavier...", - "A quiet clink is heard...", - "An arrow hits the coin!", - "The coin is shot in mid-air.", - "The answer is 42", - "And yet...", - "A sliver of copper falls off...", - "Lucky number 7...", - "The coin lands on its side!", - "A bald eagle soars above", - "There wasn't enough room for the two of ya anyways...", - "Woosh woosh woosh", - "banana rotate" - }; + Plugin.AddTimer(2, () => { + if (rnd.Next(4) == 0) { + PrintToParticipants(events[rnd.Next(events.Length)]); + Plugin.AddTimer(2, () => decide(heads, false)); + } else { + var side = rnd.Next(2) == 1; + PrintToParticipants($"The coin lands on {(side ? "Heads" : "Tails")}!"); + Manager.EndLastRequest(this, + side == heads ? LRResult.GUARD_WIN : LRResult.PRISONER_WIN); + } + }); + } - public override void OnEnd(LRResult result) - { - state = LRState.Completed; - if (result == LRResult.PrisonerWin) - guard.Pawn.Value?.CommitSuicide(false, true); - else - prisoner.Pawn.Value?.CommitSuicide(false, true); - } + public override void OnEnd(LRResult result) { + State = LRState.COMPLETED; + if (result == LRResult.PRISONER_WIN) + Guard.Pawn.Value?.CommitSuicide(false, true); + else + Prisoner.Pawn.Value?.CommitSuicide(false, true); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/GunToss.cs b/mod/Jailbreak.LastRequest/LastRequests/GunToss.cs index 36411ab7..725df533 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/GunToss.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/GunToss.cs @@ -1,44 +1,32 @@ -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest.LastRequests; -public class GunToss( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : AbstractLastRequest(plugin, manager, prisoner, guard) -{ - public override LRType type => LRType.GunToss; +public class GunToss(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) + : AbstractLastRequest(plugin, manager, prisoner, guard) { + public override LRType Type => LRType.GUN_TOSS; - public override void Setup() - { - // Strip weapons, teleport T to CT - prisoner.RemoveWeapons(); - guard.RemoveWeapons(); - guard.Teleport(prisoner); - state = LRState.Pending; + public override void Setup() { + // Strip weapons, teleport T to CT + Prisoner.RemoveWeapons(); + Guard.RemoveWeapons(); + Guard.Teleport(Prisoner); + State = LRState.PENDING; - plugin.AddTimer(3, Execute); - } + Plugin.AddTimer(3, Execute); + } - public override void Execute() - { - prisoner.GiveNamedItem("weapon_knife"); - guard.GiveNamedItem("weapon_knife"); - prisoner.GiveNamedItem("weapon_deagle"); - guard.GiveNamedItem("weapon_deagle"); - state = LRState.Active; - } + public override void Execute() { + Prisoner.GiveNamedItem("weapon_knife"); + Guard.GiveNamedItem("weapon_knife"); + Prisoner.GiveNamedItem("weapon_deagle"); + Guard.GiveNamedItem("weapon_deagle"); + State = LRState.ACTIVE; + } - public override void OnEnd(LRResult result) - { - state = LRState.Completed; - } + public override void OnEnd(LRResult result) { State = LRState.COMPLETED; } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/KnifeFight.cs b/mod/Jailbreak.LastRequest/LastRequests/KnifeFight.cs index 69821e52..f04d5a30 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/KnifeFight.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/KnifeFight.cs @@ -1,32 +1,20 @@ -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest.LastRequests; -public class KnifeFight( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : WeaponizedRequest(plugin, manager, - prisoner, guard) -{ - public override LRType type => LRType.KnifeFight; +public class KnifeFight(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) + : WeaponizedRequest(plugin, manager, prisoner, guard) { + public override LRType Type => LRType.KNIFE_FIGHT; - public override void Execute() - { - PrintToParticipants("Go!"); - prisoner.GiveNamedItem("weapon_knife"); - guard.GiveNamedItem("weapon_knife"); - this.state = LRState.Active; - } + public override void Execute() { + PrintToParticipants("Go!"); + Prisoner.GiveNamedItem("weapon_knife"); + Guard.GiveNamedItem("weapon_knife"); + State = LRState.ACTIVE; + } - public override void OnEnd(LRResult result) - { - state = LRState.Completed; - } + public override void OnEnd(LRResult result) { State = LRState.COMPLETED; } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/MagForMag.cs b/mod/Jailbreak.LastRequest/LastRequests/MagForMag.cs index bd210c28..bd129fc4 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/MagForMag.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/MagForMag.cs @@ -1,136 +1,114 @@ 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.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest.LastRequests; -public class MagForMag( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : WeaponizedRequest(plugin, manager, prisoner, guard) -{ - public override LRType type => LRType.GunToss; - private CCSPlayerController whosShot; - private int bulletCount = 7; - - public override void Setup() - { - plugin.RegisterEventHandler(OnPlayerShoot); - base.Setup(); - - whosShot = new Random().Next(2) == 0 ? prisoner : guard; - PrintToParticipants(whosShot.PlayerName + " will shoot first."); - prisoner.GiveNamedItem("weapon_deagle"); - guard.GiveNamedItem("weapon_deagle"); - - var weapon = FindWeapon(prisoner, "weapon_deagle"); - if (weapon != null) - setAmmoAmount(weapon, 0, 0); - weapon = FindWeapon(guard, "weapon_deagle"); - if (weapon != null) - setAmmoAmount(weapon, 0, 0); - } - - private static CBasePlayerWeapon? FindWeapon(CCSPlayerController player, String name) - { - if (!player.IsReal()) - return null; - - var pawn = player.PlayerPawn.Value; - - if (pawn == null) - return null; - - var weapons = pawn.WeaponServices?.MyWeapons; - - return weapons?.Select(weaponOpt => weaponOpt.Value).OfType() - .FirstOrDefault(weapon => weapon.DesignerName.Contains(name)); - } - - private static void setAmmoAmount(CBasePlayerWeapon weapon, int primary, int reserve) - { - weapon.Clip1 = primary; - Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_iClip1"); - weapon.Clip2 = reserve; - Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_pReserveAmmo"); - } - - public override void Execute() - { - state = LRState.Active; - var deagle = FindWeapon(whosShot, "weapon_deagle"); - if (deagle != null) - setAmmoAmount(deagle, bulletCount, 0); - - plugin.AddTimer(30, () => - { - if (state != LRState.Active) - return; - prisoner.GiveNamedItem("weapon_knife"); - guard.GiveNamedItem("weapon_knife"); - }); - plugin.AddTimer(60, () => - { - if (state != LRState.Active) return; - PrintToParticipants("Time's Up!"); - var result = guard.Health > prisoner.Health ? LRResult.GuardWin : LRResult.PrisonerWin; - if (guard.Health == prisoner.Health) - { - PrintToParticipants("Even health, since " + whosShot.PlayerName + " had the shot last, they lose."); - result = whosShot.Slot == prisoner.Slot ? LRResult.GuardWin : LRResult.PrisonerWin; - } - else - { - PrintToParticipants("Health was the deciding factor. "); - } - - manager.EndLastRequest(this, result); - if (result == LRResult.GuardWin) - prisoner.Pawn.Value?.CommitSuicide(false, true); - else - guard.Pawn.Value?.CommitSuicide(false, true); - }, TimerFlags.STOP_ON_MAPCHANGE); - } - - public HookResult OnPlayerShoot(EventPlayerShoot @event, GameEventInfo info) - { - if (state != LRState.Active) - return HookResult.Continue; - - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - - if (player.Slot != prisoner.Slot && player.Slot != guard.Slot) - return HookResult.Continue; - - var shootersDeagle = FindWeapon(player, "weapon_deagle"); - if (shootersDeagle == null) - return HookResult.Continue; - - if (shootersDeagle.Clip1 != 0) - return HookResult.Continue; - - PrintToParticipants(player.PlayerName + " has shot."); - var opponent = player.Slot == prisoner.Slot ? guard : prisoner; - opponent.PrintToChat("Your shot"); - var deagle = FindWeapon(opponent, "weapon_deagle"); - if (deagle != null) - setAmmoAmount(deagle, 0, bulletCount); - whosShot = opponent; - return HookResult.Continue; - } - - public override void OnEnd(LRResult result) - { - plugin.RemoveListener("player_shoot", OnPlayerShoot); - state = LRState.Completed; - } +public class MagForMag(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) + : WeaponizedRequest(plugin, manager, prisoner, guard) { + private const int BULLET_COUNT = 7; + private CCSPlayerController? whosShot; + public override LRType Type => LRType.GUN_TOSS; + + public override void Setup() { + Plugin.RegisterEventHandler(OnPlayerShoot); + base.Setup(); + + whosShot = new Random().Next(2) == 0 ? Prisoner : Guard; + PrintToParticipants(whosShot.PlayerName + " will shoot first."); + Prisoner.GiveNamedItem("weapon_deagle"); + Guard.GiveNamedItem("weapon_deagle"); + + var weapon = findWeapon(Prisoner, "weapon_deagle"); + if (weapon != null) setAmmoAmount(weapon, 0, 0); + weapon = findWeapon(Guard, "weapon_deagle"); + if (weapon != null) setAmmoAmount(weapon, 0, 0); + } + + private static CBasePlayerWeapon? findWeapon(CCSPlayerController player, + string name) { + if (!player.IsReal()) return null; + + var pawn = player.PlayerPawn.Value; + + if (pawn == null) return null; + + var weapons = pawn.WeaponServices?.MyWeapons; + + return weapons?.Select(weaponOpt => weaponOpt.Value) + .OfType() + .FirstOrDefault(weapon => weapon.DesignerName.Contains(name)); + } + + private static void setAmmoAmount(CBasePlayerWeapon weapon, int primary, + int reserve) { + weapon.Clip1 = primary; + Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_iClip1"); + weapon.Clip2 = reserve; + Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_pReserveAmmo"); + } + + public override void Execute() { + State = LRState.ACTIVE; + var deagle = findWeapon(whosShot!, "weapon_deagle"); + if (deagle != null) setAmmoAmount(deagle, BULLET_COUNT, 0); + + Plugin.AddTimer(30, () => { + if (State != LRState.ACTIVE) return; + Prisoner.GiveNamedItem("weapon_knife"); + Guard.GiveNamedItem("weapon_knife"); + }); + Plugin.AddTimer(60, () => { + if (State != LRState.ACTIVE) return; + PrintToParticipants("Time's Up!"); + var result = Guard.Health > Prisoner.Health ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN; + if (Guard.Health == Prisoner.Health) { + PrintToParticipants("Even health, since " + whosShot!.PlayerName + + " had the shot last, they lose."); + result = whosShot.Slot == Prisoner.Slot ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN; + } else { PrintToParticipants("Health was the deciding factor. "); } + + Manager.EndLastRequest(this, result); + if (result == LRResult.GUARD_WIN) + Prisoner.Pawn.Value?.CommitSuicide(false, true); + else + Guard.Pawn.Value?.CommitSuicide(false, true); + }, TimerFlags.STOP_ON_MAPCHANGE); + } + + public HookResult OnPlayerShoot(EventPlayerShoot @event, GameEventInfo info) { + if (State != LRState.ACTIVE) return HookResult.Continue; + + var player = @event.Userid; + if (!player.IsReal()) return HookResult.Continue; + + if (player!.Slot != Prisoner.Slot && player.Slot != Guard.Slot) + return HookResult.Continue; + + var shootersDeagle = findWeapon(player, "weapon_deagle"); + if (shootersDeagle == null) return HookResult.Continue; + + if (shootersDeagle.Clip1 != 0) return HookResult.Continue; + + PrintToParticipants(player.PlayerName + " has shot."); + var opponent = player.Slot == Prisoner.Slot ? Guard : Prisoner; + opponent.PrintToChat("Your shot"); + var deagle = findWeapon(opponent, "weapon_deagle"); + if (deagle != null) setAmmoAmount(deagle, 0, BULLET_COUNT); + whosShot = opponent; + return HookResult.Continue; + } + + public override void OnEnd(LRResult result) { + Plugin.RemoveListener(OnPlayerShoot); + State = LRState.COMPLETED; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/NoScope.cs b/mod/Jailbreak.LastRequest/LastRequests/NoScope.cs index 4df6c038..e7829c4f 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/NoScope.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/NoScope.cs @@ -7,85 +7,71 @@ namespace Jailbreak.LastRequest.LastRequests; -public class NoScope( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : WeaponizedRequest(plugin, manager, - prisoner, guard) -{ - public override LRType type => LRType.NoScope; - - public override void Setup() - { - base.Setup(); - - plugin.RegisterListener(OnTick); - } - - private void OnTick() - { - if (state != LRState.Active) return; - - if (!prisoner.IsReal() || !guard.IsReal()) - return; - - if (prisoner.PlayerPawn.Value == null || guard.PlayerPawn.Value == null) return; - DisableScope(prisoner); - DisableScope(guard); - } - - private void DisableScope(CCSPlayerController player) - { - if (!player.IsReal()) - return; - var pawn = player.PlayerPawn.Value; - if (pawn == null || !pawn.IsValid) - return; - var weaponServices = pawn.WeaponServices; - if (weaponServices == null) - return; - var activeWeapon = weaponServices.ActiveWeapon.Value; - if (activeWeapon == null || !activeWeapon.IsValid) - return; - activeWeapon.NextSecondaryAttackTick = Server.TickCount + 500; - } - - public override void Execute() - { - PrintToParticipants("Go!"); - prisoner.GiveNamedItem("weapon_ssg08"); - guard.GiveNamedItem("weapon_ssg08"); - this.state = LRState.Active; - - plugin.AddTimer(30, () => - { - if (state != LRState.Active) return; - prisoner.GiveNamedItem("weapon_knife"); - guard.GiveNamedItem("weapon_knife"); - }, TimerFlags.STOP_ON_MAPCHANGE); - - plugin.AddTimer(60, () => - { - if (state != LRState.Active) return; - - manager.EndLastRequest(this, guard.Health > prisoner.Health ? LRResult.GuardWin : LRResult.PrisonerWin); - }, TimerFlags.STOP_ON_MAPCHANGE); - } - - public override void OnEnd(LRResult result) - { - this.state = LRState.Completed; - plugin.RemoveListener("OnTick", OnTick); - - if(result != LRResult.GuardWin && result != LRResult.PrisonerWin) - return; - - var winner = result == LRResult.GuardWin ? guard : prisoner; - - winner.RemoveWeapons(); - winner.GiveNamedItem("weapon_knife"); - winner.GiveNamedItem("weapon_ak47"); - } +public class NoScope(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) + : WeaponizedRequest(plugin, manager, prisoner, guard) { + public override LRType Type => LRType.NO_SCOPE; + + public override void Setup() { + base.Setup(); + + Plugin.RegisterListener(OnTick); + } + + private void OnTick() { + if (State != LRState.ACTIVE) return; + + if (!Prisoner.IsReal() || !Guard.IsReal()) return; + + if (Prisoner.PlayerPawn.Value == null || Guard.PlayerPawn.Value == null) + return; + disableScope(Prisoner); + disableScope(Guard); + } + + private void disableScope(CCSPlayerController player) { + if (!player.IsReal()) return; + var pawn = player.PlayerPawn.Value; + if (pawn == null || !pawn.IsValid) return; + var weaponServices = pawn.WeaponServices; + if (weaponServices == null) return; + var activeWeapon = weaponServices.ActiveWeapon.Value; + if (activeWeapon == null || !activeWeapon.IsValid) return; + activeWeapon.NextSecondaryAttackTick = Server.TickCount + 500; + } + + public override void Execute() { + PrintToParticipants("Go!"); + Prisoner.GiveNamedItem("weapon_ssg08"); + Guard.GiveNamedItem("weapon_ssg08"); + State = LRState.ACTIVE; + + Plugin.AddTimer(30, () => { + if (State != LRState.ACTIVE) return; + Prisoner.GiveNamedItem("weapon_knife"); + Guard.GiveNamedItem("weapon_knife"); + }, TimerFlags.STOP_ON_MAPCHANGE); + + Plugin.AddTimer(60, () => { + if (State != LRState.ACTIVE) return; + + Manager.EndLastRequest(this, + Guard.Health > Prisoner.Health ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN); + }, TimerFlags.STOP_ON_MAPCHANGE); + } + + public override void OnEnd(LRResult result) { + State = LRState.COMPLETED; + Plugin.RemoveListener(OnTick); + + if (result != LRResult.GUARD_WIN && result != LRResult.PRISONER_WIN) return; + + var winner = result == LRResult.GUARD_WIN ? Guard : Prisoner; + + winner.RemoveWeapons(); + winner.GiveNamedItem("weapon_knife"); + winner.GiveNamedItem("weapon_ak47"); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/Race.cs b/mod/Jailbreak.LastRequest/LastRequests/Race.cs index f874d185..1f574964 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/Race.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/Race.cs @@ -1,6 +1,4 @@ using System.Drawing; -using System.Xml.Schema; -using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Timers; using CounterStrikeSharp.API.Modules.Utils; @@ -14,124 +12,111 @@ namespace Jailbreak.LastRequest.LastRequests; -public class Race( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard, - IRaceLRMessages messages) : TeleportingRequest(plugin, manager, prisoner, guard) -{ - public override LRType type => LRType.Race; +public class Race(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard, + IRaceLRMessages messages) + : TeleportingRequest(plugin, manager, prisoner, guard) { + private DateTime raceStart; + private Timer? raceTimer; + private BeamCircle? start, end; + private Vector? startLocation, endLocation; + public override LRType Type => LRType.RACE; - private BeamCircle? start, end; - private Vector startLocation, endLocation; + public override void Setup() { + base.Setup(); - private Timer? raceTimer; - private DateTime raceStart; + Prisoner.RemoveWeapons(); - public override void Setup() - { - base.Setup(); + Guard.RemoveWeapons(); + Guard.GiveNamedItem("weapon_knife"); - prisoner.RemoveWeapons(); + Plugin.AddTimer(3, () => { + if (State != LRState.PENDING) return; + Prisoner.GiveNamedItem("weapon_knife"); + }); - guard.RemoveWeapons(); - guard.GiveNamedItem("weapon_knife"); + messages.EndRaceInstruction.ToPlayerChat(Prisoner); - plugin.AddTimer(3, () => - { - if (state != LRState.Pending) - return; - prisoner.GiveNamedItem("weapon_knife"); - }); + messages.RaceStartingMessage(Prisoner).ToPlayerChat(Guard); - messages.END_RACE_INSTRUCTION.ToPlayerChat(prisoner); + startLocation = Prisoner.Pawn?.Value?.AbsOrigin?.Clone(); - messages.RACE_STARTING_MESSAGE(prisoner).ToPlayerChat(guard); + if (startLocation == null) return; + start = new BeamCircle(Plugin, startLocation, 20, 16); + start.SetColor(Color.Aqua); + start.Draw(); + } - startLocation = prisoner.Pawn.Value.AbsOrigin.Clone(); + // Called when the prisoner types !endrace + public override void Execute() { + State = LRState.ACTIVE; - start = new BeamCircle(plugin, startLocation, 20, 16); - start.SetColor(Color.Aqua); - start.Draw(); - } + endLocation = Prisoner.Pawn?.Value?.AbsOrigin?.Clone(); - // Called when the prisoner types !endrace - public override void Execute() - { - state = LRState.Active; + if (endLocation == null) return; + end = new BeamCircle(Plugin, endLocation, 10, 32); + end.SetColor(Color.Red); + end.Draw(); - endLocation = prisoner.Pawn.Value.AbsOrigin.Clone(); + Prisoner.Pawn?.Value?.Teleport(startLocation); + Guard.Pawn.Value?.Teleport(startLocation); - end = new BeamCircle(plugin, endLocation, 10, 32); - end.SetColor(Color.Red); - end.Draw(); + Guard.Freeze(); + Prisoner.Freeze(); - prisoner.Pawn.Value.Teleport(startLocation); - guard.Pawn.Value?.Teleport(startLocation); + Plugin.AddTimer(1, () => { + Guard.UnFreeze(); + Prisoner.UnFreeze(); + }); - guard.Freeze(); - prisoner.Freeze(); + raceStart = DateTime.Now; - plugin.AddTimer(1, () => - { - guard.UnFreeze(); - prisoner.UnFreeze(); - }); + raceTimer = Plugin.AddTimer(0.1f, tick, TimerFlags.REPEAT); + } - raceStart = DateTime.Now; + private void tick() { + if (Prisoner.AbsOrigin == null || Guard.AbsOrigin == null) return; + var requiredDistance = getRequiredDistance(); + var requiredDistanceSqured = MathF.Pow(requiredDistance, 2); - raceTimer = plugin.AddTimer(0.1f, Tick, TimerFlags.REPEAT); - } + end?.SetRadius(requiredDistance / 2); + end?.Update(); - private void Tick() - { - if (prisoner.AbsOrigin == null || guard.AbsOrigin == null) - return; - var requiredDistance = getRequiredDistance(); - var requiredDistanceSqured = MathF.Pow(requiredDistance, 2); - - end?.SetRadius(requiredDistance / 2); - end?.Update(); - - var guardDist = guard.Pawn.Value.AbsOrigin.Clone().DistanceSquared(endLocation); - - if (guardDist < requiredDistanceSqured) - { - manager.EndLastRequest(this, LRResult.GuardWin); - return; - } - - var prisonerDist = prisoner.Pawn.Value.AbsOrigin.Clone().DistanceSquared(endLocation); - if (prisonerDist < requiredDistanceSqured) - { - manager.EndLastRequest(this, LRResult.PrisonerWin); - } - } + if (endLocation == null) return; + var guardDist = Guard.Pawn?.Value?.AbsOrigin?.Clone() + .DistanceSquared(endLocation); - // https://www.desmos.com/calculator/e1qwgpmtmz - private float getRequiredDistance() - { - var elapsedSeconds = (DateTime.Now - raceStart).TotalSeconds; - - return (float)(10 + elapsedSeconds + Math.Pow(elapsedSeconds, 2.9) / 5000); + if (guardDist < requiredDistanceSqured) { + Manager.EndLastRequest(this, LRResult.GUARD_WIN); + return; } - public override void OnEnd(LRResult result) - { - state = LRState.Completed; - switch (result) - { - case LRResult.GuardWin: - prisoner.Pawn.Value?.CommitSuicide(false, true); - break; - case LRResult.PrisonerWin: - guard.Pawn.Value?.CommitSuicide(false, true); - break; - } - - raceTimer?.Kill(); - start?.Remove(); - end?.Remove(); + var prisonerDist = Prisoner.Pawn?.Value?.AbsOrigin?.Clone() + .DistanceSquared(endLocation); + if (prisonerDist < requiredDistanceSqured) + Manager.EndLastRequest(this, LRResult.PRISONER_WIN); + } + + // https://www.desmos.com/calculator/e1qwgpmtmz + private float getRequiredDistance() { + var elapsedSeconds = (DateTime.Now - raceStart).TotalSeconds; + + return (float)(10 + elapsedSeconds + Math.Pow(elapsedSeconds, 2.9) / 5000); + } + + public override void OnEnd(LRResult result) { + State = LRState.COMPLETED; + switch (result) { + case LRResult.GUARD_WIN: + Prisoner.Pawn.Value?.CommitSuicide(false, true); + break; + case LRResult.PRISONER_WIN: + Guard.Pawn.Value?.CommitSuicide(false, true); + break; } + + raceTimer?.Kill(); + start?.Remove(); + end?.Remove(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/RockPaperScissors.cs b/mod/Jailbreak.LastRequest/LastRequests/RockPaperScissors.cs index 1da7d88a..cee777ed 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/RockPaperScissors.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/RockPaperScissors.cs @@ -6,116 +6,97 @@ namespace Jailbreak.LastRequest.LastRequests; -public class RockPaperScissors : AbstractLastRequest -{ - private ChatMenu _chatMenu; - private int _prisonerChoice = -1, _guardChoice = -1; - - public RockPaperScissors(BasePlugin plugin, ILastRequestManager manager, CCSPlayerController prisoner, - CCSPlayerController guard) : base(plugin, manager, prisoner, guard) - { - _chatMenu = new ChatMenu("Rock Paper Scissors"); - foreach (var option in new[] { "Rock", "Paper", "Scissors" }) - _chatMenu.AddMenuOption(option, OnSelect); +public class RockPaperScissors : AbstractLastRequest { + private readonly ChatMenu chatMenu; + private int prisonerChoice = -1, guardChoice = -1; + + public RockPaperScissors(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) : base(plugin, + manager, prisoner, guard) { + chatMenu = new ChatMenu("Rock Paper Scissors"); + foreach (var option in new[] { "Rock", "Paper", "Scissors" }) + chatMenu.AddMenuOption(option, OnSelect); + } + + public override LRType Type => LRType.ROCK_PAPER_SCISSORS; + + public override void Setup() { + chatMenu.Title = + $"Rock Paper Scissors - {Prisoner.PlayerName} vs {Guard.PlayerName}"; + prisonerChoice = -1; + guardChoice = -1; + Plugin.AddTimer(3, Execute); + } + + private void OnSelect(CCSPlayerController player, ChatMenuOption option) { + if (player.Slot != Prisoner.Slot && player.Slot != Guard.Slot) return; + MenuManager.CloseActiveMenu(player); + + var choice = Array.IndexOf(new[] { "Rock", "Paper", "Scissors" }, + option.Text); + + if (player.Slot == Prisoner.Slot) + prisonerChoice = choice; + else + guardChoice = choice; + + if (prisonerChoice == -1 || guardChoice == -1) { + PrintToParticipants(player.PlayerName + " has made their choice..."); + return; } - public override void Setup() - { - _chatMenu.Title = $"Rock Paper Scissors - {prisoner.PlayerName} vs {guard.PlayerName}"; - _prisonerChoice = -1; - _guardChoice = -1; - plugin.AddTimer(3, Execute); + PrintToParticipants("Both players have made their choice!"); + if (prisonerChoice == guardChoice) { + PrintToParticipants("It's a tie!"); + Setup(); + return; } - private void OnSelect(CCSPlayerController player, ChatMenuOption option) - { - if (player.Slot != prisoner.Slot && player.Slot != guard.Slot) - return; - MenuManager.CloseActiveMenu(player); - - int choice = Array.IndexOf(new[] { "Rock", "Paper", "Scissors" }, option.Text); - - if (player.Slot == prisoner.Slot) - _prisonerChoice = choice; - else - _guardChoice = choice; - - if (_prisonerChoice == -1 || _guardChoice == -1) - { - PrintToParticipants(player.PlayerName + " has made their choice..."); - return; - } - - PrintToParticipants("Both players have made their choice!"); - if (_prisonerChoice == _guardChoice) - { - PrintToParticipants("It's a tie!"); - Setup(); - return; - } - - if (state != LRState.Active) - return; - - if (_prisonerChoice == 0 && _guardChoice == 2 || _prisonerChoice == 1 && _guardChoice == 0 || - _prisonerChoice == 2 && _guardChoice == 1) - manager.EndLastRequest(this, LRResult.PrisonerWin); - else - manager.EndLastRequest(this, LRResult.GuardWin); - } - - public override LRType type => LRType.RockPaperScissors; - - public override void Execute() - { - state = LRState.Active; - MenuManager.OpenChatMenu(prisoner, _chatMenu); - MenuManager.OpenChatMenu(guard, _chatMenu); - - plugin.AddTimer(20, Timeout, TimerFlags.STOP_ON_MAPCHANGE); - } - - private void Timeout() - { - if (state != LRState.Active) - return; - if (_prisonerChoice != -1) - { - manager.EndLastRequest(this, LRResult.PrisonerWin); - } - else if (_guardChoice != -1) - { - manager.EndLastRequest(this, LRResult.GuardWin); - } - else - { - manager.EndLastRequest(this, LRResult.TimedOut); - } - } - - public override void OnEnd(LRResult result) - { - state = LRState.Completed; - if (result == LRResult.GuardWin) - { - prisoner.Pawn.Value!.CommitSuicide(false, true); - } - else if (result == LRResult.PrisonerWin) - { - guard.Pawn.Value!.CommitSuicide(false, true); - } - - PrintToParticipants($"Prisoner chose {GetChoice(_prisonerChoice)}, Guard chose {GetChoice(_guardChoice)}"); - } - - private string GetChoice(int choice) - { - return choice switch - { - 0 => "Rock", - 1 => "Paper", - 2 => "Scissors", - _ => "Unknown" - }; - } + if (State != LRState.ACTIVE) return; + + if (prisonerChoice == 0 && guardChoice == 2 + || prisonerChoice == 1 && guardChoice == 0 + || prisonerChoice == 2 && guardChoice == 1) + Manager.EndLastRequest(this, LRResult.PRISONER_WIN); + else + Manager.EndLastRequest(this, LRResult.GUARD_WIN); + } + + public override void Execute() { + State = LRState.ACTIVE; + MenuManager.OpenChatMenu(Prisoner, chatMenu); + MenuManager.OpenChatMenu(Guard, chatMenu); + + Plugin.AddTimer(20, timeout, TimerFlags.STOP_ON_MAPCHANGE); + } + + private void timeout() { + if (State != LRState.ACTIVE) return; + if (prisonerChoice != -1) + Manager.EndLastRequest(this, LRResult.PRISONER_WIN); + else if (guardChoice != -1) + Manager.EndLastRequest(this, LRResult.GUARD_WIN); + else + Manager.EndLastRequest(this, LRResult.TIMED_OUT); + } + + public override void OnEnd(LRResult result) { + State = LRState.COMPLETED; + if (result == LRResult.GUARD_WIN) + Prisoner.Pawn.Value!.CommitSuicide(false, true); + else if (result == LRResult.PRISONER_WIN) + Guard.Pawn.Value!.CommitSuicide(false, true); + + PrintToParticipants( + $"Prisoner chose {getChoice(prisonerChoice)}, Guard chose {getChoice(guardChoice)}"); + } + + private string getChoice(int choice) { + return choice switch { + 0 => "Rock", + 1 => "Paper", + 2 => "Scissors", + _ => "Unknown" + }; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/ShotForShot.cs b/mod/Jailbreak.LastRequest/LastRequests/ShotForShot.cs index dd2289ff..920f2fb0 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/ShotForShot.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/ShotForShot.cs @@ -1,133 +1,115 @@ 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.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest.LastRequests; -public class ShotForShot( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : WeaponizedRequest(plugin, manager, prisoner, guard) -{ - public override LRType type => LRType.ShotForShot; - private CCSPlayerController whosShot; - - public override void Setup() - { - plugin.RegisterEventHandler(OnPlayerShoot); - base.Setup(); - - whosShot = new Random().Next(2) == 0 ? prisoner : guard; - PrintToParticipants(whosShot.PlayerName + " will shoot first."); - prisoner.GiveNamedItem("weapon_deagle"); - guard.GiveNamedItem("weapon_deagle"); - - var weapon = FindWeapon(prisoner, "weapon_deagle"); - if (weapon != null) - setAmmoAmount(weapon, 0, 0); - weapon = FindWeapon(guard, "weapon_deagle"); - if (weapon != null) - setAmmoAmount(weapon, 0, 0); +public class ShotForShot(BasePlugin plugin, ILastRequestManager manager, + CCSPlayerController prisoner, CCSPlayerController guard) + : WeaponizedRequest(plugin, manager, prisoner, guard) { + private CCSPlayerController? whosShot; + public override LRType Type => LRType.SHOT_FOR_SHOT; + + public override void Setup() { + Plugin.RegisterEventHandler(OnPlayerShoot); + base.Setup(); + + whosShot = new Random().Next(2) == 0 ? Prisoner : Guard; + PrintToParticipants(whosShot.PlayerName + " will shoot first."); + Prisoner.GiveNamedItem("weapon_deagle"); + Guard.GiveNamedItem("weapon_deagle"); + + var weapon = findWeapon(Prisoner, "weapon_deagle"); + if (weapon != null) setAmmoAmount(weapon, 0, 0); + weapon = findWeapon(Guard, "weapon_deagle"); + if (weapon != null) setAmmoAmount(weapon, 0, 0); + } + + private static CBasePlayerWeapon? findWeapon(CCSPlayerController player, + string name) { + if (!player.IsReal()) return null; + + var pawn = player.PlayerPawn.Value; + + if (pawn == null) return null; + + var weapons = pawn.WeaponServices?.MyWeapons; + + return weapons?.Select(weaponOpt => weaponOpt.Value) + .OfType() + .FirstOrDefault(weapon => weapon.DesignerName.Contains(name)); + } + + private static void setAmmoAmount(CBasePlayerWeapon weapon, int primary, + int reserve) { + weapon.Clip1 = primary; + Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_iClip1"); + weapon.Clip2 = reserve; + Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_pReserveAmmo"); + } + + public override void Execute() { + State = LRState.ACTIVE; + if (whosShot == null) return; + var deagle = findWeapon(whosShot, "weapon_deagle"); + if (deagle != null) setAmmoAmount(deagle, 1, 0); + + Plugin.AddTimer(30, () => { + if (State != LRState.ACTIVE) return; + Prisoner.GiveNamedItem("weapon_knife"); + Guard.GiveNamedItem("weapon_knife"); + }); + Plugin.AddTimer(60, () => { + if (State != LRState.ACTIVE) return; + PrintToParticipants("Time's Up!"); + var result = Guard.Health > Prisoner.Health ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN; + if (Guard.Health == Prisoner.Health) { + PrintToParticipants("Even health, since " + whosShot.PlayerName + + " had the shot last, they lose."); + result = whosShot.Slot == Prisoner.Slot ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN; + } else { PrintToParticipants("Health was the deciding factor. "); } + + if (result == LRResult.GUARD_WIN) + Prisoner.Pawn.Value?.CommitSuicide(false, true); + else + Guard.Pawn.Value?.CommitSuicide(false, true); + }, TimerFlags.STOP_ON_MAPCHANGE); + } + + private HookResult OnPlayerShoot(EventPlayerShoot @event, + GameEventInfo info) { + if (State != LRState.ACTIVE) return HookResult.Continue; + + var player = @event.Userid; + if (player == null || whosShot == null || !player.IsReal()) + return HookResult.Continue; + + if (player.Slot != Prisoner.Slot && player.Slot != Guard.Slot) + return HookResult.Continue; + if (player.Slot != whosShot.Slot) { + PrintToParticipants(player.PlayerName + " cheated."); + player.Pawn.Value?.CommitSuicide(false, true); + return HookResult.Handled; } - private static CBasePlayerWeapon? FindWeapon(CCSPlayerController player, String name) - { - if (!player.IsReal()) - return null; - - var pawn = player.PlayerPawn.Value; - - if (pawn == null) - return null; - - var weapons = pawn.WeaponServices?.MyWeapons; - - return weapons?.Select(weaponOpt => weaponOpt.Value).OfType() - .FirstOrDefault(weapon => weapon.DesignerName.Contains(name)); - } - - private static void setAmmoAmount(CBasePlayerWeapon weapon, int primary, int reserve) - { - weapon.Clip1 = primary; - Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_iClip1"); - weapon.Clip2 = reserve; - Utilities.SetStateChanged(weapon, "CBasePlayerWeapon", "m_pReserveAmmo"); - } - - public override void Execute() - { - state = LRState.Active; - var deagle = FindWeapon(whosShot, "weapon_deagle"); - if (deagle != null) - setAmmoAmount(deagle, 1, 0); - - plugin.AddTimer(30, () => - { - if (state != LRState.Active) - return; - prisoner.GiveNamedItem("weapon_knife"); - guard.GiveNamedItem("weapon_knife"); - }); - plugin.AddTimer(60, () => - { - if (state != LRState.Active) return; - PrintToParticipants("Time's Up!"); - var result = guard.Health > prisoner.Health ? LRResult.GuardWin : LRResult.PrisonerWin; - if (guard.Health == prisoner.Health) - { - PrintToParticipants("Even health, since " + whosShot.PlayerName + " had the shot last, they lose."); - result = whosShot.Slot == prisoner.Slot ? LRResult.GuardWin : LRResult.PrisonerWin; - } - else - { - PrintToParticipants("Health was the deciding factor. "); - } - - if (result == LRResult.GuardWin) - prisoner.Pawn.Value?.CommitSuicide(false, true); - else - guard.Pawn.Value?.CommitSuicide(false, true); - }, TimerFlags.STOP_ON_MAPCHANGE); - } - - private HookResult OnPlayerShoot(EventPlayerShoot @event, GameEventInfo info) - { - if (state != LRState.Active) - return HookResult.Continue; - - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - - if (player.Slot != prisoner.Slot && player.Slot != guard.Slot) - return HookResult.Continue; - if (player.Slot != whosShot.Slot) - { - PrintToParticipants(player.PlayerName + " cheated."); - player.Pawn.Value?.CommitSuicide(false, true); - return HookResult.Handled; - } - - PrintToParticipants(player.PlayerName + " has shot."); - var opponent = player.Slot == prisoner.Slot ? guard : prisoner; - opponent.PrintToChat("Your shot"); - var deagle = FindWeapon(opponent, "weapon_deagle"); - if (deagle != null) - setAmmoAmount(deagle, 1, 0); - whosShot = opponent; - return HookResult.Continue; - } - - public override void OnEnd(LRResult result) - { - plugin.RemoveListener("player_shoot", OnPlayerShoot); - state = LRState.Completed; - } + PrintToParticipants(player.PlayerName + " has shot."); + var opponent = player.Slot == Prisoner.Slot ? Guard : Prisoner; + opponent.PrintToChat("Your shot"); + var deagle = findWeapon(opponent, "weapon_deagle"); + if (deagle != null) setAmmoAmount(deagle, 1, 0); + whosShot = opponent; + return HookResult.Continue; + } + + public override void OnEnd(LRResult result) { + Plugin.RemoveListener(OnPlayerShoot); + State = LRState.COMPLETED; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/TeleportingRequest.cs b/mod/Jailbreak.LastRequest/LastRequests/TeleportingRequest.cs index 3fd81221..c3ab7f1b 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/TeleportingRequest.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/TeleportingRequest.cs @@ -5,24 +5,20 @@ namespace Jailbreak.LastRequest.LastRequests; -public abstract class TeleportingRequest( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) : AbstractLastRequest(plugin, manager, prisoner, guard) -{ - public override void Setup() - { - state = LRState.Pending; +public abstract class TeleportingRequest(BasePlugin plugin, + ILastRequestManager manager, CCSPlayerController prisoner, + CCSPlayerController guard) + : AbstractLastRequest(plugin, manager, prisoner, guard) { + public override void Setup() { + State = LRState.PENDING; - guard.Teleport(prisoner); + Guard.Teleport(Prisoner); - guard.Freeze(); - prisoner.Freeze(); - plugin.AddTimer(1, () => - { - guard.UnFreeze(); - prisoner.UnFreeze(); - }); - } + Guard.Freeze(); + Prisoner.Freeze(); + Plugin.AddTimer(1, () => { + Guard.UnFreeze(); + Prisoner.UnFreeze(); + }); + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/LastRequests/WeaponizedRequest.cs b/mod/Jailbreak.LastRequest/LastRequests/WeaponizedRequest.cs index 4ceb2842..3dec811a 100644 --- a/mod/Jailbreak.LastRequest/LastRequests/WeaponizedRequest.cs +++ b/mod/Jailbreak.LastRequest/LastRequests/WeaponizedRequest.cs @@ -1,51 +1,41 @@ using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Utils; -using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest.LastRequests; /// -/// Represents a Last Request that involves direct PvP combat. -/// -/// Automatically strips weapons, counts down, and calls Execute after 4 seconds. +/// Represents a Last Request that involves direct PvP combat. +/// Automatically strips weapons, counts down, and calls Execute after 4 seconds. /// -public abstract class WeaponizedRequest( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) - : TeleportingRequest(plugin, manager, prisoner, guard) -{ - public override void Setup() - { - base.Setup(); +public abstract class WeaponizedRequest(BasePlugin plugin, + ILastRequestManager manager, CCSPlayerController prisoner, + CCSPlayerController guard) + : TeleportingRequest(plugin, manager, prisoner, guard) { + public override void Setup() { + base.Setup(); - // Strip weapons, teleport T to CT - prisoner.RemoveWeapons(); - guard.RemoveWeapons(); - for (var i = 3; i >= 1; i--) - { - var copy = i; - plugin.AddTimer(3 - i, () => { PrintToParticipants($"{copy}..."); }); - } - - plugin.AddTimer(3, Execute); + // Strip weapons, teleport T to CT + Prisoner.RemoveWeapons(); + Guard.RemoveWeapons(); + for (var i = 3; i >= 1; i--) { + var copy = i; + Plugin.AddTimer(3 - i, () => { PrintToParticipants($"{copy}..."); }); } - public override void OnEnd(LRResult result) - { - switch (result) - { - case LRResult.GuardWin: - prisoner.Pawn.Value?.CommitSuicide(false, true); - break; - case LRResult.PrisonerWin: - guard.Pawn.Value?.CommitSuicide(false, true); - break; - } + Plugin.AddTimer(3, Execute); + } - state = LRState.Completed; + public override void OnEnd(LRResult result) { + switch (result) { + case LRResult.GUARD_WIN: + Prisoner.Pawn.Value?.CommitSuicide(false, true); + break; + case LRResult.PRISONER_WIN: + Guard.Pawn.Value?.CommitSuicide(false, true); + break; } + + State = LRState.COMPLETED; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Jailbreak.Logs.csproj b/mod/Jailbreak.Logs/Jailbreak.Logs.csproj index ff0d0386..8820ab28 100644 --- a/mod/Jailbreak.Logs/Jailbreak.Logs.csproj +++ b/mod/Jailbreak.Logs/Jailbreak.Logs.csproj @@ -7,11 +7,7 @@ - - - - - - + + diff --git a/mod/Jailbreak.Logs/Listeners/LogDamageListeners.cs b/mod/Jailbreak.Logs/Listeners/LogDamageListeners.cs index e0f1b658..0db85d5a 100644 --- a/mod/Jailbreak.Logs/Listeners/LogDamageListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogDamageListeners.cs @@ -1,70 +1,57 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; - -using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; namespace Jailbreak.Logs.Listeners; -public class LogDamageListeners : IPluginBehavior -{ - private readonly IRichLogService _logs; - - public LogDamageListeners(IRichLogService logs) - { - _logs = logs; - } - - - - [GameEventHandler] - public HookResult OnGrenadeThrown(EventGrenadeThrown @event, GameEventInfo info) - { - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - var grenade = @event.Weapon; - - _logs.Append(_logs.Player(player), $"threw a {grenade}"); - +public class LogDamageListeners : IPluginBehavior { + private readonly IRichLogService logs; + + public LogDamageListeners(IRichLogService logs) { this.logs = logs; } + + [GameEventHandler] + public HookResult OnGrenadeThrown(EventGrenadeThrown @event, + GameEventInfo info) { + var player = @event.Userid; + if (player == null || !player.IsReal()) return HookResult.Continue; + var grenade = @event.Weapon; + + logs.Append(logs.Player(player), $"threw a {grenade}"); + + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) { + var player = @event.Userid; + if (player == null || !player.IsReal()) return HookResult.Continue; + var attacker = @event.Attacker; + + var isWorld = attacker == null || !attacker.IsReal(); + var health = @event.DmgHealth; + + if (isWorld) { + if (health > 0) + logs.Append("The world hurt", logs.Player(player), + $"for {health} damage"); + else + logs.Append("The world killed", logs.Player(player)); + } else { + if (attacker == null) { + logs.Append(logs.Player(player), "was hurt by an unknown source", + $"for {health} damage"); return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) - { - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - var attacker = @event.Attacker; - - bool isWorld = attacker == null || !attacker.IsReal(); - int health = @event.DmgHealth; + } - if (isWorld) - { - if (health > 0) - { - _logs.Append($"The world hurt", _logs.Player(player), $"for {health} damage"); - } - else - { - _logs.Append("The world killed", _logs.Player(player)); - } - } - else - { - if (health > 0) - { - _logs.Append( _logs.Player(attacker), "hurt", _logs.Player(player), $"for {health} damage"); - } - else - { - _logs.Append(_logs.Player(attacker!), "killed", _logs.Player(player)); - } - } - - return HookResult.Continue; + if (health > 0) + logs.Append(logs.Player(attacker), "hurt", logs.Player(player), + $"for {health} damage"); + else + logs.Append(logs.Player(attacker), "killed", logs.Player(player)); } -} + + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityListeners.cs index 10cc2a80..f4dd4bc4 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityListeners.cs @@ -1,49 +1,38 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Memory; -using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; -using CounterStrikeSharp.API.Modules.Utils; -using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; namespace Jailbreak.Logs.Listeners; -public class LogEntityListeners : IPluginBehavior -{ - private readonly IRichLogService _logs; - - public LogEntityListeners(IRichLogService logs) - { - _logs = logs; - } - - [EntityOutputHook("func_button", "OnPressed")] - public HookResult OnButtonPressed(CEntityIOOutput output, string name, CEntityInstance activator, - CEntityInstance caller, CVariant value, float delay) - { - if (!activator.TryGetController(out var player)) - return HookResult.Continue; - - CBaseEntity? ent = Utilities.GetEntityFromIndex((int)caller.Index); - - - _logs.Append(_logs.Player(player), $"pressed a button: {ent.Entity?.Name ?? "Unlabeled"} -> {output?.Connections?.TargetDesc ?? "None"}"); - return HookResult.Continue; - } - - [EntityOutputHook("func_breakable", "OnBreak")] - public HookResult OnBreakableBroken(CEntityIOOutput output, string name, CEntityInstance activator, - CEntityInstance caller, CVariant value, float delay) - { - if (!activator.TryGetController(out var player)) - return HookResult.Continue; - - CBaseEntity? ent = Utilities.GetEntityFromIndex((int)caller.Index); - - - _logs.Append(_logs.Player(player), $"broke an entity: {ent.Entity?.Name ?? "Unlabeled"} -> {output?.Connections?.TargetDesc ?? "None"}"); - return HookResult.Continue; - } -} +public class LogEntityListeners(IRichLogService logs) : IPluginBehavior { + [EntityOutputHook("func_button", "OnPressed")] + public HookResult OnButtonPressed(CEntityIOOutput output, string name, + CEntityInstance activator, CEntityInstance caller, CVariant value, + float delay) { + if (!activator.TryGetController(out var player)) return HookResult.Continue; + if (player == null || !player.IsReal()) return HookResult.Continue; + + var ent = Utilities.GetEntityFromIndex((int)caller.Index); + + logs.Append(logs.Player(player), + $"pressed a button: {ent?.Entity?.Name ?? "Unlabeled"} -> {output?.Connections?.TargetDesc ?? "None"}"); + return HookResult.Continue; + } + + [EntityOutputHook("func_breakable", "OnBreak")] + public HookResult OnBreakableBroken(CEntityIOOutput output, string name, + CEntityInstance activator, CEntityInstance caller, CVariant value, + float delay) { + if (!activator.TryGetController(out var player)) return HookResult.Continue; + if (player == null || !player.IsReal()) return HookResult.Continue; + + var ent = Utilities.GetEntityFromIndex((int)caller.Index); + + logs.Append(logs.Player(player), + $"broke an entity: {ent?.Entity?.Name ?? "Unlabeled"} -> {output?.Connections?.TargetDesc ?? "None"}"); + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 07e8e029..875e6fc4 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -1,14 +1,12 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; -using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; namespace Jailbreak.Logs.Listeners; public class LogEntityParentListeners(IRichLogService logs) : IPluginBehavior { - private BasePlugin parent = null!; - private static readonly string[] WEAPON_STRINGS = [ "weapon_ak47", "weapon_aug", "weapon_awp", "weapon_bizon", "weapon_cz75a", "weapon_deagle", "weapon_famas", "weapon_fiveseven", "weapon_g3sg1", @@ -22,8 +20,6 @@ public class LogEntityParentListeners(IRichLogService logs) : IPluginBehavior { ]; public void Start(BasePlugin _parent) { - parent = _parent; - _parent .RegisterListener< CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( diff --git a/mod/Jailbreak.Logs/LogsCommand.cs b/mod/Jailbreak.Logs/LogsCommand.cs index 2c3fc698..6adb6807 100644 --- a/mod/Jailbreak.Logs/LogsCommand.cs +++ b/mod/Jailbreak.Logs/LogsCommand.cs @@ -7,12 +7,10 @@ namespace Jailbreak.Logs; -public class LogsCommand(ILogService logs) : IPluginBehavior -{ - [ConsoleCommand("css_logs")] - [RequiresPermissionsOr("@css/ban", "@css/generic", "@css/kick")] - public void Command_Logs(CCSPlayerController? executor, CommandInfo info) - { - logs.PrintLogs(executor); - } +public class LogsCommand(ILogService logs) : IPluginBehavior { + [ConsoleCommand("css_logs")] + [RequiresPermissionsOr("@css/ban", "@css/generic", "@css/kick")] + public void Command_Logs(CCSPlayerController? executor, CommandInfo info) { + logs.PrintLogs(executor); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsManager.cs b/mod/Jailbreak.Logs/LogsManager.cs index 253f52f4..8676dcd7 100644 --- a/mod/Jailbreak.Logs/LogsManager.cs +++ b/mod/Jailbreak.Logs/LogsManager.cs @@ -1,111 +1,79 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Objects; using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; -using Jailbreak.Public.Mod.Logs; -using Jailbreak.Public.Mod.Rebel; -using Jailbreak.Public.Mod.Warden; -using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Logs; -public class LogsManager : IPluginBehavior, ILogService, IRichLogService -{ - private readonly List _logMessages = new(); +public class LogsManager : IPluginBehavior, IRichLogService { + private readonly List logMessages = []; + private readonly ILogMessages messages; - private IRichPlayerTag _richPlayerTag; - private ILogMessages _messages; + private readonly IRichPlayerTag richPlayerTag; - public LogsManager(IServiceProvider serviceProvider, ILogMessages messages, IRichPlayerTag richPlayerTag) - { - _messages = messages; - _richPlayerTag = richPlayerTag; - } + public LogsManager(ILogMessages messages, IRichPlayerTag richPlayerTag) { + this.messages = messages; + this.richPlayerTag = richPlayerTag; + } - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - _messages.BEGIN_JAILBREAK_LOGS - .ToServerConsole() - .ToAllConsole(); + public void Append(string message) { + logMessages.Add(messages.CREATE_LOG(message)); + } - // By default, print all logs to player consoles at the end of the round. - foreach (var log in _logMessages) - log.ToServerConsole() - .ToAllConsole(); + public IEnumerable GetMessages() { + return logMessages.SelectMany(view => view.ToWriter().Plain); + } - _messages.END_JAILBREAK_LOGS - .ToServerConsole() - .ToAllConsole(); + public void Clear() { logMessages.Clear(); } - return HookResult.Continue; - } + public void PrintLogs(CCSPlayerController? player) { + if (player == null || !player.IsReal()) { + messages.BeginJailbreakLogs.ToServerConsole(); + foreach (var log in logMessages) log.ToServerConsole(); + messages.EndJailbreakLogs.ToServerConsole(); - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - Clear(); - return HookResult.Continue; + return; } - public void Append(params FormatObject[] objects) - { - _logMessages.Add(_messages.CREATE_LOG(objects)); - } - public FormatObject Player(CCSPlayerController playerController) - { - return new TreeFormatObject() - { - playerController, - $"[{playerController.UserId}]", - _richPlayerTag.Rich(playerController) - }; - } + messages.BeginJailbreakLogs.ToPlayerConsole(player); + foreach (var log in logMessages) log.ToPlayerConsole(player); + messages.EndJailbreakLogs.ToPlayerConsole(player); + } - public void Append(string message) - { - _logMessages.Add(_messages.CREATE_LOG(message)); - } + public void Append(params FormatObject[] objects) { + logMessages.Add(messages.CREATE_LOG(objects)); + } - public IEnumerable GetMessages() - { - return _logMessages.SelectMany(view => view.ToWriter().Plain); - } + public FormatObject Player(CCSPlayerController playerController) { + return new TreeFormatObject { + playerController, + $"[{playerController.UserId}]", + richPlayerTag.Rich(playerController) + }; + } - public void Clear() - { - _logMessages.Clear(); - } + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { + messages.BeginJailbreakLogs.ToServerConsole().ToAllConsole(); - public void PrintLogs(CCSPlayerController? player) - { - if (player == null || !player.IsReal()) - { - _messages.BEGIN_JAILBREAK_LOGS - .ToServerConsole(); - foreach (var log in _logMessages) - log.ToServerConsole(); - _messages.END_JAILBREAK_LOGS - .ToServerConsole(); - - return; - } - - - _messages.BEGIN_JAILBREAK_LOGS - .ToPlayerConsole(player); - foreach (var log in _logMessages) - log.ToPlayerConsole(player); - _messages.END_JAILBREAK_LOGS - .ToPlayerConsole(player); - } -} + // By default, print all logs to player consoles at the end of the round. + foreach (var log in logMessages) log.ToServerConsole().ToAllConsole(); + + messages.EndJailbreakLogs.ToServerConsole().ToAllConsole(); + + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { + Clear(); + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsServiceExtension.cs b/mod/Jailbreak.Logs/LogsServiceExtension.cs index 8aece7b5..caa470ef 100644 --- a/mod/Jailbreak.Logs/LogsServiceExtension.cs +++ b/mod/Jailbreak.Logs/LogsServiceExtension.cs @@ -1,4 +1,4 @@ -using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Logs.Listeners; using Jailbreak.Logs.Tags; using Jailbreak.Public.Extensions; @@ -7,21 +7,21 @@ namespace Jailbreak.Logs; -public static class LogsServiceExtension -{ - public static void AddJailbreakLogs(this IServiceCollection services) - { - services.AddPluginBehavior(); - services.AddTransient(provider => provider.GetRequiredService()); +public static class LogsServiceExtension { + public static void AddJailbreakLogs(this IServiceCollection services) { + services.AddPluginBehavior(); + services.AddTransient(provider + => provider.GetRequiredService()); + + services.AddPluginBehavior(); - services.AddPluginBehavior(); services.AddPluginBehavior(); services.AddPluginBehavior(); - services.AddPluginBehavior(); + services.AddPluginBehavior(); - // PlayerTagHelper is a lower-level class that avoids dependency loops. - services.AddTransient(); + // PlayerTagHelper is a lower-level class that avoids dependency loops. + services.AddTransient(); services.AddTransient(); } -} +} \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs b/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs index ff43c536..ac29d73d 100644 --- a/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs +++ b/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs @@ -1,49 +1,45 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Objects; -using Jailbreak.Formatting.Views; -using Jailbreak.Public.Behaviors; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Extensions; -using Jailbreak.Public.Mod.Logs; using Jailbreak.Public.Mod.Rebel; using Jailbreak.Public.Mod.Warden; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Logs.Tags; -public class PlayerTagHelper : IRichPlayerTag, IPlayerTag -{ - private Lazy _wardenService; - private Lazy _rebelService; - private Lazy _specialTreatmentService; - - public PlayerTagHelper(IServiceProvider provider) - { - // Lazy-load dependencies to avoid loops, since we are a lower-level class. - _wardenService = new ( () => provider.GetRequiredService() ); - _rebelService = new ( () => provider.GetRequiredService() ); - _specialTreatmentService = new ( () => provider.GetRequiredService() ); - } - - public FormatObject Rich(CCSPlayerController player) - { - if (_wardenService.Value.IsWarden(player)) - return new StringFormatObject("(WARDEN)", ChatColors.DarkBlue); - if (player.GetTeam() == CsTeam.CounterTerrorist) - return new StringFormatObject("(CT)", ChatColors.BlueGrey); - if (_rebelService.Value.IsRebel(player)) - return new StringFormatObject("(REBEL)", ChatColors.DarkRed); - if (_specialTreatmentService.Value.IsSpecialTreatment(player)) - return new StringFormatObject("(ST)", ChatColors.Green); - - return new StringFormatObject("(T)", ChatColors.Yellow); - } - - public string Plain(CCSPlayerController playerController) - { - return Rich(playerController).ToPlain(); - } -} +public class PlayerTagHelper : IRichPlayerTag { + private readonly Lazy rebelService; + private readonly Lazy stService; + private readonly Lazy wardenService; + + public PlayerTagHelper(IServiceProvider provider) { + // Lazy-load dependencies to avoid loops, since we are a lower-level class. + wardenService = + new Lazy(provider.GetRequiredService); + rebelService = + new Lazy(provider.GetRequiredService); + stService = + new Lazy(provider + .GetRequiredService); + } + + public FormatObject Rich(CCSPlayerController player) { + if (wardenService.Value.IsWarden(player)) + return new StringFormatObject("(WARDEN)", ChatColors.DarkBlue); + if (player.GetTeam() == CsTeam.CounterTerrorist) + return new StringFormatObject("(CT)", ChatColors.BlueGrey); + if (rebelService.Value.IsRebel(player)) + return new StringFormatObject("(REBEL)", ChatColors.DarkRed); + if (stService.Value.IsSpecialTreatment(player)) + return new StringFormatObject("(ST)", ChatColors.Green); + + return new StringFormatObject("(T)", ChatColors.Yellow); + } + + public string Plain(CCSPlayerController playerController) { + return Rich(playerController).ToPlain(); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Mute/Jailbreak.Mute.csproj b/mod/Jailbreak.Mute/Jailbreak.Mute.csproj index 70f814b3..f430fd60 100644 --- a/mod/Jailbreak.Mute/Jailbreak.Mute.csproj +++ b/mod/Jailbreak.Mute/Jailbreak.Mute.csproj @@ -7,12 +7,8 @@ - - - - - - + + diff --git a/mod/Jailbreak.Mute/MuteServiceExtension.cs b/mod/Jailbreak.Mute/MuteServiceExtension.cs index 1280fcb2..ac310316 100644 --- a/mod/Jailbreak.Mute/MuteServiceExtension.cs +++ b/mod/Jailbreak.Mute/MuteServiceExtension.cs @@ -4,10 +4,8 @@ namespace Jailbreak.Mute; -public static class MuteServiceExtension -{ - public static void AddJailbreakMute(this IServiceCollection services) - { - services.AddPluginBehavior(); - } +public static class MuteServiceExtension { + public static void AddJailbreakMute(this IServiceCollection services) { + services.AddPluginBehavior(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Mute/MuteSystem.cs b/mod/Jailbreak.Mute/MuteSystem.cs index 9df2d49f..7c89be7f 100644 --- a/mod/Jailbreak.Mute/MuteSystem.cs +++ b/mod/Jailbreak.Mute/MuteSystem.cs @@ -14,204 +14,175 @@ namespace Jailbreak.Mute; -public class MuteSystem(IServiceProvider provider) : IPluginBehavior, IMuteService -{ - private BasePlugin parent; - private DateTime lastPeace = DateTime.MinValue; - private DateTime peaceEnd = DateTime.MinValue; - private DateTime ctPeaceEnd = DateTime.MinValue; - - private IPeaceMessages messages; - private IWardenService warden; - - private Timer? prisonerTimer, guardTimer; - - public void Start(BasePlugin parent) - { - this.parent = parent; - - messages = provider.GetRequiredService(); - warden = provider.GetRequiredService(); - - parent.RegisterListener(OnPlayerSpeak); - } - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - UnPeaceMute(); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) - { - UnPeaceMute(); - return HookResult.Continue; - } - - public void Dispose() - { - parent.RemoveListener(OnPlayerSpeak); - } - - public void PeaceMute(MuteReason reason) - { - var duration = GetPeaceDuration(reason); - var ctDuration = Math.Min(10, duration); - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal())) - if (!warden.IsWarden(player)) - mute(player); - - switch (reason) - { - case MuteReason.ADMIN: - messages.PEACE_ENACTED_BY_ADMIN(duration).ToAllChat(); - break; - case MuteReason.WARDEN_TAKEN: - messages.GENERAL_PEACE_ENACTED(duration).ToAllChat(); - break; - case MuteReason.WARDEN_INVOKED: - messages.WARDEN_ENACTED_PEACE(duration).ToAllChat(); - break; - case MuteReason.INITIAL_WARDEN: - messages.GENERAL_PEACE_ENACTED(duration).ToAllChat(); - break; - } - - peaceEnd = DateTime.Now.AddSeconds(duration); - ctPeaceEnd = DateTime.Now.AddSeconds(ctDuration); - lastPeace = DateTime.Now; - - guardTimer?.Kill(); - prisonerTimer?.Kill(); - - guardTimer = parent.AddTimer(ctDuration, unmuteGuards); - prisonerTimer = parent.AddTimer(duration, unmutePrisoners); - } - - private void unmuteGuards() - { - foreach (var player in Utilities.GetPlayers() - .Where(player => - player.IsReal() && player is { Team: CsTeam.CounterTerrorist, PawnIsAlive: true })) - unmute(player); - - messages.UNMUTED_GUARDS.ToAllChat(); - guardTimer = null; - } - - private void unmutePrisoners() - { - foreach (var player in Utilities.GetPlayers() - .Where(player => - player.IsReal() && player is { Team: CsTeam.Terrorist, PawnIsAlive: true })) - unmute(player); - - messages.UNMUTED_PRISONERS.ToAllChat(); - prisonerTimer = null; - } - - public void UnPeaceMute() - { - if (guardTimer != null) - unmuteGuards(); - - if (prisonerTimer != null) - unmutePrisoners(); - } - - private int GetPeaceDuration(MuteReason reason) - { - var prisoners = Utilities.GetPlayers() - .Count(c => c.IsReal() && c is { Team: CsTeam.Terrorist, PawnIsAlive: true }); - // https://www.desmos.com/calculator/gwd9cqw4yq - var baseTime = (int)Math.Floor((prisoners + 30) / 5.0) * 5; - - return reason switch - { - MuteReason.ADMIN => baseTime, - MuteReason.WARDEN_TAKEN => baseTime / 5, - MuteReason.INITIAL_WARDEN => 2 * baseTime / 3, - MuteReason.WARDEN_INVOKED => baseTime / 2, - _ => baseTime - }; - } - - private void mute(CCSPlayerController player) - { - if (bypassMute(player)) - return; - player.VoiceFlags |= VoiceFlags.Muted; - } - - private void unmute(CCSPlayerController player) - { - player.VoiceFlags &= ~VoiceFlags.Muted; - } - - public bool IsPeaceEnabled() - { - return DateTime.Now < peaceEnd; - } - - public DateTime GetLastPeace() - { - return lastPeace; - } - - private void OnPlayerSpeak(int playerSlot) - { - var player = Utilities.GetPlayerFromSlot(playerSlot); - if (player == null || !player.IsReal()) - return; - - if (warden.IsWarden(player)) - { - // Always let the warden speak - unmute(player); - return; - } - - if (!player.PawnIsAlive && !bypassMute(player)) - { - // Normal players can't speak when dead - messages.DEAD_REMINDER.ToPlayerCenter(player); - mute(player); - return; - } - - if (isMuted(player)) - { - // Remind any muted players they're muted - messages.MUTE_REMINDER.ToPlayerCenter(player); - return; - } - - if (bypassMute(player)) - { - // Warn admins if they're not muted - if (IsPeaceEnabled()) - { - if (player.Team == CsTeam.CounterTerrorist && DateTime.Now >= ctPeaceEnd) - return; - messages.PEACE_REMINDER.ToPlayerCenter(player); - } - - if (!player.PawnIsAlive) - messages.ADMIN_DEAD_REMINDER.ToPlayerCenter(player); - } - } - - private bool isMuted(CCSPlayerController player) - { - if (!player.IsReal()) - return false; - return (player.VoiceFlags & VoiceFlags.Muted) != 0; - } - - private bool bypassMute(CCSPlayerController player) - { - return player.IsReal() && AdminManager.PlayerHasPermissions(player, "@css/chat"); +public class MuteSystem(IServiceProvider provider) + : IPluginBehavior, IMuteService { + private DateTime ctPeaceEnd = DateTime.MinValue; + private DateTime lastPeace = DateTime.MinValue; + + private IPeaceMessages? messages; + private BasePlugin? parent; + private DateTime peaceEnd = DateTime.MinValue; + + private Timer? prisonerTimer, guardTimer; + private IWardenService? warden; + + public void PeaceMute(MuteReason reason) { + var duration = getPeaceDuration(reason); + var ctDuration = Math.Min(10, duration); + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal())) + if (!warden!.IsWarden(player)) + mute(player); + + switch (reason) { + case MuteReason.ADMIN: + messages!.PeaceEnactedByAdmin(duration).ToAllChat(); + break; + case MuteReason.WARDEN_TAKEN: + messages!.GeneralPeaceEnacted(duration).ToAllChat(); + break; + case MuteReason.WARDEN_INVOKED: + messages!.WardenEnactedPeace(duration).ToAllChat(); + break; + case MuteReason.INITIAL_WARDEN: + messages!.GeneralPeaceEnacted(duration).ToAllChat(); + break; + } + + peaceEnd = DateTime.Now.AddSeconds(duration); + ctPeaceEnd = DateTime.Now.AddSeconds(ctDuration); + lastPeace = DateTime.Now; + + guardTimer?.Kill(); + prisonerTimer?.Kill(); + + guardTimer = parent!.AddTimer(ctDuration, unmuteGuards); + prisonerTimer = parent!.AddTimer(duration, unmutePrisoners); + } + + public void UnPeaceMute() { + if (guardTimer != null) unmuteGuards(); + + if (prisonerTimer != null) unmutePrisoners(); + } + + public bool IsPeaceEnabled() { return DateTime.Now < peaceEnd; } + + public DateTime GetLastPeace() { return lastPeace; } + + public void Start(BasePlugin basePlugin) { + parent = basePlugin; + + messages = provider.GetRequiredService(); + warden = provider.GetRequiredService(); + + basePlugin.RegisterListener(OnPlayerSpeak); + } + + public void Dispose() { parent!.RemoveListener(OnPlayerSpeak); } + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { + UnPeaceMute(); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { + UnPeaceMute(); + return HookResult.Continue; + } + + private void unmuteGuards() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal() && player is { + Team: CsTeam.CounterTerrorist, PawnIsAlive: true + })) + unmute(player); + + messages!.UnmutedGuards.ToAllChat(); + guardTimer = null; + } + + private void unmutePrisoners() { + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal() + && player is { Team: CsTeam.Terrorist, PawnIsAlive: true })) + unmute(player); + + messages!.UnmutedPrisoners.ToAllChat(); + prisonerTimer = null; + } + + private int getPeaceDuration(MuteReason reason) { + var prisoners = Utilities.GetPlayers() + .Count(c + => c.IsReal() && c is { Team: CsTeam.Terrorist, PawnIsAlive: true }); + // https://www.desmos.com/calculator/gwd9cqw4yq + var baseTime = (int)Math.Floor((prisoners + 30) / 5.0) * 5; + + return reason switch { + MuteReason.ADMIN => baseTime, + MuteReason.WARDEN_TAKEN => baseTime / 5, + MuteReason.INITIAL_WARDEN => 2 * baseTime / 3, + MuteReason.WARDEN_INVOKED => baseTime / 2, + _ => baseTime + }; + } + + private void mute(CCSPlayerController player) { + if (bypassMute(player)) return; + player.VoiceFlags |= VoiceFlags.Muted; + } + + private void unmute(CCSPlayerController player) { + player.VoiceFlags &= ~VoiceFlags.Muted; + } + + private void OnPlayerSpeak(int playerSlot) { + var player = Utilities.GetPlayerFromSlot(playerSlot); + if (player == null || !player.IsReal()) return; + + if (warden!.IsWarden(player)) { + // Always let the warden speak + unmute(player); + return; } + + if (!player.PawnIsAlive && !bypassMute(player)) { + // Normal players can't speak when dead + messages!.DeadReminder.ToPlayerCenter(player); + mute(player); + return; + } + + if (isMuted(player)) { + // Remind any muted players they're muted + messages!.MuteReminder.ToPlayerCenter(player); + return; + } + + if (bypassMute(player)) { + // Warn admins if they're not muted + if (IsPeaceEnabled()) { + if (player.Team == CsTeam.CounterTerrorist + && DateTime.Now >= ctPeaceEnd) + return; + messages!.PeaceReminder.ToPlayerCenter(player); + } + + if (!player.PawnIsAlive) + messages!.AdminDeadReminder.ToPlayerCenter(player); + } + } + + private bool isMuted(CCSPlayerController player) { + if (!player.IsReal()) return false; + return (player.VoiceFlags & VoiceFlags.Muted) != 0; + } + + private bool bypassMute(CCSPlayerController player) { + return player.IsReal() + && AdminManager.PlayerHasPermissions(player, "@css/chat"); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj b/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj index cf2402c3..f430fd60 100644 --- a/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj +++ b/mod/Jailbreak.Rebel/Jailbreak.Rebel.csproj @@ -7,12 +7,8 @@ - - - - - - + + diff --git a/mod/Jailbreak.Rebel/JihadC4/JihadC4Behavior.cs b/mod/Jailbreak.Rebel/JihadC4/JihadC4Behavior.cs index bdf26f8d..f6677764 100644 --- a/mod/Jailbreak.Rebel/JihadC4/JihadC4Behavior.cs +++ b/mod/Jailbreak.Rebel/JihadC4/JihadC4Behavior.cs @@ -8,205 +8,170 @@ using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Rebel; -using Microsoft.Extensions.Logging; namespace Jailbreak.Rebel.JihadC4; -public class JihadC4Behavior(IJihadC4Notifications jihadC4Notifications, IRebelService rebelService) : IPluginBehavior, IJihadC4Service -{ - private class JihadBombMetadata(float delay, bool isDetonating) - { - public float Delay { get; set; } = delay; - public bool IsDetonating { get; set; } = isDetonating; +public class JihadC4Behavior(IJihadC4Notifications jihadC4Notifications, + IRebelService rebelService) : IPluginBehavior, IJihadC4Service { + private readonly Dictionary bombs = new(); + + // EmitSound(CBaseEntity* pEnt, const char* sSoundName, int nPitch, float flVolume, float flDelay) + private readonly MemoryFunctionVoid + // ReSharper disable once InconsistentNaming + CBaseEntity_EmitSoundParamsLinux = new( + "48 B8 ? ? ? ? ? ? ? ? 55 48 89 E5 41 55 41 54 49 89 FC 53 48 89 F3"); // LINUX ONLY. + + private BasePlugin? plugin; + + public void ClearActiveC4s() { bombs.Clear(); } + + public void TryGiveC4ToPlayer(CCSPlayerController player) { + var bombEntity = new CC4(player.GiveNamedItem("weapon_c4")); + bombs.Add(bombEntity, new JihadBombMetadata(0.75f, false)); + + jihadC4Notifications.JihadC4Received.ToPlayerChat(player); + jihadC4Notifications.JihadC4Usage1.ToPlayerChat(player); + } + + public void StartDetonationAttempt(CCSPlayerController player, float delay, + CC4 bombEntity) { + if (plugin == null) return; + + tryEmitSound(player, "jb.jihad", 1, 1f, 0f); + + bombs[bombEntity].Delay = delay; + bombs[bombEntity].IsDetonating = true; + + rebelService.MarkRebel(player); + + Server.RunOnTick(Server.TickCount + (int)(64 * delay), + () => detonate(player, bombEntity)); + } + + public void TryGiveC4ToRandomTerrorist() { + plugin!.AddTimer(1, () => { + var validTerroristPlayers = Utilities.GetPlayers() + .Where(player => player.IsReal() && player is { + Team : CsTeam.Terrorist, + PawnIsAlive: true, + IsBot : false, + IsValid : true + }) + .ToList(); + var numOfTerrorists = validTerroristPlayers.Count; + if (numOfTerrorists == 0) return; + + Random rnd = new(); + var randomIndex = rnd.Next(numOfTerrorists); + TryGiveC4ToPlayer(validTerroristPlayers[randomIndex]); + }); + } + + public void Start(BasePlugin basePlugin) { + plugin = basePlugin; + plugin.RegisterListener(playerUseC4ListenerCallback); + } + + private void playerUseC4ListenerCallback() { + foreach (var (bomb, meta) in bombs) { + if (!bomb.IsValid) continue; + if (meta.IsDetonating) continue; + + var bombCarrier = bomb.OwnerEntity.Value?.As() + .Controller.Value?.As(); + if (bombCarrier == null || !bombCarrier.IsValid + || (bombCarrier.Buttons & PlayerButtons.Use) == 0) + continue; + + var activeWeapon = bombCarrier.PlayerPawn.Value?.WeaponServices + ?.ActiveWeapon.Value; + if (activeWeapon == null || !activeWeapon.IsValid + || activeWeapon.Handle != bomb.Handle) + continue; + + StartDetonationAttempt(bombCarrier, meta.Delay, bomb); } - - private Dictionary _bombs = new(); - - private BasePlugin? _basePlugin; - - // EmitSound(CBaseEntity* pEnt, const char* sSoundName, int nPitch, float flVolume, float flDelay) - private readonly MemoryFunctionVoid CBaseEntity_EmitSoundParamsLinux = - new("48 B8 ? ? ? ? ? ? ? ? 55 48 89 E5 41 55 41 54 49 89 FC 53 48 89 F3"); // LINUX ONLY. - - public void Start(BasePlugin basePlugin) - { - _basePlugin = basePlugin; - _basePlugin.RegisterListener(PlayerUseC4ListenerCallback); - } - - private void PlayerUseC4ListenerCallback() - { - foreach (var (bomb, meta) in _bombs) - { - if (!bomb.IsValid) - continue; - if (meta.IsDetonating) - continue; - - var bombCarrier = bomb.OwnerEntity.Value?.As().Controller.Value?.As(); - if (bombCarrier == null || !bombCarrier.IsValid || (bombCarrier.Buttons & PlayerButtons.Use) == 0) - continue; - - var activeWeapon = bombCarrier.PlayerPawn.Value?.WeaponServices?.ActiveWeapon.Value; - if (activeWeapon == null || !activeWeapon.IsValid || (activeWeapon.Handle != bomb.Handle)) - continue; - - StartDetonationAttempt(bombCarrier, meta.Delay, bomb); - } - } - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - ClearActiveC4s(); - TryGiveC4ToRandomTerrorist(); - return HookResult.Continue; - } - - public void ClearActiveC4s() - { - _bombs.Clear(); + } + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { + ClearActiveC4s(); + TryGiveC4ToRandomTerrorist(); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDropC4(EventBombDropped @event, + GameEventInfo info) { + var player = @event.Userid; + if (player == null || !player.IsValid) return HookResult.Continue; + + var bombEntity = Utilities.GetEntityFromIndex((int)@event.Entindex); + if (bombEntity == null) return HookResult.Continue; + + bombs.TryGetValue(bombEntity, out var bombMetadata); + if (bombMetadata == null) return HookResult.Continue; + + if (bombMetadata.IsDetonating) { + bombEntity.Remove(); + return HookResult.Stop; } - [GameEventHandler] - public HookResult OnPlayerDropC4(EventBombDropped @event, GameEventInfo info) - { - var player = @event.Userid; - if (player == null || !player.IsValid) - return HookResult.Continue; - - var bombEntity = Utilities.GetEntityFromIndex((int)@event.Entindex); - if (bombEntity == null) - return HookResult.Continue; + return HookResult.Continue; + } - _bombs.TryGetValue(bombEntity, out var bombMetadata); - if (bombMetadata == null) - return HookResult.Continue; - - if (bombMetadata.IsDetonating) - { - bombEntity.Remove(); - return HookResult.Stop; - } - - return HookResult.Continue; + private void detonate(CCSPlayerController player, CC4 bomb) { + if (!player.IsValid || !player.IsReal() || !player.PawnIsAlive) { + bombs.TryGetValue(bomb, out _); + if (bomb.IsValid) bomb.Remove(); + bombs.Remove(bomb); + return; } - public void TryGiveC4ToPlayer(CCSPlayerController player) - { - var bombEntity = new CC4(player.GiveNamedItem("weapon_c4")); - _bombs.Add(bombEntity, new JihadBombMetadata(0.75f, false)); - - jihadC4Notifications.JIHAD_C4_RECEIVED.ToPlayerChat(player); - jihadC4Notifications.JIHAD_C4_USAGE1.ToPlayerChat(player); + tryEmitSound(player, "jb.jihadExplosion", 1, 1f, 0f); + var particleSystemEntity = + Utilities.CreateEntityByName("info_particle_system")!; + particleSystemEntity.EffectName = + "particles/explosions_fx/explosion_c4_500.vpcf"; + particleSystemEntity.StartActive = true; + + particleSystemEntity.Teleport(player.PlayerPawn.Value!.AbsOrigin!, + new QAngle(), new Vector()); + particleSystemEntity.DispatchSpawn(); + + /* Calculate damage here, only applies to alive CTs. */ + foreach (var ct in Utilities.GetPlayers() + .Where(p => p.IsReal() && p is { + Team: CsTeam.CounterTerrorist, PawnIsAlive: true, IsValid: true + })) { + var distanceFromBomb = + ct.PlayerPawn.Value!.AbsOrigin!.Distance(player.PlayerPawn.Value + .AbsOrigin!); + if (distanceFromBomb > 350f) continue; + + // 350f = "bombRadius" + var damage = 340f; + damage *= (350f - distanceFromBomb) / 350f; + float healthRef = ct.PlayerPawn.Value.Health; + if (healthRef <= damage) { ct.CommitSuicide(true, true); } else { + ct.PlayerPawn.Value.Health -= (int)damage; + Utilities.SetStateChanged(ct, "CBaseEntity", "m_iHealth"); + } } - public void StartDetonationAttempt(CCSPlayerController player, float delay, CC4 bombEntity) - { - if (_basePlugin == null) - return; - - TryEmitSound(player, "jb.jihad", 1, 1f, 0f); - - _bombs[bombEntity].Delay = delay; - _bombs[bombEntity].IsDetonating = true; - - rebelService.MarkRebel(player, 30); - - Server.RunOnTick(Server.TickCount + (int)(64 * delay), () => Detonate(player, bombEntity)); - } - - private void Detonate(CCSPlayerController player, CC4 bomb) - { - if (!player.IsValid || !player.IsReal() || !player.PawnIsAlive) - { - _bombs.TryGetValue(bomb, out var metadata); - if (bomb.IsValid) - bomb.Remove(); - _bombs.Remove(bomb); - return; - } - - TryEmitSound(player, "jb.jihadExplosion", 1, 1f, 0f); - var particleSystemEntity = - Utilities.CreateEntityByName("info_particle_system")!; - particleSystemEntity.EffectName = "particles/explosions_fx/explosion_c4_500.vpcf"; - particleSystemEntity.StartActive = true; - - particleSystemEntity.Teleport(player.PlayerPawn!.Value!.AbsOrigin!, new QAngle(), new Vector()); - particleSystemEntity.DispatchSpawn(); - - /* Calculate damage here, only applies to alive CTs. */ - foreach (var ct in Utilities.GetPlayers() - .Where((p) => p.IsReal() && p is - { Team: CsTeam.CounterTerrorist, PawnIsAlive: true, IsValid: true })) - { - var distanceFromBomb = - ct.PlayerPawn!.Value!.AbsOrigin!.Distance(player.PlayerPawn.Value.AbsOrigin!); - if (distanceFromBomb > 350f) - continue; - - // 350f = "bombRadius" - var damage = 340f; - damage *= (350f - distanceFromBomb) / 350f; - float healthRef = ct.PlayerPawn.Value.Health; - if (healthRef <= damage) - { - ct.CommitSuicide(true, true); - } - else - { - ct.PlayerPawn.Value.Health -= (int)damage; - Utilities.SetStateChanged(ct, "CBaseEntity", "m_iHealth"); - } - } - - // If they didn't have the C4 make sure to remove it. - player.CommitSuicide(true, true); - _bombs.Remove(bomb); - } - - public void TryGiveC4ToRandomTerrorist() - { - _basePlugin!.AddTimer(1, () => - { - var validTerroristPlayers = Utilities.GetPlayers() - .Where(player => - player.IsReal() && player is - { Team: CsTeam.Terrorist, PawnIsAlive: true, IsBot: false, IsValid: true }).ToList(); - var numOfTerrorists = validTerroristPlayers.Count; - if (numOfTerrorists == 0) - return; - - Random rnd = new(); - var randomIndex = rnd.Next(numOfTerrorists); - TryGiveC4ToPlayer(validTerroristPlayers[randomIndex]); - }); - } - - private void TryEmitSound(CBaseEntity entity, string soundEventName, int pitch, float volume, float delay) - { - CBaseEntity_EmitSoundParamsLinux.Invoke(entity, soundEventName, pitch, volume, delay); - } - - // Returns whether the weapon c4 was in their inventory or not. - private bool TryRemoveWeaponC4(CCSPlayerController player) - { - if (player.PlayerPawn.Value?.WeaponServices == null) - return false; - - foreach (var weapon in player.PlayerPawn.Value.WeaponServices.MyWeapons) - { - if (weapon.Value == null) - continue; - - if (weapon.Value.DesignerName == "weapon_c4") - { - weapon.Value.Remove(); - return true; - } - } - - return false; - } + // If they didn't have the C4 make sure to remove it. + player.CommitSuicide(true, true); + bombs.Remove(bomb); + } + + private void tryEmitSound(CBaseEntity entity, string soundEventName, + int pitch, float volume, float delay) { + CBaseEntity_EmitSoundParamsLinux.Invoke(entity, soundEventName, pitch, + volume, delay); + } + + private class JihadBombMetadata(float delay, bool isDetonating) { + public float Delay { get; set; } = delay; + public bool IsDetonating { get; set; } = isDetonating; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Rebel/RebelListener.cs b/mod/Jailbreak.Rebel/RebelListener.cs index a973249e..2bedd3ab 100644 --- a/mod/Jailbreak.Rebel/RebelListener.cs +++ b/mod/Jailbreak.Rebel/RebelListener.cs @@ -8,29 +8,22 @@ namespace Jailbreak.Rebel; -public class RebelListener(IRebelService rebelService, ILastRequestManager lastRequestManager) - : IPluginBehavior -{ - [GameEventHandler] - public HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) - { - var player = @event.Userid; - if (!player.IsReal()) - return HookResult.Continue; - if (player.GetTeam() != CsTeam.CounterTerrorist) - return HookResult.Continue; +public class RebelListener(IRebelService rebelService, + ILastRequestManager lastRequestManager) : IPluginBehavior { + [GameEventHandler] + public HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) { + var player = @event.Userid; + if (player == null || !player.IsReal()) return HookResult.Continue; + if (player.GetTeam() != CsTeam.CounterTerrorist) return HookResult.Continue; - var attacker = @event.Attacker; - if (!attacker.IsReal()) - return HookResult.Continue; + var attacker = @event.Attacker; + if (attacker == null || !attacker.IsReal()) return HookResult.Continue; - if (attacker.GetTeam() != CsTeam.Terrorist) - return HookResult.Continue; + if (attacker.GetTeam() != CsTeam.Terrorist) return HookResult.Continue; - if (lastRequestManager.IsInLR(attacker)) - return HookResult.Continue; - - rebelService.MarkRebel(attacker); - return HookResult.Continue; - } + if (lastRequestManager.IsInLR(attacker)) return HookResult.Continue; + + 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 dd845d64..fa357a66 100644 --- a/mod/Jailbreak.Rebel/RebelManager.cs +++ b/mod/Jailbreak.Rebel/RebelManager.cs @@ -4,167 +4,142 @@ using CounterStrikeSharp.API.Modules.Timers; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; -using Jailbreak.Public.Mod.Logs; using Jailbreak.Public.Mod.Rebel; namespace Jailbreak.Rebel; -public class RebelManager(IRebelNotifications notifs, IRichLogService logs) : IPluginBehavior, IRebelService -{ - private readonly Dictionary _rebelTimes = new(); - - public static int MAX_REBEL_TIME = 45; - - public void Start(BasePlugin parent) - { - parent.RegisterEventHandler(OnPlayerDisconnect); - parent.RegisterEventHandler(OnPlayerDeath); - parent.RegisterEventHandler(OnRoundStart); - parent.RegisterListener(OnTick); - - parent.AddTimer(1f, () => - { - foreach (var player in GetActiveRebels()) - { - if (!player.IsReal()) - continue; - - if (GetRebelTimeLeft(player) <= 0) - { - UnmarkRebel(player); - continue; - } - - ApplyRebelColor(player); - SendTimeLeft(player); - } - }, TimerFlags.REPEAT); - } +public class RebelManager(IRebelNotifications notifs, IRichLogService logs) + : IPluginBehavior, IRebelService { + public static readonly int MAX_REBEL_TIME = 45; + private readonly Dictionary rebelTimes = new(); - private void OnTick() - { - foreach (var player in GetActiveRebels()) - { - if (!player.IsReal()) - continue; + public void Start(BasePlugin basePlugin) { + basePlugin.RegisterEventHandler(OnPlayerDisconnect); + basePlugin.RegisterEventHandler(OnPlayerDeath); + basePlugin.RegisterEventHandler(OnRoundStart); + basePlugin.RegisterListener(OnTick); - if (GetRebelTimeLeft(player) <= 0) continue; + basePlugin.AddTimer(1f, () => { + foreach (var player in GetActiveRebels()) { + if (!player.IsReal()) continue; - SendTimeLeft(player); + if (GetRebelTimeLeft(player) <= 0) { + UnmarkRebel(player); + continue; } - } - - HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) - { - _rebelTimes.Clear(); - foreach (var player in Utilities.GetPlayers()) - { - if (!player.IsReal()) - continue; - ApplyRebelColor(player); - } - - return HookResult.Continue; - } - private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) - { - if (@event.Userid == null) return HookResult.Continue; - if (_rebelTimes.ContainsKey(@event.Userid)) _rebelTimes.Remove(@event.Userid); + applyRebelColor(player); + sendTimeLeft(player); + } + }, TimerFlags.REPEAT); + } - return HookResult.Continue; - } + public ISet GetActiveRebels() { + return rebelTimes.Keys.ToHashSet(); + } - private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) - { - var player = @event.Userid; - if (player == null) return HookResult.Continue; - if (!player.IsReal()) - return HookResult.Continue; - _rebelTimes.Remove(player); - return HookResult.Continue; - } - - public ISet GetActiveRebels() - { - return _rebelTimes.Keys.ToHashSet(); - } + public long GetRebelTimeLeft(CCSPlayerController player) { + if (rebelTimes.TryGetValue(player, out var time)) + return time - DateTimeOffset.Now.ToUnixTimeSeconds(); - public long GetRebelTimeLeft(CCSPlayerController player) - { - if (_rebelTimes.TryGetValue(player, out long time)) - { - return time - DateTimeOffset.Now.ToUnixTimeSeconds(); - } + return 0; + } - return 0; - } + public bool MarkRebel(CCSPlayerController player, long time = 30) { + if (!rebelTimes.ContainsKey(player)) + logs.Append(logs.Player(player), "is now a rebel."); - public bool MarkRebel(CCSPlayerController player, long time = 30) - { - if (!_rebelTimes.ContainsKey(player)) - { - logs.Append(logs.Player(player), "is now a rebel."); - } + rebelTimes[player] = DateTimeOffset.Now.ToUnixTimeSeconds() + time; + applyRebelColor(player); + return true; + } - _rebelTimes[player] = DateTimeOffset.Now.ToUnixTimeSeconds() + time; - ApplyRebelColor(player); - return true; + public void UnmarkRebel(CCSPlayerController player) { + if (rebelTimes.ContainsKey(player)) { + notifs.NoLongerRebel.ToPlayerChat(player); + logs.Append(logs.Player(player), "is no longer a rebel."); } - public void UnmarkRebel(CCSPlayerController player) - { - if (_rebelTimes.ContainsKey(player)) - { - notifs.NO_LONGER_REBEL.ToPlayerChat(player); - logs.Append(logs.Player(player), "is no longer a rebel."); - } - - _rebelTimes.Remove(player); - ApplyRebelColor(player); - } + rebelTimes.Remove(player); + applyRebelColor(player); + } - // https://www.desmos.com/calculator/g2v6vvg7ax - private float GetRebelTimePercentage(CCSPlayerController player) - { - var x = GetRebelTimeLeft(player); - if (x > MAX_REBEL_TIME) - return 1; - if (x <= 0) - return 0; - return (float)(100 - (MAX_REBEL_TIME - x) * Math.Sqrt(MAX_REBEL_TIME - x) / 3.8f) / 100; - } + private void OnTick() { + foreach (var player in GetActiveRebels()) { + if (!player.IsReal()) continue; - 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); + if (GetRebelTimeLeft(player) <= 0) continue; - return color; + sendTimeLeft(player); } + } - 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 HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info) { + rebelTimes.Clear(); + foreach (var player in Utilities.GetPlayers()) { + if (!player.IsReal()) continue; + applyRebelColor(player); } - 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 {formattedColor}rebelling"); - } + return HookResult.Continue; + } + + private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, + GameEventInfo info) { + if (@event.Userid == null) return HookResult.Continue; + if (rebelTimes.ContainsKey(@event.Userid)) rebelTimes.Remove(@event.Userid); + + return HookResult.Continue; + } + + private HookResult OnPlayerDeath(EventPlayerDeath @event, + GameEventInfo info) { + var player = @event.Userid; + if (player == null) return HookResult.Continue; + if (!player.IsReal()) return HookResult.Continue; + rebelTimes.Remove(player); + return HookResult.Continue; + } + + // https://www.desmos.com/calculator/g2v6vvg7ax + private float getRebelTimePercentage(CCSPlayerController player) { + var x = GetRebelTimeLeft(player); + if (x > MAX_REBEL_TIME) return 1; + if (x <= 0) return 0; + return (float)(100 - (MAX_REBEL_TIME - x) * Math.Sqrt(MAX_REBEL_TIME - x) + / 3.8f) / 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); + + 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 {formattedColor}rebelling"); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Rebel/RebelServiceExtension.cs b/mod/Jailbreak.Rebel/RebelServiceExtension.cs index 6dc00b9f..c12f2af0 100644 --- a/mod/Jailbreak.Rebel/RebelServiceExtension.cs +++ b/mod/Jailbreak.Rebel/RebelServiceExtension.cs @@ -5,12 +5,10 @@ namespace Jailbreak.Rebel; -public static class RebelServiceExtension -{ - public static void AddJailbreakRebel(this IServiceCollection collection) - { - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } -} +public static class RebelServiceExtension { + public static void AddJailbreakRebel(this IServiceCollection collection) { + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + collection.AddPluginBehavior(); + } +} \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs index 6bda2751..f4c34414 100644 --- a/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs @@ -10,45 +10,38 @@ namespace Jailbreak.Warden.Commands; -public class PeaceCommandsBehavior( - IWardenService warden, - IMuteService mute, - IPeaceMessages messages, - IWardenNotifications notifications, - IGenericCommandNotifications generics) - : IPluginBehavior -{ - [ConsoleCommand("css_peace", "Invokes a peace period where only the warden can talk")] - public void Command_Peace(CCSPlayerController? executor, CommandInfo info) - { - if (mute.IsPeaceEnabled()) - { - if (executor != null) - messages.PEACE_ACTIVE.ToPlayerChat(executor); - return; - } - - bool fromWarden = executor != null && warden.IsWarden(executor); +public class PeaceCommandsBehavior(IWardenService warden, IMuteService mute, + IPeaceMessages messages, IWardenNotifications notifications, + IGenericCommandNotifications generics) : IPluginBehavior { + [ConsoleCommand("css_peace", + "Invokes a peace period where only the warden can talk")] + public void Command_Peace(CCSPlayerController? executor, CommandInfo info) { + if (mute.IsPeaceEnabled()) { + if (executor != null) messages.PeaceActive.ToPlayerChat(executor); + return; + } - if (executor == null || AdminManager.PlayerHasPermissions(executor, "@css/cheats")) - { - // Server console or a high-admin is invoking the peace period, bypass cooldown - mute.PeaceMute(fromWarden ? MuteReason.WARDEN_INVOKED : MuteReason.ADMIN); - return; - } + var fromWarden = executor != null && warden.IsWarden(executor); - if (!warden.IsWarden(executor) && !AdminManager.PlayerHasPermissions(executor, "@css/chat")) - { - notifications.NOT_WARDEN.ToPlayerChat(executor); - return; - } + if (executor == null + || AdminManager.PlayerHasPermissions(executor, "@css/cheats")) { + // Server console or a high-admin is invoking the peace period, bypass cooldown + mute.PeaceMute(fromWarden ? MuteReason.WARDEN_INVOKED : MuteReason.ADMIN); + return; + } - if (DateTime.Now - mute.GetLastPeace() < TimeSpan.FromSeconds(60)) - { - generics.CommandOnCooldown(mute.GetLastPeace().AddSeconds(60)).ToPlayerChat(executor); - return; - } + if (!warden.IsWarden(executor) + && !AdminManager.PlayerHasPermissions(executor, "@css/chat")) { + notifications.NOT_WARDEN.ToPlayerChat(executor); + return; + } - mute.PeaceMute(fromWarden ? MuteReason.WARDEN_INVOKED : MuteReason.ADMIN); + if (DateTime.Now - mute.GetLastPeace() < TimeSpan.FromSeconds(60)) { + generics.CommandOnCooldown(mute.GetLastPeace().AddSeconds(60)) + .ToPlayerChat(executor); + return; } + + mute.PeaceMute(fromWarden ? MuteReason.WARDEN_INVOKED : MuteReason.ADMIN); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs b/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs index b1b38d15..49ae9c1b 100644 --- a/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs @@ -1,7 +1,6 @@ using CounterStrikeSharp.API.Core; 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; @@ -9,47 +8,38 @@ namespace Jailbreak.Warden.Commands; -public class RollCommandBehavior( - IWardenService warden, - IRollCommandNotications notifications, - IWardenNotifications wardenNotifications, - IGenericCommandNotifications generics) - : IPluginBehavior -{ - private readonly Random _rng = new(); - - [ConsoleCommand("css_roll", - "Roll a number between min and max. If no min and max are provided, it will default to 0 and 10.")] - [CommandHelper(1, "[min] [max]", CommandUsage.CLIENT_ONLY)] - public void Command_Toggle(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - - if (!warden.IsWarden(player)) - { - wardenNotifications.NOT_WARDEN.ToPlayerChat(player); - return; - } - - var min = 0; - var max = 10; - - if (command.ArgCount == 3) - { - if (!int.TryParse(command.GetArg(1), out min)) - { - generics.InvalidParameter(command.GetArg(1), "number"); - return; - } - - if (!int.TryParse(command.GetArg(2), out max)) - { - generics.InvalidParameter(command.GetArg(2), "number"); - return; - } - } - - notifications.Roll(_rng.Next(min, max)).ToAllChat(); +public class RollCommandBehavior(IWardenService warden, + IRollCommandNotications notifications, + IWardenNotifications wardenNotifications, + IGenericCommandNotifications generics) : IPluginBehavior { + private readonly Random rng = new(); + + [ConsoleCommand("css_roll", + "Roll a number between min and max. If no min and max are provided, it will default to 0 and 10.")] + [CommandHelper(1, "[min] [max]", CommandUsage.CLIENT_ONLY)] + public void Command_Toggle(CCSPlayerController? player, CommandInfo command) { + if (player == null) return; + + if (!warden.IsWarden(player)) { + wardenNotifications.NOT_WARDEN.ToPlayerChat(player); + return; } + + var min = 0; + var max = 10; + + if (command.ArgCount == 3) { + if (!int.TryParse(command.GetArg(1), out min)) { + generics.InvalidParameter(command.GetArg(1), "number"); + return; + } + + if (!int.TryParse(command.GetArg(2), out max)) { + generics.InvalidParameter(command.GetArg(2), "number"); + return; + } + } + + notifications.Roll(rng.Next(min, max)).ToAllChat(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs index 6d8c4090..10e09fb9 100644 --- a/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs @@ -9,68 +9,49 @@ namespace Jailbreak.Warden.Commands; -public class SpecialTreatmentCommandsBehavior : IPluginBehavior -{ - private IWardenService _warden; - private ISpecialTreatmentService _specialTreatment; - - private IGenericCommandNotifications _generic; - private IWardenNotifications _wardenNotifs; - - public SpecialTreatmentCommandsBehavior(IWardenService warden, ISpecialTreatmentService specialTreatment, - IGenericCommandNotifications generic, ISpecialTreatmentNotifications notifications, - IWardenNotifications wardenNotifs) - { - _warden = warden; - _specialTreatment = specialTreatment; - _generic = generic; - _wardenNotifs = wardenNotifs; +public class SpecialTreatmentCommandsBehavior(IWardenService warden, + ISpecialTreatmentService specialTreatment, + IGenericCommandNotifications generic, IWardenNotifications wardenNotifs) + : IPluginBehavior { + [ConsoleCommand("css_treat", + "Grant or revoke special treatment from a player")] + [ConsoleCommand("css_st", "Grant or revoke special treatment from a player")] + [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] + public void Command_Toggle(CCSPlayerController? player, CommandInfo command) { + if (player == null) return; + + if (!warden.IsWarden(player)) { + wardenNotifs.NOT_WARDEN.ToPlayerChat(player).ToPlayerConsole(player); + return; } - [ConsoleCommand("css_treat", "Grant or revoke special treatment from a player")] - [ConsoleCommand("css_st", "Grant or revoke special treatment from a player")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Toggle(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - - if (!_warden.IsWarden(player)) - { - _wardenNotifs.NOT_WARDEN.ToPlayerChat(player).ToPlayerConsole(player); - return; - } - - if (command.ArgCount == 1) - { - // TODO: Pop up menu of prisoners to toggle ST for - return; - } + if (command.ArgCount == 1) + // TODO: Pop up menu of prisoners to toggle ST for + return; - var targets = command.GetArgTargetResult(1); - var eligible = targets - .Where(p => p is { Team: CsTeam.Terrorist, PawnIsAlive: true }) - .ToList(); + var targets = command.GetArgTargetResult(1); + var eligible = targets + .Where(p => p is { Team: CsTeam.Terrorist, PawnIsAlive: true }) + .ToList(); - if (eligible.Count == 0) - { - _generic.PlayerNotFound(command.GetArg(1)) - .ToPlayerChat(player) - .ToPlayerConsole(player); - return; - } + if (eligible.Count == 0) { + generic.PlayerNotFound(command.GetArg(1)) + .ToPlayerChat(player) + .ToPlayerConsole(player); + return; + } - if (eligible.Count != 1) - { - _generic.PlayerFoundMultiple(command.GetArg(1)) - .ToPlayerChat(player) - .ToPlayerConsole(player); - return; - } + if (eligible.Count != 1) { + generic.PlayerFoundMultiple(command.GetArg(1)) + .ToPlayerChat(player) + .ToPlayerConsole(player); + return; + } - // One target, mark as ST. - var special = eligible.First(); + // One target, mark as ST. + var special = eligible.First(); - _specialTreatment.SetSpecialTreatment(special, !_specialTreatment.IsSpecialTreatment(special)); - } + specialTreatment.SetSpecialTreatment(special, + !specialTreatment.IsSpecialTreatment(special)); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs index 064d0847..77d0f7a6 100644 --- a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs @@ -1,5 +1,4 @@ -using System.ComponentModel.Design; -using CounterStrikeSharp.API; +using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; @@ -10,166 +9,133 @@ using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Warden; -using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Warden.Commands; -public class WardenCommandsBehavior( - IWardenNotifications _notifications, - IWardenSelectionService _queue, - IWardenService _warden, - IGenericCommandNotifications _generics, - WardenConfig _config -) : IPluginBehavior -{ - private readonly Dictionary _lastPassCommand = new(); - - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) - { - _lastPassCommand.Clear(); - return HookResult.Continue; - } +public class WardenCommandsBehavior(IWardenNotifications notifications, + IWardenSelectionService queue, IWardenService warden, + IGenericCommandNotifications generics, WardenConfig config) + : IPluginBehavior { + private readonly Dictionary lastPassCommand = + new(); + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) { + lastPassCommand.Clear(); + return HookResult.Continue; + } + + [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; - [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)) return; - if (!_warden.IsWarden(player)) return; + // Handle warden pass + notifications.PASS_WARDEN(player).ToAllChat().ToAllCenter(); - // Handle warden pass - _notifications.PASS_WARDEN(player) - .ToAllChat() - .ToAllCenter(); + // GetPlayers() returns valid players, no need to error check here. + foreach (var clients in Utilities.GetPlayers()) + clients.ExecuteClientCommand( + $"play sounds/{config.WardenPassedSoundName}"); - // GetPlayers() returns valid players, no need to error check here. - foreach (var clients in Utilities.GetPlayers()) - { - clients.ExecuteClientCommand( - $"play sounds/{_config.WardenPassedSoundName}"); - } + notifications.BECOME_NEXT_WARDEN.ToAllChat(); - _notifications.BECOME_NEXT_WARDEN.ToAllChat(); + if (!warden.TryRemoveWarden(true)) + Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); - if (!_warden.TryRemoveWarden(true)) - Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); + lastPassCommand[player] = DateTime.Now; + } - _lastPassCommand[player] = DateTime.Now; + [ConsoleCommand("css_fire", "Force the warden to pass")] + [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] + public void Command_Fire(CCSPlayerController? player, CommandInfo command) { + if (player == null) return; + + if (!warden.HasWarden || warden.Warden == null) { + notifications.CURRENT_WARDEN(null).ToPlayerChat(player); + return; } - [ConsoleCommand("css_fire", "Force the warden to pass")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Fire(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - - if (!_warden.HasWarden || _warden.Warden == null) - { - _notifications.CURRENT_WARDEN(null).ToPlayerChat(player); - return; - } - - if (!AdminManager.PlayerHasPermissions(player, "@css/ban")) - { - _generics.NoPermissionMessage("@css/ban").ToPlayerChat(player); - return; - } - - foreach (var client in Utilities.GetPlayers().Where(p => p.IsReal())) - { - if (AdminManager.PlayerHasPermissions(client, "@css/chat")) - { - _notifications.FIRE_WARDEN(_warden.Warden, player).ToPlayerChat(client); - } - else - { - _notifications.FIRE_WARDEN(_warden.Warden).ToPlayerChat(client); - } - - client.ExecuteClientCommand( - $"play sounds/{_config.WardenPassedSoundName}"); - } - - _notifications.BECOME_NEXT_WARDEN.ToAllChat(); - - _lastPassCommand[_warden.Warden] = DateTime.Now; - - if (!_warden.TryRemoveWarden(true)) - Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); + if (!AdminManager.PlayerHasPermissions(player, "@css/ban")) { + generics.NoPermissionMessage("@css/ban").ToPlayerChat(player); + return; } - [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; - - // Why add them to a cooldown list if they can't even be warden :) - if (player.Team != CsTeam.CounterTerrorist || !player.PawnIsAlive) - { - return; - } - - // If they're already in the cooldown dictionary, check if their cooldown has expired. - if (_lastPassCommand.TryGetValue(player, out var last)) - { - var cooldown = last.AddSeconds(15); - if (DateTime.Now < cooldown) - { - _generics.CommandOnCooldown(cooldown).ToPlayerChat(player); - return; - } - } - - // Queue is open ? - if (_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 i.e. the queue is not open/active. - if (!_warden.HasWarden) - { - if (_warden.TrySetWarden(player)) - return; - } - - _notifications.CURRENT_WARDEN(_warden.Warden).ToPlayerChat(player); + foreach (var client in Utilities.GetPlayers().Where(p => p.IsReal())) { + if (AdminManager.PlayerHasPermissions(client, "@css/chat")) + notifications.FIRE_WARDEN(warden.Warden, player).ToPlayerChat(client); + else + notifications.FIRE_WARDEN(warden.Warden).ToPlayerChat(client); + + client.ExecuteClientCommand( + $"play sounds/{config.WardenPassedSoundName}"); } - /// - /// If the player who just died was the warden, clear the claim cooldown dictionary, so other CT's can claim! - /// - [GameEventHandler] - public HookResult OnWardenDeath(EventPlayerDeath @event, GameEventInfo info) - { - var player = @event.Userid; - if (player == null) - return HookResult.Continue; - - if (player != _warden.Warden) - return HookResult.Continue; - - _lastPassCommand.Clear(); - return HookResult.Continue; + notifications.BECOME_NEXT_WARDEN.ToAllChat(); + + lastPassCommand[warden.Warden] = DateTime.Now; + + if (!warden.TryRemoveWarden(true)) + 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; + + // Why add them to a cooldown list if they can't even be warden :) + if (player.Team != CsTeam.CounterTerrorist || !player.PawnIsAlive) return; + + // If they're already in the cooldown dictionary, check if their cooldown has expired. + if (lastPassCommand.TryGetValue(player, out var last)) { + var cooldown = last.AddSeconds(15); + if (DateTime.Now < cooldown) { + generics.CommandOnCooldown(cooldown).ToPlayerChat(player); + return; + } } + + // Queue is open ? + if (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 i.e. the queue is not open/active. + if (!warden.HasWarden) + if (warden.TrySetWarden(player)) + return; + + notifications.CURRENT_WARDEN(warden.Warden).ToPlayerChat(player); + } + + /// + /// If the player who just died was the warden, clear the claim cooldown dictionary, so other CT's can claim! + /// + [GameEventHandler] + public HookResult OnWardenDeath(EventPlayerDeath @event, GameEventInfo info) { + var player = @event.Userid; + if (player == null) return HookResult.Continue; + + if (player != warden.Warden) return HookResult.Continue; + + lastPassCommand.Clear(); + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs b/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs index 7a0d872d..2736bc3c 100644 --- a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs +++ b/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs @@ -1,5 +1,3 @@ namespace Jailbreak.Warden.Extensions; -public class WardenFormatWriterExtensions -{ -} \ No newline at end of file +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 1b12cba3..4bd7b2bb 100644 --- a/mod/Jailbreak.Warden/Global/WardenBehavior.cs +++ b/mod/Jailbreak.Warden/Global/WardenBehavior.cs @@ -2,10 +2,10 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Entities; using CounterStrikeSharp.API.Modules.Utils; using Jailbreak.Formatting.Extensions; using Jailbreak.Formatting.Views; +using Jailbreak.Formatting.Views.Logging; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Extensions; using Jailbreak.Public.Mod.Mute; @@ -17,407 +17,330 @@ namespace Jailbreak.Warden.Global; // By making it a struct we ensure values from the CCSPlayerPawn are passed by VALUE. -struct PreWardenStats(int armorValue, int health, int maxHealth, bool hadHealthshot, bool hadHelmetArmor) -{ - public int armorValue = armorValue; - public int health = health; - public int maxHealth = maxHealth; - public bool hadHealthshot = hadHealthshot; - public bool hadHelmetArmor = hadHelmetArmor; +internal struct PreWardenStats(int armorValue, int health, int maxHealth, + bool headHealthShot, bool hadHelmetArmor) { + public readonly int ArmorValue = armorValue; + public readonly int Health = health; + public readonly int MaxHealth = maxHealth; + public readonly bool HeadHealthShot = headHealthShot; + public readonly bool HadHelmetArmor = hadHelmetArmor; } -public class WardenBehavior( - ILogger logger, - IWardenNotifications notifications, - IRichLogService logs, - ISpecialTreatmentService specialTreatment, - IRebelService rebels, - WardenConfig config, - IMuteService mute) - : IPluginBehavior, IWardenService -{ - private ISet _bluePrisoners = new HashSet(); - private BasePlugin _parent; - private Timer? _unblueTimer; - private bool firstWarden = false; - private PreWardenStats? _preWardenStats = null; - private bool _hasWarden; - private CCSPlayerController? _warden; - - public void Start(BasePlugin parent) - { - _parent = parent; - } +public class WardenBehavior(ILogger logger, + IWardenNotifications notifications, IRichLogService logs, + ISpecialTreatmentService specialTreatment, IRebelService rebels, + WardenConfig config, IMuteService mute) : IPluginBehavior, IWardenService { + private readonly ISet bluePrisoners = + new HashSet(); - /// - /// 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; - - mute.UnPeaceMute(); - - _hasWarden = true; - _warden = controller; - - - if (_warden.Pawn.Value != null) - { - _warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; - _warden.Pawn.Value.Render = Color.FromArgb(254, 0, 0, 255); - Utilities.SetStateChanged(_warden.Pawn.Value, "CBaseModelEntity", "m_clrRender"); - } - - notifications.NEW_WARDEN(_warden) - .ToAllChat() - .ToAllCenter(); - - _warden.PlayerName = "[WARDEN] " + _warden.PlayerName; - - foreach (var player in Utilities.GetPlayers().Where(player => player.IsReal())) - { - player.ExecuteClientCommand( - $"play sounds/{config.WardenNewSoundName}"); - } - - logs.Append(logs.Player(_warden), "is now the warden."); - - _unblueTimer = _parent.AddTimer(3, UnmarkPrisonersBlue); - mute.PeaceMute(firstWarden ? MuteReason.INITIAL_WARDEN : MuteReason.WARDEN_TAKEN); - - // Always store the stats of the warden b4 they became warden, in case we need to restore them later. - var wardenPawn = _warden.PlayerPawn.Value; - if (wardenPawn == null) - { - return false; - } - - if (firstWarden) - { - firstWarden = false; - - var hasHealthshot = playerHasHealthshot(_warden); - var hasHelmet = playerHasHelmetArmor(_warden); - _preWardenStats = new PreWardenStats(wardenPawn.ArmorValue, wardenPawn.Health, wardenPawn.MaxHealth, - hasHealthshot, hasHelmet); - - if (!hasHelmet) - _warden.GiveNamedItem("item_assaultsuit"); - - SetWardenStats(wardenPawn, 125, 125, 100); - if (!hasHealthshot) - _warden.GiveNamedItem("weapon_healthshot"); - } - else - { - _preWardenStats = null; - } + private bool firstWarden; - return true; - } + private BasePlugin? parent; + private PreWardenStats? preWardenStats; + private Timer? unblueTimer; - public bool TryRemoveWarden(bool isPass = false) - { - if (!_hasWarden) - return false; - - mute.UnPeaceMute(); - - _hasWarden = false; - - if (_warden != null && _warden.Pawn.Value != null) - { - _warden.PlayerName = _warden.PlayerName.Replace("[WARDEN] ", ""); - _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.Append(logs.Player(_warden), "is no longer the warden."); - } - - CCSPlayerPawn? wardenPawn = _warden!.PlayerPawn.Value; - if (wardenPawn == null) - { - return false; - } - - // if isPass we restore their old health values or their current health, whichever is less. - if (isPass && _preWardenStats != null) - { - // Regardless of if the above if statement is true or false, we want to restore the player's previous stats. - SetWardenStats(wardenPawn, - Math.Min(wardenPawn.ArmorValue, _preWardenStats.Value.armorValue), - Math.Min(wardenPawn.Health, _preWardenStats.Value.health), - Math.Min(wardenPawn.MaxHealth, _preWardenStats.Value.maxHealth) - ); - - /* This code makes sure people can't abuse the first warden's buff by removing it if they pass. */ - CCSPlayer_ItemServices? itemServices = itemServicesOrNull(_warden); - if (itemServices == null) - { - return false; - } - - if (!_preWardenStats.Value.hadHelmetArmor) - { - itemServices.HasHelmet = false; - } - - Utilities.SetStateChanged(wardenPawn, "CBasePlayerPawn", "m_pItemServices"); - - if (!_preWardenStats.Value.hadHealthshot) - { - playerHasHealthshot(_warden, true); - } - } - - _warden = null; - return true; - } + public void Start(BasePlugin basePlugin) { parent = basePlugin; } - [GameEventHandler] - public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) - { - if (!((IWardenService)this).IsWarden(ev.Userid)) - return HookResult.Continue; + /// + /// Get the current warden, if there is one. + /// + public CCSPlayerController? Warden { get; private set; } - mute.UnPeaceMute(); - ProcessWardenDeath(); - return HookResult.Continue; - } + /// + /// Whether or not a warden is currently assigned + /// + public bool HasWarden { get; private set; } - [GameEventHandler] - public HookResult OnChangeTeam(EventPlayerTeam @event, GameEventInfo info) - { - var player = @event.Userid; - if (!((IWardenService)this).IsWarden(player)) - return HookResult.Continue; + public bool TrySetWarden(CCSPlayerController controller) { + if (HasWarden) return false; - mute.UnPeaceMute(); - ProcessWardenDeath(); - return HookResult.Continue; + // Verify player is a CT + if (controller.GetTeam() != CsTeam.CounterTerrorist) return false; + if (!controller.PawnIsAlive) return false; + + mute.UnPeaceMute(); + + HasWarden = true; + Warden = controller; + + + if (Warden.Pawn.Value != null) { + Warden.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; + Warden.Pawn.Value.Render = Color.FromArgb(254, 0, 0, 255); + Utilities.SetStateChanged(Warden.Pawn.Value, "CBaseModelEntity", + "m_clrRender"); } - private void ProcessWardenDeath() - { - if (!this.TryRemoveWarden()) - logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); + notifications.NEW_WARDEN(Warden).ToAllChat().ToAllCenter(); - // Warden died! - notifications.WARDEN_DIED - .ToAllChat() - .ToAllCenter(); + Warden.PlayerName = "[WARDEN] " + Warden.PlayerName; - foreach (var player in Utilities.GetPlayers()) - { - if (!player.IsReal()) continue; - player.ExecuteClientCommand( - $"play sounds/{config.WardenKilledSoundName}"); - } + foreach (var player in Utilities.GetPlayers() + .Where(player => player.IsReal())) + player.ExecuteClientCommand($"play sounds/{config.WardenNewSoundName}"); - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + logs.Append(logs.Player(Warden), "is now the warden."); - _unblueTimer - ?.Kill(); // If the warden dies withing 3 seconds of becoming warden, we need to cancel the unblue timer - MarkPrisonersBlue(); - } + unblueTimer = parent!.AddTimer(3, unmarkPrisonersBlue); + mute.PeaceMute(firstWarden ? + MuteReason.INITIAL_WARDEN : + MuteReason.WARDEN_TAKEN); - private void UnmarkPrisonersBlue() - { - foreach (var player in _bluePrisoners) - { - if (!player.IsReal()) - continue; - var pawn = player.Pawn.Value; - if (pawn == null) - continue; - if (IgnoreColor(player)) - continue; - pawn.RenderMode = RenderMode_t.kRenderNormal; - pawn.Render = Color.FromArgb(254, 255, 255, 255); - Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); - } - - _bluePrisoners.Clear(); - } + // Always store the stats of the warden b4 they became warden, in case we need to restore them later. + var wardenPawn = Warden.PlayerPawn.Value; + if (wardenPawn == null) return false; - private void MarkPrisonersBlue() - { - foreach (CCSPlayerController player in Utilities.GetPlayers()) - { - if (!player.IsReal() || player.Team != CsTeam.Terrorist) - continue; - if (IgnoreColor(player)) - continue; - - var pawn = player.Pawn.Value; - if (pawn == null) - continue; - pawn.RenderMode = RenderMode_t.kRenderTransColor; - pawn.Render = Color.FromArgb(254, 0, 0, 255); - Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); - - _bluePrisoners.Add(player); - } - } + if (firstWarden) { + firstWarden = false; + + var hasHealthshot = playerHasHealthshot(Warden); + var hasHelmet = playerHasHelmetArmor(Warden); + preWardenStats = new PreWardenStats(wardenPawn.ArmorValue, + wardenPawn.Health, wardenPawn.MaxHealth, hasHealthshot, hasHelmet); + + if (!hasHelmet) Warden.GiveNamedItem("item_assaultsuit"); + + setWardenStats(wardenPawn, 125, 125, 100); + if (!hasHealthshot) Warden.GiveNamedItem("weapon_healthshot"); + } else { preWardenStats = null; } - private bool IgnoreColor(CCSPlayerController player) - { - if (specialTreatment.IsSpecialTreatment(player)) - return true; - if (rebels.IsRebel(player)) - return true; - return false; + return true; + } + + public bool TryRemoveWarden(bool isPass = false) { + if (!HasWarden) return false; + + mute.UnPeaceMute(); + + HasWarden = false; + + if (Warden != null && Warden.Pawn.Value != null) { + Warden.PlayerName = Warden.PlayerName.Replace("[WARDEN] ", ""); + 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.Append(logs.Player(Warden), "is no longer the warden."); } - private int getBalance() - { - var ctCount = Utilities.GetPlayers().Count(p => p.Team == CsTeam.CounterTerrorist); - var tCount = Utilities.GetPlayers().Count(p => p.Team == CsTeam.Terrorist); + var wardenPawn = Warden!.PlayerPawn.Value; + if (wardenPawn == null) return false; + + // if isPass we restore their old health values or their current health, whichever is less. + if (isPass && preWardenStats != null) { + // Regardless of if the above if statement is true or false, we want to restore the player's previous stats. + setWardenStats(wardenPawn, + Math.Min(wardenPawn.ArmorValue, preWardenStats.Value.ArmorValue), + Math.Min(wardenPawn.Health, preWardenStats.Value.Health), + Math.Min(wardenPawn.MaxHealth, preWardenStats.Value.MaxHealth)); - // Casting to a float ensures if we're diving by zero, we get infinity instead of an error. - var ratio = ((float)tCount / config.TerroristRatio) - ctCount; + /* This code makes sure people can't abuse the first warden's buff by removing it if they pass. */ + var itemServices = itemServicesOrNull(Warden); + if (itemServices == null) return false; - return ratio switch - { - > 0 => 1, - 0 => 0, - _ => -1 - }; + if (!preWardenStats.Value.HadHelmetArmor) itemServices.HasHelmet = false; + + Utilities.SetStateChanged(wardenPawn, "CBasePlayerPawn", + "m_pItemServices"); + + if (!preWardenStats.Value.HeadHealthShot) + playerHasHealthshot(Warden, true); } - private CCSPlayer_ItemServices? itemServicesOrNull(CCSPlayerController player) - { - CPlayer_ItemServices? itemServices = player.PlayerPawn.Value?.ItemServices; - return (itemServices != null) ? new CCSPlayer_ItemServices(itemServices.Handle) : null; + Warden = null; + return true; + } + + [GameEventHandler] + public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) { + if (!((IWardenService)this).IsWarden(ev.Userid)) return HookResult.Continue; + + mute.UnPeaceMute(); + processWardenDeath(); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnChangeTeam(EventPlayerTeam @event, GameEventInfo info) { + var player = @event.Userid; + if (!((IWardenService)this).IsWarden(player)) return HookResult.Continue; + + mute.UnPeaceMute(); + processWardenDeath(); + return HookResult.Continue; + } + + private void processWardenDeath() { + if (!TryRemoveWarden()) + logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); + + // Warden died! + notifications.WARDEN_DIED.ToAllChat().ToAllCenter(); + + foreach (var player in Utilities.GetPlayers()) { + if (!player.IsReal()) continue; + player.ExecuteClientCommand( + $"play sounds/{config.WardenKilledSoundName}"); } - private void SetWardenStats(CCSPlayerPawn wardenPawn, int armor = -1, int health = -1, int maxHealth = -1) - { - if (armor != -1) - { - wardenPawn.ArmorValue = armor; - Utilities.SetStateChanged(wardenPawn, "CCSPlayerPawn", "m_ArmorValue"); - } - - if (health != -1) - { - wardenPawn.Health = health; - Utilities.SetStateChanged(wardenPawn, "CBaseEntity", "m_iHealth"); - } - - if (maxHealth != -1) - { - wardenPawn.MaxHealth = maxHealth; - Utilities.SetStateChanged(wardenPawn, "CBaseEntity", "m_iMaxHealth"); - } + notifications.BECOME_NEXT_WARDEN.ToAllChat(); + + unblueTimer + ?.Kill(); // If the warden dies withing 3 seconds of becoming warden, we need to cancel the unblue timer + markPrisonersBlue(); + } + + private void unmarkPrisonersBlue() { + foreach (var player in bluePrisoners) { + if (!player.IsReal()) continue; + var pawn = player.Pawn.Value; + if (pawn == null) continue; + if (ignoreColor(player)) continue; + pawn.RenderMode = RenderMode_t.kRenderNormal; + pawn.Render = Color.FromArgb(254, 255, 255, 255); + Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); } - private bool playerHasHelmetArmor(CCSPlayerController player) - { - CCSPlayer_ItemServices? itemServices = itemServicesOrNull(player); - return (itemServices != null) ? itemServices.HasHelmet : false; + bluePrisoners.Clear(); + } + + private void markPrisonersBlue() { + foreach (var player in Utilities.GetPlayers()) { + if (!player.IsReal() || player.Team != CsTeam.Terrorist) continue; + if (ignoreColor(player)) continue; + + var pawn = player.Pawn.Value; + if (pawn == null) continue; + pawn.RenderMode = RenderMode_t.kRenderTransColor; + pawn.Render = Color.FromArgb(254, 0, 0, 255); + Utilities.SetStateChanged(pawn, "CBaseModelEntity", "m_clrRender"); + + bluePrisoners.Add(player); + } + } + + private bool ignoreColor(CCSPlayerController player) { + if (specialTreatment.IsSpecialTreatment(player)) return true; + if (rebels.IsRebel(player)) return true; + return false; + } + + private int getBalance() { + var ctCount = Utilities.GetPlayers() + .Count(p => p.Team == CsTeam.CounterTerrorist); + var tCount = Utilities.GetPlayers().Count(p => p.Team == CsTeam.Terrorist); + + // Casting to a float ensures if we're diving by zero, we get infinity instead of an error. + var ratio = (float)tCount / config.TerroristRatio - ctCount; + + return ratio switch { + > 0 => 1, + 0 => 0, + _ => -1 + }; + } + + private CCSPlayer_ItemServices? + itemServicesOrNull(CCSPlayerController player) { + var itemServices = player.PlayerPawn.Value?.ItemServices; + return itemServices != null ? + new CCSPlayer_ItemServices(itemServices.Handle) : + null; + } + + private void setWardenStats(CCSPlayerPawn wardenPawn, int armor = -1, + int health = -1, int maxHealth = -1) { + if (armor != -1) { + wardenPawn.ArmorValue = armor; + Utilities.SetStateChanged(wardenPawn, "CCSPlayerPawn", "m_ArmorValue"); } - private bool playerHasHealthshot(CCSPlayerController player, bool removeIfHas = false) - { - CCSPlayerPawn? playerPawn = player.PlayerPawn.Value; - if (playerPawn == null || playerPawn.WeaponServices == null) - { - return false; - } - - foreach (var weapon in playerPawn.WeaponServices.MyWeapons) - { - if (weapon.Value == null) continue; - if (weapon.Value.DesignerName.Equals("weapon_healthshot")) - { - if (removeIfHas) - { - weapon.Value.Remove(); - } - - return true; - } - } - - return false; + if (health != -1) { + wardenPawn.Health = health; + Utilities.SetStateChanged(wardenPawn, "CBaseEntity", "m_iHealth"); } - [GameEventHandler] - public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) - { - this.TryRemoveWarden(); - mute.UnPeaceMute(); - return HookResult.Continue; + if (maxHealth != -1) { + wardenPawn.MaxHealth = maxHealth; + Utilities.SetStateChanged(wardenPawn, "CBaseEntity", "m_iMaxHealth"); } + } + + private bool playerHasHelmetArmor(CCSPlayerController player) { + var itemServices = itemServicesOrNull(player); + return itemServices is { HasHelmet: true }; + } + + private bool playerHasHealthshot(CCSPlayerController player, + bool removeIfHas = false) { + var playerPawn = player.PlayerPawn.Value; + if (playerPawn == null || playerPawn.WeaponServices == null) return false; - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) - { - firstWarden = true; - _preWardenStats = null; - - int ctArmorValue = getBalance() switch - { - 0 => 50, // Balanced teams - 1 => 100, // Ts outnumber CTs - -1 => 25, // CTs outnumber Ts - _ => 50 // default (should never happen) - }; - - /* Round start CT buff */ - foreach (var guardController in Utilities.GetPlayers() - .Where(p => p.IsReal() && p is { Team: CsTeam.CounterTerrorist, PawnIsAlive: true })) - { - CCSPlayerPawn? guardPawn = guardController.PlayerPawn.Value; - if (guardPawn == null) - continue; - - guardPawn.ArmorValue = ctArmorValue; - Utilities.SetStateChanged(guardPawn, "CCSPlayerPawn", "m_ArmorValue"); - } - - return HookResult.Continue; + foreach (var weapon in playerPawn.WeaponServices.MyWeapons) { + if (weapon.Value == null) continue; + if (weapon.Value.DesignerName.Equals("weapon_healthshot")) { + if (removeIfHas) weapon.Value.Remove(); + + return true; + } } - [GameEventHandler] - public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, GameEventInfo info) - { - if (!((IWardenService)this).IsWarden(ev.Userid)) - return HookResult.Continue; + return false; + } + + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) { + TryRemoveWarden(); + mute.UnPeaceMute(); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) { + firstWarden = true; + preWardenStats = null; + + var ctArmorValue = getBalance() switch { + 0 => 50, // Balanced teams + 1 => 100, // Ts outnumber CTs + -1 => 25, // CTs outnumber Ts + _ => 50 // default (should never happen) + }; + + /* Round start CT buff */ + foreach (var guardController in Utilities.GetPlayers() + .Where(p => p.IsReal() && p is { + Team: CsTeam.CounterTerrorist, PawnIsAlive: true + })) { + var guardPawn = guardController.PlayerPawn.Value; + if (guardPawn == null) continue; + + guardPawn.ArmorValue = ctArmorValue; + Utilities.SetStateChanged(guardPawn, "CCSPlayerPawn", "m_ArmorValue"); + } - if (!this.TryRemoveWarden()) - logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); + return HookResult.Continue; + } + [GameEventHandler] + public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, + GameEventInfo info) { + if (!((IWardenService)this).IsWarden(ev.Userid)) return HookResult.Continue; - notifications.WARDEN_LEFT - .ToAllChat() - .ToAllCenter(); + if (!TryRemoveWarden()) + logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); - foreach (var player in Utilities.GetPlayers()) - { - if (!player.IsReal()) continue; - player.ExecuteClientCommand( - $"play sounds/{config.WardenPassedSoundName}"); - } - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + notifications.WARDEN_LEFT.ToAllChat().ToAllCenter(); - return HookResult.Continue; + foreach (var player in Utilities.GetPlayers()) { + if (!player.IsReal()) continue; + player.ExecuteClientCommand( + $"play sounds/{config.WardenPassedSoundName}"); } + + notifications.BECOME_NEXT_WARDEN.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 7e5e9c97..31fbe2e3 100644 --- a/mod/Jailbreak.Warden/Jailbreak.Warden.csproj +++ b/mod/Jailbreak.Warden/Jailbreak.Warden.csproj @@ -7,12 +7,8 @@ - - - - - - + + diff --git a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs index be1190f0..9a53d367 100644 --- a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs +++ b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs @@ -9,70 +9,59 @@ namespace Jailbreak.Warden.Markers; -public class WardenMarkerBehavior : IPluginBehavior -{ - private const float MinRadius = 60f, MaxRadius = 360f; - private readonly IWardenService _warden; +public class WardenMarkerBehavior : IPluginBehavior { + private const float MIN_RADIUS = 60f, MAX_RADIUS = 360f; + private readonly IWardenService warden; - private BeamCircle? _marker; + private Vector? currentPos; - private Vector? _currentPos; - private long _placementTime; - private float _radius = MinRadius; + private BeamCircle? marker; + private long placementTime; + private float radius = MIN_RADIUS; - public WardenMarkerBehavior(IWardenService warden) - { - _warden = warden; - } + public WardenMarkerBehavior(IWardenService warden) { this.warden = warden; } - public void Start(BasePlugin plugin) - { - _marker = new BeamCircle(plugin, new Vector(), 60f, (int)Math.PI * 15); - plugin.AddCommandListener("player_ping", CommandListener_PlayerPing); - } + public void Start(BasePlugin basePlugin) { + marker = new BeamCircle(basePlugin, new Vector(), 60f, (int)Math.PI * 15); + basePlugin.AddCommandListener("player_ping", CommandListener_PlayerPing); + } - [GameEventHandler] - public HookResult OnPing(EventPlayerPing @event, GameEventInfo info) - { - var player = @event.Userid; + [GameEventHandler] + public HookResult OnPing(EventPlayerPing @event, GameEventInfo info) { + var player = @event.Userid; - if (!_warden.IsWarden(player)) - return HookResult.Handled; - var vec = new Vector(@event.X, @event.Y, @event.Z); + if (!warden.IsWarden(player)) return HookResult.Handled; + var vec = new Vector(@event.X, @event.Y, @event.Z); - if (_currentPos != null) - { - var distance = _currentPos.Distance(vec); - var timeElapsed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - _placementTime; - if (timeElapsed < 500) - { - if (distance <= MaxRadius * 1.5) - { - distance = Math.Clamp(distance, MinRadius, MaxRadius); - _marker?.SetRadius(distance); - _marker?.Update(); - _radius = distance; - return HookResult.Handled; - } - } - else if (distance <= _radius) - { - _marker?.Remove(); - return HookResult.Handled; - } + if (currentPos != null) { + var distance = currentPos.Distance(vec); + var timeElapsed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + - placementTime; + if (timeElapsed < 500) { + if (distance <= MAX_RADIUS * 1.5) { + distance = Math.Clamp(distance, MIN_RADIUS, MAX_RADIUS); + marker?.SetRadius(distance); + marker?.Update(); + radius = distance; + return HookResult.Handled; } - - _radius = MinRadius; - _currentPos = vec; - _placementTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - _marker?.Move(vec); - _marker?.SetRadius(_radius); - _marker?.Update(); + } else if (distance <= radius) { + marker?.Remove(); return HookResult.Handled; + } } - private HookResult CommandListener_PlayerPing(CCSPlayerController? player, CommandInfo info) - { - return _warden.IsWarden(player) ? HookResult.Continue : HookResult.Handled; - } + radius = MIN_RADIUS; + currentPos = vec; + placementTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + marker?.Move(vec); + marker?.SetRadius(radius); + marker?.Update(); + return HookResult.Handled; + } + + private HookResult CommandListener_PlayerPing(CCSPlayerController? player, + CommandInfo info) { + return warden.IsWarden(player) ? HookResult.Continue : HookResult.Handled; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs index f441ec7e..aaa6dae3 100644 --- a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs +++ b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs @@ -8,105 +8,98 @@ namespace Jailbreak.Warden.Paint; -public class WardenPaintBehavior : IPluginBehavior -{ - private Vector? _lastPosition; - private readonly IWardenService _warden; - private BasePlugin? _parent; - - public WardenPaintBehavior(IWardenService warden) - { - _warden = warden; - } - - public void Start(BasePlugin parent) - { - _parent = parent; - parent.RegisterListener(Paint); - } - - private void Paint() - { - if (!_warden.HasWarden) - return; - - var warden = _warden.Warden; - if (warden == null || !warden.IsReal()) - return; - - if ((warden.Buttons & PlayerButtons.Use) == 0) return; - - var position = FindFloorIntersection(warden); - if (position == null) - return; - - var start = _lastPosition ?? position; - start = start.Clone(); - - if (_lastPosition != null && position.DistanceSquared(_lastPosition) < 25 * 25) return; - - _lastPosition = position; - if (start.DistanceSquared(position) > 150 * 150) start = position; - - if(_parent == null) - throw new NullReferenceException("Parent plugin is null"); - - new BeamLine(_parent, start.Clone(), position.Clone()).Draw(30f); - } - - private Vector? FindFloorIntersection(CCSPlayerController player) - { - if (player.Pawn.Value == null || player.PlayerPawn.Value == null) - return 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; - - 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; - - var pitch = Math.PI / 180 * eyeAngle.X; - var yaw = Math.PI / 180 * eyeAngle.Y; - - // get direction vector from angles - 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, eyeVector, new Vector(eyeAngle.X, eyeAngle.Y, eyeAngle.Z), - pawn.AbsOrigin.Z); - } - - private Vector? FindFloorIntersection(Vector start, Vector worldAngles, Vector rotationAngles, float z) - { - 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; - - // var angleA = ToRadians(90); - var sideB = start.Z - z; - var angleC = ToRadians(pitch); - - - 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)); - - var destination = start.Clone(); - destination.X += worldAngles.X * sideC; - destination.Y += worldAngles.Y * sideC; - destination.Z = z; - return destination; - } - - private static float ToRadians(float angle) - { - return (float)(Math.PI / 180) * angle; - } +public class WardenPaintBehavior : IPluginBehavior { + private readonly IWardenService wardenService; + private Vector? lastPosition; + private BasePlugin? parent; + + public WardenPaintBehavior(IWardenService warden) { wardenService = warden; } + + public void Start(BasePlugin basePlugin) { + parent = basePlugin; + basePlugin.RegisterListener(paint); + } + + private void paint() { + if (!wardenService.HasWarden) return; + + var warden = wardenService.Warden; + if (warden == null || !warden.IsReal()) return; + + if ((warden.Buttons & PlayerButtons.Use) == 0) return; + + var position = findFloorIntersection(warden); + if (position == null) return; + + var start = lastPosition ?? position; + start = start.Clone(); + + if (lastPosition != null + && position.DistanceSquared(lastPosition) < 25 * 25) + return; + + lastPosition = position; + if (start.DistanceSquared(position) > 150 * 150) start = position; + + if (parent == null) + throw new NullReferenceException("Parent plugin is null"); + + new BeamLine(parent, start.Clone(), position.Clone()).Draw(30f); + } + + private Vector? findFloorIntersection(CCSPlayerController player) { + if (player.Pawn.Value == null || player.PlayerPawn.Value == null) + return 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; + + 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; + + var pitch = Math.PI / 180 * eyeAngle.X; + var yaw = Math.PI / 180 * eyeAngle.Y; + + // get direction vector from angles + 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, eyeVector, + new Vector(eyeAngle.X, eyeAngle.Y, eyeAngle.Z), pawn.AbsOrigin.Z); + } + + private Vector? findFloorIntersection(Vector start, Vector worldAngles, + Vector rotationAngles, float z) { + 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; + + // var angleA = ToRadians(90); + var sideB = start.Z - z; + var angleC = toRadians(pitch); + + + 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)); + + var destination = start.Clone(); + destination.X += worldAngles.X * sideC; + destination.Y += worldAngles.Y * sideC; + destination.Z = z; + return destination; + } + + private static float toRadians(float angle) { + return (float)(Math.PI / 180) * angle; + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/Selection/QueueFavorState.cs b/mod/Jailbreak.Warden/Selection/QueueFavorState.cs index 3f1036ac..eba4e6c3 100644 --- a/mod/Jailbreak.Warden/Selection/QueueFavorState.cs +++ b/mod/Jailbreak.Warden/Selection/QueueFavorState.cs @@ -1,17 +1,11 @@ namespace Jailbreak.Warden.Selection; -public class QueueFavorState -{ - public const int BaseTickets = 2; +public class QueueFavorState { + 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 BaseTickets - + Favor - + RoundsWithoutWarden; - } + public int GetTickets() { return BASE_TICKETS + 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 e36f121c..b962c0bf 100644 --- a/mod/Jailbreak.Warden/Selection/QueueState.cs +++ b/mod/Jailbreak.Warden/Selection/QueueState.cs @@ -1,9 +1,8 @@ namespace Jailbreak.Warden.Selection; -public class QueueState -{ - /// - /// Whether or not this player is currently in the queue - /// - public bool InQueue { get; set; } = false; +public class QueueState { + /// + /// 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 315a51d6..49d4295a 100644 --- a/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs +++ b/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs @@ -14,168 +14,146 @@ namespace Jailbreak.Warden.Selection; /// -/// Behavior responsible for choosing the next warden +/// Behavior responsible for choosing the next warden /// -public class WardenSelectionBehavior : IPluginBehavior, IWardenSelectionService -{ - private readonly ICoroutines _coroutines; +public class + WardenSelectionBehavior : IPluginBehavior, IWardenSelectionService { + private readonly ICoroutines coroutines; - private readonly IPlayerState _favor; + private readonly IPlayerState favor; - private readonly ILogger _logger; + private readonly ILogger logger; - private readonly IWardenNotifications _notifications; + 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; + /// + /// 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; - private readonly IWardenService _warden; + /// + /// Whether or not to use the queue. + /// When true, the queue should be skipped and turn to first-come-first-serve. + /// + private bool queueInactive; - 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(); + public WardenSelectionBehavior(IPlayerStateFactory factory, + IWardenService warden, IWardenNotifications notifications, + ILogger logger, ICoroutines coroutines) { + this.warden = warden; + this.notifications = notifications; + this.logger = logger; + this.coroutines = coroutines; + queue = factory.Round(); + favor = factory.Global(); - _queueInactive = true; - } + queueInactive = true; + } - public void Start(BasePlugin parent) - { - } + public void Start(BasePlugin basePlugin) { } - public void Dispose() - { - } + public void Dispose() { } - public bool TryEnter(CCSPlayerController player) - { - if (!CanEnterQueue(player)) - return false; + public bool TryEnter(CCSPlayerController player) { + if (!canEnterQueue(player)) return false; - _queue.Get(player).InQueue = true; - return true; - } + queue.Get(player).InQueue = true; + return true; + } - public bool TryExit(CCSPlayerController player) - { - if (!CanEnterQueue(player)) - return false; + public bool TryExit(CCSPlayerController player) { + if (!canEnterQueue(player)) return false; - _queue.Get(player).InQueue = false; - return true; - } + queue.Get(player).InQueue = false; + return true; + } - public bool InQueue(CCSPlayerController player) - { - return _queue.Get(player).InQueue; - } + public bool InQueue(CCSPlayerController player) { + return queue.Get(player).InQueue; + } - public bool Active => !_queueInactive; + public bool Active => !queueInactive; - [GameEventHandler] - public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) - { - // Enable the warden queue - _queueInactive = false; + [GameEventHandler] + public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) { + // Enable the warden queue + queueInactive = false; - _notifications.PICKING_SHORTLY.ToAllChat(); + notifications.PICKING_SHORTLY.ToAllChat(); - // Start a timer to pick the warden in 7 seconds - ScheduleChooseWarden(); + // Start a timer to pick the warden in 7 seconds + ScheduleChooseWarden(); - return HookResult.Continue; - } + return HookResult.Continue; + } - [MethodImpl(MethodImplOptions.NoOptimization)] - public void ScheduleChooseWarden(float time = 7.0f) - { - _coroutines.Round(OnChooseWarden, time); - } + [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(); - /// - /// 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)); - 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; + logger.LogTrace("[WardenSelectionBehavior] Picking warden from {@Eligible}", + eligible); + + if (eligible.Count == 0) { + notifications.NO_WARDENS.ToAllChat(); + queueInactive = true; + + return; } - private bool CanEnterQueue(CCSPlayerController player) - { - if (player.GetTeam() != CsTeam.CounterTerrorist) - return false; + var favors = eligible.ToDictionary(player => player, + player => favor.Get(player)); + var tickets = favors.Sum(f => f.Value.GetTickets()); + var chosen = Random.Shared.Next(tickets); - if (!player.PawnIsAlive) - return false; + logger.LogTrace("[Warden Raffle] Picking {@Chosen} out of {@Tickets}", + chosen, tickets); - // Cannot enter queue if queue is not running - if (_queueInactive) - return false; + var pointer = 0; + foreach (var (player, f) in favors) { + var thisTickets = f.GetTickets(); + logger.LogTrace("[Warden Raffle] {@Pointer} -> {@End}: #{@Slot} {@Name}", + pointer, pointer + thisTickets, player.Slot, player.PlayerName); - // Edge case: Is there already a warden? - if (_warden.HasWarden) - return false; + // If winning ticket belongs to this player, assign them as warden. + if (pointer <= chosen && chosen < pointer + thisTickets) { + warden.TrySetWarden(player); + f.RoundsWithoutWarden = 0; + } else { f.RoundsWithoutWarden++; } - return true; + 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/SpecialTreatment/SpecialTreatmentBehavior.cs b/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs index 255456f6..01ab46e7 100644 --- a/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs +++ b/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs @@ -10,74 +10,57 @@ namespace Jailbreak.Warden.SpecialTreatment; -public class SpecialTreatmentBehavior( - IPlayerStateFactory factory, - IRebelService rebel, - ISpecialTreatmentNotifications notifications) - : IPluginBehavior, ISpecialTreatmentService -{ - private readonly IPlayerState _sts = factory.Round(); - - private class SpecialTreatmentState - { - public bool HasSpecialTreatment { get; set; } = false; - } - - public bool IsSpecialTreatment(CCSPlayerController player) - { - return _sts.Get(player) - .HasSpecialTreatment; - } - - public void Grant(CCSPlayerController player) - { - // Player is already granted ST - if (IsSpecialTreatment(player)) - return; - - _sts.Get(player).HasSpecialTreatment = true; - - if (rebel.IsRebel(player)) - rebel.UnmarkRebel(player); - this.SetSpecialColor(player, /* hasSt */ true); - - notifications.GRANTED - .ToPlayerChat(player) - .ToPlayerCenter(player); - - notifications.GRANTED_TO(player) - .ToAllChat(); - } - - public void Revoke(CCSPlayerController player) - { - // Player is already revoked - if (!IsSpecialTreatment(player)) - return; - - _sts.Get(player).HasSpecialTreatment = false; - - this.SetSpecialColor(player, false); - - notifications.REVOKED - .ToPlayerChat(player) - .ToPlayerCenter(player); - - notifications.REVOKED_FROM(player) - .ToAllChat(); - } - - private void SetSpecialColor(CCSPlayerController player, bool hasSt) - { - if (!player.IsValid || player.Pawn.Value == null) - return; - - var color = hasSt - ? Color.FromArgb(254, 0, 255, 0) - : Color.FromArgb(254, 255, 255, 255); - - player.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; - player.Pawn.Value.Render = color; - Utilities.SetStateChanged(player.Pawn.Value, "CBaseModelEntity", "m_clrRender"); - } +public class SpecialTreatmentBehavior(IPlayerStateFactory factory, + IRebelService rebel, ISpecialTreatmentNotifications notifications) + : IPluginBehavior, ISpecialTreatmentService { + private readonly IPlayerState sts = + factory.Round(); + + public bool IsSpecialTreatment(CCSPlayerController player) { + return sts.Get(player).HasSpecialTreatment; + } + + public void Grant(CCSPlayerController player) { + // Player is already granted ST + if (IsSpecialTreatment(player)) return; + + sts.Get(player).HasSpecialTreatment = true; + + if (rebel.IsRebel(player)) rebel.UnmarkRebel(player); + setSpecialColor(player, /* hasSt */ true); + + notifications.Granted.ToPlayerChat(player).ToPlayerCenter(player); + + notifications.GrantedTo(player).ToAllChat(); + } + + public void Revoke(CCSPlayerController player) { + // Player is already revoked + if (!IsSpecialTreatment(player)) return; + + sts.Get(player).HasSpecialTreatment = false; + + setSpecialColor(player, false); + + notifications.Revoked.ToPlayerChat(player).ToPlayerCenter(player); + + notifications.RevokedFrom(player).ToAllChat(); + } + + private void setSpecialColor(CCSPlayerController player, bool hasSt) { + if (!player.IsValid || player.Pawn.Value == null) return; + + var color = hasSt ? + Color.FromArgb(254, 0, 255, 0) : + Color.FromArgb(254, 255, 255, 255); + + player.Pawn.Value.RenderMode = RenderMode_t.kRenderTransColor; + player.Pawn.Value.Render = color; + Utilities.SetStateChanged(player.Pawn.Value, "CBaseModelEntity", + "m_clrRender"); + } + + private class SpecialTreatmentState { + public bool HasSpecialTreatment { get; set; } + } } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/WardenConfig.cs b/mod/Jailbreak.Warden/WardenConfig.cs index 9d0f6958..ee680fd0 100644 --- a/mod/Jailbreak.Warden/WardenConfig.cs +++ b/mod/Jailbreak.Warden/WardenConfig.cs @@ -1,9 +1,8 @@ namespace Jailbreak.Warden; -public class WardenConfig -{ - public string WardenKilledSoundName { get; } = "wardenKilled"; - public string WardenPassedSoundName { get; } = "wardenPassed"; - public string WardenNewSoundName { get; } = "wardenNew"; - public int TerroristRatio { get; } = 3; +public class WardenConfig { + public string WardenKilledSoundName { get; } = "wardenKilled"; + public string WardenPassedSoundName { get; } = "wardenPassed"; + public string WardenNewSoundName { get; } = "wardenNew"; + public int TerroristRatio { get; } = 3; } \ No newline at end of file diff --git a/mod/Jailbreak.Warden/WardenServiceExtension.cs b/mod/Jailbreak.Warden/WardenServiceExtension.cs index e78d67ad..ea31e10c 100644 --- a/mod/Jailbreak.Warden/WardenServiceExtension.cs +++ b/mod/Jailbreak.Warden/WardenServiceExtension.cs @@ -6,26 +6,26 @@ using Jailbreak.Warden.Paint; using Jailbreak.Warden.Selection; using Jailbreak.Warden.SpecialTreatment; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Warden; -public static class WardenServiceExtension -{ - public static void AddJailbreakWarden(this IServiceCollection serviceCollection) - { - serviceCollection.AddConfig("warden"); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); +public static class WardenServiceExtension { + public static void AddJailbreakWarden( + this IServiceCollection serviceCollection) { + serviceCollection.AddConfig("warden"); + serviceCollection.AddPluginBehavior(); + serviceCollection + .AddPluginBehavior(); + serviceCollection + .AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); + 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 ae3ce208..2261657c 100644 --- a/public/Jailbreak.Formatting/Base/IView.cs +++ b/public/Jailbreak.Formatting/Base/IView.cs @@ -2,7 +2,6 @@ namespace Jailbreak.Formatting.Base; -public interface IView -{ - void Render(FormatWriter writer); +public interface IView { + void Render(FormatWriter writer); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Base/SimpleView.cs b/public/Jailbreak.Formatting/Base/SimpleView.cs index b4c8f671..c39edf4d 100644 --- a/public/Jailbreak.Formatting/Base/SimpleView.cs +++ b/public/Jailbreak.Formatting/Base/SimpleView.cs @@ -1,70 +1,49 @@ using System.Collections; - using Jailbreak.Formatting.Core; namespace Jailbreak.Formatting.Base; -public class SimpleView : IView, IEnumerable> -{ - public struct Newline - { - - } - - public static Newline NEWLINE = new Newline(); - - private List> _lines = new(); +public class SimpleView : IView, IEnumerable> { + public static readonly Newline NEWLINE = new(); - public SimpleView() - { + private readonly List> lines = new(); - } + public IEnumerator> GetEnumerator() { + return lines.GetEnumerator(); + } - /// - /// Add an item to the end of the last row in this SimpleView - /// Eg, { abc, 123, weee } is all one row - /// - /// - public void Add(FormatObject item) - { - if (_lines.Count == 0) - _lines.Add(new List()); + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - _lines[_lines.Count - 1].Add(item); - } + public void Render(FormatWriter writer) { + foreach (var formatObjects in lines) writer.Line(formatObjects.ToArray()); + } - /// - /// Add multiple items at a time to this SimpleView - /// - /// - public void Add(params FormatObject[] line) - { - if (_lines.Count == 0) - _lines.Add(new List()); + /// + /// Add an item to the end of the last row in this SimpleView + /// Eg, { abc, 123, weee } is all one row + /// + /// + public void Add(FormatObject item) { + if (lines.Count == 0) lines.Add(new List()); - _lines[_lines.Count - 1].AddRange(line); - } + lines[lines.Count - 1].Add(item); + } - /// - /// Add a new line to this SimpleView - /// - /// - public void Add(Newline newline) - { - _lines.Add(new List()); - } + /// + /// Add multiple items at a time to this SimpleView + /// + /// + public void Add(params FormatObject[] line) { + if (lines.Count == 0) lines.Add(new List()); - public void Render(FormatWriter writer) - { - foreach (var formatObjects in _lines) - writer.Line(formatObjects.ToArray()); - } + lines[lines.Count - 1].AddRange(line); + } - public IEnumerator> GetEnumerator() - => _lines.GetEnumerator(); + /// + /// Add a new line to this SimpleView + /// + /// + public void Add(Newline newline) { lines.Add(new List()); } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } -} + public struct Newline { } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Core/FormatObject.cs b/public/Jailbreak.Formatting/Core/FormatObject.cs index e4da9b8f..7cd68eb6 100644 --- a/public/Jailbreak.Formatting/Core/FormatObject.cs +++ b/public/Jailbreak.Formatting/Core/FormatObject.cs @@ -4,53 +4,41 @@ namespace Jailbreak.Formatting.Core; -public abstract class FormatObject -{ - /// - /// Output this format object compatible with CS2 chat formatting. - /// - /// - public virtual string ToChat() - { - return ToPlain(); - } - - /// - /// Output this format object in a panorama-compatible format. - /// - /// - public virtual string ToPanorama() - { - return ToPlain().Sanitize(); - } - - /// - /// Output plaintext - /// - /// - public abstract string ToPlain(); - - - public static implicit operator FormatObject(string value) - { - return new StringFormatObject(value); - } - - public static implicit operator FormatObject(CCSPlayerController value) - { - return new PlayerFormatObject(value); - } - - public static implicit operator FormatObject(int value) - { - return new IntegerFormatObject(value); - } - - public static FormatObject FromObject(object value) - { - return new StringFormatObject(value.ToString() ?? "null"); - } - - public override string ToString() - => ToPlain(); -} +public abstract class FormatObject { + /// + /// Output this format object compatible with CS2 chat formatting. + /// + /// + public virtual string ToChat() { return ToPlain(); } + + /// + /// Output this format object in a panorama-compatible format. + /// + /// + public virtual string ToPanorama() { return ToPlain().Sanitize(); } + + /// + /// Output plaintext + /// + /// + public abstract string ToPlain(); + + + public static implicit operator FormatObject(string value) { + return new StringFormatObject(value); + } + + public static implicit operator FormatObject(CCSPlayerController value) { + return new PlayerFormatObject(value); + } + + public static implicit operator FormatObject(int value) { + return new IntegerFormatObject(value); + } + + public static FormatObject FromObject(object value) { + return new StringFormatObject(value.ToString() ?? "null"); + } + + public override string ToString() { return ToPlain(); } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Core/FormatWriter.cs b/public/Jailbreak.Formatting/Core/FormatWriter.cs index 760bcdc5..38faac9c 100644 --- a/public/Jailbreak.Formatting/Core/FormatWriter.cs +++ b/public/Jailbreak.Formatting/Core/FormatWriter.cs @@ -1,25 +1,26 @@ namespace Jailbreak.Formatting.Core; -public class FormatWriter -{ - private readonly List _lines = new(); +public class FormatWriter { + private readonly List lines = new(); - public IEnumerable Lines => _lines; + public IEnumerable Lines => lines; - public IEnumerable Chat - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToChat()))); + public IEnumerable Chat + => Lines.Select( + array => string.Join(' ', array.Select(obj => obj.ToChat()))); - public IEnumerable Panorama - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToPanorama()))); + public IEnumerable Panorama + => Lines.Select(array + => string.Join(' ', array.Select(obj => obj.ToPanorama()))); - public IEnumerable Plain - => Lines.Select(array => string.Join(' ', array.Select(obj => obj.ToPlain()))); + public IEnumerable Plain + => Lines.Select(array + => string.Join(' ', array.Select(obj => obj.ToPlain()))); - public FormatWriter Line(params FormatObject[] args) - { - _lines.Add(args); + public FormatWriter Line(params FormatObject[] args) { + lines.Add(args); - return this; - } + return this; + } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs index b82f2d02..9065c8ba 100644 --- a/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs +++ b/public/Jailbreak.Formatting/Extensions/ViewExtensions.cs @@ -1,110 +1,93 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Public.Extensions; namespace Jailbreak.Formatting.Extensions; -public static class ViewExtensions -{ - - public static FormatWriter ToWriter(this IView view) - { - var writer = new FormatWriter(); +public static class ViewExtensions { + public static FormatWriter ToWriter(this IView view) { + var writer = new FormatWriter(); - view.Render(writer); + view.Render(writer); - return writer; - } + return writer; + } - public static IView ToServerConsole(this IView view) - { - var writer = view.ToWriter(); + public static IView ToServerConsole(this IView view) { + var writer = view.ToWriter(); - foreach (string s in writer.Plain) - { - Server.PrintToConsole(s); - } + foreach (var s in writer.Plain) Server.PrintToConsole(s); - return view; - } + return view; + } - #region Individual + public static IView ToAllConsole(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); - public static IView ToPlayerConsole(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + return view; + } - var writer = view.ToWriter(); + public static IView ToAllChat(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); - foreach (var writerLine in writer.Plain) - player.PrintToConsole(writerLine); + return view; + } - return view; - } + public static IView ToAllCenter(this IView view) { + Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); - public static IView ToPlayerChat(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + return view; + } - var writer = view.ToWriter(); + #region Individual - foreach (var writerLine in writer.Chat) - player.PrintToChat(writerLine); + public static IView ToPlayerConsole(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); - public static IView ToPlayerCenter(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + foreach (var writerLine in writer.Plain) player.PrintToConsole(writerLine); - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Plain); + return view; + } - player.PrintToCenter(merged); + public static IView ToPlayerChat(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); - public static IView ToPlayerCenterHtml(this IView view, CCSPlayerController player) - { - if (!player.IsReal() || player.IsBot) - return view; + foreach (var writerLine in writer.Chat) player.PrintToChat(writerLine); - var writer = view.ToWriter(); - var merged = string.Join('\n', writer.Panorama); + return view; + } - player.PrintToCenterHtml(merged); + public static IView ToPlayerCenter(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - return view; - } + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Plain); - #endregion + player.PrintToCenter(merged); - public static IView ToAllConsole(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerConsole(player)); + return view; + } - return view; - } + public static IView ToPlayerCenterHtml(this IView view, + CCSPlayerController player) { + if (!player.IsReal() || player.IsBot) return view; - public static IView ToAllChat(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerChat(player)); + var writer = view.ToWriter(); + var merged = string.Join('\n', writer.Panorama); - return view; - } + player.PrintToCenterHtml(merged); - public static IView ToAllCenter(this IView view) - { - Utilities.GetPlayers().ForEach(player => view.ToPlayerCenter(player)); + return view; + } - return view; - } -} + #endregion +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj b/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj index 6ee87dd0..376ac50a 100644 --- a/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj +++ b/public/Jailbreak.Formatting/Jailbreak.Formatting.csproj @@ -7,11 +7,7 @@ - - - - - + diff --git a/public/Jailbreak.Formatting/Languages/English.cs b/public/Jailbreak.Formatting/Languages/English.cs index a016d8ec..29c06496 100644 --- a/public/Jailbreak.Formatting/Languages/English.cs +++ b/public/Jailbreak.Formatting/Languages/English.cs @@ -2,6 +2,4 @@ namespace Jailbreak.Formatting.Languages; -public class English : IDialect -{ -} \ No newline at end of file +public class English : IDialect { } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Logistics/IDialect.cs b/public/Jailbreak.Formatting/Logistics/IDialect.cs index 2d43dd0a..dbe1f80b 100644 --- a/public/Jailbreak.Formatting/Logistics/IDialect.cs +++ b/public/Jailbreak.Formatting/Logistics/IDialect.cs @@ -1,9 +1,7 @@ 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 +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 752d747c..a1f84b58 100644 --- a/public/Jailbreak.Formatting/Logistics/ILanguage.cs +++ b/public/Jailbreak.Formatting/Logistics/ILanguage.cs @@ -1,11 +1,8 @@ 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 -{ -} \ No newline at end of file +public interface ILanguage 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 a12c066c..05969643 100644 --- a/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs +++ b/public/Jailbreak.Formatting/Logistics/LanguageConfig.cs @@ -1,69 +1,80 @@ using Jailbreak.Formatting.Views; - using Microsoft.Extensions.DependencyInjection; namespace Jailbreak.Formatting.Logistics; -public class LanguageConfig - where TDialect: IDialect -{ - - private IServiceCollection _collection; - - 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(); - - public void WithWarden() - where TWarden : class, ILanguage, IWardenNotifications - => _collection.AddSingleton(); - - public void WithRebel() - where TRebel : class, ILanguage, IRebelNotifications - => _collection.AddSingleton(); - - public void WithJihadC4() - where TJihadC4 : class, ILanguage, IJihadC4Notifications - => _collection.AddSingleton(); - - public void WithSpecialDay() - where TSpecialDay : class, ILanguage, ISpecialDayNotifications - => _collection.AddSingleton(); - - public void WithLogging() - where TLogging : class, ILanguage, ILogMessages - => _collection.AddSingleton(); - - public void WithRollCommand() - where TRollCommand : class, ILanguage, IRollCommandNotications - => _collection.AddSingleton(); - - public void WithLastRequest() - where TLastRequest : class, ILanguage, ILastRequestMessages - => _collection.AddSingleton(); - - public void WithSpecialTreatment() - where TSpecialTreatment : class, ILanguage, ISpecialTreatmentNotifications - => _collection.AddSingleton(); - - public void WithMute() - where TMute : class, ILanguage, IPeaceMessages - => _collection.AddSingleton(); - - public void WithRaceLR() - where TRaceLR : class, ILanguage, IRaceLRMessages - => _collection.AddSingleton(); - - public void WithLastGuard() - where TLastGuard : class, ILanguage, ILastGuardNotifications - => _collection.AddSingleton(); -} +public class LanguageConfig where TDialect : IDialect { + private readonly IServiceCollection collection; + + public LanguageConfig(IServiceCollection collection) { + this.collection = collection; + } + + 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 WithRebel() + where TRebel : class, ILanguage, IRebelNotifications { + collection.AddSingleton(); + } + + public void WithJihadC4() + where TJihadC4 : class, ILanguage, IJihadC4Notifications { + collection.AddSingleton(); + } + + public void WithSpecialDay() + where TSpecialDay : class, ILanguage, ISpecialDayNotifications { + collection.AddSingleton(); + } + + public void WithLogging() + where TLogging : class, ILanguage, ILogMessages { + collection.AddSingleton(); + } + + public void WithRollCommand() + where TRollCommand : class, ILanguage, IRollCommandNotications { + collection.AddSingleton(); + } + + public void WithLastRequest() + where TLastRequest : class, ILanguage, ILastRequestMessages { + collection.AddSingleton(); + } + + public void WithSpecialTreatment() + where TSpecialTreatment : class, ILanguage, + ISpecialTreatmentNotifications { + collection + .AddSingleton(); + } + + public void WithMute() + where TMute : class, ILanguage, IPeaceMessages { + collection.AddSingleton(); + } + + public void WithRaceLR() + where TRaceLR : class, ILanguage, IRaceLRMessages { + collection.AddSingleton(); + } + + public void WithLastGuard() + where TLastGuard : class, ILanguage, ILastGuardNotifications { + 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 ecc2afd6..da5fae9c 100644 --- a/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs +++ b/public/Jailbreak.Formatting/Logistics/RegisterLanguageExtensions.cs @@ -2,15 +2,11 @@ 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 class RegisterLanguageExtensions { + public static void AddLanguage(this IServiceCollection collection, + Action> factory) where TDialect : IDialect { + var config = new LanguageConfig(collection); - factory(config); - } + factory(config); + } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs b/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs index 7f271b2e..55932701 100644 --- a/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/HiddenFormatObject.cs @@ -2,39 +2,29 @@ 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 class HiddenFormatObject : FormatObject { + public FormatObject Value; + + public HiddenFormatObject(FormatObject value) { Value = value; } + + public bool Plain { get; set; } = true; + + public bool Panorama { get; set; } = true; + + public bool Chat { get; set; } = true; + + public override string ToChat() { + if (Chat) return Value.ToChat(); + return string.Empty; + } + + public override string ToPanorama() { + if (Panorama) return Value.ToPanorama(); + return string.Empty; + } + + public override string ToPlain() { + if (Plain) return Value.ToPlain(); + return string.Empty; + } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/IntegerFormatObject.cs b/public/Jailbreak.Formatting/Objects/IntegerFormatObject.cs index f0ca90e5..148f82b3 100644 --- a/public/Jailbreak.Formatting/Objects/IntegerFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/IntegerFormatObject.cs @@ -1,32 +1,14 @@ -using CounterStrikeSharp.API.Modules.Utils; -using Jailbreak.Formatting.Core; +using Jailbreak.Formatting.Core; namespace Jailbreak.Formatting.Objects; -public class IntegerFormatObject : FormatObject -{ - private readonly char _chatColor; +public class IntegerFormatObject(int value, char chatColor = '\x09') + : FormatObject { + public int Value { get; } = value; - public IntegerFormatObject(int value, char chatColor = '\x09') - { - Value = value; - _chatColor = chatColor; - } + public override string ToChat() { return $"{chatColor}{Value.ToString()}"; } - public int Value { get; } + public override string ToPanorama() { return Value.ToString(); } - public override string ToChat() - { - return $"{_chatColor}{Value.ToString()}"; - } - - public override string ToPanorama() - { - return Value.ToString(); - } - - public override string ToPlain() - { - return Value.ToString(); - } + public override string ToPlain() { return Value.ToString(); } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs b/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs index 3143fecf..43c39a52 100644 --- a/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/PlayerFormatObject.cs @@ -5,27 +5,12 @@ namespace Jailbreak.Formatting.Objects; -public class PlayerFormatObject : FormatObject -{ - private readonly string _name; +public class PlayerFormatObject(CCSPlayerController player) : FormatObject { + private readonly string name = player.PlayerName; - public PlayerFormatObject(CCSPlayerController player) - { - _name = player.PlayerName; - } + public override string ToChat() { return $"{ChatColors.Yellow}{name}"; } - public override string ToChat() - { - return $"{ChatColors.Yellow}{_name}"; - } + public override string ToPanorama() { return name.Sanitize(); } - public override string ToPanorama() - { - return _name.Sanitize(); - } - - public override string ToPlain() - { - return _name; - } -} + public override string ToPlain() { return name; } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/StringFormatObject.cs b/public/Jailbreak.Formatting/Objects/StringFormatObject.cs index c19c7037..c678f39e 100644 --- a/public/Jailbreak.Formatting/Objects/StringFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/StringFormatObject.cs @@ -2,30 +2,13 @@ namespace Jailbreak.Formatting.Objects; -public class StringFormatObject : FormatObject -{ - private readonly char _chatColor; +public class StringFormatObject(string value, char chatColor = '\x01') + : FormatObject { + public string Value { get; } = value; - public StringFormatObject(string value, char chatColor = '\x01') - { - Value = value; - _chatColor = chatColor; - } + public override string ToChat() { return $"{chatColor}{Value}"; } - public string Value { get; } + public override string ToPanorama() { return Value; } - public override string ToChat() - { - return $"{_chatColor}{Value}"; - } - - public override string ToPanorama() - { - return Value; - } - - public override string ToPlain() - { - return Value; - } + public override string ToPlain() { return Value; } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Objects/TreeFormatObject.cs b/public/Jailbreak.Formatting/Objects/TreeFormatObject.cs index cb616eb2..33051657 100644 --- a/public/Jailbreak.Formatting/Objects/TreeFormatObject.cs +++ b/public/Jailbreak.Formatting/Objects/TreeFormatObject.cs @@ -1,86 +1,67 @@ using System.Collections; - using Jailbreak.Formatting.Core; namespace Jailbreak.Formatting.Objects; /// -/// Merges several FormatObjects into one. -/// This class will throw an error if any of it's descendant formatobjects are itself, -/// to prevent looping. +/// Merges several FormatObjects into one. +/// This class will throw an error if any of it's descendant formatobjects are itself, +/// to prevent looping. /// -public class TreeFormatObject : FormatObject, IEnumerable -{ - private List _children = new(); - - private int _locked = 0; - - public TreeFormatObject() - { - - } - - /// - /// Lock this object, execute callback, then unlock. - /// - /// - private T Lock(Func callback) - { - // Achieve a re-entrant mutex for this thread. - // We can re-enter this lock as long as we are in the same thread, but others are blocked. - // this allows us to do the internal increment safely. - lock (this) - { - // set _locked to 1 if value is 0 - int old = Interlocked.CompareExchange(ref _locked, 1, 0); - - if (old == 1) - throw new Exception("Possible loop detected in TreeFormatObject! Already locked during traversal"); - - var result = callback(); - _locked = 0; - - return result; - } - } - - public override string ToPlain() - { - return Lock(() => - { - var childPlain = _children.Select(child => child.ToPlain()); - return string.Join(' ', childPlain); - }); - } - - public override string ToChat() - { - return Lock(() => - { - var childChat = _children.Select(child => child.ToChat()); - return string.Join(' ', childChat); - }); - } - - public override string ToPanorama() - { - return Lock(() => - { - var childPanorama = _children.Select(child => child.ToPanorama()); - return string.Join(' ', childPanorama); - }); - } - - public void Add(FormatObject formatObject) - => _children.Add(formatObject); - - public IEnumerator GetEnumerator() - { - return _children.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } -} +public class TreeFormatObject : FormatObject, IEnumerable { + private readonly List children = new(); + + private int locked; + + public IEnumerator GetEnumerator() { + return children.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } + + /// + /// Lock this object, execute callback, then unlock. + /// + /// + private T @lock(Func callback) { + // Achieve a re-entrant mutex for this thread. + // We can re-enter this lock as long as we are in the same thread, but others are blocked. + // this allows us to do the internal increment safely. + lock (this) { + // set _locked to 1 if value is 0 + var old = Interlocked.CompareExchange(ref locked, 1, 0); + + if (old == 1) + throw new Exception( + "Possible loop detected in TreeFormatObject! Already locked during traversal"); + + var result = callback(); + locked = 0; + + return result; + } + } + + public override string ToPlain() { + return @lock(() => { + var childPlain = children.Select(child => child.ToPlain()); + return string.Join(' ', childPlain); + }); + } + + public override string ToChat() { + return @lock(() => { + var childChat = children.Select(child => child.ToChat()); + return string.Join(' ', childChat); + }); + } + + public override string ToPanorama() { + return @lock(() => { + var childPanorama = children.Select(child => child.ToPanorama()); + return string.Join(' ', childPanorama); + }); + } + + public void Add(FormatObject formatObject) { children.Add(formatObject); } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs b/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs index 08b4670f..b3f2c58d 100644 --- a/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IGenericCommandNotifications.cs @@ -2,11 +2,10 @@ namespace Jailbreak.Formatting.Views; -public interface IGenericCommandNotifications -{ - public IView PlayerNotFound(string query); - public IView PlayerFoundMultiple(string query); - public IView CommandOnCooldown(DateTime cooldownEndsAt); - public IView InvalidParameter(string parameter, string expected); - public IView NoPermissionMessage(string permission); +public interface IGenericCommandNotifications { + public IView PlayerNotFound(string query); + public IView PlayerFoundMultiple(string query); + public IView CommandOnCooldown(DateTime cooldownEndsAt); + public IView InvalidParameter(string parameter, string expected); + public IView NoPermissionMessage(string permission); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IJihadC4Notifications.cs b/public/Jailbreak.Formatting/Views/IJihadC4Notifications.cs index 1afab605..1c126bd1 100644 --- a/public/Jailbreak.Formatting/Views/IJihadC4Notifications.cs +++ b/public/Jailbreak.Formatting/Views/IJihadC4Notifications.cs @@ -1,20 +1,10 @@ -using CounterStrikeSharp.API.Core; -using Jailbreak.Formatting.Base; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Jailbreak.Formatting.Base; namespace Jailbreak.Formatting.Views; -public interface IJihadC4Notifications -{ - // public IView PlayerDetonateC4(CCSPlayerController player); - // public IView JIHAD_C4_DROPPED { get; } - public IView JIHAD_C4_PICKUP { get; } - public IView JIHAD_C4_RECEIVED { get; } - public IView JIHAD_C4_USAGE1 { get; } - // public IView JIHAD_C4_USAGE2 { get; } +public interface IJihadC4Notifications { + public IView JihadC4Pickup { get; } + public IView JihadC4Received { get; } + public IView JihadC4Usage1 { get; } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs b/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs index c58b45ee..421f4bc8 100644 --- a/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs @@ -2,8 +2,6 @@ namespace Jailbreak.Formatting.Views; -public interface ILastGuardNotifications -{ - public IView LG_STARTED(int ctHealth, int tHealth); - +public interface ILastGuardNotifications { + public IView LG_STARTED(int ctHealth, int tHealth); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs b/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs index 3256db99..da40c182 100644 --- a/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs +++ b/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs @@ -5,16 +5,15 @@ namespace Jailbreak.Formatting.Views; -public interface ILastRequestMessages -{ - public IView LastRequestEnabled(); - public IView LastRequestDisabled(); - public IView LastRequestNotEnabled(); - public IView InvalidLastRequest(string query); - public IView InvalidPlayerChoice(CCSPlayerController player, string reason); - public IView InformLastRequest(AbstractLastRequest lr); - public IView AnnounceLastRequest(AbstractLastRequest lr); - public IView LastRequestDecided(AbstractLastRequest lr, LRResult result); - public IView DamageBlockedInsideLastRequest { get; } - public IView DamageBlockedNotInSameLR { get; } +public interface ILastRequestMessages { + public IView DamageBlockedInsideLastRequest { get; } + public IView DamageBlockedNotInSameLR { get; } + public IView LastRequestEnabled(); + public IView LastRequestDisabled(); + public IView LastRequestNotEnabled(); + public IView InvalidLastRequest(string query); + public IView InvalidPlayerChoice(CCSPlayerController player, string reason); + public IView InformLastRequest(AbstractLastRequest lr); + public IView AnnounceLastRequest(AbstractLastRequest lr); + public IView LastRequestDecided(AbstractLastRequest lr, LRResult result); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ILogMessages.cs b/public/Jailbreak.Formatting/Views/ILogMessages.cs index 759cae8e..be462cde 100644 --- a/public/Jailbreak.Formatting/Views/ILogMessages.cs +++ b/public/Jailbreak.Formatting/Views/ILogMessages.cs @@ -1,6 +1,5 @@ using CounterStrikeSharp.API; using CounterStrikeSharp.API.Modules.Utils; - using Jailbreak.Formatting.Base; using Jailbreak.Formatting.Core; using Jailbreak.Formatting.Objects; @@ -8,32 +7,24 @@ namespace Jailbreak.Formatting.Views; -public interface ILogMessages -{ - - public FormatObject TIME() - { - var gamerules = ServerExtensions.GetGameRules(); - var start = gamerules.RoundStartTime; - var current = Server.CurrentTime; - var elapsed = current - start; +public interface ILogMessages { + public IView BeginJailbreakLogs { get; } - var minutes = Math.Floor(elapsed / 60f).ToString("00"); - var seconds = Math.Floor(elapsed % 60).ToString("00"); + public IView EndJailbreakLogs { get; } - return new StringFormatObject($"[{minutes}:{seconds}]", ChatColors.Gold); - } + public FormatObject Time() { + var gamerules = ServerExtensions.GetGameRules(); + var start = gamerules.RoundStartTime; + var current = Server.CurrentTime; + var elapsed = current - start; - public IView CREATE_LOG(params FormatObject[] objects) - { - return new SimpleView() - { - TIME(), - objects - }; - } + var minutes = Math.Floor(elapsed / 60f).ToString("00"); + var seconds = Math.Floor(elapsed % 60).ToString("00"); - public IView BEGIN_JAILBREAK_LOGS { get; } + return new StringFormatObject($"[{minutes}:{seconds}]", ChatColors.Gold); + } - public IView END_JAILBREAK_LOGS { get; } -} + public IView CREATE_LOG(params FormatObject[] objects) { + return new SimpleView { Time(), objects }; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IPeaceMessages.cs b/public/Jailbreak.Formatting/Views/IPeaceMessages.cs index 0e969665..0d42ac6a 100644 --- a/public/Jailbreak.Formatting/Views/IPeaceMessages.cs +++ b/public/Jailbreak.Formatting/Views/IPeaceMessages.cs @@ -1,27 +1,24 @@ -using CounterStrikeSharp.API.Core; -using Jailbreak.Formatting.Base; +using Jailbreak.Formatting.Base; namespace Jailbreak.Formatting.Views; -public interface IPeaceMessages -{ - public IView PEACE_ENACTED_BY_ADMIN(int seconds); +public interface IPeaceMessages { + public IView UnmutedGuards { get; } - public IView WARDEN_ENACTED_PEACE(int seconds); + public IView UnmutedPrisoners { get; } - public IView GENERAL_PEACE_ENACTED(int seconds); + public IView MuteReminder { get; } - public IView UNMUTED_GUARDS { get; } + public IView PeaceReminder { get; } - public IView UNMUTED_PRISONERS { get; } + public IView DeadReminder { get; } - public IView MUTE_REMINDER { get; } - - public IView PEACE_REMINDER { get; } + public IView AdminDeadReminder { get; } - public IView DEAD_REMINDER { get; } - - public IView ADMIN_DEAD_REMINDER { get; } - - public IView PEACE_ACTIVE { get; } + public IView PeaceActive { get; } + public IView PeaceEnactedByAdmin(int seconds); + + public IView WardenEnactedPeace(int seconds); + + public IView GeneralPeaceEnacted(int seconds); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs b/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs index 39def4cd..ecdaf4c3 100644 --- a/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs +++ b/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs @@ -3,9 +3,8 @@ namespace Jailbreak.Formatting.Views; -public interface IRaceLRMessages -{ - public IView END_RACE_INSTRUCTION { get; } +public interface IRaceLRMessages { + public IView EndRaceInstruction { get; } - public IView RACE_STARTING_MESSAGE(CCSPlayerController prisoner); + public IView RaceStartingMessage(CCSPlayerController prisoner); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IRebelNotifications.cs b/public/Jailbreak.Formatting/Views/IRebelNotifications.cs index 26303309..76098506 100644 --- a/public/Jailbreak.Formatting/Views/IRebelNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IRebelNotifications.cs @@ -2,7 +2,6 @@ namespace Jailbreak.Formatting.Views; -public interface IRebelNotifications -{ - public IView NO_LONGER_REBEL { get; } -} +public interface IRebelNotifications { + public IView NoLongerRebel { get; } +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IRollCommandNotications.cs b/public/Jailbreak.Formatting/Views/IRollCommandNotications.cs index f1fbe675..0cd92aa0 100644 --- a/public/Jailbreak.Formatting/Views/IRollCommandNotications.cs +++ b/public/Jailbreak.Formatting/Views/IRollCommandNotications.cs @@ -2,7 +2,6 @@ namespace Jailbreak.Formatting.Views; -public interface IRollCommandNotications -{ - IView Roll(int roll); +public interface IRollCommandNotications { + IView Roll(int roll); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ISpecialDayNotifications.cs b/public/Jailbreak.Formatting/Views/ISpecialDayNotifications.cs index e16efef9..1018c31f 100644 --- a/public/Jailbreak.Formatting/Views/ISpecialDayNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ISpecialDayNotifications.cs @@ -2,13 +2,12 @@ namespace Jailbreak.Formatting.Views; -public interface ISpecialDayNotifications -{ - public IView SD_WARDAY_STARTED { get; } - public IView SD_FREEDAY_STARTED { get; } - public IView SD_FFA_STARTING { get; } - public IView SD_FFA_STARTED { get; } - public IView SD_CUSTOM_STARTED { get; } - public IView SD_CANT_START { get; } - public IView SD_NOT_WARDEN { get; } +public interface ISpecialDayNotifications { + public IView SdWardayStarted { get; } + public IView SdFreedayStarted { get; } + public IView SdFfaStarting { get; } + public IView SdFfaStarted { get; } + public IView SdCustomStarted { get; } + public IView SdCantStart { get; } + public IView SdNotWarden { get; } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ISpecialTreatmentNotifications.cs b/public/Jailbreak.Formatting/Views/ISpecialTreatmentNotifications.cs index 43f08600..8208d9be 100644 --- a/public/Jailbreak.Formatting/Views/ISpecialTreatmentNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ISpecialTreatmentNotifications.cs @@ -1,17 +1,14 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Base; namespace Jailbreak.Formatting.Views; -public interface ISpecialTreatmentNotifications -{ - public IView GRANTED { get; } - - public IView REVOKED { get; } +public interface ISpecialTreatmentNotifications { + public IView Granted { get; } - public IView GRANTED_TO(CCSPlayerController player); + public IView Revoked { get; } - public IView REVOKED_FROM(CCSPlayerController player); + public IView GrantedTo(CCSPlayerController player); -} + public IView RevokedFrom(CCSPlayerController player); +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs b/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs index eb4a5880..cd520796 100644 --- a/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ITeamsNotifications.cs @@ -2,22 +2,21 @@ namespace Jailbreak.Formatting.Views; -public interface IRatioNotifications -{ - public IView NOT_ENOUGH_GUARDS { get; } +public interface IRatioNotifications { + 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 55d5224e..bb23b6ed 100644 --- a/public/Jailbreak.Formatting/Views/IWardenNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IWardenNotifications.cs @@ -1,44 +1,47 @@ using CounterStrikeSharp.API.Core; using Jailbreak.Formatting.Base; + // ReSharper disable InconsistentNaming 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 NOT_WARDEN { get; } - public IView FIRE_COMMAND_FAILED { get; } - - /// - /// Create a view for when the specified player passes warden - /// - /// - /// - public IView PASS_WARDEN(CCSPlayerController player); - - /// - /// Create a view for when this player becomes a new warden - /// - /// - /// - public IView NEW_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 CURRENT_WARDEN(CCSPlayerController? player); - public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player); - - public IView FIRE_WARDEN(CCSPlayerController player); - public IView FIRE_WARDEN(CCSPlayerController player, CCSPlayerController admin); -} +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 NOT_WARDEN { get; } + public IView FIRE_COMMAND_FAILED { get; } + + /// + /// Create a view for when the specified player passes warden + /// + /// + /// + public IView PASS_WARDEN(CCSPlayerController player); + + /// + /// Create a view for when this player becomes a new warden + /// + /// + /// + public IView NEW_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 CURRENT_WARDEN(CCSPlayerController? player); + + public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player); + + public IView FIRE_WARDEN(CCSPlayerController player); + + public IView FIRE_WARDEN(CCSPlayerController player, + CCSPlayerController admin); +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/Logging/IRichLogService.cs b/public/Jailbreak.Formatting/Views/Logging/IRichLogService.cs index 05669315..22a0f33d 100644 --- a/public/Jailbreak.Formatting/Views/Logging/IRichLogService.cs +++ b/public/Jailbreak.Formatting/Views/Logging/IRichLogService.cs @@ -1,13 +1,11 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Core; using Jailbreak.Public.Mod.Logs; -namespace Jailbreak.Formatting.Views; +namespace Jailbreak.Formatting.Views.Logging; -public interface IRichLogService : ILogService -{ - void Append(params FormatObject[] objects); +public interface IRichLogService : ILogService { + void Append(params FormatObject[] objects); - FormatObject Player(CCSPlayerController playerController); -} + FormatObject Player(CCSPlayerController playerController); +} \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/Logging/IRichPlayerTag.cs b/public/Jailbreak.Formatting/Views/Logging/IRichPlayerTag.cs index ad4bab87..81854159 100644 --- a/public/Jailbreak.Formatting/Views/Logging/IRichPlayerTag.cs +++ b/public/Jailbreak.Formatting/Views/Logging/IRichPlayerTag.cs @@ -1,16 +1,14 @@ using CounterStrikeSharp.API.Core; - using Jailbreak.Formatting.Core; using Jailbreak.Public.Mod.Logs; -namespace Jailbreak.Formatting.Views; +namespace Jailbreak.Formatting.Views.Logging; -public interface IRichPlayerTag : IPlayerTag -{ - /// - /// Get a tag for this player, which contains context about the player's current actions - /// - /// - /// - FormatObject Rich(CCSPlayerController player); -} +public interface IRichPlayerTag : IPlayerTag { + /// + /// Get a tag for this player, which contains context about the player's current actions + /// + /// + /// + FormatObject Rich(CCSPlayerController player); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/API.cs b/public/Jailbreak.Public/API.cs index 8f14661a..c772c142 100644 --- a/public/Jailbreak.Public/API.cs +++ b/public/Jailbreak.Public/API.cs @@ -3,14 +3,14 @@ namespace Jailbreak.Public; /// -/// The entry point to the Jailbreak API +/// The entry point to the Jailbreak API /// -public static class API -{ - /// - /// Grants access to the currently running service provider, if there is one. - /// The service provider can be used to get instantiated IPluginBehaviors and other - /// objects exposed to Jailbreak mods - /// - public static PluginCapability Provider { get; } = new("jailbreak:core"); -} +public static class API { + /// + /// Grants access to the currently running service provider, if there is one. + /// The service provider can be used to get instantiated IPluginBehaviors and other + /// objects exposed to Jailbreak mods + /// + public static PluginCapability Provider { get; } = + new("jailbreak:core"); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs b/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs index a1125ec0..74d4f3b4 100644 --- a/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs +++ b/public/Jailbreak.Public/Behaviors/IPluginBehavior.cs @@ -3,18 +3,13 @@ namespace Jailbreak.Public.Behaviors; /// -/// A plugin extension class that is +/// A plugin extension class that is /// -public interface IPluginBehavior : IDisposable -{ - void IDisposable.Dispose() - { - } +public interface IPluginBehavior : IDisposable { + void IDisposable.Dispose() { } - /// - /// Tells the plugin that it will be starting imminently - /// - void Start(BasePlugin parent) - { - } + /// + /// Tells the plugin that it will be starting imminently + /// + void Start(BasePlugin basePlugin) { } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Configuration/IConfigService.cs b/public/Jailbreak.Public/Configuration/IConfigService.cs index 5380d3d6..9d1bca5e 100644 --- a/public/Jailbreak.Public/Configuration/IConfigService.cs +++ b/public/Jailbreak.Public/Configuration/IConfigService.cs @@ -1,16 +1,14 @@ namespace Jailbreak.Public.Configuration; -public interface IConfigService -{ - public const string ConfigPath = "jailbreak.json"; +public interface IConfigService { + public const string CONFIG_PATH = "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/EntityIOExtensions.cs b/public/Jailbreak.Public/Extensions/EntityIOExtensions.cs index b57e342d..e3e2465f 100644 --- a/public/Jailbreak.Public/Extensions/EntityIOExtensions.cs +++ b/public/Jailbreak.Public/Extensions/EntityIOExtensions.cs @@ -3,26 +3,22 @@ namespace Jailbreak.Public.Extensions; -public static class EntityIOExtensions -{ - public static bool TryGetController(this CEntityInstance pawn, out CCSPlayerController? controller) - { - controller = null; +public static class EntityIOExtensions { + public static bool TryGetController(this CEntityInstance pawn, + out CCSPlayerController? controller) { + controller = null; - if (!pawn.IsValid) - return false; + if (!pawn.IsValid) return false; - var index = (int)pawn.Index; - var playerPawn = Utilities.GetEntityFromIndex(index); + var index = (int)pawn.Index; + var playerPawn = Utilities.GetEntityFromIndex(index); - if (!playerPawn.IsValid) - return false; + if (playerPawn == null || !playerPawn.IsValid) return false; - if (!playerPawn.OriginalController.IsValid) - return false; + if (!playerPawn.OriginalController.IsValid) return false; - controller = playerPawn.OriginalController.Value; + controller = playerPawn.OriginalController.Value; - return controller?.IsReal() == true; - } -} + return controller?.IsReal() == true; + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/PlayerExtensions.cs b/public/Jailbreak.Public/Extensions/PlayerExtensions.cs index a379ebef..4012cdf8 100644 --- a/public/Jailbreak.Public/Extensions/PlayerExtensions.cs +++ b/public/Jailbreak.Public/Extensions/PlayerExtensions.cs @@ -5,95 +5,79 @@ namespace Jailbreak.Public.Extensions; -public static class PlayerExtensions -{ - 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 == null) - return false; - if (!player.IsValid) - return false; - - if (player.Connected != PlayerConnectedState.PlayerConnected) - return false; - - if (player.IsHLTV) - return false; - - return true; - } - - public static void Teleport(this CCSPlayerController player, CCSPlayerController target) - { - if (!player.IsReal() || !target.IsReal()) - return; - - var playerPawn = player.Pawn.Value; - if (playerPawn == null) - return; - - var targetPawn = target.Pawn.Value; - if (targetPawn == null) - return; - - if (targetPawn is { AbsRotation: not null, AbsOrigin: not null }) - Teleport(player, targetPawn.AbsOrigin, targetPawn.AbsRotation); - } - - public static void Teleport(this CCSPlayerController player, Vector pos, QAngle? rot = null) - { - if (!player.IsReal()) - return; - - var playerPawn = player.Pawn.Value; - if (playerPawn == null) - return; - - playerPawn.Teleport(pos, rot ?? playerPawn.AbsRotation!, new Vector()); - } - - public static void Freeze(this CCSPlayerController player) - { - if (!player.Pawn.IsValid || player.Connected != PlayerConnectedState.PlayerConnected) - return; - - if (player.Pawn.Value == null) - return; - - player.Pawn.Value.Freeze(); - } - - public static void UnFreeze(this CCSPlayerController player) - { - if (!player.Pawn.IsValid || player.Connected != PlayerConnectedState.PlayerConnected) - return; - - if (player.Pawn.Value == null) - return; - - player.Pawn.Value.UnFreeze(); - } - - public static void Freeze(this CBasePlayerPawn pawn) - { - pawn.MoveType = MoveType_t.MOVETYPE_OBSOLETE; - - Schema.SetSchemaValue(pawn.Handle, "CBaseEntity", "m_nActualMoveType", 1); - Utilities.SetStateChanged(pawn, "CBaseEntity", "m_MoveType"); - } - - public static void UnFreeze(this CBasePlayerPawn pawn) - { - pawn.MoveType = MoveType_t.MOVETYPE_WALK; - - Schema.SetSchemaValue(pawn.Handle, "CBaseEntity", "m_nActualMoveType", 2); - Utilities.SetStateChanged(pawn, "CBaseEntity", "m_MoveType"); - } +public static class PlayerExtensions { + 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 == null) return false; + if (!player.IsValid) return false; + + if (player.Connected != PlayerConnectedState.PlayerConnected) return false; + + if (player.IsHLTV) return false; + + return true; + } + + public static void Teleport(this CCSPlayerController player, + CCSPlayerController target) { + if (!player.IsReal() || !target.IsReal()) return; + + var playerPawn = player.Pawn.Value; + if (playerPawn == null) return; + + var targetPawn = target.Pawn.Value; + if (targetPawn == null) return; + + if (targetPawn is { AbsRotation: not null, AbsOrigin: not null }) + Teleport(player, targetPawn.AbsOrigin, targetPawn.AbsRotation); + } + + public static void Teleport(this CCSPlayerController player, Vector pos, + QAngle? rot = null) { + if (!player.IsReal()) return; + + var playerPawn = player.Pawn.Value; + if (playerPawn == null) return; + + playerPawn.Teleport(pos, rot ?? playerPawn.AbsRotation!, new Vector()); + } + + public static void Freeze(this CCSPlayerController player) { + if (!player.Pawn.IsValid + || player.Connected != PlayerConnectedState.PlayerConnected) + return; + + if (player.Pawn.Value == null) return; + + player.Pawn.Value.Freeze(); + } + + public static void UnFreeze(this CCSPlayerController player) { + if (!player.Pawn.IsValid + || player.Connected != PlayerConnectedState.PlayerConnected) + return; + + if (player.Pawn.Value == null) return; + + player.Pawn.Value.UnFreeze(); + } + + public static void Freeze(this CBasePlayerPawn pawn) { + pawn.MoveType = MoveType_t.MOVETYPE_OBSOLETE; + + Schema.SetSchemaValue(pawn.Handle, "CBaseEntity", "m_nActualMoveType", 1); + Utilities.SetStateChanged(pawn, "CBaseEntity", "m_MoveType"); + } + + public static void UnFreeze(this CBasePlayerPawn pawn) { + pawn.MoveType = MoveType_t.MOVETYPE_WALK; + + Schema.SetSchemaValue(pawn.Handle, "CBaseEntity", "m_nActualMoveType", 2); + Utilities.SetStateChanged(pawn, "CBaseEntity", "m_MoveType"); + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/ServerExtensions.cs b/public/Jailbreak.Public/Extensions/ServerExtensions.cs index f59e538d..829fc30a 100644 --- a/public/Jailbreak.Public/Extensions/ServerExtensions.cs +++ b/public/Jailbreak.Public/Extensions/ServerExtensions.cs @@ -5,26 +5,27 @@ 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 class ServerExtensions { + public static void PrintToCenterAll(string message) { + VirtualFunctions.ClientPrintAll(HudDestination.Center, message, 0, 0, 0, 0); + } - /// - /// Get the current CCSGameRules for the server - /// - /// - public static CCSGameRules GetGameRules() - { - // From killstr3ak - return Utilities.FindAllEntitiesByDesignerName("cs_gamerules").First().GameRules!; - } - - public static CCSGameRulesProxy GetGameRulesProxy() - { - // From killstr3ak - return Utilities.FindAllEntitiesByDesignerName("cs_gamerules").First()!; - } -} + /// + /// Get the current CCSGameRules for the server + /// + /// + public static CCSGameRules GetGameRules() { + // From killstr3ak + return Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .First() + .GameRules!; + } + + public static CCSGameRulesProxy GetGameRulesProxy() { + // From killstr3ak + return Utilities + .FindAllEntitiesByDesignerName("cs_gamerules") + .First(); + } +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs b/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs index 7712a260..f36449e0 100644 --- a/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs +++ b/public/Jailbreak.Public/Extensions/ServiceCollectionExtensions.cs @@ -4,60 +4,62 @@ namespace Jailbreak.Public.Extensions; -public static class ServiceCollectionExtensions -{ - /// - /// Add a to the global service collection - /// - /// - /// - public static void AddPluginBehavior(this IServiceCollection collection) - where TExtension : class, IPluginBehavior - { - // Add the root extension itself as a scoped service. - // This means every time Load is called in the main Jailbreak loader, - // the extension will be fetched and kept as a singleton for the duration - // until "Unload" is called. - collection.AddScoped(); +public static class ServiceCollectionExtensions { + /// + /// 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(); - collection.AddTransient(provider => provider.GetRequiredService()); - } + collection.AddTransient(provider + => provider.GetRequiredService()); + } - /// - /// 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(); + /// + /// 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()); - } + collection.AddTransient(provider + => provider.GetRequiredService()); + collection.AddTransient(provider + => provider.GetRequiredService()); + } - /// - /// 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. + /// + /// 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)); - } + // 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 f86de3d5..c8eb9412 100644 --- a/public/Jailbreak.Public/Extensions/StringExtensions.cs +++ b/public/Jailbreak.Public/Extensions/StringExtensions.cs @@ -1,10 +1,7 @@ namespace Jailbreak.Public.Extensions; -public static class StringExtensions -{ - public static string Sanitize(this string unknown) - { - return unknown - .Replace("<", "<"); - } +public static class StringExtensions { + public static string Sanitize(this string unknown) { + return unknown.Replace("<", "<"); + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/VectorExtensions.cs b/public/Jailbreak.Public/Extensions/VectorExtensions.cs index b522920b..f56f926e 100644 --- a/public/Jailbreak.Public/Extensions/VectorExtensions.cs +++ b/public/Jailbreak.Public/Extensions/VectorExtensions.cs @@ -2,55 +2,40 @@ namespace Jailbreak.Public.Extensions; -public static class VectorExtensions -{ - public static Vector Clone(this Vector vector) - { - var vec = new Vector - { - X = vector.X, - Y = vector.Y, - Z = vector.Z - }; - return vec; - } +public static class VectorExtensions { + public static Vector Clone(this Vector vector) { + var vec = new Vector { X = vector.X, Y = vector.Y, Z = vector.Z }; + return vec; + } - public static Vector Add(this Vector vector, Vector other) - { - vector.X += other.X; - vector.Y += other.Y; - vector.Z += other.Z; - return vector; - } + public static Vector Add(this Vector vector, Vector other) { + vector.X += other.X; + vector.Y += other.Y; + vector.Z += other.Z; + return vector; + } - public static Vector Scale(this Vector vector, float scale) - { - vector.X *= scale; - vector.Y *= scale; - vector.Z *= scale; - return vector; - } + public static Vector Scale(this Vector vector, float scale) { + vector.X *= scale; + vector.Y *= scale; + vector.Z *= scale; + return vector; + } - public static Vector Normalize(this Vector vector) - { - var length = vector.Length(); - vector.X /= length; - vector.Y /= length; - vector.Z /= length; - return vector; - } + public static Vector Normalize(this Vector vector) { + var length = vector.Length(); + vector.X /= length; + vector.Y /= length; + vector.Z /= length; + return vector; + } - public static float Distance(this Vector vector, Vector other) - { - return (float)Math.Sqrt(vector.DistanceSquared(other)); - } + public static float Distance(this Vector vector, Vector other) { + return (float)Math.Sqrt(vector.DistanceSquared(other)); + } - public static float DistanceSquared(this Vector vector, Vector other) - { - return (float)( - Math.Pow(vector.X - other.X, 2) + - Math.Pow(vector.Y - other.Y, 2) + - Math.Pow(vector.Z - other.Z, 2) - ); - } + public static float DistanceSquared(this Vector vector, Vector other) { + return (float)(Math.Pow(vector.X - other.X, 2) + + Math.Pow(vector.Y - other.Y, 2) + Math.Pow(vector.Z - other.Z, 2)); + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Generic/ICoroutines.cs b/public/Jailbreak.Public/Generic/ICoroutines.cs index 1cdadad3..a41a2a0c 100644 --- a/public/Jailbreak.Public/Generic/ICoroutines.cs +++ b/public/Jailbreak.Public/Generic/ICoroutines.cs @@ -1,12 +1,11 @@ namespace Jailbreak.Public.Generic; -public interface ICoroutines -{ - /// - /// 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); +public interface ICoroutines { + /// + /// 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 c55954b6..6fd8f466 100644 --- a/public/Jailbreak.Public/Generic/IPlayerState.cs +++ b/public/Jailbreak.Public/Generic/IPlayerState.cs @@ -3,12 +3,10 @@ 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() -{ - TState Get(CCSPlayerController controller); +public interface IPlayerState where TState : class, new() { + 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 263d1d15..fc77f5d6 100644 --- a/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs +++ b/public/Jailbreak.Public/Generic/IPlayerStateFactory.cs @@ -1,28 +1,24 @@ namespace Jailbreak.Public.Generic; -public interface IPlayerStateFactory -{ - /// - /// This state lasts from when the player connect to until the player disconnects. - /// - /// - /// - IPlayerState Global() - where T : class, new(); +public interface IPlayerStateFactory { + /// + /// This state lasts from when the player connect to until the player disconnects. + /// + /// + /// + IPlayerState Global() where T : class, new(); - /// - /// This state resets when the player dies - /// - /// - /// - IPlayerState Alive() - where T : class, new(); + /// + /// This state resets when the player dies + /// + /// + /// + IPlayerState Alive() where T : class, new(); - /// - /// This state resets when the round ends or begins. - /// - /// - /// - IPlayerState Round() - where T : class, new(); + /// + /// This state resets when the round ends or begins. + /// + /// + /// + IPlayerState Round() 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 85518f26..bd6c370b 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/Damage/IBlockAllDamage.cs b/public/Jailbreak.Public/Mod/Damage/IBlockAllDamage.cs index cf50a99c..663e302f 100644 --- a/public/Jailbreak.Public/Mod/Damage/IBlockAllDamage.cs +++ b/public/Jailbreak.Public/Mod/Damage/IBlockAllDamage.cs @@ -1,31 +1,26 @@ using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; using Jailbreak.Public.Extensions; namespace Jailbreak.Public.Mod.Damage; -public interface IBlockUserDamage -{ - HookResult BlockUserDamage(EventPlayerHurt @event, GameEventInfo info) - { - var player = @event.Userid; - var attacker = @event.Attacker; - if (player == null || !player.IsReal()) - return HookResult.Continue; +public interface IBlockUserDamage { + HookResult BlockUserDamage(EventPlayerHurt @event, GameEventInfo info) { + var player = @event.Userid; + var attacker = @event.Attacker; + if (player == null || !player.IsReal()) return HookResult.Continue; - if (!ShouldBlockDamage(player, attacker, @event)) - { - return HookResult.Continue; - } - if (player.PlayerPawn.IsValid) - { - CCSPlayerPawn playerPawn = player.PlayerPawn.Value!; - playerPawn.Health = playerPawn.LastHealth; - } - @event.DmgArmor = 0; - @event.DmgHealth = 0; - return HookResult.Stop; + if (!ShouldBlockDamage(player, attacker, @event)) + return HookResult.Continue; + if (player.PlayerPawn.IsValid) { + var playerPawn = player.PlayerPawn.Value!; + playerPawn.Health = playerPawn.LastHealth; } - bool ShouldBlockDamage(CCSPlayerController victim, CCSPlayerController? attacker, EventPlayerHurt @event); + @event.DmgArmor = 0; + @event.DmgHealth = 0; + return HookResult.Stop; + } + + bool ShouldBlockDamage(CCSPlayerController victim, + CCSPlayerController? attacker, EventPlayerHurt @event); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs b/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs index 58fbb7ed..9d947e4e 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamCircle.cs @@ -3,65 +3,52 @@ namespace Jailbreak.Public.Mod.Draw; -public class BeamCircle : BeamedShape -{ - private readonly BeamLine?[] _lines; - private Vector[] _offsets; - private float _radius; - - public BeamCircle(BasePlugin plugin, Vector position, float radius, int resolution) : base(plugin, position, - resolution) - { - _radius = radius; - _lines = new BeamLine[resolution]; - - _offsets = GenerateOffsets(); - } - - private float DegToRadian(float d) - { - return (float)(d * (Math.PI / 180)); +public class BeamCircle : BeamedShape { + private readonly BeamLine?[] lines; + private Vector[] offsets; + private float radius; + + public BeamCircle(BasePlugin plugin, Vector position, float radius, + int resolution) : base(plugin, position, resolution) { + this.radius = radius; + lines = new BeamLine[resolution]; + + offsets = generateOffsets(); + } + + private float degToRadian(float d) { return (float)(d * (Math.PI / 180)); } + + private Vector[] generateOffsets() { + var newOffsets = 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)); + newOffsets[i] = new Vector(x, y, 0); } - private Vector[] GenerateOffsets() - { - 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)); - offsets[i] = new Vector(x, y, 0); - } - - return offsets; - } - - public override void Draw() - { - 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]; - if (line == null) - { - line = new BeamLine(Plugin, start, end); - line.SetColor(Color); - line.Draw(); - _lines[i] = line; - } - else - { - line.Move(start, end); - line.Update(); - } - } + return newOffsets; + } + + public override void Draw() { + 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]; + if (line == null) { + line = new BeamLine(Plugin, start, end); + line.SetColor(Color); + line.Draw(); + lines[i] = line; + } else { + line.Move(start, end); + line.Update(); + } } + } - public void SetRadius(float radius) - { - _radius = radius; - _offsets = GenerateOffsets(); - } + public void SetRadius(float _radius) { + 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 2d47b90b..843c40b1 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamLine.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamLine.cs @@ -5,61 +5,45 @@ namespace Jailbreak.Public.Mod.Draw; -public class BeamLine(BasePlugin plugin, Vector position, Vector end) : DrawableShape(plugin, position), IColorable -{ - private CEnvBeam? _beam; - private Color _color = Color.White; - private float _width = 1f; - - public void SetColor(Color color) - { - _color = color; - } - - public Color GetColor() - { - return _color; - } - - public void Move(Vector start, Vector end1) - { - Position = start; - end = end1; - } - - public override void Draw() - { - Remove(); - var beam = Utilities.CreateEntityByName("env_beam"); - if (beam == null) return; - beam.RenderMode = RenderMode_t.kRenderTransColor; - 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; - _beam = beam; - - Utilities.SetStateChanged(beam, "CBeam", "m_vecEndPos"); - } - - public override void Remove() - { - KillTimer?.Kill(); - if(_beam != null && _beam.IsValid) - _beam?.Remove(); - _beam = null; - } - - public void SetWidth(float width) - { - _width = width; - } - - public float GetWidth() - { - return _width; - } +public class BeamLine(BasePlugin plugin, Vector position, Vector end) + : DrawableShape(plugin, position), IColorable { + private CEnvBeam? beam; + private Color color = Color.White; + private float width = 1f; + + public void SetColor(Color _color) { color = _color; } + + public Color GetColor() { return color; } + + public void Move(Vector start, Vector end1) { + Position = start; + end = end1; + } + + public override void Draw() { + Remove(); + var newBeam = Utilities.CreateEntityByName("env_beam"); + if (newBeam == null) return; + newBeam.RenderMode = RenderMode_t.kRenderTransColor; + newBeam.Width = width; + newBeam.Render = GetColor(); + + newBeam.Teleport(Position, new QAngle(), new Vector()); + newBeam.EndPos.X = end.X; + newBeam.EndPos.Y = end.Y; + newBeam.EndPos.Z = end.Z; + beam = newBeam; + + Utilities.SetStateChanged(newBeam, "CBeam", "m_vecEndPos"); + } + + public override void Remove() { + KillTimer?.Kill(); + if (beam != null && beam.IsValid) beam?.Remove(); + beam = null; + } + + public void SetWidth(float _width) { width = _width; } + + public float GetWidth() { 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 95e830a1..10a5515e 100644 --- a/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs +++ b/public/Jailbreak.Public/Mod/Draw/BeamedShape.cs @@ -5,33 +5,24 @@ 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(BasePlugin plugin, Vector position, int resolution) - : DrawableShape(plugin, position), IColorable -{ - protected readonly BeamLine?[] Beams = new BeamLine[resolution]; - protected Color Color = Color.White; - protected int Resolution; +public abstract class BeamedShape(BasePlugin plugin, Vector position, + int resolution) : DrawableShape(plugin, position), IColorable { + protected readonly BeamLine?[] Beams = new BeamLine[resolution]; + protected Color Color = Color.White; + protected int Resolution; - // TODO: Add support for rotation across arbitrary axis + // TODO: Add support for rotation across arbitrary axis - public Color GetColor() - { - return Color; - } + public Color GetColor() { return Color; } - public void SetColor(Color color) - { - Color = color; - } + public void SetColor(Color color) { Color = color; } - public override void Remove() - { - for (var i = 0; i < Beams.Length; i++) - { - Beams[i]?.Remove(); - Beams[i] = null; - } + public override void Remove() { + for (var i = 0; i < Beams.Length; i++) { + 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 a4c0b15f..c4e13e79 100644 --- a/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs +++ b/public/Jailbreak.Public/Mod/Draw/DrawableShape.cs @@ -6,41 +6,34 @@ namespace Jailbreak.Public.Mod.Draw; /// -/// Represents a drawable shape +/// Represents a drawable shape /// -public abstract class DrawableShape(BasePlugin plugin, Vector position) -{ - protected Timer? KillTimer; // Internal timer used to remove the shape after a certain amount of time +public abstract class DrawableShape(BasePlugin plugin, Vector position) { + protected Timer? + KillTimer; // Internal timer used to remove the shape after a certain amount of time - protected BasePlugin Plugin = plugin; + protected BasePlugin Plugin = plugin; - protected Vector Position = position; // Represents the origin of the shape + protected Vector Position = position; // Represents the origin of the shape - // Note that this can mean different things for different shapes - protected DateTime StartTime = DateTime.Now; + // Note that this can mean different things for different shapes + protected DateTime StartTime = DateTime.Now; - public abstract void Draw(); + public abstract void Draw(); - public virtual void Update() - { - Remove(); - Draw(); - } + 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); - } + public void Draw(float lifetime) { + Draw(); + KillTimer = Plugin.AddTimer(lifetime, Remove, TimerFlags.STOP_ON_MAPCHANGE); + } - public virtual void Move(Vector position) - { - Position = position; - } + public virtual void Move(Vector position) { Position = position; } - public abstract void Remove(); + public abstract void Remove(); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Draw/IColorable.cs b/public/Jailbreak.Public/Mod/Draw/IColorable.cs index b0e9f1fe..2a8cb12e 100644 --- a/public/Jailbreak.Public/Mod/Draw/IColorable.cs +++ b/public/Jailbreak.Public/Mod/Draw/IColorable.cs @@ -2,8 +2,7 @@ namespace Jailbreak.Public.Mod.Draw; -public interface IColorable -{ - void SetColor(Color color); - Color GetColor(); +public interface IColorable { + void SetColor(Color color); + Color GetColor(); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastGuard/ILastGuardService.cs b/public/Jailbreak.Public/Mod/LastGuard/ILastGuardService.cs index 746155db..d3554607 100644 --- a/public/Jailbreak.Public/Mod/LastGuard/ILastGuardService.cs +++ b/public/Jailbreak.Public/Mod/LastGuard/ILastGuardService.cs @@ -2,8 +2,7 @@ namespace Jailbreak.Public.Mod.LastGuard; -public interface ILastGuardService -{ - int CalculateHealth(); - void StartLastGuard(CCSPlayerController lastGuard); +public interface ILastGuardService { + int CalculateHealth(); + void StartLastGuard(CCSPlayerController lastGuard); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/AbstractLastRequest.cs b/public/Jailbreak.Public/Mod/LastRequest/AbstractLastRequest.cs index b0310f48..1830fa95 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/AbstractLastRequest.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/AbstractLastRequest.cs @@ -3,27 +3,23 @@ namespace Jailbreak.Public.Mod.LastRequest; -public abstract class AbstractLastRequest( - BasePlugin plugin, - ILastRequestManager manager, - CCSPlayerController prisoner, - CCSPlayerController guard) -{ - public CCSPlayerController prisoner { get; protected set; } = prisoner; - public CCSPlayerController guard { get; protected set; } = guard; - public abstract LRType type { get; } +public abstract class AbstractLastRequest(BasePlugin plugin, + ILastRequestManager manager, CCSPlayerController prisoner, + CCSPlayerController guard) { + protected readonly ILastRequestManager Manager = manager; + protected readonly BasePlugin Plugin = plugin; + public CCSPlayerController Prisoner { get; protected set; } = prisoner; + public CCSPlayerController Guard { get; protected set; } = guard; + public abstract LRType Type { get; } - public LRState state { get; protected set; } - protected BasePlugin plugin = plugin; - protected ILastRequestManager manager = manager; + public LRState State { get; protected set; } - public void PrintToParticipants(string message) - { - prisoner.PrintToChat(message); - guard.PrintToChat(message); - } + public void PrintToParticipants(string message) { + Prisoner.PrintToChat(message); + Guard.PrintToChat(message); + } - public abstract void Setup(); - public abstract void Execute(); - public abstract void OnEnd(LRResult result); + public abstract void Setup(); + public abstract void Execute(); + public abstract void OnEnd(LRResult result); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRResult.cs b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRResult.cs index 3621ce28..828f05ff 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRResult.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRResult.cs @@ -1,9 +1,5 @@ namespace Jailbreak.Public.Mod.LastRequest.Enums; -public enum LRResult -{ - PrisonerWin, - GuardWin, - TimedOut, - Interrupted +public enum LRResult { + PRISONER_WIN, GUARD_WIN, TIMED_OUT, INTERRUPTED } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRState.cs b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRState.cs index 2c75f3c3..46ec6bba 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRState.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRState.cs @@ -1,9 +1,5 @@ namespace Jailbreak.Public.Mod.LastRequest.Enums; -public enum LRState -{ - Pending, - Active, - Completed, - Cancelled +public enum LRState { + PENDING, ACTIVE, COMPLETED, CANCELLED } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRType.cs b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRType.cs index 79916b8d..9e07ea86 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/Enums/LRType.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/Enums/LRType.cs @@ -1,68 +1,51 @@ -using CounterStrikeSharp.API.Core; -using Microsoft.Extensions.Logging.Abstractions; - namespace Jailbreak.Public.Mod.LastRequest.Enums; -public enum LRType -{ - GunToss, - RockPaperScissors, - KnifeFight, - NoScope, - Coinflip, - ShotForShot, - MagForMag, - Race +public enum LRType { + GUN_TOSS, + ROCK_PAPER_SCISSORS, + KNIFE_FIGHT, + NO_SCOPE, + COINFLIP, + SHOT_FOR_SHOT, + MAG_FOR_MAG, + RACE } -public static class LRTypeExtensions -{ - public static string ToFriendlyString(this LRType type) - { - return type switch - { - LRType.GunToss => "Gun Toss", - LRType.RockPaperScissors => "Rock Paper Scissors", - LRType.KnifeFight => "Knife Fight", - LRType.NoScope => "No Scope", - LRType.Coinflip => "Coinflip", - LRType.ShotForShot => "Shot For Shot", - LRType.MagForMag => "Mag For Mag", - LRType.Race => "Race", - _ => "Unknown" - }; - } +public static class LRTypeExtensions { + public static string ToFriendlyString(this LRType type) { + return type switch { + LRType.GUN_TOSS => "Gun Toss", + LRType.ROCK_PAPER_SCISSORS => "Rock Paper Scissors", + LRType.KNIFE_FIGHT => "Knife Fight", + LRType.NO_SCOPE => "No Scope", + LRType.COINFLIP => "Coinflip", + LRType.SHOT_FOR_SHOT => "Shot For Shot", + LRType.MAG_FOR_MAG => "Mag For Mag", + LRType.RACE => "Race", + _ => "Unknown" + }; + } - public static LRType FromIndex(int index) - { - return (LRType)index; - } + public static LRType FromIndex(int index) { return (LRType)index; } - public static LRType? FromString(string type) - { - if (Enum.TryParse(type, true, out var result)) - return result; - type = type.ToLower().Replace(" ", ""); - switch (type) - { - case "rps": - return LRType.RockPaperScissors; - case "s4s": - case "sfs": - return LRType.ShotForShot; - case "m4m": - case "mfm": - return LRType.MagForMag; - } - - if (type.Contains("knife")) - return LRType.KnifeFight; - if (type.Contains("scope")) - return LRType.NoScope; - if (type.Contains("gun")) - return LRType.GunToss; - if (type.Contains("coin") || type.Contains("fifty")) - return LRType.Coinflip; - return null; + public static LRType? FromString(string type) { + if (Enum.TryParse(type, true, out var result)) return result; + type = type.ToLower().Replace(" ", ""); + switch (type) { + case "rps": + return LRType.ROCK_PAPER_SCISSORS; + case "s4s": + case "sfs": + return LRType.SHOT_FOR_SHOT; + case "m4m": + case "mfm": + return LRType.MAG_FOR_MAG; } + + if (type.Contains("knife")) return LRType.KNIFE_FIGHT; + if (type.Contains("scope")) return LRType.NO_SCOPE; + if (type.Contains("gun")) return LRType.GUN_TOSS; + if (type.Contains("coin") || type.Contains("fifty")) return LRType.COINFLIP; + return null; + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/ILastRequestFactory.cs b/public/Jailbreak.Public/Mod/LastRequest/ILastRequestFactory.cs index eaa285b8..b0936fe1 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/ILastRequestFactory.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/ILastRequestFactory.cs @@ -4,8 +4,9 @@ namespace Jailbreak.Public.Mod.LastRequest; -public interface ILastRequestFactory : IPluginBehavior -{ - AbstractLastRequest CreateLastRequest(CCSPlayerController prisoner, CCSPlayerController guard, LRType type); - bool IsValidType(LRType type); +public interface ILastRequestFactory : IPluginBehavior { + AbstractLastRequest CreateLastRequest(CCSPlayerController prisoner, + CCSPlayerController guard, LRType type); + + bool IsValidType(LRType type); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/LastRequest/ILastRequestManager.cs b/public/Jailbreak.Public/Mod/LastRequest/ILastRequestManager.cs index 3f55b0fd..3584e75d 100644 --- a/public/Jailbreak.Public/Mod/LastRequest/ILastRequestManager.cs +++ b/public/Jailbreak.Public/Mod/LastRequest/ILastRequestManager.cs @@ -4,24 +4,24 @@ namespace Jailbreak.Public.Mod.LastRequest; -public interface ILastRequestManager : IPluginBehavior -{ - public bool IsLREnabled { get; set; } - public IList ActiveLRs { get; } +public interface ILastRequestManager : IPluginBehavior { + public bool IsLREnabled { get; set; } + public IList ActiveLRs { get; } - bool InitiateLastRequest(CCSPlayerController prisoner, CCSPlayerController guard, LRType lrType); - bool EndLastRequest(AbstractLastRequest lr, LRResult result); + bool InitiateLastRequest(CCSPlayerController prisoner, + CCSPlayerController guard, LRType lrType); - public bool IsInLR(CCSPlayerController player) - { - return GetActiveLR(player) != null; - } + bool EndLastRequest(AbstractLastRequest lr, LRResult result); - public AbstractLastRequest? GetActiveLR(CCSPlayerController player) - { - return ActiveLRs.FirstOrDefault(lr => lr.guard.Slot == player.Slot || lr.prisoner.Slot == player.Slot); - } + public bool IsInLR(CCSPlayerController player) { + return GetActiveLR(player) != null; + } - public void EnableLR(CCSPlayerController? died = null); - public void DisableLR(); + public AbstractLastRequest? GetActiveLR(CCSPlayerController player) { + return ActiveLRs.FirstOrDefault(lr + => lr.Guard.Slot == player.Slot || lr.Prisoner.Slot == player.Slot); + } + + public void EnableLR(CCSPlayerController? died = null); + public void DisableLR(); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Logs/ILogService.cs b/public/Jailbreak.Public/Mod/Logs/ILogService.cs index 4be4b511..33a864b6 100644 --- a/public/Jailbreak.Public/Mod/Logs/ILogService.cs +++ b/public/Jailbreak.Public/Mod/Logs/ILogService.cs @@ -2,10 +2,9 @@ namespace Jailbreak.Public.Mod.Logs; -public interface ILogService -{ - void Append(string message); - IEnumerable GetMessages(); - void Clear(); - void PrintLogs(CCSPlayerController? player); -} +public interface ILogService { + void Append(string message); + IEnumerable GetMessages(); + void Clear(); + void PrintLogs(CCSPlayerController? player); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Logs/IPlayerTag.cs b/public/Jailbreak.Public/Mod/Logs/IPlayerTag.cs index dbdc79ff..9970f297 100644 --- a/public/Jailbreak.Public/Mod/Logs/IPlayerTag.cs +++ b/public/Jailbreak.Public/Mod/Logs/IPlayerTag.cs @@ -2,12 +2,11 @@ namespace Jailbreak.Public.Mod.Logs; -public interface IPlayerTag -{ - /// - /// Get a tag that contains context about the player. - /// - /// - /// - string Plain(CCSPlayerController playerController); -} +public interface IPlayerTag { + /// + /// Get a tag that contains context about the player. + /// + /// + /// + string Plain(CCSPlayerController playerController); +} \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Mute/IMuteService.cs b/public/Jailbreak.Public/Mod/Mute/IMuteService.cs index f47099dc..353b5ae8 100644 --- a/public/Jailbreak.Public/Mod/Mute/IMuteService.cs +++ b/public/Jailbreak.Public/Mod/Mute/IMuteService.cs @@ -1,14 +1,11 @@ -using CounterStrikeSharp.API.Core; +namespace Jailbreak.Public.Mod.Mute; -namespace Jailbreak.Public.Mod.Mute; +public interface IMuteService { + void PeaceMute(MuteReason reason); -public interface IMuteService -{ - void PeaceMute(MuteReason reason); + void UnPeaceMute(); - void UnPeaceMute(); + bool IsPeaceEnabled(); - bool IsPeaceEnabled(); - - DateTime GetLastPeace(); + DateTime GetLastPeace(); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Mute/MuteReason.cs b/public/Jailbreak.Public/Mod/Mute/MuteReason.cs index 595160f7..da8b4ef4 100644 --- a/public/Jailbreak.Public/Mod/Mute/MuteReason.cs +++ b/public/Jailbreak.Public/Mod/Mute/MuteReason.cs @@ -1,9 +1,5 @@ namespace Jailbreak.Public.Mod.Mute; -public enum MuteReason -{ - ADMIN, - WARDEN_INVOKED, - INITIAL_WARDEN, - WARDEN_TAKEN +public enum MuteReason { + ADMIN, WARDEN_INVOKED, INITIAL_WARDEN, WARDEN_TAKEN } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Rebel/IJihadC4Service.cs b/public/Jailbreak.Public/Mod/Rebel/IJihadC4Service.cs index be237ea4..3168d3b3 100644 --- a/public/Jailbreak.Public/Mod/Rebel/IJihadC4Service.cs +++ b/public/Jailbreak.Public/Mod/Rebel/IJihadC4Service.cs @@ -2,26 +2,28 @@ namespace Jailbreak.Public.Mod.Rebel; -public interface IJihadC4Service -{ +public interface IJihadC4Service { + /// + /// Tries to give the jihad C4 to the player, assuming the player object passed in is valid. + /// + /// + void TryGiveC4ToPlayer(CCSPlayerController player); - /// - /// Tries to give the jihad C4 to the player, assuming the player object passed in is valid. - /// - /// - void TryGiveC4ToPlayer(CCSPlayerController player); + /// + /// Tries to detonate the jihad c4, relative to the player's position and after the specified delay. + /// + /// + /// + /// + void StartDetonationAttempt(CCSPlayerController player, float delay, + CC4 bombEntity); - /// - /// Tries to detonate the jihad c4, relative to the player's position and after the specified delay. - /// - /// - void StartDetonationAttempt(CCSPlayerController player, float delay, CC4 bombEntity); - - /// - /// Attempts to give the Jihad C4 to a random Terrorist, if they already have one and they are chosen then nothing will happen. - /// - void TryGiveC4ToRandomTerrorist(); - - void ClearActiveC4s(); + /// + /// Attempts to give the Jihad C4 to a random Terrorist, if they already have one and they are chosen then nothing will + /// happen. + /// + void TryGiveC4ToRandomTerrorist(); + // ReSharper disable once InconsistentNaming + void ClearActiveC4s(); } \ 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 688718ae..139c6563 100644 --- a/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs +++ b/public/Jailbreak.Public/Mod/Rebel/IRebelService.cs @@ -2,18 +2,16 @@ namespace Jailbreak.Public.Mod.Rebel; -public interface IRebelService -{ - ISet GetActiveRebels(); +public interface IRebelService { + ISet GetActiveRebels(); - bool IsRebel(CCSPlayerController player) - { - return GetRebelTimeLeft(player) > 0; - } + bool IsRebel(CCSPlayerController player) { + return GetRebelTimeLeft(player) > 0; + } - long GetRebelTimeLeft(CCSPlayerController player); + long GetRebelTimeLeft(CCSPlayerController player); - bool MarkRebel(CCSPlayerController player, long time = 30); + bool MarkRebel(CCSPlayerController player, long time = 30); - void UnmarkRebel(CCSPlayerController player); + void UnmarkRebel(CCSPlayerController player); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Mod/Warden/ISpecialTreatmentService.cs b/public/Jailbreak.Public/Mod/Warden/ISpecialTreatmentService.cs index b6b2ae27..0bead995 100644 --- a/public/Jailbreak.Public/Mod/Warden/ISpecialTreatmentService.cs +++ b/public/Jailbreak.Public/Mod/Warden/ISpecialTreatmentService.cs @@ -2,28 +2,26 @@ namespace Jailbreak.Public.Mod.Warden; -public interface ISpecialTreatmentService -{ - public bool IsSpecialTreatment(CCSPlayerController player); +public interface ISpecialTreatmentService { + public bool IsSpecialTreatment(CCSPlayerController player); - public void SetSpecialTreatment(CCSPlayerController player, bool special) - { - if (special) - Grant(player); - else - Revoke(player); - } + public void SetSpecialTreatment(CCSPlayerController player, bool special) { + if (special) + Grant(player); + else + Revoke(player); + } - /// - /// Give this player ST for the rest of the round - /// - /// - public void Grant(CCSPlayerController player); + /// + /// Give this player ST for the rest of the round + /// + /// + public void Grant(CCSPlayerController player); - /// - /// Revoke the player's special treatment for the current round - /// Does nothing if not ST. - /// - /// - public void Revoke(CCSPlayerController player); + /// + /// Revoke the player's special treatment for the current round + /// Does nothing if not ST. + /// + /// + public void Revoke(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 b25730f7..80ff3504 100644 --- a/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs +++ b/public/Jailbreak.Public/Mod/Warden/IWardenSelectionService.cs @@ -2,29 +2,28 @@ namespace Jailbreak.Public.Mod.Warden; -public interface IWardenSelectionService -{ - /// - /// Whether or not the warden queue is currently in use - /// - bool Active { get; } +public interface IWardenSelectionService { + /// + /// Whether or not the warden queue is currently in use + /// + bool Active { get; } - /// - /// Enter this player into the warden queue - /// - /// - bool TryEnter(CCSPlayerController player); + /// + /// Enter this player into the warden queue + /// + /// + bool TryEnter(CCSPlayerController player); - /// - /// Remove this player from the warden queue - /// - /// - bool TryExit(CCSPlayerController player); + /// + /// Remove this player from the warden queue + /// + /// + bool TryExit(CCSPlayerController player); - /// - /// Determine whether this player is in the queue or not - /// - /// - /// - bool InQueue(CCSPlayerController player); + /// + /// Determine whether this player is in the queue or not + /// + /// + /// + bool InQueue(CCSPlayerController player); } \ 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 da8dbc59..b55a0091 100644 --- a/public/Jailbreak.Public/Mod/Warden/IWardenService.cs +++ b/public/Jailbreak.Public/Mod/Warden/IWardenService.cs @@ -3,23 +3,20 @@ namespace Jailbreak.Public.Mod.Warden; -public interface IWardenService -{ - public CCSPlayerController? Warden { get; } +public interface IWardenService { + public CCSPlayerController? Warden { get; } - /// - /// Whether or not a warden is currently assigned - /// - public bool HasWarden { get; } + /// + /// Whether or not a warden is currently assigned + /// + public bool HasWarden { get; } - public bool IsWarden(CCSPlayerController? player) - { - if (player == null || !player.IsReal()) - return false; - return HasWarden && Warden != null && Warden.Slot == player.Slot; - } + public bool IsWarden(CCSPlayerController? player) { + if (player == null || !player.IsReal()) return false; + return HasWarden && Warden != null && Warden.Slot == player.Slot; + } - public bool TrySetWarden(CCSPlayerController warden); + public bool TrySetWarden(CCSPlayerController warden); - public bool TryRemoveWarden(bool isPass = false); + public bool TryRemoveWarden(bool isPass = false); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Utils/FreezeManager.cs b/public/Jailbreak.Public/Utils/FreezeManager.cs index c702a0c6..7529d560 100644 --- a/public/Jailbreak.Public/Utils/FreezeManager.cs +++ b/public/Jailbreak.Public/Utils/FreezeManager.cs @@ -4,44 +4,34 @@ namespace Jailbreak.Public.Utils; -public class FreezeManager(BasePlugin plugin) -{ - private readonly Dictionary _frozenPlayers = []; - private static FreezeManager Manager; - private readonly BasePlugin _plugin = plugin; - - public static void CreateInstance(BasePlugin plugin) - { - Manager = new FreezeManager(plugin); - } - - public static void FreezePlayer(CCSPlayerController player, int delay) - { - if (!player.IsReal()) - return; - - if (Manager._frozenPlayers.ContainsKey(player)) - return; - - player.Freeze(); - - Manager._frozenPlayers.Add(player, Manager._plugin.AddTimer(delay, () => - { - player.UnFreeze(); - Manager._frozenPlayers.Remove(player); - })); - } - - public static void UnfreezePlayer(CCSPlayerController player) - { - if (!player.IsReal()) - return; - - if (!Manager._frozenPlayers.ContainsKey(player)) - return; - - Manager._frozenPlayers[player].Kill(); - Manager._frozenPlayers.Remove(player); - player.UnFreeze(); - } +public class FreezeManager(BasePlugin plugin) { + private static FreezeManager? _manager; + private readonly Dictionary frozenPlayers = []; + private readonly BasePlugin plugin = plugin; + + public static void CreateInstance(BasePlugin plugin) { + _manager = new FreezeManager(plugin); + } + + public static void FreezePlayer(CCSPlayerController player, int delay) { + if (!player.IsReal()) return; + + if (_manager!.frozenPlayers.ContainsKey(player)) return; + + player.Freeze(); + + _manager.frozenPlayers.Add(player, _manager.plugin.AddTimer(delay, () => { + player.UnFreeze(); + _manager.frozenPlayers.Remove(player); + })); + } + + public static void UnfreezePlayer(CCSPlayerController player) { + if (!player.IsReal()) return; + + if (!_manager!.frozenPlayers.TryGetValue(player, out var value)) return; + value.Kill(); + _manager.frozenPlayers.Remove(player); + player.UnFreeze(); + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Utils/TemporaryConvar.cs b/public/Jailbreak.Public/Utils/TemporaryConvar.cs index 265d418a..f4361167 100644 --- a/public/Jailbreak.Public/Utils/TemporaryConvar.cs +++ b/public/Jailbreak.Public/Utils/TemporaryConvar.cs @@ -2,23 +2,18 @@ namespace Jailbreak.Public.Utils; -public class TemporaryConvar : IDisposable -{ - private readonly ConVar _handle; - private readonly T _previousValue; +public class TemporaryConvar : IDisposable { + private readonly ConVar handle; + private readonly T previousValue; - 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 TemporaryConvar(string name, T value) { + handle = ConVar.Find(name) ?? throw new InvalidOperationException(); + if (handle == null) + throw new InvalidOperationException($"ConVar {name} does not exist!"); - _previousValue = _handle.GetPrimitiveValue(); - _handle.SetValue(value); - } + previousValue = handle.GetPrimitiveValue(); + handle.SetValue(value); + } - public void Dispose() - { - _handle.SetValue(_previousValue); - } + 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 4bffc03d..9925779b 100644 --- a/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs +++ b/src/Jailbreak.Generic/Coroutines/CoroutineManager.cs @@ -7,26 +7,22 @@ namespace Jailbreak.Generic.Coroutines; -public class CoroutineManager : ICoroutines, IPluginBehavior -{ - private readonly List _destroyOnRoundEnd = new(); +public class CoroutineManager : ICoroutines, IPluginBehavior { + private readonly List destroyOnRoundEnd = []; - public void Round(Action callback, float time = 10) - { - var timer = New(callback, time); - _destroyOnRoundEnd.Add(timer); - } + public void Round(Action callback, float time = 10) { + var timer = create(callback, time); + destroyOnRoundEnd.Add(timer); + } - private Timer New(Action callback, float time = 10) - { - return new Timer(time, callback, TimerFlags.STOP_ON_MAPCHANGE); - } + private Timer create(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()); + [GameEventHandler] + public HookResult OnRoundEnd(EventRoundEnd ev, GameEventInfo info) { + destroyOnRoundEnd.ForEach(timer => timer.Kill()); - return HookResult.Continue; - } + return HookResult.Continue; + } } \ No newline at end of file diff --git a/src/Jailbreak.Generic/GenericServiceExtension.cs b/src/Jailbreak.Generic/GenericServiceExtension.cs index 28fe83c5..6fe12cdb 100644 --- a/src/Jailbreak.Generic/GenericServiceExtension.cs +++ b/src/Jailbreak.Generic/GenericServiceExtension.cs @@ -7,16 +7,15 @@ namespace Jailbreak.Generic; -public static class GenericServiceExtension -{ - public static void AddJailbreakGeneric(this IServiceCollection serviceCollection) - { - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); - serviceCollection.AddPluginBehavior(); +public static class GenericServiceExtension { + 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 3c762bb6..24e82f5c 100644 --- a/src/Jailbreak.Generic/Jailbreak.Generic.csproj +++ b/src/Jailbreak.Generic/Jailbreak.Generic.csproj @@ -7,11 +7,7 @@ - - - - - + diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs index 7a77e8c3..b4ec991b 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/AliveStateTracker.cs @@ -4,17 +4,12 @@ namespace Jailbreak.Generic.PlayerState.Behaviors; -public class AliveStateTracker : BaseStateTracker, IPluginBehavior -{ - public void Start(BasePlugin parent) - { - } - - [GameEventHandler] - public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) - { - Reset(ev.Userid); - - return HookResult.Continue; - } +public class AliveStateTracker : BaseStateTracker, IPluginBehavior { + public void Start(BasePlugin basePlugin) { } + + [GameEventHandler] + public HookResult OnDeath(EventPlayerDeath ev, GameEventInfo info) { + if (ev.Userid != null) Reset(ev.Userid); + 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 40c4e01e..545e1875 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/BaseStateTracker.cs @@ -2,29 +2,22 @@ namespace Jailbreak.Generic.PlayerState.Behaviors; -public class BaseStateTracker : IDisposable -{ - private readonly List _trackedPlayerStates = new(); +public class BaseStateTracker : IDisposable { + private readonly List trackedPlayerStates = new(); - public void Dispose() - { - ResetAll(); - } + public void Dispose() { ResetAll(); } - protected void Reset(CCSPlayerController controller) - { - foreach (var trackedPlayerState in _trackedPlayerStates) - trackedPlayerState.Reset(controller); - } + protected void Reset(CCSPlayerController controller) { + foreach (var trackedPlayerState in trackedPlayerStates) + trackedPlayerState.Reset(controller); + } - protected void ResetAll() - { - foreach (var trackedPlayerState in _trackedPlayerStates) - trackedPlayerState.Drop(); - } + protected void ResetAll() { + foreach (var trackedPlayerState in trackedPlayerStates) + trackedPlayerState.Drop(); + } - public void Track(ITrackedPlayerState state) - { - _trackedPlayerStates.Add(state); - } + 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 718043c7..133ccbb2 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/GlobalStateTracker.cs @@ -4,33 +4,28 @@ namespace Jailbreak.Generic.PlayerState.Behaviors; -public class GlobalStateTracker : BaseStateTracker, IPluginBehavior -{ - public void Start(BasePlugin parent) - { - } +public class GlobalStateTracker : BaseStateTracker, IPluginBehavior { + public void Start(BasePlugin basePlugin) { } - /// - /// Disconnect handler to reset states on user leave - /// - /// - /// - [GameEventHandler] - public HookResult OnDisconnect(EventPlayerDisconnect ev, GameEventInfo info) - { - Reset(ev.Userid); - return HookResult.Continue; - } + /// + /// Disconnect handler to reset states on user leave + /// + /// + /// + [GameEventHandler] + public HookResult OnDisconnect(EventPlayerDisconnect ev, GameEventInfo info) { + if (ev.Userid != null) 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; - } -} + /// + /// Reset all global states when a new game starts + /// + /// + /// + /// + public HookResult OnGameEnd(EventGameEnd ev, GameEventInfo info) { + ResetAll(); + return HookResult.Continue; + } +} \ No newline at end of file diff --git a/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs b/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs index 8d9a74ea..9948ed33 100644 --- a/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs +++ b/src/Jailbreak.Generic/PlayerState/Behaviors/RoundStateTracker.cs @@ -4,17 +4,13 @@ namespace Jailbreak.Generic.PlayerState.Behaviors; -public class RoundStateTracker : BaseStateTracker, IPluginBehavior -{ - public void Start(BasePlugin parent) - { - } +public class RoundStateTracker : BaseStateTracker, IPluginBehavior { + public void Start(BasePlugin basePlugin) { } - [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 05bbd37d..b1431edc 100644 --- a/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs +++ b/src/Jailbreak.Generic/PlayerState/ITrackedPlayerState.cs @@ -2,16 +2,15 @@ namespace Jailbreak.Generic.PlayerState; -public interface ITrackedPlayerState -{ - /// - /// Reset a state for a specific player - /// - /// - void Reset(CCSPlayerController controller); +public interface ITrackedPlayerState { + /// + /// Reset a state for a specific player + /// + /// + void Reset(CCSPlayerController controller); - /// - /// Reset states for all players - /// - void Drop(); + /// + /// 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 d6e4b830..9ad67daa 100644 --- a/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs +++ b/src/Jailbreak.Generic/PlayerState/PlayerStateFactory.cs @@ -3,35 +3,31 @@ namespace Jailbreak.Generic.PlayerState; -public class PlayerStateFactory(GlobalStateTracker global, AliveStateTracker alive, RoundStateTracker round) - : IPlayerStateFactory -{ - public IPlayerState Global() where T : class, new() - { - var state = new PlayerStateImpl(); +public class PlayerStateFactory(GlobalStateTracker global, + AliveStateTracker alive, RoundStateTracker round) : IPlayerStateFactory { + 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 0dd1c4d2..611f2558 100644 --- a/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs +++ b/src/Jailbreak.Generic/PlayerState/PlayerStateImpl.cs @@ -4,25 +4,19 @@ namespace Jailbreak.Generic.PlayerState; public class PlayerStateImpl : IPlayerState, ITrackedPlayerState - where TState : class, new() -{ - private readonly Dictionary _states = new(); + where TState : class, 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 fb25a63b..60b572a1 100644 --- a/src/Jailbreak/Config/ConfigService.cs +++ b/src/Jailbreak/Config/ConfigService.cs @@ -7,62 +7,57 @@ namespace Jailbreak.Config; /// -/// A service to load and parse configuration files. +/// A service to load and parse configuration files. /// -public class ConfigService : IConfigService -{ - private readonly ILogger _logger; - - /// - /// Constructor - /// - /// - public ConfigService(ILogger logger) - { - _logger = logger; - } - - /// - /// - /// - /// - /// - /// - public T Get(string path, bool fail = false) - where T : class, new() - { - var jsonPath = Path.Combine(Server.GameDirectory, IConfigService.ConfigPath); - - if (!File.Exists(jsonPath)) - return Fail(fail, "Config file does not exist"); - - var jsonText = File.ReadAllText(jsonPath); - - var jsonObject = JsonNode.Parse(jsonText); - if (jsonObject == null) - return Fail(fail, $"Unable to parse configuration file at {jsonPath}"); - - var configObject = jsonObject[path]; - if (configObject == null) - return Fail(fail, $"Unable to navigate to config section {path}"); - - var config = configObject.Deserialize(); - if (config == null) - return Fail(fail, $"Unable to deserialize ({configObject.ToJsonString()}) into {typeof(T).FullName}."); - - return config; - } - - private T Fail(bool fail, string message) - where T : class, new() - { - // We would be returning default. - // Check if caller wants us to cry and scream instead. - if (fail) - throw new InvalidOperationException(message); - - _logger.LogWarning("[Config] Tripped load fail state with message: {@Message}", message); - - return new T(); - } +public class ConfigService : IConfigService { + private readonly ILogger logger; + + /// + /// Constructor + /// + /// + public ConfigService(ILogger logger) { this.logger = logger; } + + /// + /// + /// + /// + /// + /// + 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 = 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; + } + + // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local + 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 6f78f318..b4138395 100644 --- a/src/Jailbreak/Jailbreak.cs +++ b/src/Jailbreak/Jailbreak.cs @@ -1,7 +1,6 @@ using System.Collections.Immutable; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Capabilities; - using Jailbreak.Public; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Utils; @@ -11,92 +10,86 @@ namespace Jailbreak; /// -/// The classic Jail gamemode, ported to Counter-Strike 2. +/// The classic Jail gamemode, ported to Counter-Strike 2. /// -public class Jailbreak : BasePlugin -{ - private IReadOnlyList? _extensions; - - private readonly IServiceProvider _provider; - private IServiceScope? _scope = null; - - /// - /// The Jailbreak plugin. - /// - /// - public Jailbreak(IServiceProvider provider) - { - _provider = provider; - } +public class Jailbreak : BasePlugin { + private readonly IServiceProvider provider; + private IReadOnlyList? extensions; + private IServiceScope? scope; - /// - public override string ModuleName => "Jailbreak"; + /// + /// The Jailbreak plugin. + /// + /// + public Jailbreak(IServiceProvider provider) { this.provider = provider; } - /// - public override string ModuleVersion => $"{GitVersionInformation.SemVer} ({GitVersionInformation.ShortSha})"; + /// + public override string ModuleName => "Jailbreak"; - /// - public override string ModuleAuthor => "EdgeGamers Development"; + /// + public override string ModuleVersion + => $"{GitVersionInformation.SemVer} ({GitVersionInformation.ShortSha})"; - /// - public override void Load(bool hotReload) - { - RegisterListener((manifest) => - { - manifest.AddResource("particles/explosions_fx/explosion_c4_500.vpcf"); - manifest.AddResource("soundevents/soundevents_jb.vsndevts"); - manifest.AddResource("sounds/explosion.vsnd"); - manifest.AddResource("sounds/jihad.vsnd"); - }); - - // Load Managers - FreezeManager.CreateInstance(this); + /// + public override string ModuleAuthor => "EdgeGamers Development"; - Logger.LogInformation("[Jailbreak] Loading..."); + /// + public override void Load(bool hotReload) { + RegisterListener(manifest => { + manifest.AddResource("particles/explosions_fx/explosion_c4_500.vpcf"); + manifest.AddResource("soundevents/soundevents_jb.vsndevts"); + manifest.AddResource("sounds/explosion.vsnd"); + manifest.AddResource("sounds/jihad.vsnd"); + }); - _scope = _provider.CreateScope(); - _extensions = _scope.ServiceProvider.GetServices() - .ToImmutableList(); + // Load Managers + FreezeManager.CreateInstance(this); - Logger.LogInformation("[Jailbreak] Found {@BehaviorCount} behaviors.", _extensions.Count); + Logger.LogInformation("[Jailbreak] Loading..."); - foreach (var extension in _extensions) - { - // Register all event handlers on the extension object - RegisterAllAttributes(extension); + scope = provider.CreateScope(); + extensions = scope.ServiceProvider.GetServices() + .ToImmutableList(); - // Tell the extension to start it's magic - extension.Start(this); + Logger.LogInformation("[Jailbreak] Found {@BehaviorCount} behaviors.", + extensions.Count); - Logger.LogInformation("[Jailbreak] Loaded behavior {@Behavior}", extension.GetType().FullName); - } + foreach (var extension in extensions) { + // Register all event handlers on the extension object + RegisterAllAttributes(extension); - // Expose the scope to other plugins - Capabilities.RegisterPluginCapability(API.Provider, () => - { - if (this._scope == null) - throw new InvalidOperationException("Jailbreak does not have a running scope! Is the jailbreak plugin loaded?"); + // Tell the extension to start it's magic + extension.Start(this); - return this._scope.ServiceProvider; - }); - - base.Load(hotReload); + Logger.LogInformation("[Jailbreak] Loaded behavior {@Behavior}", + extension.GetType().FullName); } - /// - public override void Unload(bool hotReload) - { - Logger.LogInformation("[Jailbreak] Shutting down..."); + // Expose the scope to other plugins + Capabilities.RegisterPluginCapability(API.Provider, () => { + if (scope == null) + throw new InvalidOperationException( + "Jailbreak does not have a running scope! Is the jailbreak plugin loaded?"); - if (_extensions != null) - foreach (var extension in _extensions) - extension.Dispose(); + return scope.ServiceProvider; + }); - // Dispose of original extensions scope - // When loading again we will get a new scope to avoid leaking state. - _scope?.Dispose(); - _scope = null; + base.Load(hotReload); + } - base.Unload(hotReload); - } -} + /// + public override void Unload(bool hotReload) { + Logger.LogInformation("[Jailbreak] Shutting down..."); + + 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(); + scope = null; + + base.Unload(hotReload); + } +} \ No newline at end of file diff --git a/src/Jailbreak/Jailbreak.csproj b/src/Jailbreak/Jailbreak.csproj index 37a221bf..50fefe89 100644 --- a/src/Jailbreak/Jailbreak.csproj +++ b/src/Jailbreak/Jailbreak.csproj @@ -18,7 +18,7 @@ true - + true @@ -30,7 +30,7 @@ false true - + $(GitVersion_ToolArgments) /verbosity Normal $(GitVersion_ToolArgments) /overrideconfig mode=ContinuousDelivery $(GitVersion_ToolArgments) /overrideconfig assembly-file-versioning-format="{SemVer}" @@ -45,7 +45,7 @@ $(MSBuildThisFileDirectory)/../../build $(PublishBaseDirectory)/Jailbreak - + false false true @@ -56,28 +56,27 @@ - - - - - - - - - - + + + + + + + + + + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + - + diff --git a/src/Jailbreak/JailbreakServiceCollection.cs b/src/Jailbreak/JailbreakServiceCollection.cs index 5f7ebbbe..417567d1 100644 --- a/src/Jailbreak/JailbreakServiceCollection.cs +++ b/src/Jailbreak/JailbreakServiceCollection.cs @@ -1,6 +1,4 @@ -using System.Reflection; - -using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Core; using Jailbreak.Config; using Jailbreak.Debug; using Jailbreak.English.Generic; @@ -24,39 +22,36 @@ 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(); - serviceCollection.AddJailbreakGeneric(); - serviceCollection.AddJailbreakLogs(); - serviceCollection.AddJailbreakRebel(); - serviceCollection.AddJailbreakMute(); - serviceCollection.AddJailbreakWarden(); - serviceCollection.AddJailbreakDebug(); - serviceCollection.AddJailbreakLastRequest(); - serviceCollection.AddJailbreakLastGuard(); +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(); + serviceCollection.AddJailbreakGeneric(); + serviceCollection.AddJailbreakLogs(); + serviceCollection.AddJailbreakRebel(); + serviceCollection.AddJailbreakMute(); + serviceCollection.AddJailbreakWarden(); + serviceCollection.AddJailbreakDebug(); + serviceCollection.AddJailbreakLastRequest(); + serviceCollection.AddJailbreakLastGuard(); - // Add in english localization - serviceCollection.AddLanguage(config => - { - config.WithGenericCommand(); - config.WithWarden(); - config.WithRebel(); - config.WithLogging(); - config.WithRollCommand(); - config.WithJihadC4(); - config.WithLastRequest(); - config.WithSpecialTreatment(); - config.WithMute(); - config.WithRaceLR(); - config.WithLastGuard(); - }); - } -} + // Add in english localization + serviceCollection.AddLanguage(config => { + config.WithGenericCommand(); + config.WithWarden(); + config.WithRebel(); + config.WithLogging(); + config.WithRollCommand(); + config.WithJihadC4(); + config.WithLastRequest(); + config.WithSpecialTreatment(); + config.WithMute(); + config.WithRaceLR(); + config.WithLastGuard(); + }); + } +} \ No newline at end of file From c5e9ec7813160aad6e5d428c86c84074fadf5278 Mon Sep 17 00:00:00 2001 From: ShookEagle <163607647+ShookEagle@users.noreply.github.com> Date: Wed, 10 Jul 2024 22:05:53 -0500 Subject: [PATCH 21/27] fixes (#215) Co-authored-by: Isaac --- .../Listeners/LogEntityParentListeners.cs | 37 +++++++------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 875e6fc4..66e6586d 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -26,26 +26,17 @@ public void Start(BasePlugin _parent) { OnEntityParentChanged); } - /*public void Dispose() - { - parent.RemoveListener("OnEntityParentChanged", OnEntityParentChanged); - }*/ - public void OnEntityParentChanged(CEntityInstance affectedEntity, - CEntityInstance newParent) { - if (!affectedEntity.IsValid - || !WEAPON_STRINGS.Contains(affectedEntity.DesignerName)) - return; + parent.RegisterListener(OnEntityParentChanged); + } + public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) + { + if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; - var weaponEntity = - Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null || weaponEntity.PrevOwner == null) return; + var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); + if (weaponEntity == null || weaponEntity.PrevOwner.Get().OriginalController.Get() == null) return; - var weaponOwner = - Utilities.GetEntityFromIndex( - (int)weaponEntity.PrevOwner.Index); - if (weaponOwner == null) return; - Server.PrintToChatAll($"{weaponOwner.PlayerName}"); - Server.PrintToChatAll($"{(int)weaponEntity.PrevOwner.Index}"); + var weaponOwner = weaponEntity.PrevOwner.Get().OriginalController.Get(); + if (weaponOwner == null) return; if (!newParent.IsValid) //a.k.a parent is world { @@ -54,11 +45,9 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, return; } - var weaponPickerUpper = - Utilities.GetEntityFromIndex((int)newParent.Index); - if (weaponPickerUpper == null) return; + var weaponPickerUpper = Utilities.GetEntityFromIndex((int)newParent.Index).OriginalController.Get(); + if (weaponPickerUpper == null) return; - logs.Append(logs.Player(weaponPickerUpper), "picked up", - logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString}"); - } + _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString()}"); + } } \ No newline at end of file From e0c2db090242f4109c31bd4ba80f0ec667bced32 Mon Sep 17 00:00:00 2001 From: Isaac Date: Tue, 9 Jul 2024 14:54:42 -0700 Subject: [PATCH 22/27] Re-apply JSON upgrade --- public/Jailbreak.Public/Jailbreak.Public.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/Jailbreak.Public/Jailbreak.Public.csproj b/public/Jailbreak.Public/Jailbreak.Public.csproj index bd6c370b..cc1b91a1 100644 --- a/public/Jailbreak.Public/Jailbreak.Public.csproj +++ b/public/Jailbreak.Public/Jailbreak.Public.csproj @@ -8,7 +8,7 @@ - + From 3f441b3796ee4b80076bf96df5a02e725b3e5a0b Mon Sep 17 00:00:00 2001 From: MSWS Date: Wed, 10 Jul 2024 20:08:28 -0700 Subject: [PATCH 23/27] Fix build errors --- .../Listeners/LogEntityParentListeners.cs | 37 ++++++++++++------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 66e6586d..c1ffd149 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -24,19 +24,27 @@ public void Start(BasePlugin _parent) { .RegisterListener< CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( OnEntityParentChanged); + + _parent + .RegisterListener< + CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( + OnEntityParentChanged); } - parent.RegisterListener(OnEntityParentChanged); - } - public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstance newParent) - { - if (!affectedEntity.IsValid || !weaponStrings.Contains(affectedEntity.DesignerName)) return; + public void OnEntityParentChanged(CEntityInstance affectedEntity, + CEntityInstance newParent) { + if (!affectedEntity.IsValid + || !WEAPON_STRINGS.Contains(affectedEntity.DesignerName)) + return; - var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); - if (weaponEntity == null || weaponEntity.PrevOwner.Get().OriginalController.Get() == null) return; + var weaponEntity = + Utilities.GetEntityFromIndex((int)affectedEntity.Index); + if (weaponEntity == null + || weaponEntity.PrevOwner.Get().OriginalController.Get() == null) + return; - var weaponOwner = weaponEntity.PrevOwner.Get().OriginalController.Get(); - if (weaponOwner == null) return; + var weaponOwner = weaponEntity.PrevOwner.Get().OriginalController.Get(); + if (weaponOwner == null) return; if (!newParent.IsValid) //a.k.a parent is world { @@ -45,9 +53,12 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, CEntityInstanc return; } - var weaponPickerUpper = Utilities.GetEntityFromIndex((int)newParent.Index).OriginalController.Get(); - if (weaponPickerUpper == null) return; + var weaponPickerUpper = Utilities + .GetEntityFromIndex((int)newParent.Index) + .OriginalController.Get(); + if (weaponPickerUpper == null) return; - _logs.Append(_logs.Player(weaponPickerUpper), "picked up", _logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString()}"); - } + logs.Append(logs.Player(weaponPickerUpper), "picked up", + logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString()}"); + } } \ No newline at end of file From b311af332bf81cd06e84859d59b76eddd891f088 Mon Sep 17 00:00:00 2001 From: MSWS Date: Wed, 10 Jul 2024 20:11:32 -0700 Subject: [PATCH 24/27] Remove duplicate registration --- .../Listeners/LogEntityParentListeners.cs | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index c1ffd149..31505b29 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -24,11 +24,6 @@ public void Start(BasePlugin _parent) { .RegisterListener< CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( OnEntityParentChanged); - - _parent - .RegisterListener< - CounterStrikeSharp.API.Core.Listeners.OnEntityParentChanged>( - OnEntityParentChanged); } public void OnEntityParentChanged(CEntityInstance affectedEntity, @@ -40,13 +35,13 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, var weaponEntity = Utilities.GetEntityFromIndex((int)affectedEntity.Index); if (weaponEntity == null - || weaponEntity.PrevOwner.Get().OriginalController.Get() == null) + || weaponEntity.PrevOwner.Get()?.OriginalController.Get() == null) return; - var weaponOwner = weaponEntity.PrevOwner.Get().OriginalController.Get(); + var weaponOwner = weaponEntity.PrevOwner.Get()?.OriginalController.Get(); if (weaponOwner == null) return; - if (!newParent.IsValid) //a.k.a parent is world + if (!newParent.IsValid) // a.k.a parent is world { logs.Append(logs.Player(weaponOwner), $"dropped their {weaponEntity.ToFriendlyString}"); @@ -55,10 +50,10 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, var weaponPickerUpper = Utilities .GetEntityFromIndex((int)newParent.Index) - .OriginalController.Get(); + ?.OriginalController.Get(); if (weaponPickerUpper == null) return; - logs.Append(logs.Player(weaponPickerUpper), "picked up", + logs.Append(weaponPickerUpper, "picked up", logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString()}"); } } \ No newline at end of file From 36376820aca98108e07006f5576dbd444c7c45a8 Mon Sep 17 00:00:00 2001 From: ShookEagle <163607647+ShookEagle@users.noreply.github.com> Date: Wed, 10 Jul 2024 22:30:42 -0500 Subject: [PATCH 25/27] cleanup actually this time (#218) * cleanup actually this time * ms is bullying me :( jk --- .../Listeners/LogEntityParentListeners.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 31505b29..6276a252 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -44,7 +44,7 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, if (!newParent.IsValid) // a.k.a parent is world { logs.Append(logs.Player(weaponOwner), - $"dropped their {weaponEntity.ToFriendlyString}"); + $"dropped their {weaponEntity.ToFriendlyString()}"); return; } @@ -53,7 +53,11 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, ?.OriginalController.Get(); if (weaponPickerUpper == null) return; - logs.Append(weaponPickerUpper, "picked up", - logs.Player(weaponOwner), $"'s {weaponEntity.ToFriendlyString()}"); + if (weaponPickerUpper == weaponOwner) + { + logs.Append(weaponPickerUpper, $"picked up their {weaponEntity.ToFriendlyString()}"); + return; + } + logs.Append(weaponPickerUpper, "picked up", logs.Player(weaponOwner), $"{weaponEntity.ToFriendlyString()}"); } } \ No newline at end of file From 7eec75c97d5fa725344bb6e259fb36e72f4328c0 Mon Sep 17 00:00:00 2001 From: MSWS Date: Thu, 11 Jul 2024 13:06:11 -0700 Subject: [PATCH 26/27] Cleanup, move Formatting into same Jailbreak DotSettings --- Formatting.DotSettings | 82 ----- Jailbreak.sln.DotSettings | 81 +++++ mod/Jailbreak.Draw/Jailbreak.Draw.csproj | 14 - mod/Jailbreak.Teams/Jailbreak.Teams.csproj | 14 - mod/Jailbreak.Teams/Queue/QueueBehavior.cs | 320 ------------------- mod/Jailbreak.Teams/Queue/QueueState.cs | 21 -- mod/Jailbreak.Teams/Ratio/RatioBehavior.cs | 117 ------- mod/Jailbreak.Teams/Ratio/RatioConfig.cs | 22 -- mod/Jailbreak.Teams/TeamsServiceExtension.cs | 18 -- 9 files changed, 81 insertions(+), 608 deletions(-) delete mode 100644 Formatting.DotSettings delete mode 100644 mod/Jailbreak.Draw/Jailbreak.Draw.csproj delete mode 100644 mod/Jailbreak.Teams/Jailbreak.Teams.csproj delete mode 100644 mod/Jailbreak.Teams/Queue/QueueBehavior.cs delete mode 100644 mod/Jailbreak.Teams/Queue/QueueState.cs delete mode 100644 mod/Jailbreak.Teams/Ratio/RatioBehavior.cs delete mode 100644 mod/Jailbreak.Teams/Ratio/RatioConfig.cs delete mode 100644 mod/Jailbreak.Teams/TeamsServiceExtension.cs diff --git a/Formatting.DotSettings b/Formatting.DotSettings deleted file mode 100644 index 01c99f3b..00000000 --- a/Formatting.DotSettings +++ /dev/null @@ -1,82 +0,0 @@ - - Built-in: Full Cleanup - public private override virtual file new abstract internal protected sealed static readonly extern unsafe volatile async required - Remove - 0 - END_OF_LINE - END_OF_LINE - False - False - True - END_OF_LINE - END_OF_LINE - TOGETHER_SAME_LINE - False - True - True - True - True - True - True - INDENT - 2 - END_OF_LINE - True - True - True - True - True - True - END_OF_LINE - False - False - False - False - False - False - False - False - False - 10 - 5 - 5 - 10 - 5 - COMPACT - END_OF_LINE - True - True - NEVER - NEVER - False - False - NEVER - False - False - NEVER - True - True - True - False - 2 - END_OF_LINE - False - True - True - False - CHOP_IF_LONG - CHOP_IF_LONG - WRAP_IF_LONG - 80 - WRAP_IF_LONG - True - API - <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, ProtectedInternal, Internal, PrivateProtected" Description="Non-Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> - <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> - <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> - <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> - <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> - <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, Public, FileLocal" Description="Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> - <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> - <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> - <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> \ No newline at end of file diff --git a/Jailbreak.sln.DotSettings b/Jailbreak.sln.DotSettings index 6b68132e..256efc9f 100644 --- a/Jailbreak.sln.DotSettings +++ b/Jailbreak.sln.DotSettings @@ -1,7 +1,88 @@  + Built-in: Full Cleanup + public private override virtual file new abstract internal protected sealed static readonly extern unsafe volatile async required + Remove + 0 + END_OF_LINE + END_OF_LINE + False + False + True + END_OF_LINE + END_OF_LINE + TOGETHER_SAME_LINE + False + True + True + True + True + True + True + INDENT + 2 + END_OF_LINE + True + True + True + True + True + True + END_OF_LINE + False + False + False + False + False + False + False + False + False + 10 + 5 + 5 + 10 + 5 + COMPACT + END_OF_LINE + True + True + NEVER + NEVER + False + False + NEVER + False + False + NEVER + True + True + True + False + 2 + END_OF_LINE + False + True + True + False + CHOP_IF_LONG + CHOP_IF_LONG + WRAP_IF_LONG + 80 + WRAP_IF_LONG + True + API IO LR ST + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, ProtectedInternal, Internal, PrivateProtected" Description="Non-Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, Public, FileLocal" Description="Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> diff --git a/mod/Jailbreak.Draw/Jailbreak.Draw.csproj b/mod/Jailbreak.Draw/Jailbreak.Draw.csproj deleted file mode 100644 index af27e9c6..00000000 --- a/mod/Jailbreak.Draw/Jailbreak.Draw.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net7.0 - enable - enable - Jailbreak.Drawable - - - - - - - diff --git a/mod/Jailbreak.Teams/Jailbreak.Teams.csproj b/mod/Jailbreak.Teams/Jailbreak.Teams.csproj deleted file mode 100644 index 7997b564..00000000 --- a/mod/Jailbreak.Teams/Jailbreak.Teams.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - - diff --git a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs b/mod/Jailbreak.Teams/Queue/QueueBehavior.cs deleted file mode 100644 index bf23c043..00000000 --- a/mod/Jailbreak.Teams/Queue/QueueBehavior.cs +++ /dev/null @@ -1,320 +0,0 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Admin; -using CounterStrikeSharp.API.Modules.Commands; -using CounterStrikeSharp.API.Modules.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.Teams; -using Microsoft.Extensions.Logging; - -namespace Jailbreak.Teams.Queue; - -public class QueueBehavior : IGuardQueue, IPluginBehavior -{ - private int _counter; - private readonly ILogger _logger; - - private readonly IRatioNotifications _notifications; - private readonly IPlayerState _state; - private BasePlugin _parent; - - 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.NOT_ENOUGH_GUARDS.ToAllChat(); - _notifications.PLEASE_JOIN_GUARD_QUEUE.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.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(); - } - - 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) - { - _parent = 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 (!state.IsGuard) - _parent.AddTimer(0.1f, () => - { - if (!invoked.IsReal()) - return; - if (invoked.GetTeam() != CsTeam.CounterTerrorist) - return; - _notifications.ATTEMPT_TO_JOIN_FROM_TEAM_MENU - .ToPlayerChat(invoked) - .ToPlayerCenter(invoked); - invoked.ChangeTeam(CsTeam.Terrorist); - }); - - if (!int.TryParse(command.ArgByIndex(1), out var team)) - return HookResult.Stop; - - if (Utilities.GetPlayers().All(c => c.GetTeam() != CsTeam.CounterTerrorist)) - return HookResult.Continue; // If no CTs, let anyone on CT team - - // Force player to prisoner if they attempt to join prisoners - // Allows for uncapped prisoners regardless of maps - if ((CsTeam)team == CsTeam.Terrorist ) - { - // Apparently ChangeTeam doesn't kill them here, - // so we need to force the suicide. ~ Moo - if (invoked.GetTeam() == CsTeam.CounterTerrorist) - invoked.CommitSuicide(/* explode: */ true, true); - - invoked.ChangeTeam(CsTeam.Terrorist); - } - - // 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; - } - - // Prisoner attempted to use auto-select, cancel the action. - if ((CsTeam)team == CsTeam.None && invoked.GetTeam() == CsTeam.Terrorist) - { - _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 (TryExitQueue(player)) - _notifications.LEFT_GUARD - .ToPlayerCenter(player) - .ToPlayerChat(player); - - return HookResult.Continue; - } - - private void HandleQueueRequest(CCSPlayerController player) - { - if (TryEnterQueue(player)) - _notifications.JOINED_GUARD_QUEUE - .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); - else - player.PrintToCenter("An error occured removing you from the queue."); - } - - [ConsoleCommand("css_guard", "Joins the guard queue")] - [ConsoleCommand("css_g", "Joins the guard queue")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Guard(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - if (player.AuthorizedSteamID == null) - { - player.PrintToCenter("Steam has not yet authorized you. Please try again later."); - return; - } - - // AdminData? data = AdminManager.GetPlayerAdminData(player.AuthorizedSteamID!); - - // if (data == null || !data.Groups.Contains("#ego/e")) - // { - // player.PrintToCenter("You must be an =(e)= to join the guard queue. Apply at https://edgm.rs/join"); - // return; - // } - - HandleQueueRequest(player); - } - - [ConsoleCommand("css_leave", "Leaves the guard queue")] - [CommandHelper(0, "", CommandUsage.CLIENT_ONLY)] - public void Command_Leave(CCSPlayerController? player, CommandInfo command) - { - if (player == null) - return; - HandleLeaveRequest(player); - } -} diff --git a/mod/Jailbreak.Teams/Queue/QueueState.cs b/mod/Jailbreak.Teams/Queue/QueueState.cs deleted file mode 100644 index 71f76235..00000000 --- a/mod/Jailbreak.Teams/Queue/QueueState.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Jailbreak.Teams.Queue; - -public class QueueState -{ - /// - /// 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 - /// - 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. - /// - 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 deleted file mode 100644 index a400d03f..00000000 --- a/mod/Jailbreak.Teams/Ratio/RatioBehavior.cs +++ /dev/null @@ -1,117 +0,0 @@ -using CounterStrikeSharp.API; -using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Core.Attributes.Registration; -using CounterStrikeSharp.API.Modules.Cvars; -using CounterStrikeSharp.API.Modules.Entities.Constants; -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; - -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() - { - - } -} diff --git a/mod/Jailbreak.Teams/Ratio/RatioConfig.cs b/mod/Jailbreak.Teams/Ratio/RatioConfig.cs deleted file mode 100644 index 6bd6f942..00000000 --- a/mod/Jailbreak.Teams/Ratio/RatioConfig.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Jailbreak.Teams.Ratio; - -public class RatioConfig -{ - /// - /// 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. - /// - public double Maximum { get; set; } = 4; - - /// - /// 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 deleted file mode 100644 index 21fbab08..00000000 --- a/mod/Jailbreak.Teams/TeamsServiceExtension.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Jailbreak.Public.Extensions; -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"); - - collection.AddPluginBehavior(); - collection.AddPluginBehavior(); - } -} \ No newline at end of file From 8d991b78308da58f460adcabde5f5c88ee8893c5 Mon Sep 17 00:00:00 2001 From: MSWS Date: Thu, 11 Jul 2024 19:48:57 -0700 Subject: [PATCH 27/27] More cleanup --- Jailbreak.sln.DotSettings | 5 + .../LastGuard/LastGuardNotifications.cs | 4 +- .../LastRequest/LastRequestMessages.cs | 16 ++ .../LastRequest/RaceLRMessages.cs | 16 ++ lang/Jailbreak.English/Mute/PeaceMessages.cs | 4 +- .../Rebel/JihadC4Notifications.cs | 8 - .../Warden/SpecialTreatmentNotifications.cs | 2 +- .../Warden/WardenNotifications.cs | 38 ++-- .../Subcommands/AbstractCommand.cs | 15 +- .../Subcommands/LastRequest.cs | 35 ++-- mod/Jailbreak.LastGuard/LastGuard.cs | 170 +++++++++--------- mod/Jailbreak.LastRequest/EndRaceCommand.cs | 10 +- .../LastRequestCommand.cs | 30 ++-- .../LastRequestManager.cs | 71 ++++---- .../LastRequestPlayerSelector.cs | 13 +- .../Listeners/LogEntityParentListeners.cs | 12 +- mod/Jailbreak.Logs/LogsManager.cs | 17 +- mod/Jailbreak.Logs/LogsServiceExtension.cs | 16 +- mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs | 26 ++- mod/Jailbreak.Mute/MuteSystem.cs | 20 +-- .../Commands/PeaceCommandsBehavior.cs | 2 +- .../Commands/RollCommandBehavior.cs | 2 +- .../SpecialTreatmentCommandsBehavior.cs | 2 +- .../Commands/WardenCommandsBehavior.cs | 18 +- .../WardenFormatWriterExtensions.cs | 3 - mod/Jailbreak.Warden/Global/WardenBehavior.cs | 10 +- .../Markers/WardenMarkerBehavior.cs | 5 +- .../Paint/WardenPaintBehavior.cs | 6 +- .../Selection/WardenSelectionBehavior.cs | 4 +- .../SpecialTreatmentBehavior.cs | 2 +- .../Views/ILastGuardNotifications.cs | 2 +- .../Views/ILastRequestMessages.cs | 2 + .../Views/ILogMessages.cs | 2 +- .../Views/IRaceLRMessages.cs | 4 + .../Views/IWardenNotifications.cs | 30 ++-- .../Extensions/WeaponExtensions.cs | 124 ++++++++----- .../Jailbreak.Public/Jailbreak.Public.csproj | 4 +- 37 files changed, 399 insertions(+), 351 deletions(-) delete mode 100644 mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs diff --git a/Jailbreak.sln.DotSettings b/Jailbreak.sln.DotSettings index 256efc9f..f2391294 100644 --- a/Jailbreak.sln.DotSettings +++ b/Jailbreak.sln.DotSettings @@ -72,6 +72,7 @@ True API IO + LG LR ST <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, ProtectedInternal, Internal, PrivateProtected" Description="Non-Public Methods"><ElementKinds><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> @@ -83,6 +84,10 @@ <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static readonly fields (not private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></Policy> + True + True + True + True diff --git a/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs b/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs index 31cf64aa..73a8d838 100644 --- a/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs +++ b/lang/Jailbreak.English/LastGuard/LastGuardNotifications.cs @@ -9,14 +9,14 @@ namespace Jailbreak.English.LastGuard; public class LastGuardNotifications : ILastGuardNotifications, ILanguage { - public static readonly FormatObject PREFIX = + private static readonly FormatObject PREFIX = new HiddenFormatObject( $" {ChatColors.DarkRed}[{ChatColors.LightRed}Last Guard{ChatColors.DarkRed}]") { // Hide in panorama and center text Plain = false, Panorama = false, Chat = true }; - public IView LG_STARTED(int ctHealth, int tHealth) { + public IView LGStarted(int ctHealth, int tHealth) { return new SimpleView { PREFIX, $"{ChatColors.Red}Last Guard has been activated! Last guard has", diff --git a/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs b/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs index a25e4aca..324a5f2c 100644 --- a/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs +++ b/lang/Jailbreak.English/LastRequest/LastRequestMessages.cs @@ -89,6 +89,22 @@ public IView LastRequestDecided(AbstractLastRequest lr, LRResult result) { }; } + public IView CannotLR(string reason) { + return new SimpleView { + PREFIX, + $"{ChatColors.Red}You cannot LR: {ChatColors.White + reason + ChatColors.Red}." + }; + } + + public IView CannotLR(CCSPlayerController player, string reason) { + return new SimpleView { + PREFIX, + ChatColors.Red + "You cannot LR", + player, + ": " + ChatColors.White + reason + ChatColors.Red + "." + }; + } + public IView DamageBlockedInsideLastRequest => new SimpleView { PREFIX, "You or they are in LR, damage blocked." }; diff --git a/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs b/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs index 7fd52796..6f80ea4f 100644 --- a/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs +++ b/lang/Jailbreak.English/LastRequest/RaceLRMessages.cs @@ -34,4 +34,20 @@ public IView RaceStartingMessage(CCSPlayerController prisoner) { } }; } + + public IView NotInRaceLR() + => new SimpleView { + { + LastRequestMessages.PREFIX, + $"You must be in a race {ChatColors.Blue + "!lr" + ChatColors.White} to use this command" + } + }; + + public IView NotInPendingState() + => new SimpleView { + { + LastRequestMessages.PREFIX, + "You must be in the pending state to use this command." + } + }; } \ No newline at end of file diff --git a/lang/Jailbreak.English/Mute/PeaceMessages.cs b/lang/Jailbreak.English/Mute/PeaceMessages.cs index 96a0fcb9..46dc2ba8 100644 --- a/lang/Jailbreak.English/Mute/PeaceMessages.cs +++ b/lang/Jailbreak.English/Mute/PeaceMessages.cs @@ -17,13 +17,13 @@ public class PeaceMessages : IPeaceMessages, public IView PeaceEnactedByAdmin(int seconds) { return new SimpleView { - PREFIX, "An admin has enacted peace for", seconds, "seconds." + PREFIX, "An admin enacted peace for", seconds, "seconds." }; } public IView WardenEnactedPeace(int seconds) { return new SimpleView { - PREFIX, "Warden has enacted peace for", seconds, "seconds." + PREFIX, "Warden enacted peace for", seconds, "seconds." }; } diff --git a/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs b/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs index b9a42880..6c99ecb6 100644 --- a/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs +++ b/lang/Jailbreak.English/Rebel/JihadC4Notifications.cs @@ -7,7 +7,6 @@ namespace Jailbreak.English.Rebel; public class JihadC4Notifications : IJihadC4Notifications, ILanguage { - // public IView JIHAD_C4_DROPPED => new SimpleView { RebelNotifications.PREFIX, "You dropped your Jihad C4!" }; public IView JihadC4Pickup => new SimpleView { RebelNotifications.PREFIX, "You picked up a Jihad C4!" @@ -21,11 +20,4 @@ public IView JihadC4Usage1 RebelNotifications.PREFIX, $"To detonate it, hold it out and press {ChatColors.Yellow + "E" + ChatColors.Default}." }; - // public IView JIHAD_C4_USAGE2 => new SimpleView { RebelNotifications.PREFIX, $"You can drop the C4 to other players with {ChatColors.Yellow + "G" + ChatColors.Default}." }; - - - // public IView PlayerDetonateC4(CCSPlayerController player) - // { - // return new SimpleView { RebelNotifications.PREFIX, $"{player.PlayerName} has detonated a Jihad C4!" }; - // } } \ No newline at end of file diff --git a/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs b/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs index 1b5cd05a..69bd087f 100644 --- a/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs +++ b/lang/Jailbreak.English/Warden/SpecialTreatmentNotifications.cs @@ -33,7 +33,7 @@ public IView GrantedTo(CCSPlayerController player) { return new SimpleView { PREFIX, player, - $"now has {ChatColors.Grey}Special Treatment{ChatColors.White}!" + $"now has {ChatColors.Green}Special Treatment{ChatColors.White}!" }; } diff --git a/lang/Jailbreak.English/Warden/WardenNotifications.cs b/lang/Jailbreak.English/Warden/WardenNotifications.cs index a772cea4..8ecba9ce 100644 --- a/lang/Jailbreak.English/Warden/WardenNotifications.cs +++ b/lang/Jailbreak.English/Warden/WardenNotifications.cs @@ -17,7 +17,7 @@ public class WardenNotifications : IWardenNotifications, Plain = false, Panorama = false, Chat = true }; - public IView PICKING_SHORTLY + public IView PickingShortly => new SimpleView { { PREFIX, $"{ChatColors.Grey}Picking a warden shortly..." }, SimpleView.NEWLINE, { @@ -26,59 +26,59 @@ public IView PICKING_SHORTLY } }; - public IView NO_WARDENS + public IView NoWardens => new SimpleView { PREFIX, $"No wardens in queue! The next player to run {ChatColors.Blue}!warden{ChatColors.White} will become a warden." }; - public IView WARDEN_LEFT + public IView WardenLeft => new SimpleView { PREFIX, "The warden has left the game." }; - public IView WARDEN_DIED + public IView WardenDied => new SimpleView { PREFIX, $"{ChatColors.Red}The warden has {ChatColors.DarkRed}died{ChatColors.Red}! CTs must pursue {ChatColors.Blue}!warden{ChatColors.Red}." }; - public IView BECOME_NEXT_WARDEN + public IView BecomeNextWarden => new SimpleView { PREFIX, $"{ChatColors.Grey}Type {ChatColors.Blue}!warden{ChatColors.Grey} to become the next warden" }; - public IView JOIN_RAFFLE + public IView JoinRaffle => new SimpleView { PREFIX, $"{ChatColors.Grey}You've {ChatColors.Green}joined {ChatColors.Grey}the warden raffle." }; - public IView LEAVE_RAFFLE + public IView LeaveRaffle => new SimpleView { PREFIX, $"{ChatColors.Grey}You've {ChatColors.Red}left {ChatColors.Grey}the warden raffle." }; - public IView NOT_WARDEN + public IView NotWarden => new SimpleView { PREFIX, $"{ChatColors.LightRed}You are not the warden." }; - public IView FIRE_COMMAND_FAILED + public IView FireCommandFailed => new SimpleView { PREFIX, "The fire command has failed to work for some unknown reason..." }; - public IView PASS_WARDEN(CCSPlayerController player) { + public IView PassWarden(CCSPlayerController player) { return new SimpleView { PREFIX, player, "resigned from being warden." }; } - public IView FIRE_WARDEN(CCSPlayerController player) { + public IView FireWarden(CCSPlayerController player) { return new SimpleView { PREFIX, player, "was fired from being warden." }; } - public IView FIRE_WARDEN(CCSPlayerController player, - CCSPlayerController admin) { + public IView + FireWarden(CCSPlayerController player, CCSPlayerController admin) { return new SimpleView { PREFIX, admin, @@ -88,17 +88,17 @@ public IView FIRE_WARDEN(CCSPlayerController player, }; } - public IView NEW_WARDEN(CCSPlayerController player) { + public IView NewWarden(CCSPlayerController player) { return new SimpleView { PREFIX, player, "is now the warden!" }; } - public IView CURRENT_WARDEN(CCSPlayerController? player) { - if (player is not null) - return new SimpleView { PREFIX, "The warden is", player, "." }; - return new SimpleView { PREFIX, "There is no warden." }; + public IView CurrentWarden(CCSPlayerController? player) { + return player is not null ? + new SimpleView { PREFIX, "The warden is", player, "." } : + new SimpleView { PREFIX, "There is no warden." }; } - public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player) { + public IView FireCommandSuccess(CCSPlayerController player) { return new SimpleView { PREFIX, player, "was fired and is no longer the warden." }; diff --git a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs index 3afa1ae8..b75e57fc 100644 --- a/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs +++ b/mod/Jailbreak.Debug/Subcommands/AbstractCommand.cs @@ -75,14 +75,11 @@ public abstract void OnCommand(CCSPlayerController? executor, return null; } - if (matches.Count() > 1) { - if (command.CallingPlayer != null) - lang.PlayerFoundMultiple(command.GetArg(argIndex)) - .ToPlayerChat(command.CallingPlayer); - return null; - } - - return matches; + if (matches.Count() <= 1) return matches; + if (command.CallingPlayer != null) + lang.PlayerFoundMultiple(command.GetArg(argIndex)) + .ToPlayerChat(command.CallingPlayer); + return null; } protected string GetTargetLabel(WrappedInfo info, int argIndex = 1) { @@ -126,7 +123,7 @@ protected string GetTargetLabels(WrappedInfo info, int argIndex = 1) { protected string GetTargetLabels(CommandInfo info, int argIndex = 1) { var label = GetTargetLabel(info, argIndex); - if (label.ToLower().EndsWith("s")) return label + "'"; + if (label.ToLower().EndsWith('s')) return label + "'"; return label + "'s"; } } diff --git a/mod/Jailbreak.Debug/Subcommands/LastRequest.cs b/mod/Jailbreak.Debug/Subcommands/LastRequest.cs index e1534f32..4fdabdf2 100644 --- a/mod/Jailbreak.Debug/Subcommands/LastRequest.cs +++ b/mod/Jailbreak.Debug/Subcommands/LastRequest.cs @@ -35,22 +35,25 @@ public override void OnCommand(CCSPlayerController? executor, WrappedInfo info) { if (executor == null || !executor.IsReal()) return; - if (info.ArgCount == 1) { - MenuManager.OpenCenterHtmlMenu(plugin, executor, menuSelector.GetMenu()); - return; - } + switch (info.ArgCount) { + case 1: + MenuManager.OpenCenterHtmlMenu(plugin, executor, + menuSelector.GetMenu()); + return; + case 2: + switch (info.GetArg(1).ToLower()) { + case "enable": + manager.EnableLR(); + info.ReplyToCommand("Last Request enabled."); + return; + case "disable": + manager.DisableLR(); + info.ReplyToCommand("Last Request disabled."); + return; + } - if (info.ArgCount == 2) - switch (info.GetArg(1).ToLower()) { - case "enable": - manager.EnableLR(); - info.ReplyToCommand("Last Request enabled."); - return; - case "disable": - manager.DisableLR(); - info.ReplyToCommand("Last Request disabled."); - return; - } + break; + } var type = LRTypeExtensions.FromString(info.GetArg(1)); if (type is null) { @@ -69,7 +72,7 @@ public override void OnCommand(CCSPlayerController? executor, if (fromPlayer == null) return; switch (info.ArgCount) { - case 3 when executor != null: { + case 3: { if (executor.Team == CsTeam.Terrorist) manager.InitiateLastRequest(executor, fromPlayer.First(), type.Value); else // They aren't necessarily on different teams, but this is debug so that's OK diff --git a/mod/Jailbreak.LastGuard/LastGuard.cs b/mod/Jailbreak.LastGuard/LastGuard.cs index 7654a885..cdc98a06 100644 --- a/mod/Jailbreak.LastGuard/LastGuard.cs +++ b/mod/Jailbreak.LastGuard/LastGuard.cs @@ -11,84 +11,94 @@ namespace Jailbreak.LastGuard; -public class LastGuard(LastGuardConfig config, ILastGuardNotifications notifications, ILastRequestManager lrManager) - : ILastGuardService, IPluginBehavior -{ - private bool canStart; - - [GameEventHandler] - public HookResult OnPlayerDeathEvent(EventPlayerDeath @event, GameEventInfo info) - { - checkLastGuard(@event.Userid); - return HookResult.Continue; - } - - [GameEventHandler] - public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) - { - checkLastGuard(@event.Userid); - return HookResult.Continue; - } - - private void checkLastGuard(CCSPlayerController? poi) - { - if (poi == null) return; - if (poi.Team != CsTeam.CounterTerrorist) return; - var aliveCts = Utilities.GetPlayers() - .Count(plr => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }) - 1; - - if (aliveCts != 1 || lrManager.IsLREnabled) return; - var lastGuard = Utilities.GetPlayers().First(plr => - plr.IsReal() && plr != poi && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }); - - if (canStart) - StartLastGuard(lastGuard); - } - - [GameEventHandler] - public HookResult OnRoundStartEvent(EventRoundStart @event, GameEventInfo info) - { - canStart = Utilities.GetPlayers() - .Count(plr => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.CounterTerrorist }) >= - config.MinimumCTs; - return HookResult.Continue; - } - - public int CalculateHealth() - { - var aliveTerrorists = Utilities.GetPlayers() - .Where(plr => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.Terrorist }).ToList(); - - return aliveTerrorists.Select(player => player.PlayerPawn?.Value?.Health ?? 0) - .Select(playerHealth => (int)(Math.Min(playerHealth, 200) * 0.8)).Sum(); - } - - public void StartLastGuard(CCSPlayerController lastGuard) - { - var guardPlayerPawn = lastGuard.PlayerPawn.Value; - - if (guardPlayerPawn == null || !guardPlayerPawn.IsValid) return; - - var guardCalcHealth = CalculateHealth(); - - guardPlayerPawn.Health = guardCalcHealth; - Utilities.SetStateChanged(guardPlayerPawn, "CBaseEntity", "m_iHealth"); - - // foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) - // player.ExecuteClientCommand("play sounds/lastct"); - - var aliveTerrorists = Utilities.GetPlayers() - .Where(p => p.IsReal() && p is { PawnIsAlive: true, Team: CsTeam.Terrorist }).ToList(); - - var prisonerHp = aliveTerrorists.Sum(prisoner => prisoner.PlayerPawn?.Value?.Health ?? 0); - - notifications.LG_STARTED(guardCalcHealth, prisonerHp).ToAllCenter().ToAllChat(); - - if (string.IsNullOrEmpty(config.LastGuardWeapon)) return; - - foreach (var player in aliveTerrorists) - { - player.GiveNamedItem(config.LastGuardWeapon); - } - } +public class LastGuard(LastGuardConfig config, + ILastGuardNotifications notifications, ILastRequestManager lrManager) + : ILastGuardService, IPluginBehavior { + private bool canStart; + + public int CalculateHealth() { + var aliveTerrorists = Utilities.GetPlayers() + .Where(plr + => plr.IsReal() && plr is { PawnIsAlive: true, Team: CsTeam.Terrorist }) + .ToList(); + + return aliveTerrorists + .Select(player => player.PlayerPawn?.Value?.Health ?? 0) + .Select(playerHealth => (int)(Math.Min(playerHealth, 200) * 0.8)) + .Sum(); + } + + public void StartLastGuard(CCSPlayerController lastGuard) { + var guardPlayerPawn = lastGuard.PlayerPawn.Value; + + if (guardPlayerPawn == null || !guardPlayerPawn.IsValid) return; + + var guardCalcHealth = CalculateHealth(); + + guardPlayerPawn.Health = guardCalcHealth; + Utilities.SetStateChanged(guardPlayerPawn, "CBaseEntity", "m_iHealth"); + + // foreach (var player in Utilities.GetPlayers().Where(p => p.IsReal())) + // player.ExecuteClientCommand("play sounds/lastct"); + + var aliveTerrorists = Utilities.GetPlayers() + .Where(p + => p.IsReal() && p is { PawnIsAlive: true, Team: CsTeam.Terrorist }) + .ToList(); + + var prisonerHp = + aliveTerrorists.Sum(prisoner => prisoner.PlayerPawn?.Value?.Health ?? 0); + + notifications.LGStarted(guardCalcHealth, prisonerHp) + .ToAllCenter() + .ToAllChat(); + + if (string.IsNullOrEmpty(config.LastGuardWeapon)) return; + + foreach (var player in aliveTerrorists) + player.GiveNamedItem(config.LastGuardWeapon); + } + + [GameEventHandler] + public HookResult OnPlayerDeathEvent(EventPlayerDeath @event, + GameEventInfo info) { + checkLastGuard(@event.Userid); + return HookResult.Continue; + } + + [GameEventHandler] + public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, + GameEventInfo info) { + checkLastGuard(@event.Userid); + return HookResult.Continue; + } + + private void checkLastGuard(CCSPlayerController? poi) { + if (poi == null) return; + if (poi.Team != CsTeam.CounterTerrorist) return; + var aliveCts = Utilities.GetPlayers() + .Count(plr + => plr.IsReal() && plr is { + PawnIsAlive: true, Team: CsTeam.CounterTerrorist + }) - 1; + + if (aliveCts != 1 || lrManager.IsLREnabled) return; + var lastGuard = Utilities.GetPlayers() + .First(plr => plr.IsReal() && plr != poi && plr is { + PawnIsAlive: true, Team: CsTeam.CounterTerrorist + }); + + if (canStart) StartLastGuard(lastGuard); + } + + [GameEventHandler] + public HookResult OnRoundStartEvent(EventRoundStart @event, + GameEventInfo info) { + canStart = Utilities.GetPlayers() + .Count(plr + => plr.IsReal() && plr is { + PawnIsAlive: true, Team: CsTeam.CounterTerrorist + }) >= config.MinimumCTs; + return HookResult.Continue; + } } \ No newline at end of file diff --git a/mod/Jailbreak.LastRequest/EndRaceCommand.cs b/mod/Jailbreak.LastRequest/EndRaceCommand.cs index 958bf106..53ba6440 100644 --- a/mod/Jailbreak.LastRequest/EndRaceCommand.cs +++ b/mod/Jailbreak.LastRequest/EndRaceCommand.cs @@ -1,13 +1,16 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Commands; +using Jailbreak.Formatting.Extensions; +using Jailbreak.Formatting.Views; using Jailbreak.Public.Behaviors; using Jailbreak.Public.Mod.LastRequest; using Jailbreak.Public.Mod.LastRequest.Enums; namespace Jailbreak.LastRequest; -public class EndRaceCommand(ILastRequestManager lrManager) : IPluginBehavior { +public class EndRaceCommand(ILastRequestManager lrManager, + IRaceLRMessages messages) : IPluginBehavior { [ConsoleCommand("css_endrace", "Used to set the end point of a race LR")] [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] public void Command_EndRace(CCSPlayerController? executor, CommandInfo info) { @@ -15,13 +18,12 @@ public void Command_EndRace(CCSPlayerController? executor, CommandInfo info) { var lr = lrManager.GetActiveLR(executor); if (lr is not { Type: LRType.RACE }) { - info.ReplyToCommand("You must be in a race LR to use this command."); + messages.NotInRaceLR().ToPlayerChat(executor); return; } if (lr.State != LRState.PENDING) { - info.ReplyToCommand( - "You must be in the pending state to use this command."); + messages.NotInPendingState().ToPlayerChat(executor); return; } diff --git a/mod/Jailbreak.LastRequest/LastRequestCommand.cs b/mod/Jailbreak.LastRequest/LastRequestCommand.cs index acaaee77..d01994ff 100644 --- a/mod/Jailbreak.LastRequest/LastRequestCommand.cs +++ b/mod/Jailbreak.LastRequest/LastRequestCommand.cs @@ -31,28 +31,29 @@ public void Start(BasePlugin basePlugin) { public void Command_LastRequest(CCSPlayerController? executor, CommandInfo info) { if (executor == null || !executor.IsReal()) return; - if (executor.Team != CsTeam.Terrorist) { - info.ReplyToCommand("You must be a terrorist to LR."); + if (!manager.IsLREnabled) { + messages.LastRequestNotEnabled().ToPlayerChat(executor); return; } - if (!executor.PawnIsAlive) { - info.ReplyToCommand("You must be alive to LR."); + if (executor.Team != CsTeam.Terrorist) { + messages.CannotLR("You are not a Prisoner").ToPlayerChat(executor); return; } - if (!manager.IsLREnabled) { - messages.LastRequestNotEnabled().ToPlayerChat(executor); + if (!executor.PawnIsAlive) { + messages.CannotLR("You are not alive").ToPlayerChat(executor); return; } + if (!playerSelector!.WouldHavePlayers()) { - info.ReplyToCommand("There are no players available to LR."); + messages.CannotLR("No players available to LR").ToPlayerChat(executor); return; } if (manager.IsInLR(executor)) { - info.ReplyToCommand("You are already in an LR!"); + messages.CannotLR("You are already in an LR").ToPlayerChat(executor); return; } @@ -89,23 +90,18 @@ public void Command_LastRequest(CCSPlayerController? executor, var player = target.Players.First(); if (player.Team != CsTeam.CounterTerrorist) { - messages.InvalidPlayerChoice(player, "They're not on CT!"); + messages.CannotLR(player, "They are not a Guard").ToPlayerChat(executor); return; } if (!player.PawnIsAlive) { - messages.InvalidPlayerChoice(player, "They're not alive!"); + messages.CannotLR(player, "They are not alive").ToPlayerChat(executor); return; } if (manager.IsInLR(player)) { - messages.InvalidPlayerChoice(player, "They're already in an LR!"); - return; - } - - //One final check in case they got the menu open in the last round - if (!manager.IsLREnabled) { - messages.LastRequestNotEnabled().ToPlayerChat(executor); + messages.CannotLR(player, "They are already in an LR") + .ToPlayerChat(executor); return; } diff --git a/mod/Jailbreak.LastRequest/LastRequestManager.cs b/mod/Jailbreak.LastRequest/LastRequestManager.cs index 0e5c19c3..a563eecf 100644 --- a/mod/Jailbreak.LastRequest/LastRequestManager.cs +++ b/mod/Jailbreak.LastRequest/LastRequestManager.cs @@ -31,14 +31,13 @@ public bool ShouldBlockDamage(CCSPlayerController player, // Neither of them is in an LR return false; - if (playerLR == null != (attackerLR == null)) { + if ((playerLR == null) != (attackerLR == null)) { // One of them is in an LR messages.DamageBlockedInsideLastRequest.ToPlayerCenter(attacker); return true; } - // Both of them are in LR - // verify they're in same LR + // Both of them are in LR, verify they're in same LR if (playerLR == null) return false; if (playerLR.Prisoner.Equals(attacker) || playerLR.Guard.Equals(attacker)) @@ -75,31 +74,25 @@ public void EnableLR(CCSPlayerController? died = null) { public bool InitiateLastRequest(CCSPlayerController prisoner, CCSPlayerController guard, LRType type) { - try { - var lr = factory!.CreateLastRequest(prisoner, guard, type); - lr.Setup(); - ActiveLRs.Add(lr); - - if (prisoner.Pawn.Value != null) { - prisoner.Pawn.Value.Health = 100; - prisoner.PlayerPawn.Value!.ArmorValue = 0; - Utilities.SetStateChanged(prisoner.Pawn.Value, "CBaseEntity", - "m_iHealth"); - } - - - if (guard.Pawn.Value != null) { - guard.Pawn.Value.Health = 100; - guard.PlayerPawn.Value!.ArmorValue = 0; - Utilities.SetStateChanged(guard.Pawn.Value, "CBaseEntity", "m_iHealth"); - } + var lr = factory!.CreateLastRequest(prisoner, guard, type); + lr.Setup(); + ActiveLRs.Add(lr); + + if (prisoner.Pawn.Value != null) { + prisoner.Pawn.Value.Health = 100; + prisoner.PlayerPawn.Value!.ArmorValue = 0; + Utilities.SetStateChanged(prisoner.Pawn.Value, "CBaseEntity", + "m_iHealth"); + } - messages.InformLastRequest(lr).ToAllChat(); - return true; - } catch (ArgumentException e) { - Console.WriteLine(e); - return false; + if (guard.Pawn.Value != null) { + guard.Pawn.Value.Health = 100; + guard.PlayerPawn.Value!.ArmorValue = 0; + Utilities.SetStateChanged(guard.Pawn.Value, "CBaseEntity", "m_iHealth"); } + + messages.InformLastRequest(lr).ToAllChat(); + return true; } public bool EndLastRequest(AbstractLastRequest lr, LRResult result) { @@ -156,11 +149,11 @@ public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) { if (IsLREnabled) { // Handle active LRs var activeLr = ((ILastRequestManager)this).GetActiveLR(player); - if (activeLr != null && activeLr.State != LRState.COMPLETED) { - var isPrisoner = activeLr.Prisoner.Slot == player.Slot; - EndLastRequest(activeLr, - isPrisoner ? LRResult.GUARD_WIN : LRResult.PRISONER_WIN); - } + if (activeLr == null || activeLr.State == LRState.COMPLETED) + return HookResult.Continue; + var isPrisoner = activeLr.Prisoner.Slot == player.Slot; + EndLastRequest(activeLr, + isPrisoner ? LRResult.GUARD_WIN : LRResult.PRISONER_WIN); return HookResult.Continue; } @@ -184,15 +177,15 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, if (!player.IsReal() || ServerExtensions.GetGameRules().WarmupPeriod) return HookResult.Continue; - if (IsLREnabled) return HookResult.Continue; - - var activeLr = ((ILastRequestManager)this).GetActiveLR(player); + if (IsLREnabled) { + var activeLr = ((ILastRequestManager)this).GetActiveLR(player); + if (activeLr != null) { + EndLastRequest(activeLr, + player.Team == CsTeam.Terrorist ? + LRResult.GUARD_WIN : + LRResult.PRISONER_WIN); + } - if (activeLr != null && activeLr.State != LRState.ACTIVE) { - EndLastRequest(activeLr, - player.Team == CsTeam.Terrorist ? - LRResult.GUARD_WIN : - LRResult.PRISONER_WIN); return HookResult.Continue; } diff --git a/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs b/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs index fb1cf0a6..a984fcbc 100644 --- a/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs +++ b/mod/Jailbreak.LastRequest/LastRequestPlayerSelector.cs @@ -13,13 +13,12 @@ public CenterHtmlMenu CreateMenu(CCSPlayerController player, Func command) { var menu = new CenterHtmlMenu(command.Invoke("[Player]"), plugin); - foreach (var target in Utilities.GetPlayers()) { - if (!target.IsReal()) continue; - if (!target.PawnIsAlive - || target.Team != CsTeam.CounterTerrorist && !debug) - continue; + foreach (var target in Utilities.GetPlayers() + .Where(target => target.IsReal()) + .Where(target => target.PawnIsAlive + && (target.Team == CsTeam.CounterTerrorist || debug))) { menu.AddMenuOption(target.PlayerName, - (_, _) => OnSelect(player, command, target.UserId.ToString()), + (_, _) => onSelect(player, command, target.UserId.ToString()), !debug && manager.IsInLR(target)); } @@ -33,7 +32,7 @@ public bool WouldHavePlayers() { }); } - private void OnSelect(CCSPlayerController player, + private void onSelect(CCSPlayerController player, Func command, string? value) { MenuManager.CloseActiveMenu(player); player.ExecuteClientCommandFromServer(command.Invoke(value)); diff --git a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs index 6276a252..9ca9d771 100644 --- a/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs +++ b/mod/Jailbreak.Logs/Listeners/LogEntityParentListeners.cs @@ -53,11 +53,13 @@ public void OnEntityParentChanged(CEntityInstance affectedEntity, ?.OriginalController.Get(); if (weaponPickerUpper == null) return; - if (weaponPickerUpper == weaponOwner) - { - logs.Append(weaponPickerUpper, $"picked up their {weaponEntity.ToFriendlyString()}"); - return; + if (weaponPickerUpper == weaponOwner) { + logs.Append(weaponPickerUpper, + $"picked up their {weaponEntity.ToFriendlyString()}"); + return; } - logs.Append(weaponPickerUpper, "picked up", logs.Player(weaponOwner), $"{weaponEntity.ToFriendlyString()}"); + + logs.Append(weaponPickerUpper, "picked up", logs.Player(weaponOwner), + $"{weaponEntity.ToFriendlyString()}"); } } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/LogsManager.cs b/mod/Jailbreak.Logs/LogsManager.cs index 8676dcd7..10f76f43 100644 --- a/mod/Jailbreak.Logs/LogsManager.cs +++ b/mod/Jailbreak.Logs/LogsManager.cs @@ -11,19 +11,12 @@ namespace Jailbreak.Logs; -public class LogsManager : IPluginBehavior, IRichLogService { +public class LogsManager(ILogMessages messages, IRichPlayerTag richPlayerTag) + : IPluginBehavior, IRichLogService { private readonly List logMessages = []; - private readonly ILogMessages messages; - - private readonly IRichPlayerTag richPlayerTag; - - public LogsManager(ILogMessages messages, IRichPlayerTag richPlayerTag) { - this.messages = messages; - this.richPlayerTag = richPlayerTag; - } public void Append(string message) { - logMessages.Add(messages.CREATE_LOG(message)); + logMessages.Add(messages.CreateLog(message)); } public IEnumerable GetMessages() { @@ -37,7 +30,6 @@ public void PrintLogs(CCSPlayerController? player) { messages.BeginJailbreakLogs.ToServerConsole(); foreach (var log in logMessages) log.ToServerConsole(); messages.EndJailbreakLogs.ToServerConsole(); - return; } @@ -48,7 +40,7 @@ public void PrintLogs(CCSPlayerController? player) { } public void Append(params FormatObject[] objects) { - logMessages.Add(messages.CREATE_LOG(objects)); + logMessages.Add(messages.CreateLog(objects)); } public FormatObject Player(CCSPlayerController playerController) { @@ -67,7 +59,6 @@ public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) { foreach (var log in logMessages) log.ToServerConsole().ToAllConsole(); messages.EndJailbreakLogs.ToServerConsole().ToAllConsole(); - return HookResult.Continue; } diff --git a/mod/Jailbreak.Logs/LogsServiceExtension.cs b/mod/Jailbreak.Logs/LogsServiceExtension.cs index caa470ef..cc64d2ba 100644 --- a/mod/Jailbreak.Logs/LogsServiceExtension.cs +++ b/mod/Jailbreak.Logs/LogsServiceExtension.cs @@ -13,15 +13,15 @@ public static void AddJailbreakLogs(this IServiceCollection services) { services.AddTransient(provider => provider.GetRequiredService()); - services.AddPluginBehavior(); + services.AddPluginBehavior(); - services.AddPluginBehavior(); - services.AddPluginBehavior(); - services.AddPluginBehavior(); + services.AddPluginBehavior(); + services.AddPluginBehavior(); + services.AddPluginBehavior(); - // PlayerTagHelper is a lower-level class that avoids dependency loops. - services.AddTransient(); - services.AddTransient(); - } + // PlayerTagHelper is a lower-level class that avoids dependency loops. + services.AddTransient(); + services.AddTransient(); + } } \ No newline at end of file diff --git a/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs b/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs index ac29d73d..87c1e178 100644 --- a/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs +++ b/mod/Jailbreak.Logs/Tags/PlayerTagHelper.cs @@ -10,21 +10,17 @@ namespace Jailbreak.Logs.Tags; -public class PlayerTagHelper : IRichPlayerTag { - private readonly Lazy rebelService; - private readonly Lazy stService; - private readonly Lazy wardenService; - - public PlayerTagHelper(IServiceProvider provider) { - // Lazy-load dependencies to avoid loops, since we are a lower-level class. - wardenService = - new Lazy(provider.GetRequiredService); - rebelService = - new Lazy(provider.GetRequiredService); - stService = - new Lazy(provider - .GetRequiredService); - } +public class PlayerTagHelper(IServiceProvider provider) : IRichPlayerTag { + private readonly Lazy rebelService = + new(provider.GetRequiredService); + + private readonly Lazy stService = + new(provider.GetRequiredService); + + private readonly Lazy wardenService = + new(provider.GetRequiredService); + + // Lazy-load dependencies to avoid loops, since we are a lower-level class. public FormatObject Rich(CCSPlayerController player) { if (wardenService.Value.IsWarden(player)) diff --git a/mod/Jailbreak.Mute/MuteSystem.cs b/mod/Jailbreak.Mute/MuteSystem.cs index 7c89be7f..fb9f8cab 100644 --- a/mod/Jailbreak.Mute/MuteSystem.cs +++ b/mod/Jailbreak.Mute/MuteSystem.cs @@ -162,18 +162,16 @@ private void OnPlayerSpeak(int playerSlot) { return; } - if (bypassMute(player)) { - // Warn admins if they're not muted - if (IsPeaceEnabled()) { - if (player.Team == CsTeam.CounterTerrorist - && DateTime.Now >= ctPeaceEnd) - return; - messages!.PeaceReminder.ToPlayerCenter(player); - } - - if (!player.PawnIsAlive) - messages!.AdminDeadReminder.ToPlayerCenter(player); + if (!bypassMute(player)) return; + + // Warn admins if they're not muted + if (IsPeaceEnabled()) { + if (player.Team == CsTeam.CounterTerrorist && DateTime.Now >= ctPeaceEnd) + return; + messages!.PeaceReminder.ToPlayerCenter(player); } + + if (!player.PawnIsAlive) messages!.AdminDeadReminder.ToPlayerCenter(player); } private bool isMuted(CCSPlayerController player) { diff --git a/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs index f4c34414..93189832 100644 --- a/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/PeaceCommandsBehavior.cs @@ -32,7 +32,7 @@ public void Command_Peace(CCSPlayerController? executor, CommandInfo info) { if (!warden.IsWarden(executor) && !AdminManager.PlayerHasPermissions(executor, "@css/chat")) { - notifications.NOT_WARDEN.ToPlayerChat(executor); + notifications.NotWarden.ToPlayerChat(executor); return; } diff --git a/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs b/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs index 49ae9c1b..293b5f6e 100644 --- a/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/RollCommandBehavior.cs @@ -21,7 +21,7 @@ public void Command_Toggle(CCSPlayerController? player, CommandInfo command) { if (player == null) return; if (!warden.IsWarden(player)) { - wardenNotifications.NOT_WARDEN.ToPlayerChat(player); + wardenNotifications.NotWarden.ToPlayerChat(player); return; } diff --git a/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs index 10e09fb9..b62390ee 100644 --- a/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/SpecialTreatmentCommandsBehavior.cs @@ -21,7 +21,7 @@ public void Command_Toggle(CCSPlayerController? player, CommandInfo command) { if (player == null) return; if (!warden.IsWarden(player)) { - wardenNotifs.NOT_WARDEN.ToPlayerChat(player).ToPlayerConsole(player); + wardenNotifs.NotWarden.ToPlayerChat(player).ToPlayerConsole(player); return; } diff --git a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs index 77d0f7a6..69e859cc 100644 --- a/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs +++ b/mod/Jailbreak.Warden/Commands/WardenCommandsBehavior.cs @@ -34,14 +34,14 @@ public void Command_Pass(CCSPlayerController? player, CommandInfo command) { if (!warden.IsWarden(player)) return; // Handle warden pass - notifications.PASS_WARDEN(player).ToAllChat().ToAllCenter(); + notifications.PassWarden(player).ToAllChat().ToAllCenter(); // GetPlayers() returns valid players, no need to error check here. foreach (var clients in Utilities.GetPlayers()) clients.ExecuteClientCommand( $"play sounds/{config.WardenPassedSoundName}"); - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + notifications.BecomeNextWarden.ToAllChat(); if (!warden.TryRemoveWarden(true)) Server.PrintToChatAll("[BUG] Couldn't remove warden :^("); @@ -55,7 +55,7 @@ public void Command_Fire(CCSPlayerController? player, CommandInfo command) { if (player == null) return; if (!warden.HasWarden || warden.Warden == null) { - notifications.CURRENT_WARDEN(null).ToPlayerChat(player); + notifications.CurrentWarden(null).ToPlayerChat(player); return; } @@ -66,15 +66,15 @@ public void Command_Fire(CCSPlayerController? player, CommandInfo command) { foreach (var client in Utilities.GetPlayers().Where(p => p.IsReal())) { if (AdminManager.PlayerHasPermissions(client, "@css/chat")) - notifications.FIRE_WARDEN(warden.Warden, player).ToPlayerChat(client); + notifications.FireWarden(warden.Warden, player).ToPlayerChat(client); else - notifications.FIRE_WARDEN(warden.Warden).ToPlayerChat(client); + notifications.FireWarden(warden.Warden).ToPlayerChat(client); client.ExecuteClientCommand( $"play sounds/{config.WardenPassedSoundName}"); } - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + notifications.BecomeNextWarden.ToAllChat(); lastPassCommand[warden.Warden] = DateTime.Now; @@ -106,13 +106,13 @@ public void Command_Warden(CCSPlayerController? player, CommandInfo command) { if (queue.Active) { if (!queue.InQueue(player)) { if (queue.TryEnter(player)) - notifications.JOIN_RAFFLE.ToPlayerChat(player); + notifications.JoinRaffle.ToPlayerChat(player); return; } if (queue.InQueue(player)) if (queue.TryExit(player)) - notifications.LEAVE_RAFFLE.ToPlayerChat(player); + notifications.LeaveRaffle.ToPlayerChat(player); return; } @@ -122,7 +122,7 @@ public void Command_Warden(CCSPlayerController? player, CommandInfo command) { if (warden.TrySetWarden(player)) return; - notifications.CURRENT_WARDEN(warden.Warden).ToPlayerChat(player); + notifications.CurrentWarden(warden.Warden).ToPlayerChat(player); } /// diff --git a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs b/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs deleted file mode 100644 index 2736bc3c..00000000 --- a/mod/Jailbreak.Warden/Extensions/WardenFormatWriterExtensions.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace Jailbreak.Warden.Extensions; - -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 4bd7b2bb..fe562321 100644 --- a/mod/Jailbreak.Warden/Global/WardenBehavior.cs +++ b/mod/Jailbreak.Warden/Global/WardenBehavior.cs @@ -71,7 +71,7 @@ public bool TrySetWarden(CCSPlayerController controller) { "m_clrRender"); } - notifications.NEW_WARDEN(Warden).ToAllChat().ToAllCenter(); + notifications.NewWarden(Warden).ToAllChat().ToAllCenter(); Warden.PlayerName = "[WARDEN] " + Warden.PlayerName; @@ -175,7 +175,7 @@ private void processWardenDeath() { logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); // Warden died! - notifications.WARDEN_DIED.ToAllChat().ToAllCenter(); + notifications.WardenDied.ToAllChat().ToAllCenter(); foreach (var player in Utilities.GetPlayers()) { if (!player.IsReal()) continue; @@ -183,7 +183,7 @@ private void processWardenDeath() { $"play sounds/{config.WardenKilledSoundName}"); } - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + notifications.BecomeNextWarden.ToAllChat(); unblueTimer ?.Kill(); // If the warden dies withing 3 seconds of becoming warden, we need to cancel the unblue timer @@ -331,7 +331,7 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, logger.LogWarning("[Warden] BUG: Problem removing current warden :^("); - notifications.WARDEN_LEFT.ToAllChat().ToAllCenter(); + notifications.WardenLeft.ToAllChat().ToAllCenter(); foreach (var player in Utilities.GetPlayers()) { if (!player.IsReal()) continue; @@ -339,7 +339,7 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect ev, $"play sounds/{config.WardenPassedSoundName}"); } - notifications.BECOME_NEXT_WARDEN.ToAllChat(); + notifications.BecomeNextWarden.ToAllChat(); return HookResult.Continue; } diff --git a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs index 9a53d367..44322422 100644 --- a/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs +++ b/mod/Jailbreak.Warden/Markers/WardenMarkerBehavior.cs @@ -9,9 +9,8 @@ namespace Jailbreak.Warden.Markers; -public class WardenMarkerBehavior : IPluginBehavior { +public class WardenMarkerBehavior(IWardenService warden) : IPluginBehavior { private const float MIN_RADIUS = 60f, MAX_RADIUS = 360f; - private readonly IWardenService warden; private Vector? currentPos; @@ -19,8 +18,6 @@ public class WardenMarkerBehavior : IPluginBehavior { private long placementTime; private float radius = MIN_RADIUS; - public WardenMarkerBehavior(IWardenService warden) { this.warden = warden; } - public void Start(BasePlugin basePlugin) { marker = new BeamCircle(basePlugin, new Vector(), 60f, (int)Math.PI * 15); basePlugin.AddCommandListener("player_ping", CommandListener_PlayerPing); diff --git a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs index aaa6dae3..a6cc2805 100644 --- a/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs +++ b/mod/Jailbreak.Warden/Paint/WardenPaintBehavior.cs @@ -8,13 +8,11 @@ namespace Jailbreak.Warden.Paint; -public class WardenPaintBehavior : IPluginBehavior { - private readonly IWardenService wardenService; +public class WardenPaintBehavior(IWardenService wardenService) + : IPluginBehavior { private Vector? lastPosition; private BasePlugin? parent; - public WardenPaintBehavior(IWardenService warden) { wardenService = warden; } - public void Start(BasePlugin basePlugin) { parent = basePlugin; basePlugin.RegisterListener(paint); diff --git a/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs b/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs index 49d4295a..4046965a 100644 --- a/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs +++ b/mod/Jailbreak.Warden/Selection/WardenSelectionBehavior.cs @@ -82,7 +82,7 @@ public HookResult OnRoundStart(EventRoundStart ev, GameEventInfo info) { // Enable the warden queue queueInactive = false; - notifications.PICKING_SHORTLY.ToAllChat(); + notifications.PickingShortly.ToAllChat(); // Start a timer to pick the warden in 7 seconds ScheduleChooseWarden(); @@ -109,7 +109,7 @@ protected void OnChooseWarden() { eligible); if (eligible.Count == 0) { - notifications.NO_WARDENS.ToAllChat(); + notifications.NoWardens.ToAllChat(); queueInactive = true; return; diff --git a/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs b/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs index 01ab46e7..04719a47 100644 --- a/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs +++ b/mod/Jailbreak.Warden/SpecialTreatment/SpecialTreatmentBehavior.cs @@ -27,7 +27,7 @@ public void Grant(CCSPlayerController player) { sts.Get(player).HasSpecialTreatment = true; if (rebel.IsRebel(player)) rebel.UnmarkRebel(player); - setSpecialColor(player, /* hasSt */ true); + setSpecialColor(player, true); notifications.Granted.ToPlayerChat(player).ToPlayerCenter(player); diff --git a/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs b/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs index 421f4bc8..a4e09405 100644 --- a/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs +++ b/public/Jailbreak.Formatting/Views/ILastGuardNotifications.cs @@ -3,5 +3,5 @@ namespace Jailbreak.Formatting.Views; public interface ILastGuardNotifications { - public IView LG_STARTED(int ctHealth, int tHealth); + public IView LGStarted(int ctHealth, int tHealth); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs b/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs index da40c182..0006e376 100644 --- a/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs +++ b/public/Jailbreak.Formatting/Views/ILastRequestMessages.cs @@ -16,4 +16,6 @@ public interface ILastRequestMessages { public IView InformLastRequest(AbstractLastRequest lr); public IView AnnounceLastRequest(AbstractLastRequest lr); public IView LastRequestDecided(AbstractLastRequest lr, LRResult result); + public IView CannotLR(string reason); + public IView CannotLR(CCSPlayerController player, string reason); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/ILogMessages.cs b/public/Jailbreak.Formatting/Views/ILogMessages.cs index be462cde..e9c72fdd 100644 --- a/public/Jailbreak.Formatting/Views/ILogMessages.cs +++ b/public/Jailbreak.Formatting/Views/ILogMessages.cs @@ -24,7 +24,7 @@ public FormatObject Time() { return new StringFormatObject($"[{minutes}:{seconds}]", ChatColors.Gold); } - public IView CREATE_LOG(params FormatObject[] objects) { + public IView CreateLog(params FormatObject[] objects) { return new SimpleView { Time(), objects }; } } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs b/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs index ecdaf4c3..a909abd5 100644 --- a/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs +++ b/public/Jailbreak.Formatting/Views/IRaceLRMessages.cs @@ -7,4 +7,8 @@ public interface IRaceLRMessages { public IView EndRaceInstruction { get; } public IView RaceStartingMessage(CCSPlayerController prisoner); + + public IView NotInRaceLR(); + + public IView NotInPendingState(); } \ No newline at end of file diff --git a/public/Jailbreak.Formatting/Views/IWardenNotifications.cs b/public/Jailbreak.Formatting/Views/IWardenNotifications.cs index bb23b6ed..ae5e0815 100644 --- a/public/Jailbreak.Formatting/Views/IWardenNotifications.cs +++ b/public/Jailbreak.Formatting/Views/IWardenNotifications.cs @@ -6,29 +6,29 @@ 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 NOT_WARDEN { get; } - public IView FIRE_COMMAND_FAILED { 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; } + public IView NotWarden { get; } + public IView FireCommandFailed { get; } /// /// Create a view for when the specified player passes warden /// /// /// - public IView PASS_WARDEN(CCSPlayerController player); + public IView PassWarden(CCSPlayerController player); /// /// Create a view for when this player becomes a new warden /// /// /// - public IView NEW_WARDEN(CCSPlayerController player); + public IView NewWarden(CCSPlayerController player); /// /// Format a response to a request about the current warden. @@ -36,12 +36,12 @@ public interface IWardenNotifications { /// /// /// - public IView CURRENT_WARDEN(CCSPlayerController? player); + public IView CurrentWarden(CCSPlayerController? player); - public IView FIRE_COMMAND_SUCCESS(CCSPlayerController player); + public IView FireCommandSuccess(CCSPlayerController player); - public IView FIRE_WARDEN(CCSPlayerController player); + public IView FireWarden(CCSPlayerController player); - public IView FIRE_WARDEN(CCSPlayerController player, + public IView FireWarden(CCSPlayerController player, CCSPlayerController admin); } \ No newline at end of file diff --git a/public/Jailbreak.Public/Extensions/WeaponExtensions.cs b/public/Jailbreak.Public/Extensions/WeaponExtensions.cs index ae478adc..ad6ee3b9 100644 --- a/public/Jailbreak.Public/Extensions/WeaponExtensions.cs +++ b/public/Jailbreak.Public/Extensions/WeaponExtensions.cs @@ -2,50 +2,84 @@ namespace Jailbreak.Public.Extensions; -public static class WeaponExtensions -{ - public static string ToFriendlyString(this CCSWeaponBase weaponEntity) - { - var designerName = weaponEntity.DesignerName; - switch (designerName) - { - case "weapon_ak47": return "AK47"; - case "weapon_aug": return "AUG"; - case "weapon_awp": return "AWP"; - case "weapon_bizon": return "Bizon"; - case "weapon_cz75a": return "CZ75"; - case "weapon_deagle": return "Desert Eagle"; - case "weapon_famas": return "Famas"; - case "weapon_fiveseven": return "Five Seven"; - case "weapon_g3sg1": return "G3SG1"; - case "weapon_galilar": return "Galil"; - case "weapon_glock": return "Glock 18"; - case "weapon_hkp2000": return "HPK2000"; - case "weapon_m249": return "M249"; - case "weapon_m4a1": return "M4A1"; - case "weapon_m4a1_silencer": return "M4A1S"; - case "weapon_m4a4": return "M4A4"; - case "weapon_mac10": return "MAC10"; - case "weapon_mag7": return "MAG7"; - case "weapon_mp5sd": return "MP5SD"; - case "weapon_mp7": return "MP7"; - case "weapon_mp9": return "MP9"; - case "weapon_negev": return "Negev"; - case "weapon_nova": return "Nova"; - case "weapon_p250": return "P250"; - case "weapon_p90": return "P90"; - case "weapon_revolver": return "Revolver"; - case "weapon_sawedoff": return "Sawed Off"; - case "weapon_scar20": return "Scar20"; - case "weapon_sg553": return "SG553"; - case "weapon_sg556": return "SG556"; - case "weapon_ssg08": return "SSG08"; - case "weapon_taser": return "Zeus"; - case "weapon_tec9": return "Tec9"; - case "weapon_ump45": return "UMP45"; - case "weapon_usp_silencer": return "USPS"; - case "weapon_xm1014": return "XM1014"; - default: return "UNKNOWN: Pleace Contact Tech"; - } +public static class WeaponExtensions { + public static string ToFriendlyString(this CCSWeaponBase weaponEntity) { + var designerName = weaponEntity.DesignerName; + switch (designerName) { + case "weapon_ak47": + return "AK47"; + case "weapon_aug": + return "AUG"; + case "weapon_awp": + return "AWP"; + case "weapon_bizon": + return "Bizon"; + case "weapon_cz75a": + return "CZ75"; + case "weapon_deagle": + return "Desert Eagle"; + case "weapon_famas": + return "Famas"; + case "weapon_fiveseven": + return "Five Seven"; + case "weapon_g3sg1": + return "G3SG1"; + case "weapon_galilar": + return "Galil"; + case "weapon_glock": + return "Glock 18"; + case "weapon_hkp2000": + return "HPK2000"; + case "weapon_m249": + return "M249"; + case "weapon_m4a1": + return "M4A1"; + case "weapon_m4a1_silencer": + return "M4A1S"; + case "weapon_m4a4": + return "M4A4"; + case "weapon_mac10": + return "MAC10"; + case "weapon_mag7": + return "MAG7"; + case "weapon_mp5sd": + return "MP5SD"; + case "weapon_mp7": + return "MP7"; + case "weapon_mp9": + return "MP9"; + case "weapon_negev": + return "Negev"; + case "weapon_nova": + return "Nova"; + case "weapon_p250": + return "P250"; + case "weapon_p90": + return "P90"; + case "weapon_revolver": + return "Revolver"; + case "weapon_sawedoff": + return "Sawed Off"; + case "weapon_scar20": + return "Scar20"; + case "weapon_sg553": + return "SG553"; + case "weapon_sg556": + return "SG556"; + case "weapon_ssg08": + return "SSG08"; + case "weapon_taser": + return "Zeus"; + case "weapon_tec9": + return "Tec9"; + case "weapon_ump45": + return "UMP45"; + case "weapon_usp_silencer": + return "USPS"; + case "weapon_xm1014": + return "XM1014"; + default: + return "UNKNOWN: Pleace Contact Tech"; } + } } \ No newline at end of file diff --git a/public/Jailbreak.Public/Jailbreak.Public.csproj b/public/Jailbreak.Public/Jailbreak.Public.csproj index 49a1c520..7a3174f6 100644 --- a/public/Jailbreak.Public/Jailbreak.Public.csproj +++ b/public/Jailbreak.Public/Jailbreak.Public.csproj @@ -7,8 +7,8 @@ - - + +