Refactor skill lookup logic and vote system, update language files

Refactored command handling to improve player and skill lookup logic, replaced some list operations with direct queries, and updated method signatures for clarity and null safety. The vote system was reworked to support more robust vote tracking, cooldowns, and localized chat messages. Language files were updated to add new vote-related translations. Various code style and nullability improvements were made throughout the plugin.
This commit is contained in:
Juzlus 2025-09-04 04:53:23 +02:00
parent 54b265d43d
commit e33975fe8b
117 changed files with 1532 additions and 1674 deletions

View file

@ -15,12 +15,12 @@ namespace jRandomSkills
public static void Load()
{
var config = Config.config?.Settings;
var config = Config.LoadedConfig?.Settings;
if (config == null || config == null) return;
var commands = new Dictionary<IEnumerable<string>, (string description, CommandInfo.CommandCallback handler)>
{
{ SplitCommands(config.SetSkillCommands), ("Delete record", Command_SetSkill) },
{ SplitCommands(config.SetSkillCommands), ("Set skill", Command_SetSkill) },
{ SplitCommands(config.SkillsListCommands), ("Delete all records", Command_SkillsListMenu) },
{ SplitCommands(config.UseSkillCommands), ("Use/Type skill", Command_UseTypeSkill) },
{ SplitCommands(config.ChangeMapCommands), ("Change map", Command_ChangeMap) },
@ -47,7 +47,8 @@ namespace jRandomSkills
private static void Command_UseTypeSkill(CCSPlayerController? player, CommandInfo _)
{
if (player == null) return;
var playerInfo = Instance.skillPlayer.FirstOrDefault(p => p.SteamID == player.SteamID);
var playerInfo = Instance.SkillPlayer.FirstOrDefault(p => p.SteamID == player.SteamID);
if (playerInfo == null) return;
var playerPawn = player.PlayerPawn.Value;
if (playerPawn?.CBodyComponent == null) return;
@ -56,9 +57,9 @@ namespace jRandomSkills
string[] commands = _.ArgString.Trim().Split(" ", StringSplitOptions.RemoveEmptyEntries);
Debug.WriteToDebug($"Player {player.PlayerName} used the skill: {playerInfo.Skill}");
if (commands == null || commands.Length == 0)
Instance.SkillAction(playerInfo!.Skill.ToString(), "UseSkill", new object[] { player });
Instance.SkillAction(playerInfo.Skill.ToString(), "UseSkill", [player]);
else
Instance.SkillAction(playerInfo!.Skill.ToString(), "TypeSkill", new object[] { player, commands });
Instance.SkillAction(playerInfo.Skill.ToString(), "TypeSkill", [player, commands]);
}
[RequiresPermissions("@jRandmosSkills/admin")]
@ -66,8 +67,9 @@ namespace jRandomSkills
private static void Command_SetSkill(CCSPlayerController? player, CommandInfo command)
{
if (player == null) return;
(List<CCSPlayerController> players, string targetname) = FindTarget.Find(command, 2, false, true);
var targetPlayer = Utilities.GetPlayers().FirstOrDefault(p => !p.IsBot
&& (p.SteamID.ToString().Equals(command.GetArg(1), StringComparison.CurrentCultureIgnoreCase)
|| p.PlayerName.Equals(command.GetArg(1), StringComparison.CurrentCultureIgnoreCase)) );
if (command.ArgCount < 2)
{
@ -77,7 +79,7 @@ namespace jRandomSkills
return;
}
if (players.Count == 0)
if (targetPlayer == null)
{
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
SkillUtils.PrintToChat(player, Localization.GetTranslation("player_not_found_setskill"), true);
@ -96,34 +98,30 @@ namespace jRandomSkills
return;
}
foreach (CCSPlayerController target in players)
var skillPlayer = Instance.SkillPlayer.FirstOrDefault(p => p.SteamID == targetPlayer.SteamID);
if (skillPlayer != null)
{
var skillPlayer = Instance.skillPlayer.FirstOrDefault(p => p.SteamID == target.SteamID);
if (skillPlayer != null)
{
Instance.SkillAction(skillPlayer.Skill.ToString(), "DisableSkill", [targetPlayer]);
skillPlayer.Skill = skill.Skill;
Instance.SkillAction(skill.Skill.ToString(), "EnableSkill", [targetPlayer]);
Instance.SkillAction(skillPlayer.Skill.ToString(), "DisableSkill", new object[] { target });
skillPlayer.Skill = skill.Skill;
Instance.SkillAction(skill.Skill.ToString(), "EnableSkill", new object[] { target });
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
SkillUtils.PrintToChat(player, $"{Localization.GetTranslation("done_setskill")}: {ChatColors.LightRed}{skill.Name} {ChatColors.Lime}{Localization.GetTranslation("for_setskill")} {ChatColors.LightRed}{target.PlayerName}", false);
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
}
else
{
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
SkillUtils.PrintToChat(player, Localization.GetTranslation("error_setskill"), true);
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
}
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
SkillUtils.PrintToChat(player, $"{Localization.GetTranslation("done_setskill")}: {ChatColors.LightRed}{skill.Name} {ChatColors.Lime}{Localization.GetTranslation("for_setskill")} {ChatColors.LightRed}{targetPlayer.PlayerName}", false);
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
}
else
{
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
SkillUtils.PrintToChat(player, Localization.GetTranslation("error_setskill"), true);
player.PrintToChat($" {ChatColors.Green}―――――――――――{ChatColors.DarkRed}◥◣◆◢◤{ChatColors.Green}―――――――――――");
}
}
[CommandHelper(minArgs: 0, whoCanExecute: CommandUsage.CLIENT_ONLY)]
private static void Command_SkillsListMenu(CCSPlayerController? player, CommandInfo command)
{
if (player == null) return;
Menu.DisplaySkillsList(player);
}
@ -135,10 +133,10 @@ namespace jRandomSkills
player.Vote(VoteType.ChangeMap, command.ArgString);
return;
}
ChangeMap(player, command);
ChangeMap(command);
}
private static void ChangeMap(CCSPlayerController? player, CommandInfo command)
private static void ChangeMap(CommandInfo command)
{
string map = command.GetArg(1);
@ -163,13 +161,13 @@ namespace jRandomSkills
{
if (player != null && player.IsValid && !AdminManager.PlayerHasPermissions(player, "@TESTTEST/TESTAFD"))
{
player.Vote(VoteType.StartGame, command.ArgString);
player.Vote(VoteType.StartGame);
return;
}
StartGame(player, command);
StartGame(command);
}
private static void StartGame(CCSPlayerController? player, CommandInfo command)
private static void StartGame(CommandInfo command)
{
int cheats = command.GetArg(1) == "sv" ? 1 : 0;
Server.ExecuteCommand($"mp_freezetime {(cheats == 1 ? 0 : 5)}");
@ -190,13 +188,13 @@ namespace jRandomSkills
{
if (player != null && player.IsValid && !AdminManager.PlayerHasPermissions(player, "@TESTTEST/TESTAFD"))
{
player.Vote(VoteType.SwapTeam, command.ArgString);
player.Vote(VoteType.SwapTeam);
return;
}
Swap(player, command);
Swap();
}
private static void Swap(CCSPlayerController? _player, CommandInfo command)
private static void Swap()
{
foreach (var player in Utilities.GetPlayers())
if (Instance.IsPlayerValid(player) && new CsTeam[] { CsTeam.CounterTerrorist, CsTeam.Terrorist }.Contains(player.Team))
@ -209,13 +207,13 @@ namespace jRandomSkills
{
if (player != null && player.IsValid && !AdminManager.PlayerHasPermissions(player, "@TESTTEST/TESTAFD"))
{
player.Vote(VoteType.ShuffleTeam, command.ArgString);
player.Vote(VoteType.ShuffleTeam);
return;
}
Shuffle(player, command);
Shuffle();
}
private static void Shuffle(CCSPlayerController? _player, CommandInfo command)
private static void Shuffle()
{
var players = Utilities.GetPlayers().FindAll(p => (Instance.IsPlayerValid(p) && new CsTeam[] { CsTeam.CounterTerrorist, CsTeam.Terrorist }.Contains(p.Team)));
double CTlimit = Instance.Random.Next(0, 2) == 0 ? Math.Floor(players.Count / 2.0) : Math.Ceiling(players.Count / 2.0);
@ -233,13 +231,13 @@ namespace jRandomSkills
{
if (player != null && player.IsValid && !AdminManager.PlayerHasPermissions(player, "@TESTTEST/TESTAFD"))
{
player.Vote(VoteType.PauseGame, command.ArgString);
player.Vote(VoteType.PauseGame);
return;
}
Pause(player, command);
Pause();
}
private static void Pause(CCSPlayerController? player, CommandInfo command)
private static void Pause()
{
Server.PrintToChatAll($" {(gamePaused ? ChatColors.Green : ChatColors.Red)}{Localization.GetTranslation(gamePaused ? "unpause" : "pause")}");
Server.ExecuteCommand( gamePaused ? "mp_unpause_match" : "mp_pause_match");
@ -250,6 +248,7 @@ namespace jRandomSkills
[CommandHelper(minArgs: 0, whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private static void Command_Heal(CCSPlayerController? player, CommandInfo command)
{
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PlayerPawn.Value.IsValid || player.LifeState != (byte)LifeState_t.LIFE_ALIVE) return;
SkillUtils.AddHealth(player.PlayerPawn.Value, 100);
player.PrintToChat($" {ChatColors.Green}{Localization.GetTranslation("healed")}");
}
@ -269,7 +268,8 @@ namespace jRandomSkills
{
if (!int.TryParse(command.GetArg(1), out int ctScore) || !int.TryParse(command.GetArg(2), out int tScore))
{
SkillUtils.PrintToChat(player, Localization.GetTranslation("correct_form_setscore"), true);
if (player != null && player.IsValid)
SkillUtils.PrintToChat(player, Localization.GetTranslation("correct_form_setscore"), true);
return;
}

View file

@ -1,49 +1,75 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Utils;
using jRandomSkills.src.utils;
namespace jRandomSkills
{
public static class VoteSystem
{
private static HashSet<VoteData> votes = new HashSet<VoteData>();
private static readonly HashSet<VoteData> votes = [];
public static void Load()
private static VoteData? CreateVote(VoteType voteType, string? args = null)
{
jRandomSkills.Instance.DeregisterEventHandler<EventPlayerChat>((@event, info) =>
{
var player = @event.Userid;
var text = @event.Text;
return HookResult.Continue;
});
}
var vote = new VoteData(10,
() => {
Server.ExecuteCommand($"{VoteTypeCommands.GetCommand(voteType)}{(!string.IsNullOrEmpty(args) ? $" {args}" : "")}");
}, 60, 2, 5, 2, voteType, args);
if (vote.MinimumPlayersToStartVoting > Utilities.GetPlayers().Count(p => !p.IsBot))
return null;
private static VoteData CreateVote(VoteType voteType, string? args = null)
{
var vote = new VoteData(10,
() => {
Server.ExecuteCommand($"{VoteTypeCommands.GetCommand(voteType)}{(args != null ? $" {args}" : "")}");
}, 60, voteType, args);
votes.Add(vote);
string commandName = $"!{VoteTypeCommands.GetCommand(vote.Type)?.Replace("css_", "")}{(!string.IsNullOrEmpty(vote?.Args) ? $" {vote?.Args}" : "")}";
jRandomSkills.Instance.AddTimer(vote?.TimeToVote ?? 0, () =>
Server.PrintToChatAll($" {ChatColors.Lime}{Localization.GetTranslation("vote_started", commandName)}");
foreach (var player in Utilities.GetPlayers())
player.EmitSound("UIPanorama.tab_mainmenu_news");
if (vote == null) return vote;
jRandomSkills.Instance.AddTimer(vote.TimeToVote, () =>
{
if (!votes.Contains(vote) || !vote.GetActive()) return;
vote.SetActive(false);
Server.PrintToChatAll($" {ChatColors.Red}{Localization.GetTranslation("vote_timeout", commandName)}");
});
float[] times = [vote.TimeToVote, vote.TimeToVote + vote.TimeToNextVoting, vote.TimeToVote + vote.TimeToNextSameVoting];
jRandomSkills.Instance.AddTimer(times.Max(), () =>
{
if (!votes.Contains(vote)) return;
votes.Remove(vote);
Server.PrintToChatAll($" {ChatColors.Red}Vote '!{VoteTypeCommands.GetCommand(vote.Type)?.Replace("css_", "")}' timed out!");
});
return vote;
}
public static void Vote(this CCSPlayerController player, VoteType voteType, string? args = null)
{
var vote = votes.FirstOrDefault(v => v.Type == voteType);
var vote = votes.FirstOrDefault(v => v.Type == voteType && v.Args == args && v.GetActive());
if (vote == null)
{
if (votes.Any(v => v.NextVoting() > DateTime.Now))
{
player.PrintToChat($" {ChatColors.Red}{Localization.GetTranslation("vote_wait")}");
return;
}
else if (votes.Any(v => v.Type == voteType && v.NextSameVoting() > DateTime.Now))
{
player.PrintToChat($" {ChatColors.Red}{Localization.GetTranslation("vote_same_wait")}");
return;
}
vote = CreateVote(voteType, args);
}
if (vote == null)
{
player.PrintToChat($" {ChatColors.Red}{Localization.GetTranslation("vote_not_enough_players")}");
return;
}
if (!vote.PlayersVoted.Add(player.SteamID))
player.PrintToChat($" {ChatColors.Red}You have already voted!");
player.PrintToChat($" {ChatColors.Red}{Localization.GetTranslation("vote_alredy_voted")}");
else CheckVote(vote);
}
@ -56,30 +82,46 @@ namespace jRandomSkills
if (voted >= playersNeeded)
{
vote.SuccessAction.Invoke();
votes.Remove(vote);
vote.SetActive(false);
}
else
Server.PrintToChatAll($" {ChatColors.Yellow}Vote '!{VoteTypeCommands.GetCommand(vote.Type)?.Replace("css_", "")}': {ChatColors.Green}{voted}/{playersNeeded}");
Server.PrintToChatAll($" {ChatColors.Yellow}{Localization.GetTranslation("vote_vote")} '!{VoteTypeCommands.GetCommand(vote.Type)?.Replace("css_", "")}{(!string.IsNullOrEmpty(vote?.Args) ? $" {vote?.Args}" : "")}': {ChatColors.Green}{voted}/{playersNeeded}");
}
}
public class VoteData
public class VoteData(float timeToVote, Action successAction, float percentagesToSuccess, float timeToNextVoting, float timeToNextSameVoting, int minimumPlayersToStartVoting, VoteType type, string? args = null)
{
public float TimeToVote { get; set; }
public Action SuccessAction { get; set; }
public float PercentagesToSuccess { get; set; }
public VoteType Type { get; set; }
public string Args { get; set; }
public HashSet<ulong> PlayersVoted { get; set; }
private bool Active { get; set; } = true;
public float TimeToVote { get; set; } = timeToVote;
public Action SuccessAction { get; set; } = successAction;
public float PercentagesToSuccess { get; set; } = percentagesToSuccess;
public float TimeToNextVoting { get; set; } = timeToNextVoting;
public float TimeToNextSameVoting { get; set; } = timeToNextSameVoting;
public int MinimumPlayersToStartVoting { get; set; } = minimumPlayersToStartVoting;
public VoteType Type { get; set; } = type;
public string? Args { get; set; } = args;
public HashSet<ulong> PlayersVoted { get; set; } = [];
public VoteData(float timeToVote, Action successAction, float percentagesToSuccess, VoteType type, string? args = null)
private DateTime CreatedTime { get; set; } = DateTime.Now;
public void SetActive(bool active)
{
TimeToVote = timeToVote;
SuccessAction = successAction;
PercentagesToSuccess = percentagesToSuccess;
Type = type;
Args = args;
PlayersVoted = new HashSet<ulong>();
Active = active;
}
public bool GetActive()
{
return Active;
}
public DateTime NextVoting()
{
return CreatedTime.AddSeconds(TimeToVote + TimeToNextVoting);
}
public DateTime NextSameVoting()
{
return CreatedTime.AddSeconds(TimeToVote + TimeToNextSameVoting);
}
}
@ -95,7 +137,7 @@ namespace jRandomSkills
public static class VoteTypeCommands
{
private static readonly Dictionary<VoteType, string> names = new Dictionary<VoteType, string>()
private static readonly Dictionary<VoteType, string> names = new()
{
{ VoteType.StartGame, "css_start" },
{ VoteType.PauseGame, "css_pause" },