From 11425906ed3ff70361ff79a11960d4d38de2b8f0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 11:39:02 +0200 Subject: [PATCH 001/359] Update ErrorAction.cs --- ScriptedEvents/Actions/Server/ErrorAction.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/ScriptedEvents/Actions/Server/ErrorAction.cs b/ScriptedEvents/Actions/Server/ErrorAction.cs index 7fa5f5a6..03e03997 100644 --- a/ScriptedEvents/Actions/Server/ErrorAction.cs +++ b/ScriptedEvents/Actions/Server/ErrorAction.cs @@ -2,13 +2,10 @@ { using System; - using Exiled.API.Features; - using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class ErrorAction : IScriptAction, IHelpInfo From 3e4b9f5422e3e18b314baf0588725e0eb97cc3a0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 11:39:05 +0200 Subject: [PATCH 002/359] Update IHelpInfo.cs --- ScriptedEvents/API/Interfaces/IHelpInfo.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/ScriptedEvents/API/Interfaces/IHelpInfo.cs b/ScriptedEvents/API/Interfaces/IHelpInfo.cs index 73347b6f..f0cd5dd8 100644 --- a/ScriptedEvents/API/Interfaces/IHelpInfo.cs +++ b/ScriptedEvents/API/Interfaces/IHelpInfo.cs @@ -1,7 +1,5 @@ namespace ScriptedEvents.API.Interfaces { - using ScriptedEvents.Structures; - /// /// Signifies that an action can be used in the "HELP" action to get information about it. /// From d379d5be3362eccf4421ba6bfb7389836e9ad832 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 11:39:14 +0200 Subject: [PATCH 003/359] minor++ --- ScriptedEvents/MainPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index b8b73ccb..5b85b3f3 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -76,7 +76,7 @@ public class MainPlugin : Plugin public override string Author => "Thunder and Elektryk_Andrzej"; /// - public override Version Version => new(3, 1, 6); + public override Version Version => new(3, 2, 0); /// public override Version RequiredExiledVersion => new(8, 7, 0); From d0003b322e3e85ab47eda433dd99aae78ec28d31 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 11:39:23 +0200 Subject: [PATCH 004/359] Update MapVariables.cs --- ScriptedEvents/Variables/MapVariables.cs | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index fd6fdeb3..585659fc 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -50,7 +50,7 @@ public class CassieSpeaking : IBoolVariable public bool Value => Cassie.IsSpeaking; } - public class InRoom : IFloatVariable, IArgumentVariable, IPlayerVariable, INeedSourceVariable + public class InRoom : IFloatVariable, IArgumentVariable, IPlayerVariable { /// public string Name => "{INROOM}"; @@ -70,9 +70,6 @@ public class InRoom : IFloatVariable, IArgumentVariable, IPlayerVariable, INeedS new Argument("roomType", typeof(RoomType), "The room to filter by.", false), }; - /// - public Script Source { get; set; } - /// public float Value => Players.Count(); @@ -87,7 +84,7 @@ public IEnumerable Players } } - public class RandomDoor : IStringVariable, INeedSourceVariable, IArgumentVariable + public class RandomDoor : IStringVariable, IArgumentVariable { /// public string Name => "{RANDOMDOOR}"; @@ -107,9 +104,6 @@ public class RandomDoor : IStringVariable, INeedSourceVariable, IArgumentVariabl new Argument("zone", typeof(ZoneType), "A zone to filter by (optional).", false), }; - /// - public Script Source { get; set; } - /// public string Value { @@ -212,7 +206,7 @@ public float Value } } - public class RandomRoom : IStringVariable, IArgumentVariable, INeedSourceVariable + public class RandomRoom : IStringVariable, IArgumentVariable { /// public string Name => "{RANDOMROOM}"; @@ -232,9 +226,6 @@ public class RandomRoom : IStringVariable, IArgumentVariable, INeedSourceVariabl new Argument("zone", typeof(ZoneType), "A zone to filter by (optional).", false), }; - /// - public Script Source { get; set; } - /// public string Value { @@ -271,7 +262,7 @@ public class Scp914Active : IBoolVariable public bool Value => Scp914.IsWorking; } - public class DoorState : IStringVariable, IArgumentVariable, INeedSourceVariable + public class DoorState : IStringVariable, IArgumentVariable { /// public string Name => "{DOORSTATE}"; @@ -285,9 +276,6 @@ public class DoorState : IStringVariable, IArgumentVariable, INeedSourceVariable /// public object[] Arguments { get; set; } - /// - public Script Source { get; set; } - /// public Argument[] ExpectedArguments => new[] { From 55e764132bd8e4ffebb18e3ab7aad4eb8b13de5a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:06 +0200 Subject: [PATCH 005/359] add disengage mode to generator action --- ScriptedEvents/Actions/Map/GeneratorAction.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ScriptedEvents/Actions/Map/GeneratorAction.cs b/ScriptedEvents/Actions/Map/GeneratorAction.cs index 75e906b6..384a317a 100644 --- a/ScriptedEvents/Actions/Map/GeneratorAction.cs +++ b/ScriptedEvents/Actions/Map/GeneratorAction.cs @@ -38,6 +38,7 @@ public class GeneratorAction : IScriptAction, IHelpInfo new("LOCK", "Locks all generators, requiring a keycard to use."), new("UNLOCK", "Unlocks all generators, no longer requiring a keycard to use."), new("OVERCHARGE", "Engages all generators, causing an overcharge."), + new("DISENGAGE", "Disengages all generators."), new("ACTIVATE", "Begins activating all generators."), new("DEACTIVATE", "Deactivates all generators.")), }; @@ -70,6 +71,8 @@ public ActionResponse Execute(Script script) case "DEACTIVATE": generator.IsActivating = false; break; + case "DISENGAGE": + generator.IsEngaged = false; break; } } From d530665fa803f91f400a547f635e0c5b7772a001 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:10 +0200 Subject: [PATCH 006/359] Create EffectImmunityRuleAction.cs --- .../RoundRule/EffectImmunityRuleAction.cs | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs diff --git a/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs new file mode 100644 index 00000000..663153ee --- /dev/null +++ b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs @@ -0,0 +1,88 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + + using Exiled.API.Enums; + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class EffectImmunityRuleAction : IScriptAction, IHelpInfo + { + /// + public string Name => "EFFECTIMMUNITYRULE"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.RoundRule; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string Description => "Action for setting rules to apply immunity to effects to specific roles/teams/players on-spawn."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("SET", "Rule to give effect immunity."), + new("REMOVE", "Removes a previously-established immunity.")), + new Argument("target", typeof(PlayerCollection), "The players to affect.", true), + new Argument("effect", typeof(EffectType), "The effect give or remove immunity to.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + string mode = Arguments[0].ToUpper(); + PlayerCollection players = (PlayerCollection)Arguments[1]; + EffectType effectType = (EffectType)Arguments[2]; + var dict = MainPlugin.GetModule().PlayerEffectImmunity; + + foreach (Player plr in players) + { + List list; + if (dict.ContainsKey(plr)) + { + list = dict[plr]; + } + else + { + list = new(); + } + + switch (mode) + { + case "SET": + if (list.Contains(effectType)) + { + continue; + } + + dict[plr].Add(effectType); + break; + + case "REMOVE": + if (!list.Contains(effectType)) + { + continue; + } + + dict[plr].Remove(effectType); + break; + } + } + + return new(true); + } + } +} From 8b63ed1fb80744e22730e516417b0c46975c6ac5 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:17 +0200 Subject: [PATCH 007/359] Update EventHandlingModule.cs --- .../API/Modules/EventHandlingModule.cs | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Modules/EventHandlingModule.cs b/ScriptedEvents/API/Modules/EventHandlingModule.cs index 32ecb5c3..a96daec2 100644 --- a/ScriptedEvents/API/Modules/EventHandlingModule.cs +++ b/ScriptedEvents/API/Modules/EventHandlingModule.cs @@ -6,6 +6,7 @@ using System.Linq; using Exiled.API.Enums; + using Exiled.API.Extensions; using Exiled.API.Features; using Exiled.API.Features.Pickups; using Exiled.Events.EventArgs.Interfaces; @@ -161,6 +162,11 @@ public class EventHandlingModule : SEModule /// public Dictionary> PermRoleEffects { get; } = new(); + /// + /// Gets a dictionary of effect immunity for specific players. + /// + public Dictionary> PlayerEffectImmunity { get; } = new(); + public List DamageRules { get; } = new(); public override void Init() @@ -181,12 +187,13 @@ public override void Init() PlayerHandler.InteractingElevator += OnInteractingElevator; PlayerHandler.Escaping += OnEscaping; PlayerHandler.Spawned += OnSpawned; + PlayerHandler.ReceivingEffect += OnReceivingEffect; PlayerHandler.PickingUpItem += OnPickingUpItem; PlayerHandler.ChangingRadioPreset += OnChangingRadioPreset; PlayerHandler.ActivatingWarheadPanel += OnActivatingWarheadPanel; - Exiled.Events.Handlers.Warhead.Starting += OnStartingWarhead; // why is this located specially?? + Exiled.Events.Handlers.Warhead.Starting += OnStartingWarhead; PlayerHandler.ActivatingGenerator += GeneratorEvent; PlayerHandler.OpeningGenerator += GeneratorEvent; @@ -267,6 +274,7 @@ public override void Kill() PlayerHandler.InteractingElevator -= OnInteractingElevator; PlayerHandler.Escaping -= OnEscaping; PlayerHandler.Spawned -= OnSpawned; + PlayerHandler.ReceivingEffect -= OnReceivingEffect; PlayerHandler.PickingUpItem -= OnPickingUpItem; PlayerHandler.ChangingRadioPreset -= OnChangingRadioPreset; @@ -439,6 +447,8 @@ public void OnRestarting() RecentlyRespawned.Clear(); MostRecentSpawn = SpawnableTeamType.None; + + PlayerEffectImmunity.Clear(); } public void OnRoundStarted() @@ -490,6 +500,24 @@ public void OnRoundStarted() } } + public void OnReceivingEffect(ReceivingEffectEventArgs ev) + { + if (ev.Player == null) return; + + if (!PlayerEffectImmunity.TryGetValue(ev.Player, out List effects)) + { + return; + } + + if (!effects.Contains(ev.Effect.GetEffectType())) + { + return; + } + + ev.IsAllowed = false; + return; + } + public void OnRespawningTeam(RespawningTeamEventArgs ev) { if (DisabledKeys.Contains("RESPAWNS")) ev.IsAllowed = false; From c90fe585f79459022907559fcede70bfd7c03e42 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:21 +0200 Subject: [PATCH 008/359] Update MainPlugin.cs --- ScriptedEvents/MainPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index 5b85b3f3..7099a4b5 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -22,7 +22,7 @@ public class MainPlugin : Plugin /// /// Whether or not this build of the plugin is experimental. /// - public const bool IsExperimental = false; + public const bool IsExperimental = true; /// /// Gets a link to the Scripted Events Discord server. From 0ff2fa5483a28cfcfe809249604b525b2e0d79bc Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:23 +0200 Subject: [PATCH 009/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index be5ed668..3a15f987 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -113,6 +113,7 @@ + From 5b4be33287fd4f38541e78a57b783852eb8109d0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:30 +0200 Subject: [PATCH 010/359] add {MAPSALT} --- ScriptedEvents/Variables/MapVariables.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index 585659fc..fc92fa9a 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -32,9 +32,22 @@ public class MapVariables : IVariableGroup new RandomDoor(), new InRoom(), new CassieSpeaking(), + new Seed(), }; } + public class Seed : IStringVariable + { + /// + public string Name => "{MAPSALT}"; + + /// + public string Description => "All-in-one variable for map related information."; + + /// + public string Value => Map.Seed.ToString(); + } + public class CassieSpeaking : IBoolVariable { /// From b1d59038307363b981879d3125942277a272c3af Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 19 Aug 2024 12:29:33 +0200 Subject: [PATCH 011/359] Update RoundVariables.cs --- ScriptedEvents/Variables/RoundVariables.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ScriptedEvents/Variables/RoundVariables.cs b/ScriptedEvents/Variables/RoundVariables.cs index 02f96b11..4cb622ed 100644 --- a/ScriptedEvents/Variables/RoundVariables.cs +++ b/ScriptedEvents/Variables/RoundVariables.cs @@ -78,9 +78,7 @@ public bool Value { get { - string mode = (string)Arguments[0]; - - return mode.ToUpper() switch + return ((string)Arguments[0]).ToUpper() switch { "LOCKED" => Round.IsLocked, "STARTED" => Round.IsStarted, From a0525ba966fade6d995c0ae358665239104d3dc7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 20 Aug 2024 14:37:26 +0200 Subject: [PATCH 012/359] Update EffectImmunityRuleAction.cs --- .../RoundRule/EffectImmunityRuleAction.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs index 663153ee..4a51089e 100644 --- a/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs @@ -62,23 +62,23 @@ public ActionResponse Execute(Script script) switch (mode) { - case "SET": - if (list.Contains(effectType)) - { - continue; - } + case "SET": + if (list.Contains(effectType)) + { + continue; + } - dict[plr].Add(effectType); - break; + dict[plr].Add(effectType); + break; - case "REMOVE": - if (!list.Contains(effectType)) - { - continue; - } + case "REMOVE": + if (!list.Contains(effectType)) + { + continue; + } - dict[plr].Remove(effectType); - break; + dict[plr].Remove(effectType); + break; } } From fd322fabc82e55ddefc2f48a7202171a42e556c8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 20 Aug 2024 14:37:32 +0200 Subject: [PATCH 013/359] Update ScriptModule.cs --- ScriptedEvents/API/Modules/ScriptModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index e723a19d..02a38a4e 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -871,7 +871,7 @@ private IEnumerator RunScriptInternal(Script scr, bool dispose = true) ArgumentProcessResult res = ArgumentProcessor.Process(action.ExpectedArguments, originalArgs, action, scr); if (res.Errored) { - Logger.ScriptError(res.FailedArgument != string.Empty ? $"[Argument: {res.FailedArgument}]" : string.Empty + res.Message, scr); + Logger.ScriptError((res.FailedArgument != string.Empty ? $"[Argument: {res.FailedArgument}] " : string.Empty) + res.Message, scr); break; } From 38654f15b7d916890c5770a2df2f8abadcd9448f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 12:59:23 +0200 Subject: [PATCH 014/359] remove DISENGAGE from GENERATORS --- ScriptedEvents/Actions/Map/GeneratorAction.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/ScriptedEvents/Actions/Map/GeneratorAction.cs b/ScriptedEvents/Actions/Map/GeneratorAction.cs index 384a317a..75e906b6 100644 --- a/ScriptedEvents/Actions/Map/GeneratorAction.cs +++ b/ScriptedEvents/Actions/Map/GeneratorAction.cs @@ -38,7 +38,6 @@ public class GeneratorAction : IScriptAction, IHelpInfo new("LOCK", "Locks all generators, requiring a keycard to use."), new("UNLOCK", "Unlocks all generators, no longer requiring a keycard to use."), new("OVERCHARGE", "Engages all generators, causing an overcharge."), - new("DISENGAGE", "Disengages all generators."), new("ACTIVATE", "Begins activating all generators."), new("DEACTIVATE", "Deactivates all generators.")), }; @@ -71,8 +70,6 @@ public ActionResponse Execute(Script script) case "DEACTIVATE": generator.IsActivating = false; break; - case "DISENGAGE": - generator.IsEngaged = false; break; } } From d4997749f8de4e6999b943aaf5de7b153ea1de08 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 12:59:26 +0200 Subject: [PATCH 015/359] Update GeneratorRuleAction.cs --- ScriptedEvents/Actions/RoundRule/GeneratorRuleAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/RoundRule/GeneratorRuleAction.cs b/ScriptedEvents/Actions/RoundRule/GeneratorRuleAction.cs index c34d03a3..bb472450 100644 --- a/ScriptedEvents/Actions/RoundRule/GeneratorRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/GeneratorRuleAction.cs @@ -27,7 +27,7 @@ public class GeneratorRuleAction : IScriptAction, IHelpInfo public ActionSubgroup Subgroup => ActionSubgroup.RoundRule; /// - public string Description => "Modifies genrator behavior."; + public string Description => "Modifies generator behavior."; /// public Argument[] ExpectedArguments => new[] From a948781c974b4428c87e633e51a4b003dfb48c40 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 12:59:48 +0200 Subject: [PATCH 016/359] fix scripts in deeper folders not being accessible --- ScriptedEvents/API/Modules/ScriptModule.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index 02a38a4e..98f0df6d 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -771,22 +771,19 @@ internal string InternalRead(string scriptName, out string fileDirectory) string text = null; string mainFolderFile = Path.Combine(BasePath, scriptName + ".txt"); + string[] fileNames = Directory.GetFiles(BasePath, $"{scriptName}.txt", SearchOption.AllDirectories); + if (File.Exists(mainFolderFile)) { fileDirectory = mainFolderFile; text = File.ReadAllText(mainFolderFile); } - else + else if (fileNames.Length == 1) { - foreach (string directory in Directory.GetDirectories(BasePath)) - { - string fileName = Path.Combine(directory, scriptName + ".txt"); - if (File.Exists(fileName)) - { - fileDirectory = fileName; - text = File.ReadAllText(fileName); - } - } + string fullFilePath = fileNames.FirstOrDefault(); + + fileDirectory = fullFilePath; + text = File.ReadAllText(fullFilePath); } if (text is not null && fileDirectory is not null) From fe63103c682fa49172f0558d250b22c1f0aee5af Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 12:59:54 +0200 Subject: [PATCH 017/359] Update ListScripts.cs --- ScriptedEvents/Commands/MainCommand/ListScripts.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/ScriptedEvents/Commands/MainCommand/ListScripts.cs b/ScriptedEvents/Commands/MainCommand/ListScripts.cs index b7282f25..d62c51ef 100644 --- a/ScriptedEvents/Commands/MainCommand/ListScripts.cs +++ b/ScriptedEvents/Commands/MainCommand/ListScripts.cs @@ -25,7 +25,6 @@ public class ListScripts : ICommand /// public string Description => "Lists all event scripts."; - /// public bool SanitizeResponse => true; /// From 454524b3122720989af2f1bc1e534dc1e50e3722 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 12:59:56 +0200 Subject: [PATCH 018/359] Update MainPlugin.cs --- ScriptedEvents/MainPlugin.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index 7099a4b5..9c8afbe0 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -22,7 +22,11 @@ public class MainPlugin : Plugin /// /// Whether or not this build of the plugin is experimental. /// +#if ADEBUG public const bool IsExperimental = true; +#else + public const bool IsExperimental = false; +#endif /// /// Gets a link to the Scripted Events Discord server. From d991496bf3c3c2fd409ab9cdbaf4a1c02ebd315a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 21 Aug 2024 13:27:04 +0200 Subject: [PATCH 019/359] fix EFFECTIMMUNITYRULE bug --- .../RoundRule/EffectImmunityRuleAction.cs | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs index 4a51089e..947b5bab 100644 --- a/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/EffectImmunityRuleAction.cs @@ -50,35 +50,36 @@ public ActionResponse Execute(Script script) foreach (Player plr in players) { - List list; - if (dict.ContainsKey(plr)) - { - list = dict[plr]; - } - else - { - list = new(); - } - switch (mode) { - case "SET": - if (list.Contains(effectType)) - { - continue; - } + case "SET": + if (!dict.ContainsKey(plr)) + { + dict[plr] = new List(new[] { effectType }); + continue; + } - dict[plr].Add(effectType); - break; + if (dict[plr].Contains(effectType)) + { + continue; + } - case "REMOVE": - if (!list.Contains(effectType)) - { + dict[plr].Add(effectType); continue; - } - dict[plr].Remove(effectType); - break; + case "REMOVE": + if (!dict.ContainsKey(plr)) + { + continue; + } + + if (!dict[plr].Contains(effectType)) + { + continue; + } + + dict[plr].Remove(effectType); + continue; } } From ec770bc3b8d52aef072b02b632f55a1ee5397e72 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Fri, 23 Aug 2024 13:17:23 +0200 Subject: [PATCH 020/359] fix decomuentation error in infectrule --- ScriptedEvents/Actions/RoundRule/InfectRuleAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/RoundRule/InfectRuleAction.cs b/ScriptedEvents/Actions/RoundRule/InfectRuleAction.cs index 92b2fefb..cd7e6e1f 100644 --- a/ScriptedEvents/Actions/RoundRule/InfectRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/InfectRuleAction.cs @@ -33,7 +33,7 @@ public class InfectRuleAction : IScriptAction, IHelpInfo { new Argument("oldRole", typeof(RoleTypeId), "The role a player must die as to be infected.", true), new Argument("newRole", typeof(RoleTypeId), "The role a player will become.", true), - new Argument("movePlayer", typeof(bool), "TRUE if the player should be moved to their death position, FALSE (or leave empty) to leave at spawn.", false), + new Argument("movePlayer", typeof(bool), "TRUE if the player should be moved to the attacker on death, FALSE (or leave empty) to leave at spawn.", false), }; /// From 0f657f7ba41c65e6e2b3cf8c0604736455942e5d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Fri, 23 Aug 2024 13:17:27 +0200 Subject: [PATCH 021/359] Update EventHandlingModule.cs --- ScriptedEvents/API/Modules/EventHandlingModule.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Modules/EventHandlingModule.cs b/ScriptedEvents/API/Modules/EventHandlingModule.cs index a96daec2..62819398 100644 --- a/ScriptedEvents/API/Modules/EventHandlingModule.cs +++ b/ScriptedEvents/API/Modules/EventHandlingModule.cs @@ -500,6 +500,7 @@ public void OnRoundStarted() } } + // effect immunity action public void OnReceivingEffect(ReceivingEffectEventArgs ev) { if (ev.Player == null) return; @@ -569,7 +570,7 @@ public void OnDied(DiedEventArgs ev) Timing.CallDelayed(0.5f, () => { - ev.Player.Role.Set(rule.NewRole); + ev.Player.Role.Set(rule.NewRole, SpawnReason.ForceClass, RoleSpawnFlags.None); if (rule.MovePlayer) ev.Player.Teleport(pos); From c1f9ed1e3d0d1e3519eaa9ef443609a4d839810b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Fri, 23 Aug 2024 13:19:28 +0200 Subject: [PATCH 022/359] moronic behavior --- ScriptedEvents/Variables/MapVariables.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index fc92fa9a..2d63fd2e 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -39,7 +39,7 @@ public class MapVariables : IVariableGroup public class Seed : IStringVariable { /// - public string Name => "{MAPSALT}"; + public string Name => "{MAPSEED}"; /// public string Description => "All-in-one variable for map related information."; From 23e684838c5b964b877522e6c7ec21a381cbe78f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 4 Sep 2024 12:51:43 +0200 Subject: [PATCH 023/359] fix integration doc skill issues --- .../API/APITestLab/ScriptedEventsIntegration.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs b/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs index e23f6b90..1607bad9 100644 --- a/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs +++ b/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs @@ -8,7 +8,6 @@ using Exiled.API.Features; using Exiled.Loader; - using UnityEngine; /// /// The class for Scripted Events custom action integration. @@ -46,7 +45,7 @@ internal static class ScriptedEventsIntegration internal static MethodInfo RemoveAction => API?.GetMethod("UnregisterCustomAction"); /// - /// Gets the MethodInfo for removing a custom action. + /// Gets the MethodInfo for getting the players from a variable. /// internal static MethodInfo APIGetPlayersMethod => API?.GetMethod("GetPlayers"); @@ -65,13 +64,13 @@ internal static class ScriptedEventsIntegration /// Action implementation is Func>, where: /// /// Tuple - the action input, where: - /// string[] - The input to the action. Usually represented by single word strings, BUT can also include multiple words in one string. - /// object - The script in which the action was ran. + /// string[] - the input to the action. Usually represented by single word strings, BUT can also include multiple words in one string. + /// object - the script in which the action was ran. /// /// Tuple - the action result, where: - /// bool - Did action execute without any errors. - /// string - The action response to the console when there was an error.. - /// object[] - optional values to return from an action, either strings or Player[]s, anything different will result in an error. + /// bool - did action execute without any errors. + /// string - action response to the console when there was an error. + /// object[] - optional values to return from an action, only STRINGS or PLAYER ARRAYS, anything different will result in an ERROR. /// #pragma warning restore SA1629 // Documentation text should end with a period @@ -187,12 +186,12 @@ public static void UnregisterCustomActions() } /// - /// Gets the MethodInfo for getting the players from a variable. + /// Gets the player objects from a SE variable. /// /// The input to process. /// The script as object. /// The number of players to return (-1 for unlimited). - /// The list of players. + /// Player objects inhabiting the variable. internal static Player[] GetPlayers(string input, object script, int max = -1) { return (Player[])APIGetPlayersMethod.Invoke(null, new[] { input, script, max }); From 5ccab867b0890a44eb9443e7439c5ca970072d2f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 4 Sep 2024 12:52:03 +0200 Subject: [PATCH 024/359] update IsolateVariables method --- .../API/Modules/VariableSystemV2.cs | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/ScriptedEvents/API/Modules/VariableSystemV2.cs b/ScriptedEvents/API/Modules/VariableSystemV2.cs index a01b008f..5f94204f 100644 --- a/ScriptedEvents/API/Modules/VariableSystemV2.cs +++ b/ScriptedEvents/API/Modules/VariableSystemV2.cs @@ -364,29 +364,51 @@ public static string[] IsolateVariables(string input, Script source) source?.DebugLog($"Isolating variables from: {input}"); List result = ListPool.Pool.Get(); - for (int i = 0; i < input.Length; i++) + int inputLength = input.Length; + for (int i = 0; i < inputLength; i++) { - if (input[i] is not '{') + char openingSymbol = input[i]; + char closingSymbol = '\0'; + + switch (openingSymbol) { - continue; + case '{': + closingSymbol = '}'; break; + case '<': + closingSymbol = '>'; break; + default: + continue; } - int index = input.IndexOf('}', i); + int index = input.IndexOf(closingSymbol, i + 1); if (index == -1) { - continue; + break; } - source.DebugLog($"[IsolateVariables] Detected variable opening symbol, char {i}. Closing index {index}. Substring {index - i + 1}."); + bool hasSpace = false; + for (int j = i + 1; j < index; j++) + { + if (input[j] == ' ') + { + hasSpace = true; + break; + } + } - string variable = input.Substring(i, index - i + 1); - if (variable.Contains(" ")) + if (hasSpace) { continue; } - source.DebugLog($"[IsolateVariables] Extracted a variable: '{variable}'"); + string variable = input.Substring(i, index - i + 1); + + if (openingSymbol is '<' && !variable.Contains(':')) + { + continue; + } + source?.DebugLog($"[IsolateVariables] Extracted a variable: '{variable}'"); result.Add(variable); } From f41be48f742a1473c6dd36ff1ea4dc696ca86de2 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Thu, 5 Sep 2024 15:08:44 +0200 Subject: [PATCH 025/359] SEParser expansion + new syntax A lot of methods moved from VariableSystem and ScriptModule to SEParser + new <> syntax added --- .../API/Extensions/StringExtensions.cs | 12 + ScriptedEvents/API/Features/ApiHelper.cs | 5 +- .../API/Features/ArgumentProcessor.cs | 43 +- .../API/Features/ConditionHelperV2.cs | 3 +- ScriptedEvents/API/Features/SEParser.cs | 479 ++++++++++++++++++ ScriptedEvents/API/Modules/ScriptModule.cs | 186 +------ .../API/Modules/VariableSystemV2.cs | 119 +---- .../Actions/DebugActions/DebugMathAction.cs | 3 +- .../DebugActions/WaitUntilDebugAction.cs | 5 +- ScriptedEvents/Actions/Map/TeslaAction.cs | 3 +- .../Actions/RoundRule/DamageRuleAction.cs | 11 +- .../Actions/RoundRule/EffectRuleAction.cs | 3 +- .../Actions/Variable/AddToAction.cs | 1 - .../Actions/Variable/GlobalSaveAction.cs | 2 - .../Actions/Variable/LocalSaveAction.cs | 3 - .../Actions/Variable/TempVariableAction.cs | 3 +- .../Variables/PlayerCountVariables.cs | 3 +- 17 files changed, 534 insertions(+), 350 deletions(-) diff --git a/ScriptedEvents/API/Extensions/StringExtensions.cs b/ScriptedEvents/API/Extensions/StringExtensions.cs index 458e5c35..8c82b921 100644 --- a/ScriptedEvents/API/Extensions/StringExtensions.cs +++ b/ScriptedEvents/API/Extensions/StringExtensions.cs @@ -125,5 +125,17 @@ public static string JoinMessage(this object[] param, int skipCount = 0, string string str = StringBuilderPool.Pool.ToStringReturn(sb); return str.Substring(0, str.Length - sep.Length); } + + public static int CountOccurrences(this string text, char character) + { + int count = 0; + + foreach (char c in text) + { + if (c == character) count++; + } + + return count; + } } } diff --git a/ScriptedEvents/API/Features/ApiHelper.cs b/ScriptedEvents/API/Features/ApiHelper.cs index 64878265..9154e2e4 100644 --- a/ScriptedEvents/API/Features/ApiHelper.cs +++ b/ScriptedEvents/API/Features/ApiHelper.cs @@ -6,7 +6,6 @@ using Exiled.API.Features; using ScriptedEvents.Actions; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; /// @@ -134,7 +133,7 @@ public static Player[] GetPlayers(string input, object script, int max = -1) return null; } - ScriptModule.TryGetPlayers(input, max, out PlayerCollection list, actualScript); + SEParser.TryGetPlayers(input, max, out PlayerCollection list, actualScript); return list.GetInnerList().ToArray(); } @@ -146,7 +145,7 @@ public static Player[] GetPlayers(string input, object script, int max = -1) /// A tuple indicating success and the value. public static Tuple Math(string input, Script script) { - bool success = ConditionHelperV2.TryMath(VariableSystemV2.ReplaceVariables(input, script), out MathResult result); + bool success = ConditionHelperV2.TryMath(SEParser.ReplaceContaminatedValueSyntax(input, script), out MathResult result); return new(success, result.Result); } } diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index 127aa23a..c14d0c00 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -102,7 +102,7 @@ public static ArgumentProcessResult Process(Argument[] expectedArguments, string ArgumentProcessResult success = new(true); // raw args? aww hell nah :trollface: - List rawProcessedArgs = Exiled.API.Features.Pools.ListPool.Pool.Get(); + List rawProcessedArgs = new(); foreach (string arg in args) { if (TryProcessSmartArgument(arg, action, source, out string res, false)) @@ -133,14 +133,8 @@ public static ArgumentProcessResult Process(Argument[] expectedArguments, string success.NewParameters.AddRange(res.NewParameters); } - // If the raw argument list is larger than the expected list, do not process any extra arguments - // Edge-cases with long strings being the last parameter if (args.Length > expectedArguments.Length) { - // TODO: Figure out a method where ReplaceVariables isn't called for each extra argument. - // While also allowing variables + strings to be combined - // Eg. Using 'ReplaceVariable' instead won't turn '{PLAYERS}test' into '0test' like expected. - // This works for now, we need version 3 :| IEnumerable extraArgs = args.Skip(expectedArguments.Length); foreach (string arg in extraArgs) { @@ -150,7 +144,7 @@ public static ArgumentProcessResult Process(Argument[] expectedArguments, string } else { - success.NewParameters.Add(VariableSystemV2.ReplaceVariables(arg, source)); + success.NewParameters.Add(SEParser.ReplaceContaminatedValueSyntax(arg, source)); } Logger.Debug("New parameters: " + string.Join(", ", success.NewParameters, source)); @@ -235,7 +229,7 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action if (processForVariables) { - argument = VariableSystemV2.ReplaceVariables(argument, source); + argument = SEParser.ReplaceContaminatedValueSyntax(argument, source); if (ConditionHelperV2.TryMath(argument, out MathResult mathRes)) { @@ -261,7 +255,6 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action /// The provided input. /// The action or variable performing the process. /// The script source. - /// If brackets are required to convert variables. /// The output of the process. public static ArgumentProcessResult ProcessIndividualParameter(Argument expected, string input, IScriptComponent action, Script source, bool requireBrackets = true) { @@ -273,7 +266,21 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected if (expected is OptionsArgument options) { if (!options.Options.Any(o => o.Name.ToUpper() == input.ToUpper()) && options is not SuggestedOptionsArgument) - return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.ParameterError_Option, input, expected.ArgumentName, action.Name, string.Join(", ", options.Options.Select(x => x.Name)))); + { + return new( + false, + true, + expected.ArgumentName, + ErrorGen.Get( + ErrorCode.ParameterError_Option, + input, + expected.ArgumentName, + action.Name, + string.Join( + ", ", + options.Options.Select( + x => x.Name)))); + } success.NewParameters.Add(input); source?.DebugLog($"[OPTION ARG] [C: {action.Name}] Param {expected.ArgumentName} now has a processed value '{success.NewParameters.Last()}' and raw value '{input}'"); @@ -359,19 +366,19 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected // Array Types: case "Room[]": - if (!ScriptModule.TryGetRooms(input, out Room[] rooms, source)) + if (!SEParser.TryGetRooms(input, out Room[] rooms, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.ParameterError_Rooms, input, expected.ArgumentName)); success.NewParameters.Add(rooms); break; case "Door[]": - if (!ScriptModule.TryGetDoors(input, out Door[] doors, source)) + if (!SEParser.TryGetDoors(input, out Door[] doors, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidDoor, input)); success.NewParameters.Add(doors); break; case "Lift[]": - if (!ScriptModule.TryGetLifts(input, out Lift[] lifts, source)) + if (!SEParser.TryGetLifts(input, out Lift[] lifts, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidLift, input)); success.NewParameters.Add(lifts); @@ -379,14 +386,14 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected // Special case "PlayerCollection": - if (!ScriptModule.TryGetPlayers(input, null, out PlayerCollection players, source, requireBrackets)) + if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players, source, requireBrackets)) return new(false, true, expected.ArgumentName, players.Message); success.NewParameters.Add(players); break; case "Player": - if (!ScriptModule.TryGetPlayers(input, null, out PlayerCollection players1, source, requireBrackets)) + if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players1, source, requireBrackets)) return new(false, true, expected.ArgumentName, players1.Message); if (players1.Length == 0) @@ -426,7 +433,7 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected // Unsupported types: Parse variables in string and use that as a param (RawArguments are used for getting the raw string) // TODO: ReplaceVariable works only when a "clean" variable is provided, meaning it doesnt work when provided things like ({PLAYERSALIVE}) // so we need to fix that instead of calling ReplaceVariables all the time - success.NewParameters.Add(VariableSystemV2.ReplaceVariables(input, source, requireBrackets)); + success.NewParameters.Add(SEParser.ReplaceContaminatedValueSyntax(input, source)); break; } @@ -465,7 +472,7 @@ private static ArgumentProcessResult HandlePlayerListComprehension(string[] inAr } else { - if (!ScriptModule.TryGetPlayers(playerVarNameLoopingThrough, null, out PlayerCollection outPlayers, source)) + if (!SEParser.TryGetPlayers(playerVarNameLoopingThrough, null, out PlayerCollection outPlayers, source)) { Logger.Debug("$FOR: provided player variable to loop through is invalid", source); return new(false, true, playerVarNameLoopingThrough, ErrorGen.Get(ErrorCode.InvalidPlayerVariable, playerVarNameLoopingThrough)); diff --git a/ScriptedEvents/API/Features/ConditionHelperV2.cs b/ScriptedEvents/API/Features/ConditionHelperV2.cs index 0d45664e..54f4c855 100644 --- a/ScriptedEvents/API/Features/ConditionHelperV2.cs +++ b/ScriptedEvents/API/Features/ConditionHelperV2.cs @@ -6,7 +6,6 @@ using System.Data; using System.Text.RegularExpressions; - using ScriptedEvents.API.Modules; using ScriptedEvents.Conditions.Floats; using ScriptedEvents.Conditions.Interfaces; using ScriptedEvents.Conditions.Strings; @@ -254,7 +253,7 @@ private static ConditionResponse EvaluateInternal(string input, Script source = foreach (string fragOr in orSplit) { source?.DebugLog($"FRAG [OR]: " + fragOr); - string convertedFrag = VariableSystemV2.ReplaceVariables(fragOr, source); + string convertedFrag = SEParser.ReplaceContaminatedValueSyntax(fragOr, source); ConditionResponse eval = EvaluateSingleCondition(convertedFrag, group); if (!eval.Success) { diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 9e5374cd..0732ec9e 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -1,7 +1,17 @@ namespace ScriptedEvents.API.Features { using System; + using System.Collections.Generic; + using System.Linq; + using Exiled.API.Enums; + using Exiled.API.Features; + using Exiled.API.Features.Doors; + using Exiled.API.Features.Pools; + using Exiled.API.Features.Roles; + using Exiled.CustomItems.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; @@ -157,5 +167,474 @@ public static object Parse(string input, Type enumType, Script source, bool requ return null; } + + /// + /// Try-get a array given an input. + /// + /// The input. + /// The doors. + /// The script source. + /// Whether or not the try-get was successful. + public static bool TryGetDoors(string input, out Door[] doors, Script source) + { + List doorList = ListPool.Pool.Get(); + if (input is "*" or "ALL") + { + doorList = Door.List.ToList(); + } + else if (TryParse(input, out ZoneType zt, source)) + { + doorList = Door.List.Where(d => d.Zone.HasFlag(zt)).ToList(); + } + else if (TryParse(input, out DoorType dt, source)) + { + doorList = Door.List.Where(d => d.Type == dt).ToList(); + } + else if (TryParse(input, out RoomType rt, source)) + { + doorList = Door.List.Where(d => d.Room?.Type == rt).ToList(); + } + else + { + doorList = Door.List.Where(d => d.Name.ToLower() == input.ToLower()).ToList(); + } + + doorList = doorList.Where(d => d.IsElevator is false && d.Type is not DoorType.Scp914Door && d.Type is not DoorType.Scp079First && d.Type is not DoorType.Scp079Second && AirlockController.Get(d) is null).ToList(); + doors = ListPool.Pool.ToArrayReturn(doorList); + return doors.Length > 0; + } + + /// + /// Try-get a array given an input. + /// + /// The input. + /// The lift objects. + /// The script source. + /// Whether or not the try-get was successful. + public static bool TryGetLifts(string input, out Lift[] lifts, Script source) + { + List liftList = ListPool.Pool.Get(); + if (input is "*" or "ALL") + { + liftList = Lift.List.ToList(); + } + else if (TryParse(input, out ElevatorType et, source)) + { + liftList = Lift.List.Where(l => l.Type == et).ToList(); + } + else + { + liftList = Lift.List.Where(l => l.Name.ToLower() == input.ToLower()).ToList(); + } + + lifts = ListPool.Pool.ToArrayReturn(liftList); + return lifts.Length > 0; + } + + /// + /// Try-get a array given an input. + /// + /// The input. + /// The rooms. + /// The script source. + /// Whether or not the try-get was successful. + public static bool TryGetRooms(string input, out Room[] rooms, Script source) + { + List roomList = ListPool.Pool.Get(); + if (input is "*" or "ALL") + { + roomList = Room.List.ToList(); + } + else if (TryParse(input, out ZoneType zt, source)) + { + roomList = Room.List.Where(room => room.Zone.HasFlag(zt)).ToList(); + } + else if (TryParse(input, out RoomType rt, source)) + { + roomList = Room.List.Where(d => d.Type == rt).ToList(); + } + else + { + roomList = Room.List.Where(d => d.Name.ToLower() == input.ToLower()).ToList(); + } + + rooms = ListPool.Pool.ToArrayReturn(roomList); + return rooms.Length > 0; + } + + /// + /// Converts a string input into a player collection. + /// + /// The input. + /// The maximum amount of players to give back, or for unlimited. + /// A representing the players. + /// The script using the API. Used for per-script variables. + /// Are brackets required. + /// Whether or not the process errored. + /// This method differs from + public static bool TryGetPlayers(string input, int? amount, out PlayerCollection collection, Script source, bool brecketsRequired = true) + { + void Log(string msg) + { + Logger.Debug($"[SEParser] [TryGetPlayers] {msg}", source); + } + + input = input.RemoveWhitespace(); + List list = new(); + + if (input.ToUpper() is "*" or "ALL") + { + Log($"Input {input.ToUpper()} specifies all players on the server."); + list = Player.List.ToList(); + } + else if (VariableSystemV2.TryGetPlayers(input, source, out PlayerCollection playersFromVariable, brecketsRequired)) + { + list = playersFromVariable.GetInnerList(); + Log($"Input {input} is a valid variable. Fetch got {list.Count} players."); + } + else + { + Log($"Input {input} is not a valid variable nor does it specify all players, trying to match directly."); + Player match = Player.Get(input); + if (match is not null) + list.Add(match); + } + + if (MainPlugin.Configs.IgnoreOverwatch) + list.RemoveAll(p => p.Role.Type is RoleTypeId.Overwatch); + + if (amount.HasValue && amount.Value > 0 && list.Count > 0) + { + Log("Amount of fetched players bigger than limit, removing players."); + while (list.Count > amount.Value) + { + list.PullRandomItem(); + } + } + + // Return + Log($"Complete! Returning {list.Count} players."); + collection = new(list); + return true; + } + + /// + /// Isolates all values like. + /// + /// The input string. + /// The script source. + /// The variables used within the string. + public static string[] IsolateValueSyntax(string input, Script source, bool includeAccessors = true) + { + void Log(string msg) + { + Logger.Debug($"[SEParser] [IsolateValueSyntax] {msg}", source); + } + + Log($"Isolating values from '{input}'"); + List result = ListPool.Pool.Get(); + + int inputLength = input.Length; + for (int i = 0; i < inputLength; i++) + { + char openingSymbol = input[i]; + char closingSymbol; + + switch (openingSymbol) + { + case '{': + closingSymbol = '}'; break; + case '<': + if (!includeAccessors) continue; + closingSymbol = '>'; break; + default: + continue; + } + + int index = input.IndexOf(closingSymbol, i + 1); + if (index == -1) + { + break; + } + + bool hasSpace = false; + for (int j = i + 1; j < index; j++) + { + if (input[j] == ' ') + { + hasSpace = true; + break; + } + } + + if (hasSpace) + { + continue; + } + + string variable = input.Substring(i, index - i + 1); + + Log($"Extracted a value '{variable}'"); + result.Add(variable); + } + + return ListPool.Pool.ToArrayReturn(result); + } + + public static bool TryGetAccessor(string input, Script source, out string result) + { + // + // + result = null; + + if (!input.StartsWith("<") || !input.EndsWith(">")) + { + return false; + } + + // PLR:ROLE + // PLR + input = input.Substring(1, input.Length - 1); + + if (input.Contains(' ') || input.Contains("<") || input.Contains(">")) + { + return false; + } + + // [PLR, ROLE] + // [PLR] + string[] parts = input.Split(':'); + + if (parts.Length > 2) + { + return false; + } + else if (parts.Length == 1) + { + // [PLR, NAME] + parts.Append("NAME"); + } + + if (!VariableSystemV2.TryGetPlayers(parts[0], source, out PlayerCollection players, false)) + { + return false; + } + + if (players.Length != 1) + { + return false; + } + + Player ply = players[0]; + + switch (parts[1]) + { + case "NAME": + result = ply.Nickname; + break; + + case "DISPLAYNAME" or "DPNAME": + result = ply.DisplayNickname; + break; + + case "USERID" or "UID": + result = ply.UserId; + break; + + case "PLAYERID" or "PID": + result = ply.Id.ToString(); + break; + + case "ROLE": + result = ply.Role.Type.ToString(); + break; + + case "TEAM": + result = ply.Role.Team.ToString(); + break; + + case "ROOM": + result = ply.CurrentRoom.Type.ToString(); + break; + + case "ZONE": + result = ply.Zone.ToString(); + break; + + case "HP" or "HEALTH": + result = ply.Health.ToString(); + break; + + case "ITEMCOUNT": + result = ply.Items.Count.ToString(); + break; + + case "ITEMS": + result = ply.Items.Count > 0 + ? string.Join("|", ply.Items.Select(item => CustomItem.TryGet(item, out CustomItem ci) ? ci.Name : item.Type.ToString())) + : "NONE"; + break; + + case "HELDITEM": + result = (CustomItem.TryGet(ply.CurrentItem, out CustomItem ci) + ? ci.Name + : ply.CurrentItem?.Type.ToString()) ?? "NONE"; + break; + + case "GOD": + result = ply.IsGodModeEnabled.ToUpper(); + break; + + case "POS": + result = $"{ply.Position.x} {ply.Position.y} {ply.Position.z}"; + break; + + case "POSX": + result = ply.Position.x.ToString(); + break; + + case "POSY": + result = ply.Position.y.ToString(); + break; + + case "POSZ": + result = ply.Position.z.ToString(); + break; + + case "TIER" when ply.Role is Scp079Role scp079role: + result = scp079role.Level.ToString(); + break; + + case "TIER": + result = "NONE"; + break; + + case "GROUP": + result = ply.GroupName; + break; + + case "CUFFED": + result = ply.IsCuffed.ToUpper(); + break; + + case "CUSTOMINFO" or "CINFO" or "CUSTOMI": + result = !string.IsNullOrEmpty(ply.CustomInfo) ? ply.CustomInfo : "NONE"; + break; + + case "XSIZE": + result = ply.Scale.x.ToString(); + break; + + case "YSIZE": + result = ply.Scale.y.ToString(); + break; + + case "ZSIZE": + result = ply.Scale.z.ToString(); + break; + + case "KILLS": + result = MainPlugin.Handlers.PlayerKills.TryGetValue(ply, out int v) ? v.ToString() : "0"; + break; + + case "EFFECTS" when ply.ActiveEffects.Any(): + result = string.Join(", ", ply.ActiveEffects.Select(eff => eff.name)); + break; + + case "EFFECTS": + result = "NONE"; + break; + + case "USINGNOCLIP" when ply.Role is FpcRole role: + result = role.IsNoclipEnabled.ToUpper(); + break; + + case "USINGNOCLIP": + result = "FALSE"; + break; + + case "CANNOCLIP": + result = ply.IsNoclipPermitted.ToUpper(); + break; + + case "STAMINA": + result = ply.Stamina.ToString(); + break; + + case "ISSTAFF": + result = ply.RemoteAdminAccess.ToUpper(); + break; + + case "AHP": + result = ply.ArtificialHealth.ToString(); + break; + + default: + result = ply.SessionVariables.ContainsKey(parts[1]) + ? ply.SessionVariables[parts[1]].ToString() + : "UNDEFINED"; + break; + } + + return true; + } + + /// + /// Replaces all the occurrences of a value syntax in a string with regular text. + /// + /// The string to perform the replacements on. + /// The script that is currently running to replace values. + /// The modified string. + /// This is intended for strings that contain both regular text and value syntax. Otherwise, see . + public static string ReplaceContaminatedValueSyntax(string input, Script source) + { + void Log(string msg) + { + Logger.Debug($"[SEParser] [RCVS] {msg}", source); + } + + string[] values = IsolateValueSyntax(input, source); + + foreach (string value in values) + { + Log("Isolated value syntax: " + value); + + if (VariableSystemV2.TryGetVariable(value, source, out VariableResult vresult)) + { + if (!vresult.ProcessorSuccess) + { + Logger.Warn($"Variable '{vresult.Variable.Name}' argument error: {vresult.Message}", source); + continue; + } + + try + { + input = input.Replace(value, vresult.String(source, vresult.Reversed)); + } + catch (InvalidCastException e) + { + Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, e.Message), source); + } + catch (Exception e) + { + Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, source?.Debug == true ? e : e.Message), source); + } + + Log("Value syntax was successfully replaced."); + continue; + } + + if (TryGetAccessor(value, source, out string aresult)) + { + input.Replace(value, aresult); + Log("Value syntax was successfully replaced."); + continue; + } + + Log($"Value syntax {value} cannot be replaced (perhaps a formatting issue?)"); + } + + return input; + } } } \ No newline at end of file diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index 98f0df6d..61246d30 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -6,17 +6,13 @@ namespace ScriptedEvents.API.Modules using System.IO; using System.Linq; using System.Reflection; - using System.Text.RegularExpressions; using CommandSystem; - using Exiled.API.Enums; using Exiled.API.Features; - using Exiled.API.Features.Doors; using Exiled.API.Features.Pools; using MEC; - using PlayerRoles; using RemoteAdmin; using ScriptedEvents.Actions; @@ -30,8 +26,6 @@ namespace ScriptedEvents.API.Modules using ScriptedEvents.Structures; - using AirlockController = Exiled.API.Features.Doors.AirlockController; - /// /// A helper class to read and execute scripts, and register actions, as well as providing useful API for individual actions. /// @@ -364,7 +358,7 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre DebugLog($"[ExtractorSyntax] Variables section: {variablesSection}", script); DebugLog($"[ExtractorSyntax] Action section: {actionSection}", script); - resultVariableNames = VariableSystemV2.IsolateVariables(variablesSection, script); + resultVariableNames = SEParser.IsolateValueSyntax(variablesSection, script, false); if (resultVariableNames.Length == 0) { goto leave_extractor_parsing; @@ -502,184 +496,6 @@ public Script ReadAndRun(string scriptName, ICommandSender executor, bool dispos return scr; } - /// - /// Converts an input into a list of players. - /// - /// The input. - /// The maximum amount of players to give back, or for unlimited. - /// A representing the players. - /// The script using the API. Used for per-script variables. - /// Are brackets required. - /// Whether or not the process errored. - public static bool TryGetPlayers(string input, int? amount, out PlayerCollection collection, Script source, bool brecketsRequired = true) - { - void Log(string msg) - { - Logger.Debug($"[TryGetPlayers] {msg}", source); - } - - Log($"Trying to get '{input}' player collection."); - - input = input.RemoveWhitespace(); - List list = new(); - - // TODO: When a variable with a player id is provided, it wont work since the raw variable name cant match to the regex - // but if we convert a valid variable to int, a e.g. player variable with 1 player will then say that "yeah actually im the server" - // which is just a tiny bit stupid - string patternForPlayerIdUsage = @"^\d+(\.\d+)*\.?$"; - - if (input.ToUpper() is "*" or "ALL") - { - Log("Getting all players"); - list = Player.List.ToList(); - } - else if (Regex.IsMatch(input, patternForPlayerIdUsage)) - { - Log("Doing regex"); - string[] splitInput = input.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); - - foreach (string idInStr in splitInput) - { - if (!int.TryParse(idInStr, out int playerId)) - continue; - - if (!Player.TryGet(playerId, out Player player)) - continue; - - Log($"Extracted a player object from {idInStr} string."); - list.Add(player); - } - } - else if (VariableSystemV2.TryGetPlayers(input, source, out PlayerCollection playersFromVariable, brecketsRequired)) - { - list = playersFromVariable.GetInnerList(); - Log($"Doing by variable: got {list.Count} players"); - } - else - { - Log("Matching directly"); - Player match = Player.Get(input); - if (match is not null) - list.Add(match); - } - - // Shuffle, Remove unconnected/overwatch, limit - list.ShuffleList(); - - /* list.RemoveAll(p => !p.IsConnected); */ - - if (MainPlugin.Configs.IgnoreOverwatch) - list.RemoveAll(p => p.Role.Type is RoleTypeId.Overwatch); - - if (amount.HasValue && amount.Value > 0 && list.Count > 0) - { - Log("Removing players"); - while (list.Count > amount.Value) - { - list.PullRandomItem(); - } - } - - // Return - Log($"Complete! Returning {list.Count} players"); - collection = new(list); - return true; - } - - /// - /// Try-get a array given an input. - /// - /// The input. - /// The doors. - /// The script source. - /// Whether or not the try-get was successful. - public static bool TryGetDoors(string input, out Door[] doors, Script source) - { - List doorList = ListPool.Pool.Get(); - if (input is "*" or "ALL") - { - doorList = Door.List.ToList(); - } - else if (SEParser.TryParse(input, out ZoneType zt, source)) - { - doorList = Door.List.Where(d => d.Zone.HasFlag(zt)).ToList(); - } - else if (SEParser.TryParse(input, out DoorType dt, source)) - { - doorList = Door.List.Where(d => d.Type == dt).ToList(); - } - else if (SEParser.TryParse(input, out RoomType rt, source)) - { - doorList = Door.List.Where(d => d.Room?.Type == rt).ToList(); - } - else - { - doorList = Door.List.Where(d => d.Name.ToLower() == input.ToLower()).ToList(); - } - - doorList = doorList.Where(d => d.IsElevator is false && d.Type is not DoorType.Scp914Door && d.Type is not DoorType.Scp079First && d.Type is not DoorType.Scp079Second && AirlockController.Get(d) is null).ToList(); - doors = ListPool.Pool.ToArrayReturn(doorList); - return doors.Length > 0; - } - - /// - /// Try-get a array given an input. - /// - /// The input. - /// The lift objects. - /// The script source. - /// Whether or not the try-get was successful. - public static bool TryGetLifts(string input, out Lift[] lifts, Script source) - { - List liftList = ListPool.Pool.Get(); - if (input is "*" or "ALL") - { - liftList = Lift.List.ToList(); - } - else if (SEParser.TryParse(input, out ElevatorType et, source)) - { - liftList = Lift.List.Where(l => l.Type == et).ToList(); - } - else - { - liftList = Lift.List.Where(l => l.Name.ToLower() == input.ToLower()).ToList(); - } - - lifts = ListPool.Pool.ToArrayReturn(liftList); - return lifts.Length > 0; - } - - /// - /// Try-get a array given an input. - /// - /// The input. - /// The rooms. - /// The script source. - /// Whether or not the try-get was successful. - public static bool TryGetRooms(string input, out Room[] rooms, Script source) - { - List roomList = ListPool.Pool.Get(); - if (input is "*" or "ALL") - { - roomList = Room.List.ToList(); - } - else if (SEParser.TryParse(input, out ZoneType zt, source)) - { - roomList = Room.List.Where(room => room.Zone.HasFlag(zt)).ToList(); - } - else if (SEParser.TryParse(input, out RoomType rt, source)) - { - roomList = Room.List.Where(d => d.Type == rt).ToList(); - } - else - { - roomList = Room.List.Where(d => d.Name.ToLower() == input.ToLower()).ToList(); - } - - rooms = ListPool.Pool.ToArrayReturn(roomList); - return rooms.Length > 0; - } - /// /// Shows a RueI hint. /// diff --git a/ScriptedEvents/API/Modules/VariableSystemV2.cs b/ScriptedEvents/API/Modules/VariableSystemV2.cs index 5f94204f..a3f61e87 100644 --- a/ScriptedEvents/API/Modules/VariableSystemV2.cs +++ b/ScriptedEvents/API/Modules/VariableSystemV2.cs @@ -6,7 +6,7 @@ using Exiled.API.Features; using Exiled.API.Features.Pools; - using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.Structures; @@ -256,8 +256,8 @@ public static bool TryGetVariable(string name, Script source, out VariableResult /// The players found. If the operation was not successful, this will contain the error reason. /// If brackets are required to parse variables. /// Whether or not players were found. - /// This should be used for variables where is . Otherwise, use . - /// + /// This should be used for variables where is . Otherwise, use . + /// public static bool TryGetPlayers(string name, Script source, out PlayerCollection players, bool requireBrackets = true) { DebugLog($"[TryGetPlayers] Trying to fetch {name} variable. [requireBrackets {requireBrackets}]", source); @@ -302,119 +302,6 @@ public static string ReplaceVariable(string input, Script source, bool requireBr return input; } - /// - /// Replaces all the occurrences of variables in a string. - /// - /// The string to perform the replacements on. - /// The script that is currently running to replace variables. Used only for per-script variables. - /// If brackets are required to parse variables. - /// The modified string. - /// This is intended for strings that contain both regular text and variables. Otherwise, see . - public static string ReplaceVariables(string input, Script source, bool requireBrackets = true) - { - // TODO: make better :trollface: - if (!requireBrackets) - return ReplaceVariable(input, source, false); - - string[] variables = IsolateVariables(input, source); - - foreach (string variable in variables) - { - source.DebugLog("Isolated variable: " + variable); - - if (!TryGetVariable(variable, source, out VariableResult vresult, requireBrackets)) - { - source.DebugLog("Invalid variable."); - continue; - } - - source.DebugLog("Valid variable."); - - if (!vresult.ProcessorSuccess) - { - Logger.Warn($"Variable '{vresult.Variable.Name}' argument error: {vresult.Message}", source); - continue; - } - - try - { - input = input.Replace(variable, vresult.String(source, vresult.Reversed)); - } - catch (InvalidCastException e) - { - Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, e.Message), source); - } - catch (Exception e) - { - Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, source?.Debug == true ? e : e.Message), source); - } - } - - return input; - } - - /// - /// Isolates all variables from a string. - /// - /// The input string. - /// The script source. - /// The variables used within the string. - public static string[] IsolateVariables(string input, Script source) - { - source?.DebugLog($"Isolating variables from: {input}"); - List result = ListPool.Pool.Get(); - - int inputLength = input.Length; - for (int i = 0; i < inputLength; i++) - { - char openingSymbol = input[i]; - char closingSymbol = '\0'; - - switch (openingSymbol) - { - case '{': - closingSymbol = '}'; break; - case '<': - closingSymbol = '>'; break; - default: - continue; - } - - int index = input.IndexOf(closingSymbol, i + 1); - if (index == -1) - { - break; - } - - bool hasSpace = false; - for (int j = i + 1; j < index; j++) - { - if (input[j] == ' ') - { - hasSpace = true; - break; - } - } - - if (hasSpace) - { - continue; - } - - string variable = input.Substring(i, index - i + 1); - - if (openingSymbol is '<' && !variable.Contains(':')) - { - continue; - } - - source?.DebugLog($"[IsolateVariables] Extracted a variable: '{variable}'"); - result.Add(variable); - } - - return ListPool.Pool.ToArrayReturn(result); - } - public override void Init() { base.Init(); diff --git a/ScriptedEvents/Actions/DebugActions/DebugMathAction.cs b/ScriptedEvents/Actions/DebugActions/DebugMathAction.cs index 0ea3e8a3..2e54f528 100644 --- a/ScriptedEvents/Actions/DebugActions/DebugMathAction.cs +++ b/ScriptedEvents/Actions/DebugActions/DebugMathAction.cs @@ -6,7 +6,6 @@ using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class DebugMathAction : IScriptAction, IHiddenAction @@ -34,7 +33,7 @@ public class DebugMathAction : IScriptAction, IHiddenAction /// public ActionResponse Execute(Script script) { - string formula = VariableSystemV2.ReplaceVariables(RawArguments.JoinMessage(), script); + string formula = SEParser.ReplaceContaminatedValueSyntax(RawArguments.JoinMessage(), script); if (!ConditionHelperV2.TryMath(formula, out MathResult result)) { return new(MessageType.NotANumberOrCondition, this, "condition", null, formula, result); diff --git a/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs b/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs index d0838211..3d4b2aa4 100644 --- a/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs +++ b/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs @@ -3,15 +3,12 @@ namespace ScriptedEvents.Actions using System; using System.Collections.Generic; - using Exiled.API.Features; - using MEC; using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class WaitUntilDebugAction : ITimingAction, IHiddenAction, IHelpInfo @@ -56,7 +53,7 @@ private IEnumerator InternalWaitUntil(Script script, string input) while (true) { ConditionResponse response = ConditionHelperV2.Evaluate(input, script); - Logger.Info($"CONDITION: {VariableSystemV2.ReplaceVariables(input, script)} \\\\ SUCCESS: {response.Success} \\\\ PASSED: {response.Passed}", script); + Logger.Info($"CONDITION: {SEParser.ReplaceContaminatedValueSyntax(input, script)} \\\\ SUCCESS: {response.Success} \\\\ PASSED: {response.Passed}", script); if (response.Success) { if (response.Passed) diff --git a/ScriptedEvents/Actions/Map/TeslaAction.cs b/ScriptedEvents/Actions/Map/TeslaAction.cs index a6297e04..8eaa9a2b 100644 --- a/ScriptedEvents/Actions/Map/TeslaAction.cs +++ b/ScriptedEvents/Actions/Map/TeslaAction.cs @@ -15,7 +15,6 @@ using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; using Tesla = Exiled.API.Features.TeslaGate; @@ -73,7 +72,7 @@ public ActionResponse Execute(Script script) switch (mode) { case "PLAYERS": - if (!ScriptModule.TryGetPlayers(target, null, out PlayerCollection players, script)) + if (!SEParser.TryGetPlayers(target, null, out PlayerCollection players, script)) return new(false, players.Message); foreach (Player player in players) diff --git a/ScriptedEvents/Actions/RoundRule/DamageRuleAction.cs b/ScriptedEvents/Actions/RoundRule/DamageRuleAction.cs index 3f7af0a8..40ea9458 100644 --- a/ScriptedEvents/Actions/RoundRule/DamageRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/DamageRuleAction.cs @@ -7,7 +7,6 @@ using ScriptedEvents.API.Enums; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; using Rule = ScriptedEvents.Structures.DamageRule; @@ -57,7 +56,7 @@ public ActionResponse Execute(Script script) { rule = new(attackerRole, receiverTeam); } - else if (ScriptModule.TryGetPlayers(RawArguments[1], null, out PlayerCollection players, script)) + else if (SEParser.TryGetPlayers(RawArguments[1], null, out PlayerCollection players, script)) { rule = new(attackerRole, players); } @@ -68,7 +67,7 @@ public ActionResponse Execute(Script script) { rule = new(receiverTeam2, attackerRole2); } - else if (ScriptModule.TryGetPlayers(RawArguments[0], null, out PlayerCollection players2, script)) + else if (SEParser.TryGetPlayers(RawArguments[0], null, out PlayerCollection players2, script)) { rule = new(players2, attackerRole2); } @@ -85,7 +84,7 @@ public ActionResponse Execute(Script script) { rule = new(attackerTeam, receiverRole); } - else if (ScriptModule.TryGetPlayers(RawArguments[1], null, out PlayerCollection players, script)) + else if (SEParser.TryGetPlayers(RawArguments[1], null, out PlayerCollection players, script)) { rule = new(attackerTeam, players); } @@ -96,12 +95,12 @@ public ActionResponse Execute(Script script) { rule = new(receiverRole2, attackerTeam2); } - else if (ScriptModule.TryGetPlayers(RawArguments[0], null, out PlayerCollection players2, script)) + else if (SEParser.TryGetPlayers(RawArguments[0], null, out PlayerCollection players2, script)) { rule = new(players2, attackerTeam2); } } - else if (ScriptModule.TryGetPlayers(RawArguments[0], null, out PlayerCollection attackers, script) && ScriptModule.TryGetPlayers(RawArguments[1], null, out PlayerCollection receivers, script)) + else if (SEParser.TryGetPlayers(RawArguments[0], null, out PlayerCollection attackers, script) && SEParser.TryGetPlayers(RawArguments[1], null, out PlayerCollection receivers, script)) { rule = new(attackers, receivers); } diff --git a/ScriptedEvents/Actions/RoundRule/EffectRuleAction.cs b/ScriptedEvents/Actions/RoundRule/EffectRuleAction.cs index c6315b9e..cc864da9 100644 --- a/ScriptedEvents/Actions/RoundRule/EffectRuleAction.cs +++ b/ScriptedEvents/Actions/RoundRule/EffectRuleAction.cs @@ -11,7 +11,6 @@ using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class EffectRuleAction : IScriptAction, IHelpInfo @@ -75,7 +74,7 @@ public ActionResponse Execute(Script script) { list = 2; } - else if (ScriptModule.TryGetPlayers(RawArguments[1], null, out players, script)) + else if (SEParser.TryGetPlayers(RawArguments[1], null, out players, script)) { if (!players.Success) { diff --git a/ScriptedEvents/Actions/Variable/AddToAction.cs b/ScriptedEvents/Actions/Variable/AddToAction.cs index 3f2b0ee6..7d2acc1b 100644 --- a/ScriptedEvents/Actions/Variable/AddToAction.cs +++ b/ScriptedEvents/Actions/Variable/AddToAction.cs @@ -43,7 +43,6 @@ public ActionResponse Execute(Script script) IStringVariable var = (IStringVariable)Arguments[0]; string input = Arguments.JoinMessage(1); - input = VariableSystemV2.ReplaceVariables(input, script); input = $"{var.Value} {input}"; try diff --git a/ScriptedEvents/Actions/Variable/GlobalSaveAction.cs b/ScriptedEvents/Actions/Variable/GlobalSaveAction.cs index 52e3840e..a955017d 100644 --- a/ScriptedEvents/Actions/Variable/GlobalSaveAction.cs +++ b/ScriptedEvents/Actions/Variable/GlobalSaveAction.cs @@ -48,8 +48,6 @@ public ActionResponse Execute(Script script) string input = Arguments.JoinMessage(1); - input = VariableSystemV2.ReplaceVariables(input, script); - try { float value = ConditionHelperV2.Math(input); diff --git a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs b/ScriptedEvents/Actions/Variable/LocalSaveAction.cs index bde9ba5d..826a2f95 100644 --- a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs +++ b/ScriptedEvents/Actions/Variable/LocalSaveAction.cs @@ -6,7 +6,6 @@ using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class LocalSaveAction : IScriptAction, IHelpInfo @@ -48,8 +47,6 @@ public ActionResponse Execute(Script script) string input = Arguments.JoinMessage(1); - input = VariableSystemV2.ReplaceVariables(input, script); - try { float value = ConditionHelperV2.Math(input); diff --git a/ScriptedEvents/Actions/Variable/TempVariableAction.cs b/ScriptedEvents/Actions/Variable/TempVariableAction.cs index 1db0770e..cd709b2f 100644 --- a/ScriptedEvents/Actions/Variable/TempVariableAction.cs +++ b/ScriptedEvents/Actions/Variable/TempVariableAction.cs @@ -44,8 +44,7 @@ public ActionResponse Execute(Script script) return new(true); } - string input = RawArguments.JoinMessage(0); - input = VariableSystemV2.ReplaceVariables(input, script).Replace("\\n", "\n"); + string input = Arguments.JoinMessage().Replace("\\n", "\n"); try { diff --git a/ScriptedEvents/Variables/PlayerCountVariables.cs b/ScriptedEvents/Variables/PlayerCountVariables.cs index 8603476d..502cf8d0 100644 --- a/ScriptedEvents/Variables/PlayerCountVariables.cs +++ b/ScriptedEvents/Variables/PlayerCountVariables.cs @@ -7,7 +7,6 @@ using Exiled.API.Features; using Exiled.API.Features.Roles; using ScriptedEvents.API.Features; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; using ScriptedEvents.Variables.Interfaces; @@ -207,7 +206,7 @@ public IEnumerable Players string playersAsString = VariableStorage.Read(RawArguments[0]); List list = new(); - if (ScriptModule.TryGetPlayers(playersAsString, null, out PlayerCollection collection, Source)) + if (SEParser.TryGetPlayers(playersAsString, null, out PlayerCollection collection, Source)) { return list; } From 8c5494c62b6be9c65e0c2ec3acd4783b89402707 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Thu, 5 Sep 2024 15:10:49 +0200 Subject: [PATCH 026/359] 3.2.0 -> 4.0.0 --- ScriptedEvents/MainPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index 9c8afbe0..0ca44f2f 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -80,7 +80,7 @@ public class MainPlugin : Plugin public override string Author => "Thunder and Elektryk_Andrzej"; /// - public override Version Version => new(3, 2, 0); + public override Version Version => new(4, 0, 0); /// public override Version RequiredExiledVersion => new(8, 7, 0); From 2ed75519fa862c78ea97e2d91421ad9af9255079 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Thu, 5 Sep 2024 17:51:07 +0200 Subject: [PATCH 027/359] make better TryGetAccessor --- ScriptedEvents/API/Features/SEParser.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 0732ec9e..73916fa6 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -383,21 +383,28 @@ void Log(string msg) public static bool TryGetAccessor(string input, Script source, out string result) { + void Log(string msg) + { + Logger.Debug($"[SEParser] [TryGetAccessor] {msg}", source); + } + // // result = null; if (!input.StartsWith("<") || !input.EndsWith(">")) { + Log("Fail. Accessor definers not present."); return false; } // PLR:ROLE // PLR - input = input.Substring(1, input.Length - 1); + input = input.Substring(1, input.Length - 2); - if (input.Contains(' ') || input.Contains("<") || input.Contains(">")) + if (input.Contains(' ') || input.Contains('<') || input.Contains('>')) { + Log("Fail. After processing, accessor contains whitespace or definers."); return false; } @@ -407,6 +414,7 @@ public static bool TryGetAccessor(string input, Script source, out string result if (parts.Length > 2) { + Log("Fail. After splitting, more than 2 parts defined."); return false; } else if (parts.Length == 1) @@ -417,11 +425,13 @@ public static bool TryGetAccessor(string input, Script source, out string result if (!VariableSystemV2.TryGetPlayers(parts[0], source, out PlayerCollection players, false)) { + Log("Fail. Player variable invalid."); return false; } if (players.Length != 1) { + Log("Fail. Player amount not equal 1."); return false; } @@ -576,6 +586,7 @@ public static bool TryGetAccessor(string input, Script source, out string result break; } + Log("Success! Returning " + result); return true; } @@ -626,7 +637,7 @@ void Log(string msg) if (TryGetAccessor(value, source, out string aresult)) { - input.Replace(value, aresult); + input = input.Replace(value, aresult); Log("Value syntax was successfully replaced."); continue; } From 31653404fda04eb736b2110dcd7bcbfedd64f08d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Fri, 6 Sep 2024 12:22:57 +0200 Subject: [PATCH 028/359] Update SEParser.cs --- ScriptedEvents/API/Features/SEParser.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 73916fa6..956338a7 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -388,8 +388,8 @@ void Log(string msg) Logger.Debug($"[SEParser] [TryGetAccessor] {msg}", source); } - // - // + // "" + // "" result = null; if (!input.StartsWith("<") || !input.EndsWith(">")) @@ -398,8 +398,8 @@ void Log(string msg) return false; } - // PLR:ROLE - // PLR + // "PLR:ROLE" + // "PLR" input = input.Substring(1, input.Length - 2); if (input.Contains(' ') || input.Contains('<') || input.Contains('>')) @@ -408,8 +408,8 @@ void Log(string msg) return false; } - // [PLR, ROLE] - // [PLR] + // ["PLR", "ROLE"] + // ["PLR"] string[] parts = input.Split(':'); if (parts.Length > 2) @@ -419,7 +419,7 @@ void Log(string msg) } else if (parts.Length == 1) { - // [PLR, NAME] + // ["PLR"] -> ["PLR", "NAME"] parts.Append("NAME"); } From 2859a07bcbddfdc4614694958c5e132328c88be8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:33:38 +0200 Subject: [PATCH 029/359] Update CallAction.cs --- ScriptedEvents/Actions/Logic/CallAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/Logic/CallAction.cs b/ScriptedEvents/Actions/Logic/CallAction.cs index e99f2b6d..96612b45 100644 --- a/ScriptedEvents/Actions/Logic/CallAction.cs +++ b/ScriptedEvents/Actions/Logic/CallAction.cs @@ -102,7 +102,7 @@ public class CallAction : IHelpInfo, ITimingAction private CoroutineHandle RunScript(Script scriptToCall, Script script) { scriptToCall.Execute(); - string coroutineKey = $"CALL_WAIT_FOR_FINISH_COROUTINE_{DateTime.UtcNow.Ticks}"; + string coroutineKey = $"CALL_WAIT_FOR_FINISH_COROUTINE_{DateTime.Now.Ticks}"; CoroutineHandle handle = Timing.RunCoroutine(InternalWaitUntil(scriptToCall), coroutineKey); CoroutineHelper.AddCoroutine("CALL", handle, script); return handle; From 249190293054d6cb938721d85abd415f7ab14b01 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:33:41 +0200 Subject: [PATCH 030/359] Update BanAction.cs --- ScriptedEvents/Actions/Player/BanAction.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/ScriptedEvents/Actions/Player/BanAction.cs b/ScriptedEvents/Actions/Player/BanAction.cs index 7b906275..99660c28 100644 --- a/ScriptedEvents/Actions/Player/BanAction.cs +++ b/ScriptedEvents/Actions/Player/BanAction.cs @@ -7,7 +7,6 @@ using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; public class BanAction : IScriptAction, IHelpInfo From c5cbb9205e5c730a22c0f84b9cdc33196abf83b7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:33:48 +0200 Subject: [PATCH 031/359] add TIME action --- .../Actions/VariableMimics/Info/TimeAction.cs | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs new file mode 100644 index 00000000..7f893277 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs @@ -0,0 +1,68 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "TIME"; + + /// + public string Description => "All-in-one action for getting time related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("TICK", "The amount of seconds since 1970."), + new("SECOND", "In range 0-59"), + new("MINUTE", "In range 0-59"), + new("HOUR", "In range 0-23"), + new("MONTH", "In range 1-12"), + new("YEAR", "The amount of years since the birth of Christ"), + new("DAYOFWEEK", "1-7 (Warning! This follows the US system, where Sunday is the first day of the week)"), + new("DAYOFMONTH", "0-31"), + new("DAYOFYEAR", "0-366"), + new("ROUNDMINUTES", "The amount of elapsed round time, in minutes."), + new("ROUNDSECONDS", "The amount of elapsed round time, in seconds."), + new("ROUNDSTART", "The amount of time remaining before the round starts. -1 if round already started.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToString().ToUpper() switch + { + "TICK" => ((long)(DateTime.UtcNow - MainPlugin.Epoch).TotalSeconds).ToString(), + "SECOND" => DateTime.UtcNow.Second.ToString(), + "MINUTE" => DateTime.UtcNow.Minute.ToString(), + "HOUR" => DateTime.UtcNow.Hour.ToString(), + "MONTH" => DateTime.UtcNow.Month.ToString(), + "YEAR" => DateTime.UtcNow.Year.ToString(), + "DAYOFWEEK" => (((int)DateTime.UtcNow.DayOfWeek) + 1).ToString(), + "DAYOFMONTH" => DateTime.UtcNow.Day.ToString(), + "DAYOFYEAR" => DateTime.UtcNow.DayOfYear.ToString(), + "ROUNDMINUTES" => ((float)Round.ElapsedTime.TotalMinutes).ToString(), + "ROUNDSECONDS" => ((float)Round.ElapsedTime.TotalSeconds).ToString(), + "ROUNDSTART" => Round.LobbyWaitingTime.ToString(), + _ => throw new ArgumentException(), + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 39cada82bdadda9b8d88c6c5d583133dced64833 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:33:57 +0200 Subject: [PATCH 032/359] add WARHEADINFO action --- .../VariableMimics/Info/WarheadInfoAction.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs new file mode 100644 index 00000000..8527f1aa --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs @@ -0,0 +1,55 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "WARHEADINFO"; + + /// + public string Description => "All-in-one action for getting warhead related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("ISDETONATED"), + new("ISOPEN"), + new("ISARMED"), + new("ISCOUNTING"), + new("DETONATIONTIME")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "ISDETONATED" => Warhead.IsDetonated.ToUpper(), + "ISOPEN" => Warhead.IsKeycardActivated.ToUpper(), + "ISARMED" => Warhead.LeverStatus.ToUpper(), + "ISCOUNTING" => Warhead.IsInProgress.ToUpper(), + "DETONATIONTIME" => Warhead.DetonationTimer.ToUpper(), + _ => throw new ArgumentException("Invalid mode."), + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 4d8cd4057b91821021ecfc4a023568e37f7fcad2 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:34:11 +0200 Subject: [PATCH 033/359] add 5 math actions --- .../VariableMimics/Math/Math_AbsAction.cs | 42 +++++++ .../VariableMimics/Math/Math_PowerAction.cs | 42 +++++++ .../VariableMimics/Math/Math_RandomAction.cs | 116 ++++++++++++++++++ .../VariableMimics/Math/Math_RootAction.cs | 42 +++++++ .../VariableMimics/Math/Math_RoundAction.cs | 59 +++++++++ 5 files changed, 301 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs new file mode 100644 index 00000000..3f455699 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs @@ -0,0 +1,42 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + using UnityEngine; + + public class Math_AbsAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "MATH-ABS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns a non-negative version of the input number."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("input", typeof(float), "The input.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { (object)Mathf.Abs((float)Arguments[0]).ToString() }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs new file mode 100644 index 00000000..56aabc39 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs @@ -0,0 +1,42 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class Math_PowerAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "MATH-POWER"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns a exponentiated version of the input number."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("value", typeof(float), "Number to exponentiate.", true), + new Argument("exponent", typeof(float), "The exponentiating number.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { (object)(float)Math.Pow((float)Arguments[0], (float)Arguments[1]) }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs new file mode 100644 index 00000000..82ec8691 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs @@ -0,0 +1,116 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class Math_RandomAction : IScriptAction, IHelpInfo, ILongDescription, IMimicsVariableAction + { + /// + public string Name => "MATH-RANDOM"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns a random number from provided range."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("type", true, + new("INT", "Will return an integer."), + new("FLOAT", "Will return a decimal (floating point) number.")), + new Argument("startNumber", typeof(string), "A starting number of the random range.", true), + new Argument("endNumber", typeof(string), "An ending number of the random range.", true), + }; + + public string LongDescription => $@"The return value will be a random number from the provided range, depending on the numbers and the type. + +If 'type' is set to 'INT': +> PRINT My integer is {{RANDOM:INT:1:100}} +> My integer is 60 + +If 'type' is set to 'FLOAT': +> act PRINT My float is {{RANDOM:FLOAT:0:1}} +> My float is 0.35227"; + + public string WhatDoesActionReturn => "The random number generated."; + + /// + public ActionResponse Execute(Script script) + { + float result; + string mode = Arguments[0].ToUpper(); + switch (mode) + { + case "INT": + int r1i; + int r2i; + try + { + r1i = Convert.ToInt32(Arguments[1]); + } + catch + { + throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[1])); + } + + try + { + r2i = Convert.ToInt32(Arguments[2]) + 1; + } + catch + { + throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[2])); + } + + result = UnityEngine.Random.Range(r1i, r2i); + break; + + case "FLOAT": + float r1f; + float r2f; + + try + { + r1f = Convert.ToSingle(Arguments[1]); + } + catch + { + throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[1])); + } + + try + { + r2f = Convert.ToSingle(Arguments[2]); + } + catch + { + throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[2])); + } + + result = UnityEngine.Random.Range(r1f, r2f); + break; + + default: + throw new Exception("this error is impossible"); + } + + return new(true, variablesToRet: new[] { (object)result.ToString() }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs new file mode 100644 index 00000000..4195cd2f --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs @@ -0,0 +1,42 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class Math_RootAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "MATH-ROOT"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns a root of the input number."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("value", typeof(float), "The number to root.", true), + new Argument("rootLevel", typeof(float), "The root level. Default: 2", false), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { (object)(float)Math.Pow((float)Arguments[0], 1 / (Arguments.Length > 1 ? (float)Arguments[1] : 2)) }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs new file mode 100644 index 00000000..3bd8b0d3 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs @@ -0,0 +1,59 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + using UnityEngine; + + public class Math_RoundAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "MATH-ROUND"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns a rounded version of the input number."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("variable", typeof(float), "The variable to round. Requires the variable to be a number.", true), + new OptionsArgument("mode", false, new("UP"), new("DOWN"), new("NEAREST", "Default option")), + }; + + /// + public ActionResponse Execute(Script script) + { + float value = (float)Arguments[0]; + string result = "big fucky wucky"; + + switch (Arguments.Length < 2 ? "NEAREST" : Arguments[1].ToUpper()) + { + case "UP": + result = Mathf.Ceil(value).ToString(); break; + + case "DOWN": + result = Mathf.Floor(value).ToString(); break; + + case "NEAREST": + result = Mathf.Round(value).ToString(); break; + } + + return new(true, variablesToRet: new[] { (object)result }); + } + } +} \ No newline at end of file From 3635e8636a0ae8d3ffa3248eb27ce3afe926b779 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:34:21 +0200 Subject: [PATCH 034/359] add ZONEPLAYERS action --- .../PlayerFetch/ZonePlayersAction.cs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs new file mode 100644 index 00000000..398f84c6 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs @@ -0,0 +1,44 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Enums; + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class ZonePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ZONEPLAYERS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Math; + + /// + public string Description => "Returns the players in the specified zone."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("zone", typeof(ZoneType), "The zone to get the players from.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { Player.List.Where(ply => ply.Zone == ((ZoneType)Arguments[0])).ToArray() }); + } + } +} \ No newline at end of file From 922d3b31fadee2ef729b8745d58e5c14e02aac2b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:34:27 +0200 Subject: [PATCH 035/359] Update ActionSubgroup.cs --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index 4d467299..fca2616b 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -84,5 +84,15 @@ public enum ActionSubgroup /// Teleportation action. /// Teleportation, + + /// + /// Math action. + /// + Math, + + /// + /// Math action. + /// + MapInfo, } } From 3376a7ea50f0bc0dd8b6bff8e8e1e62b91a18ed0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:34:51 +0200 Subject: [PATCH 036/359] add interfaces for action returning --- ScriptedEvents/API/Interfaces/IMimicsVariableAction.cs | 9 +++++++++ ScriptedEvents/API/Interfaces/IReturnValueAction.cs | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 ScriptedEvents/API/Interfaces/IMimicsVariableAction.cs create mode 100644 ScriptedEvents/API/Interfaces/IReturnValueAction.cs diff --git a/ScriptedEvents/API/Interfaces/IMimicsVariableAction.cs b/ScriptedEvents/API/Interfaces/IMimicsVariableAction.cs new file mode 100644 index 00000000..e4662c6b --- /dev/null +++ b/ScriptedEvents/API/Interfaces/IMimicsVariableAction.cs @@ -0,0 +1,9 @@ +namespace ScriptedEvents.API.Interfaces +{ + /// + /// Represents an action that returns a value. + /// + public interface IMimicsVariableAction : IReturnValueAction + { + } +} diff --git a/ScriptedEvents/API/Interfaces/IReturnValueAction.cs b/ScriptedEvents/API/Interfaces/IReturnValueAction.cs new file mode 100644 index 00000000..6cfaaea8 --- /dev/null +++ b/ScriptedEvents/API/Interfaces/IReturnValueAction.cs @@ -0,0 +1,9 @@ +namespace ScriptedEvents.API.Interfaces +{ + /// + /// Represents an action that returns a value. + /// + public interface IReturnValueAction + { + } +} From 1aea123866450d8a030772238529d0edf7c7d5d8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:35:03 +0200 Subject: [PATCH 037/359] better logs --- ScriptedEvents/API/Modules/ScriptModule.cs | 27 +++++++++++----------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index 61246d30..7b687250 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -225,6 +225,11 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre bool inMultilineComment = false; Script script = new(); + void DebugLog(string message) + { + Logger.Debug($"[ScriptModule] [ReadScript] {message}", script); + } + List actionList = ListPool.Pool.Get(); Action addActionNoArgs = (action) => @@ -355,23 +360,19 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre { string variablesSection = line.Substring(0, indexOfExtractor); string actionSection = line.Substring(indexOfExtractor + 2).TrimStart(); - DebugLog($"[ExtractorSyntax] Variables section: {variablesSection}", script); - DebugLog($"[ExtractorSyntax] Action section: {actionSection}", script); + DebugLog($"[ExtractorSyntax] Variables section: {variablesSection}"); + DebugLog($"[ExtractorSyntax] Action section: {actionSection}"); resultVariableNames = SEParser.IsolateValueSyntax(variablesSection, script, false); - if (resultVariableNames.Length == 0) + if (resultVariableNames.Length != 0) { - goto leave_extractor_parsing; - } + DebugLog($"[ExtractorSyntax] Variables found before the syntax: {string.Join(", ", resultVariableNames)}"); - DebugLog($"[ExtractorSyntax] Variables found before the syntax: {string.Join(", ", resultVariableNames)}", script); - - structureParts = actionSection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(part => part.Trim()).ToList(); - keyword = structureParts[0]; + structureParts = actionSection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(part => part.Trim()).ToList(); + keyword = structureParts[0]; + } } - leave_extractor_parsing: - keyword = keyword.ToUpper(); if (!TryGetActionType(keyword, out Type actionType)) @@ -415,7 +416,7 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre script.OriginalActionArgs[newAction] = structureParts.Skip(1).Select(str => str.RemoveWhitespace()).ToArray(); script.ResultVariableNames[newAction] = resultVariableNames; - Logger.Debug($"Queuing action {keyword}, {string.Join(", ", script.OriginalActionArgs[newAction])}", script); + DebugLog($"Queuing action {keyword}, {string.Join(", ", script.OriginalActionArgs[newAction])}"); // Obsolete check if (newAction.IsObsolete(out string obsoleteReason) && !suppressWarnings && !script.SuppressWarnings) @@ -458,7 +459,7 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre script.Sender = executor; - script.DebugLog($"Debug script read successfully. Name: {script.ScriptName} | Actions: {script.Actions.Count(act => act is not NullAction)} | Flags: {string.Join(" ", script.Flags)} | Labels: {string.Join(" ", script.Labels)} | Comments: {script.Actions.Count(action => action is NullAction @null && @null.Type is "COMMENT")}"); + DebugLog($"Debug script read successfully. Name: {script.ScriptName} | Actions: {script.Actions.Count(act => act is not NullAction)} | Flags: {string.Join(" ", script.Flags)} | Labels: {string.Join(" ", script.Labels)} | Comments: {script.Actions.Count(action => action is NullAction @null && @null.Type is "COMMENT")}"); return script; } From d57018061572a7bf8eb79678daab94cef5a6d69f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:35:07 +0200 Subject: [PATCH 038/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 3a15f987..a966776e 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,6 +111,13 @@ + + + + + + + @@ -149,6 +156,7 @@ + @@ -206,6 +214,8 @@ + + @@ -309,7 +319,6 @@ - @@ -319,9 +328,7 @@ - - From f9721864162a68293b93cf45826ffe18245e8d21 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:35:49 +0200 Subject: [PATCH 039/359] remove math variables --- ScriptedEvents/Variables/MathVariables.cs | 158 ---------------------- 1 file changed, 158 deletions(-) delete mode 100644 ScriptedEvents/Variables/MathVariables.cs diff --git a/ScriptedEvents/Variables/MathVariables.cs b/ScriptedEvents/Variables/MathVariables.cs deleted file mode 100644 index 61b8c001..00000000 --- a/ScriptedEvents/Variables/MathVariables.cs +++ /dev/null @@ -1,158 +0,0 @@ -namespace ScriptedEvents.Variables.Misc -{ - using System; -#pragma warning disable SA1402 // File may only contain a single type - - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - using UnityEngine; - - public class MathVariables : IVariableGroup - { - /// - public string GroupName => "Math"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new AbsoluteNumber(), - new MathRound(), - new MathPower(), - new MathRoot(), - }; - } - - public class MathPower : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{MATH-POWER}"; - - /// - public string Description => "Returns an exponentiated number."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("value", typeof(float), "Number to exponentiate.", true), - new Argument("exponent", typeof(float), "The exponentiating number.", true), - }; - - /// - public float Value - { - get - { - return (float)Math.Pow((float)Arguments[0], (float)Arguments[1]); - } - } - } - - public class MathRoot : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{MATH-ROOT}"; - - /// - public string Description => "Returns a root of a number."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("value", typeof(float), "The number to root.", true), - new Argument("rootLevel", typeof(float), "The root level. Default: 2", false), - }; - - /// - public float Value - { - get - { - float level = Arguments.Length > 1 ? (float)Arguments[1] : 2; - return (float)Math.Pow((float)Arguments[0], 1 / level); - } - } - } - - public class MathRound : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{MATH-ROUND}"; - - /// - public string Description => "Returns a rounded number."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variable", typeof(float), "The variable to round. Requires the variable to be a number.", true), - new OptionsArgument("mode", false, new("UP"), new("DOWN"), new("NEAREST", "Default option")), - }; - - /// - public float Value - { - get - { - float value = (float)Arguments[0]; - string mode = Arguments.Length < 2 ? "NEAREST" : (string)Arguments[1]; - - return mode.ToUpper() switch - { - "UP" => Mathf.Ceil(value), - "DOWN" => Mathf.Floor(value), - "NEAREST" => Mathf.Round(value), - _ => throw new ArgumentException(), - }; - } - } - } - - public class AbsoluteNumber : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{MATH-ABS}"; - - /// - public string Description => "Returns a non-negative value of a variable without regard to its sign."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("value", typeof(float), "The value.", true), - }; - - /// - public float Value - { - get - { - return Mathf.Abs((float)Arguments[0]); - } - } - } -#pragma warning restore SA1402 // File may only contain a single type -} From 22536ed38413bda256013e86395026cac3dcc3a5 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:35:58 +0200 Subject: [PATCH 040/359] remove time variables --- ScriptedEvents/Variables/TimeVariables.cs | 73 ----------------------- 1 file changed, 73 deletions(-) delete mode 100644 ScriptedEvents/Variables/TimeVariables.cs diff --git a/ScriptedEvents/Variables/TimeVariables.cs b/ScriptedEvents/Variables/TimeVariables.cs deleted file mode 100644 index 1bc4a443..00000000 --- a/ScriptedEvents/Variables/TimeVariables.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace ScriptedEvents.Variables.WorldTime -{ -#pragma warning disable SA1402 // File may only contain a single type - using System; - - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class TimeVariables : IVariableGroup - { - /// - public string GroupName => "Time"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Time(), - }; - } - - public class Time : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{TIME}"; - - /// - public string Description => "All-in-one variable for time related information. All time information is based on the UTC timezone."; - - public string[] RawArguments { get; set; } - - public object[] Arguments { get; set; } - - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("TICK", "The amount of seconds since 1.1.1970"), - new("SECOND", "0-59"), - new("MINUTE", "0-59"), - new("HOUR", "0-23"), - new("YEAR", "The amount of years since the birth of Christ"), - new("DAYOFWEEK", "1-7 (Warning! This follows the US system, where Saturday is the first day of the week)"), - new("DAYOFMONTH", "0-31"), - new("DAYOFYEAR", "0-366"), - new("ROUNDMINUTES", "The amount of elapsed round time, in minutes."), - new("ROUNDSECONDS", "The amount of elapsed round time, in seconds."), - new("ROUNDSTART", "The amount of time remaining before the round starts. -1 if round already started.")), - }; - - /// - public float Value - { - get - { - string mode = Arguments[0].ToString().ToUpper(); - return mode switch - { - "TICK" => (long)(DateTime.UtcNow - MainPlugin.Epoch).TotalSeconds, - "SECOND" => DateTime.UtcNow.Second, - "MINUTE" => DateTime.UtcNow.Minute, - "HOUR" => DateTime.UtcNow.Hour, - "YEAR" => DateTime.UtcNow.Year, - "DAYOFWEEK" => ((int)DateTime.UtcNow.DayOfWeek) + 1, - "DAYOFMONTH" => DateTime.UtcNow.Day, - "DAYOFYEAR" => DateTime.UtcNow.DayOfYear, - "ROUNDMINUTES" => (float)Exiled.API.Features.Round.ElapsedTime.TotalMinutes, - "ROUNDSECONDS" => (float)Exiled.API.Features.Round.ElapsedTime.TotalSeconds, - "ROUNDSTART" => Exiled.API.Features.Round.LobbyWaitingTime, - _ => throw new ArgumentException($"Provided mode '{mode}' is incorrect"), - }; - } - } - } -} From b3f9e8fca0f0d1bbba76ee7a2c102cdcaf65d60c Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:36:06 +0200 Subject: [PATCH 041/359] remove warhead variables --- ScriptedEvents/Variables/WarheadVariables.cs | 64 -------------------- 1 file changed, 64 deletions(-) delete mode 100644 ScriptedEvents/Variables/WarheadVariables.cs diff --git a/ScriptedEvents/Variables/WarheadVariables.cs b/ScriptedEvents/Variables/WarheadVariables.cs deleted file mode 100644 index bcb1c9a0..00000000 --- a/ScriptedEvents/Variables/WarheadVariables.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace ScriptedEvents.Variables.Warhead -{ - using System; - - using ScriptedEvents.API.Extensions; - using ScriptedEvents.Structures; -#pragma warning disable SA1402 // File may only contain a single type. - using ScriptedEvents.Variables.Interfaces; - - using Warhead = Exiled.API.Features.Warhead; - - public class WarheadVariables : IVariableGroup - { - public string GroupName => "Warhead"; - - public IVariable[] Variables { get; } = new IVariable[] - { - new GeneralWarhead(), - }; - } - - public class GeneralWarhead : IStringVariable, IArgumentVariable - { - /// - public string Name => "{WARHEAD}"; - - /// - public string Description => "All-in-one variable for warhead related information."; - - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("ISDETONATED"), - new("ISOPEN"), - new("ISARMED"), - new("ISCOUNTING"), - new("DETONATIONTIME")), - }; - - /// - public string Value - { - get - { - string mode = Arguments[0].ToUpper(); - - return mode switch - { - "ISDETONATED" => Warhead.IsDetonated.ToUpper(), - "ISOPEN" => Warhead.IsKeycardActivated.ToUpper(), - "ISARMED" => Warhead.LeverStatus.ToUpper(), - "ISCOUNTING" => Warhead.IsInProgress.ToUpper(), - "DETONATIONTIME" => Warhead.DetonationTimer.ToUpper(), - _ => throw new ArgumentException("Invalid mode.", mode) - }; - } - } - - public string[] RawArguments { get; set; } - - public object[] Arguments { get; set; } - } -#pragma warning restore SA1402 // File may only contain a single type. -} From 6f3864bb845760a8eb82ceb4f8983299a131e791 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sat, 7 Sep 2024 12:36:12 +0200 Subject: [PATCH 042/359] remove zone variables --- ScriptedEvents/Variables/ZoneVariables.cs | 101 ---------------------- 1 file changed, 101 deletions(-) delete mode 100644 ScriptedEvents/Variables/ZoneVariables.cs diff --git a/ScriptedEvents/Variables/ZoneVariables.cs b/ScriptedEvents/Variables/ZoneVariables.cs deleted file mode 100644 index 1b3dbbf5..00000000 --- a/ScriptedEvents/Variables/ZoneVariables.cs +++ /dev/null @@ -1,101 +0,0 @@ -namespace ScriptedEvents.Variables.Zone -{ -#pragma warning disable SA1402 // File may only contain a single type - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Enums; - using Exiled.API.Features; - using ScriptedEvents.Variables.Interfaces; - - public class ZoneVariables : IVariableGroup - { - /// - public string GroupName => "Zone"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new LCZ(), - new HCZ(), - new EZ(), - new Surface(), - new Pocket(), - }; - } - - public class LCZ : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{LCZ}"; - - /// - public string Description => "The amount of players in Light Containment Zone."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(ply => ply.Zone.HasFlag(ZoneType.LightContainment)); - } - - public class HCZ : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{HCZ}"; - - /// - public string Description => "The amount of players in Heavy Containment Zone."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(ply => ply.Zone.HasFlag(ZoneType.HeavyContainment)); - } - - public class EZ : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{EZ}"; - - /// - public string Description => "The amount of players in Entrance Zone."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(ply => ply.Zone.HasFlag(ZoneType.Entrance)); - } - - public class Surface : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{SURFACE}"; - - /// - public string Description => "The amount of players on the Surface."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(ply => ply.Zone.HasFlag(ZoneType.Surface)); - } - - public class Pocket : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{POCKET}"; - - /// - public string Description => "The amount of players in the Pocket Dimension."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(ply => ply.CurrentRoom?.Type is RoomType.Pocket); - } -} From 239feb7b97980d0a1fc6e375ba1357b5780f253b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 12:59:07 +0200 Subject: [PATCH 043/359] make DateTime use Now instead of UtcNow --- ScriptedEvents/API/Features/ApiHelper.cs | 5 ++--- .../API/Features/ScriptHelpGenerator/Generator.cs | 2 +- ScriptedEvents/API/Modules/EventHandlingModule.cs | 4 ++-- ScriptedEvents/API/Modules/ScriptModule.cs | 2 +- .../Actions/DebugActions/WaitUntilDebugAction.cs | 2 +- ScriptedEvents/Actions/Misc/HelpAction.cs | 2 +- ScriptedEvents/Actions/Misc/HttpGetAction.cs | 2 +- ScriptedEvents/Actions/Misc/HttpPostAction.cs | 2 +- ScriptedEvents/Actions/Yielding/WaitAction.cs | 2 +- ScriptedEvents/Commands/CustomCommand.cs | 12 ++++++------ ScriptedEvents/DemoScripts/About.cs | 2 +- ScriptedEvents/Script.cs | 2 +- ScriptedEvents/Structures/Countdown.cs | 6 +++--- 13 files changed, 22 insertions(+), 23 deletions(-) diff --git a/ScriptedEvents/API/Features/ApiHelper.cs b/ScriptedEvents/API/Features/ApiHelper.cs index 9154e2e4..548a06c5 100644 --- a/ScriptedEvents/API/Features/ApiHelper.cs +++ b/ScriptedEvents/API/Features/ApiHelper.cs @@ -1,7 +1,6 @@ namespace ScriptedEvents.API.Features { using System; - using System.Collections.Generic; using System.Reflection; using Exiled.API.Features; @@ -125,7 +124,7 @@ public static string UnregisterCustomActions(string[] actionNames) /// Input string. /// Script object. /// Maximum amount of players to get. Leave below zero for unlimited. - /// A of players. + /// An array of players. public static Player[] GetPlayers(string input, object script, int max = -1) { if (script is Script actualScript == false) @@ -138,7 +137,7 @@ public static Player[] GetPlayers(string input, object script, int max = -1) } /// - /// Evaluates a string math equation, replacing all variables in the string. + /// Replaces all variables and tries to perform math. /// /// The input string. /// Script object. diff --git a/ScriptedEvents/API/Features/ScriptHelpGenerator/Generator.cs b/ScriptedEvents/API/Features/ScriptHelpGenerator/Generator.cs index 5a4aa9b9..05470cd1 100644 --- a/ScriptedEvents/API/Features/ScriptHelpGenerator/Generator.cs +++ b/ScriptedEvents/API/Features/ScriptHelpGenerator/Generator.cs @@ -130,7 +130,7 @@ public static bool CreateDocumentation(out string message) // Documentation data string metaPath = Path.Combine(BasePath, "DocInfo.txt"); - File.WriteAllText(metaPath, $"Documentation Generator\nGenerated at: {DateTime.UtcNow:f}\nSE version: {MainPlugin.Singleton.Version}\nExperimental DLL: {(MainPlugin.IsExperimental ? "YES" : "NO")}\n\n\n-- DO NOT MODIFY BELOW THIS LINE --\n!_V{MainPlugin.Singleton.Version}"); + File.WriteAllText(metaPath, $"Documentation Generator\nGenerated at: {DateTime.Now:f}\nSE version: {MainPlugin.Singleton.Version}\nExperimental DLL: {(MainPlugin.IsExperimental ? "YES" : "NO")}\n\n\n-- DO NOT MODIFY BELOW THIS LINE --\n!_V{MainPlugin.Singleton.Version}"); // Delete old folders if (Directory.Exists(ActionPath)) diff --git a/ScriptedEvents/API/Modules/EventHandlingModule.cs b/ScriptedEvents/API/Modules/EventHandlingModule.cs index 62819398..0e99901e 100644 --- a/ScriptedEvents/API/Modules/EventHandlingModule.cs +++ b/ScriptedEvents/API/Modules/EventHandlingModule.cs @@ -62,7 +62,7 @@ public class EventHandlingModule : SEModule /// /// Gets the amount of time since the last wave. /// - public TimeSpan TimeSinceWave => DateTime.UtcNow - lastRespawnWave; + public TimeSpan TimeSinceWave => DateTime.Now - lastRespawnWave; /// /// Gets a value indicating whether or not a wave just spawned. @@ -526,7 +526,7 @@ public void OnRespawningTeam(RespawningTeamEventArgs ev) if (!ev.IsAllowed) return; RespawnWaves++; - lastRespawnWave = DateTime.UtcNow; + lastRespawnWave = DateTime.Now; MostRecentSpawn = ev.NextKnownTeam; SpawnsByTeam[ev.NextKnownTeam]++; diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index 7b687250..cdab616c 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -646,7 +646,7 @@ private IEnumerator RunScriptInternal(Script scr, bool dispose = true) yield return Timing.WaitForOneFrame; scr.IsRunning = true; - scr.RunDate = DateTime.UtcNow; + scr.RunDate = DateTime.Now; Stopwatch runTime = Stopwatch.StartNew(); int lines = 0; diff --git a/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs b/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs index 3d4b2aa4..afa416f3 100644 --- a/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs +++ b/ScriptedEvents/Actions/DebugActions/WaitUntilDebugAction.cs @@ -40,7 +40,7 @@ public class WaitUntilDebugAction : ITimingAction, IHiddenAction, IHelpInfo /// public float? Execute(Script script, out ActionResponse message) { - string coroutineKey = $"WAITUNTIL_DEBUG_COROUTINE_{DateTime.UtcNow.Ticks}"; + string coroutineKey = $"WAITUNTIL_DEBUG_COROUTINE_{DateTime.Now.Ticks}"; CoroutineHandle handle = Timing.RunCoroutine(InternalWaitUntil(script, Arguments.JoinMessage(0)), coroutineKey); CoroutineHelper.AddCoroutine("WAITUNTIL_DEBUG", handle, script); diff --git a/ScriptedEvents/Actions/Misc/HelpAction.cs b/ScriptedEvents/Actions/Misc/HelpAction.cs index 6d62e17b..edb0d9d2 100644 --- a/ScriptedEvents/Actions/Misc/HelpAction.cs +++ b/ScriptedEvents/Actions/Misc/HelpAction.cs @@ -441,7 +441,7 @@ public ActionResponse Display(ActionResponse response) { if (IsFile) { - string message = $"Auto Generated At: {DateTime.UtcNow:f}\nExpires: {DateTime.UtcNow.AddMinutes(5):f}\n{response.Message}"; + string message = $"Auto Generated At: {DateTime.Now:f}\nExpires: {DateTime.Now.AddMinutes(5):f}\n{response.Message}"; string path = Path.Combine(MainPlugin.BaseFilePath, "HelpCommandResponse.txt"); if (File.Exists(path)) diff --git a/ScriptedEvents/Actions/Misc/HttpGetAction.cs b/ScriptedEvents/Actions/Misc/HttpGetAction.cs index 0bddd024..4ddac2b2 100644 --- a/ScriptedEvents/Actions/Misc/HttpGetAction.cs +++ b/ScriptedEvents/Actions/Misc/HttpGetAction.cs @@ -49,7 +49,7 @@ public class HttpGetAction : IHelpInfo, ITimingAction, ILongDescription /// public float? Execute(Script script, out ActionResponse message) { - string coroutineKey = $"HTTPGET_COROUTINE_{DateTime.UtcNow.Ticks}"; + string coroutineKey = $"HTTPGET_COROUTINE_{DateTime.Now.Ticks}"; CoroutineHandle handle = Timing.RunCoroutine(InternalSendHTTP(script, VariableSystemV2.ReplaceVariable(RawArguments[0], script)), coroutineKey); CoroutineHelper.AddCoroutine("HTTPGET", handle, script); message = new(true); diff --git a/ScriptedEvents/Actions/Misc/HttpPostAction.cs b/ScriptedEvents/Actions/Misc/HttpPostAction.cs index 5a605397..41b080d4 100644 --- a/ScriptedEvents/Actions/Misc/HttpPostAction.cs +++ b/ScriptedEvents/Actions/Misc/HttpPostAction.cs @@ -53,7 +53,7 @@ public class HttpPostAction : IHelpInfo, ITimingAction, ILongDescription { string body = Arguments.JoinMessage(1); - string coroutineKey = $"HTTPPOST_COROUTINE_{DateTime.UtcNow.Ticks}"; + string coroutineKey = $"HTTPPOST_COROUTINE_{DateTime.Now.Ticks}"; CoroutineHandle handle = Timing.RunCoroutine(InternalSendHTTP(script, (string)Arguments[0], body), coroutineKey); CoroutineHelper.AddCoroutine("HTTPPOST", handle, script); message = new(true); diff --git a/ScriptedEvents/Actions/Yielding/WaitAction.cs b/ScriptedEvents/Actions/Yielding/WaitAction.cs index b3cdf442..b064866d 100644 --- a/ScriptedEvents/Actions/Yielding/WaitAction.cs +++ b/ScriptedEvents/Actions/Yielding/WaitAction.cs @@ -49,7 +49,7 @@ public class WaitAction : ITimingAction, IHelpInfo if (Arguments[0].ToUpper() == "UNTIL") { - string coroutineKey = $"WAITUNTIL_COROUTINE_{DateTime.UtcNow.Ticks}"; + string coroutineKey = $"WAITUNTIL_COROUTINE_{DateTime.Now.Ticks}"; CoroutineHandle handle = Timing.RunCoroutine(InternalWaitUntil(script, RawArguments.JoinMessage(1)), coroutineKey); CoroutineHelper.AddCoroutine("WAITUNTIL", handle, script); diff --git a/ScriptedEvents/Commands/CustomCommand.cs b/ScriptedEvents/Commands/CustomCommand.cs index 7e4e69fd..6fbe08ad 100644 --- a/ScriptedEvents/Commands/CustomCommand.cs +++ b/ScriptedEvents/Commands/CustomCommand.cs @@ -71,30 +71,30 @@ public bool Execute(ArraySegment arguments, ICommandSender sender, out s if (CooldownMode == CommandCooldownMode.Global) { - if ((DateTime.UtcNow - globalCooldown).TotalSeconds < Cooldown) + if ((DateTime.Now - globalCooldown).TotalSeconds < Cooldown) { - int cooldownLeft = (int)(Cooldown - (DateTime.UtcNow - globalCooldown).TotalSeconds); + int cooldownLeft = (int)(Cooldown - (DateTime.Now - globalCooldown).TotalSeconds); response = cooldownLeft == 1 ? MainPlugin.Translations.CommandCooldown.Replace("{SECONDS}", cooldownLeft.ToString()) : MainPlugin.Translations.CommandCooldownSingular.Replace("{SECONDS}", cooldownLeft.ToString()); return false; } - globalCooldown = DateTime.UtcNow; + globalCooldown = DateTime.Now; } if (CooldownMode == CommandCooldownMode.Player && Player.TryGet(sender, out Player ply)) { - if (playerCooldown.ContainsKey(ply.UserId) && (DateTime.UtcNow - playerCooldown[ply.UserId]).TotalSeconds < Cooldown) + if (playerCooldown.ContainsKey(ply.UserId) && (DateTime.Now - playerCooldown[ply.UserId]).TotalSeconds < Cooldown) { - int cooldownLeft = (int)(Cooldown - (DateTime.UtcNow - playerCooldown[ply.UserId]).TotalSeconds); + int cooldownLeft = (int)(Cooldown - (DateTime.Now - playerCooldown[ply.UserId]).TotalSeconds); response = cooldownLeft == 1 ? MainPlugin.Translations.CommandCooldown.Replace("{SECONDS}", cooldownLeft.ToString()) : MainPlugin.Translations.CommandCooldownSingular.Replace("{SECONDS}", cooldownLeft.ToString()); return false; } - playerCooldown[ply.UserId] = DateTime.UtcNow; + playerCooldown[ply.UserId] = DateTime.Now; } Dictionary failed = new(); diff --git a/ScriptedEvents/DemoScripts/About.cs b/ScriptedEvents/DemoScripts/About.cs index 92491670..302660ab 100644 --- a/ScriptedEvents/DemoScripts/About.cs +++ b/ScriptedEvents/DemoScripts/About.cs @@ -39,7 +39,7 @@ public class About : IDemoScript # Scripted Events Contributors: {Constants.GenerateContributorList('#')} -# File Generated at: {DateTime.UtcNow:f} +# File Generated at: {DateTime.Now:f} # Plugin Version (as of generation): {MainPlugin.Singleton.Version} # Experimental DLL: {(MainPlugin.IsExperimental ? "YES" : "NO")}"; } diff --git a/ScriptedEvents/Script.cs b/ScriptedEvents/Script.cs index 4c7463ef..36f308d4 100644 --- a/ScriptedEvents/Script.cs +++ b/ScriptedEvents/Script.cs @@ -117,7 +117,7 @@ public Script() /// /// Gets the amount of time the script has been running. /// - public TimeSpan RunDuration => DateTime.UtcNow - RunDate; + public TimeSpan RunDuration => DateTime.Now - RunDate; /// /// Gets a list of flags on the script. diff --git a/ScriptedEvents/Structures/Countdown.cs b/ScriptedEvents/Structures/Countdown.cs index dfd3b809..3f17df68 100644 --- a/ScriptedEvents/Structures/Countdown.cs +++ b/ScriptedEvents/Structures/Countdown.cs @@ -20,7 +20,7 @@ public Countdown(Player target, string text, int time, Script source = null) { Target = target; Text = string.IsNullOrWhiteSpace(text) ? "Countdown" : text; - StartTime = DateTime.UtcNow; + StartTime = DateTime.Now; EndTime = StartTime.AddSeconds(time); Source = source; } @@ -48,12 +48,12 @@ public Countdown(Player target, string text, int time, Script source = null) /// /// Gets a value indicating whether or not the countdown has ended. /// - public bool Expired => DateTime.UtcNow > EndTime; + public bool Expired => DateTime.Now > EndTime; /// /// Gets a representing the amount of time left on the countdown. /// - public TimeSpan TimeLeft => EndTime - DateTime.UtcNow; + public TimeSpan TimeLeft => EndTime - DateTime.Now; /// /// Gets the source script that executed the countdown timer. From 0cea50c52c21411f257f23714b059ab90feb1c42 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 12:59:45 +0200 Subject: [PATCH 044/359] move TimeAction --- .../{Info => AllInOne}/TimeAction.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) rename ScriptedEvents/Actions/VariableMimics/{Info => AllInOne}/TimeAction.cs (78%) diff --git a/ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs similarity index 78% rename from ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs rename to ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs index 7f893277..2a97323a 100644 --- a/ScriptedEvents/Actions/VariableMimics/Info/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs @@ -47,15 +47,15 @@ public ActionResponse Execute(Script script) { string ret = Arguments[0].ToString().ToUpper() switch { - "TICK" => ((long)(DateTime.UtcNow - MainPlugin.Epoch).TotalSeconds).ToString(), - "SECOND" => DateTime.UtcNow.Second.ToString(), - "MINUTE" => DateTime.UtcNow.Minute.ToString(), - "HOUR" => DateTime.UtcNow.Hour.ToString(), - "MONTH" => DateTime.UtcNow.Month.ToString(), - "YEAR" => DateTime.UtcNow.Year.ToString(), - "DAYOFWEEK" => (((int)DateTime.UtcNow.DayOfWeek) + 1).ToString(), - "DAYOFMONTH" => DateTime.UtcNow.Day.ToString(), - "DAYOFYEAR" => DateTime.UtcNow.DayOfYear.ToString(), + "TICK" => ((long)(DateTime.Now - MainPlugin.Epoch).TotalSeconds).ToString(), + "SECOND" => DateTime.Now.Second.ToString(), + "MINUTE" => DateTime.Now.Minute.ToString(), + "HOUR" => DateTime.Now.Hour.ToString(), + "MONTH" => DateTime.Now.Month.ToString(), + "YEAR" => DateTime.Now.Year.ToString(), + "DAYOFWEEK" => (((int)DateTime.Now.DayOfWeek) + 1).ToString(), + "DAYOFMONTH" => DateTime.Now.Day.ToString(), + "DAYOFYEAR" => DateTime.Now.DayOfYear.ToString(), "ROUNDMINUTES" => ((float)Round.ElapsedTime.TotalMinutes).ToString(), "ROUNDSECONDS" => ((float)Round.ElapsedTime.TotalSeconds).ToString(), "ROUNDSTART" => Round.LobbyWaitingTime.ToString(), From c63954ac5662b3e6f486d1204b9690e35fd44553 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 12:59:53 +0200 Subject: [PATCH 045/359] move WarheadInfo --- .../VariableMimics/{Info => AllInOne}/WarheadInfoAction.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ScriptedEvents/Actions/VariableMimics/{Info => AllInOne}/WarheadInfoAction.cs (100%) diff --git a/ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs similarity index 100% rename from ScriptedEvents/Actions/VariableMimics/Info/WarheadInfoAction.cs rename to ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs From e3929a7e14aef9478b31cd25d8138871cbb088d0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:00:27 +0200 Subject: [PATCH 046/359] move wave variables to an action --- .../VariableMimics/AllInOne/WaveInfoAction.cs | 69 ++++++ .../Variables/TicketsAndRespawnsVariables.cs | 212 ------------------ 2 files changed, 69 insertions(+), 212 deletions(-) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs delete mode 100644 ScriptedEvents/Variables/TicketsAndRespawnsVariables.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs new file mode 100644 index 00000000..f6f0c4e2 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs @@ -0,0 +1,69 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class WaveInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "WAVEINFO"; + + /// + public string Description => "All-in-one action for getting wave related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("NEXTTEAM", "Returns the next SpawnableTeamType to spawn."), + new("LASTTEAM", "Returns the last spawned SpawnableTeamType."), + new("LASTUNIT", "Returns the last spawned SpawnableTeamType UNIT."), + new("TOTALWAVES", "Returns the amount of spawn waves which have occured."), + new("NTFTICKETS", "Returns the current NTF tickets."), + new("CHAOSTICKETS", "Returns the current CI tickets."), + new("TIMEUNTILNEW", "Returns the amount of seconds remaining until the new spawn wave."), + new("TIMESINCELAST", "Returns the amount of seconds since the last spawn wave."), + new("RESPAWNEDPLAYERS", "Returns the players which have spawned with the last spawn wave.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public ActionResponse Execute(Script script) + { + string mode = Arguments[0].ToUpper(); + + if (mode is "RESPAWNEDPLAYERS") + { + return new(true, variablesToRet: new[] { MainPlugin.Handlers.RecentlyRespawned }); + } + + string ret = mode switch + { + "NEXTTEAM" => Respawn.NextKnownTeam.ToString(), + "LASTTEAM" => MainPlugin.Handlers.MostRecentSpawn.ToString(), + "LASTUNIT" => MainPlugin.Handlers.MostRecentSpawnUnit.ToString(), + "TOTALWAVES" => MainPlugin.Handlers.RespawnWaves.ToString(), + "NTFTICKETS" => Respawn.NtfTickets.ToString(), + "CHAOSTICKETS" => Respawn.ChaosTickets.ToString(), + "TIMEUNTILNEXT" => Respawn.TimeUntilSpawnWave.TotalSeconds.ToString(), + "TIMESINCELAST" => MainPlugin.Handlers.TimeSinceWave.TotalSeconds.ToString(), + _ => throw new ArgumentException(), + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Variables/TicketsAndRespawnsVariables.cs b/ScriptedEvents/Variables/TicketsAndRespawnsVariables.cs deleted file mode 100644 index b65965ce..00000000 --- a/ScriptedEvents/Variables/TicketsAndRespawnsVariables.cs +++ /dev/null @@ -1,212 +0,0 @@ -namespace ScriptedEvents.Variables.TicketsAndRespawns -{ -#pragma warning disable SA1402 // File may only contain a single type - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Features; - using PlayerRoles; - using Respawning; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class TicketsAndRespawnsVariables : IVariableGroup - { - /// - public string GroupName => "Tickets & Respawn Waves"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new NextWave(), - new LastRespawnTeam(), - new LastUnitName(), - new WaveRespawning(), - new NtfTickets(), - new ChaosTickets(), - new TotalWaves(), - new TimeUntilNextWave(), - new TimeSinceLastWave(), - new RespawnedPlayers(), - new ChaosSpawns(), - new MtfSpawns(), - }; - } - - public class LastRespawnTeam : IStringVariable - { - /// - public string Name => "{LASTRESPAWNTEAM}"; - - /// - public string Description => "The most recent team that spawn."; - - /// - public string Value => MainPlugin.Handlers.MostRecentSpawn.ToString(); - } - - public class NextWave : IStringVariable - { - /// - public string Name => "{NEXTWAVE}"; - - /// - public string Description => "The next team to spawn, either NineTailedFox, ChaosInsurgency, or None."; - - /// - public string Value => Respawn.NextKnownTeam.ToString(); - } - - public class LastUnitName : IStringVariable - { - /// - public string Name => "{LASTRESPAWNUNIT}"; - - /// - public string Description => "The most recent team's unit name."; - - /// - public string Value => MainPlugin.Handlers.MostRecentSpawnUnit; - } - - public class WaveRespawning : IBoolVariable - { - /// - public string Name => "{WAVERESPAWNING}"; - - /// - public string ReversedName => "{!WAVERESPAWNING}"; - - /// - public string Description => "Whether or not a wave has respawned within the last 5 seconds."; - - /// - public bool Value => MainPlugin.Handlers.IsRespawning; - } - - public class NtfTickets : IFloatVariable - { - /// - public string Name => "{NTFTICKETS}"; - - /// - public string Description => "The amount of NTF tickets."; - - /// - public float Value => Respawn.NtfTickets; - } - - public class ChaosTickets : IFloatVariable - { - /// - public string Name => "{CHAOSTICKETS}"; - - /// - public string Description => "The amount of Chaos Insurgency tickets."; - - /// - public float Value => Respawn.ChaosTickets; - } - - public class TotalWaves : IFloatVariable - { - /// - public string Name => "{TOTALWAVES}"; - - /// - public string Description => "The amount of respawn waves."; - - /// - public float Value => MainPlugin.Handlers.RespawnWaves; - } - - public class TimeUntilNextWave : IFloatVariable - { - /// - public string Name => "{TIMEUNTILNEXTWAVE}"; - - /// - public string Description => "The amount of time until the next respawn wave, in seconds."; - - /// - public float Value => (float)Respawn.TimeUntilSpawnWave.TotalSeconds; - } - - public class TimeSinceLastWave : IFloatVariable - { - /// - public string Name => "{TIMESINCELASTWAVE}"; - - /// - public string Description => "The amount of time since the last respawn wave, in seconds. If a respawn wave has not occurred yet, this value will be very large."; - - /// - public float Value => (float)MainPlugin.Handlers.TimeSinceWave.TotalSeconds; - } - - public class RespawnedPlayers : IFloatVariable, IArgumentVariable, IPlayerVariable, INeedSourceVariable - { - /// - public string Name => "{RESPAWNEDPLAYERS}"; - - /// - public string Description => "The amount of players that have respawned in the most recent respawn wave."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("roleType", typeof(RoleTypeId), "The role to filter by.", false), - }; - - /// - public Script Source { get; set; } - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - // This is technically not necessary anymore since {FILTER} exists. TODO Think about this - if (Arguments.Length > 0) - { - return MainPlugin.Handlers.RecentlyRespawned.Where(ply => ply.Role == (RoleTypeId)Arguments[0]); - } - - return MainPlugin.Handlers.RecentlyRespawned; - } - } - } - - public class ChaosSpawns : IFloatVariable - { - /// - public string Name => "{CHAOSSPAWNS}"; - - /// - public string Description => "Total amount of Chaos Insurgency respawns."; - - /// - public float Value => MainPlugin.Handlers.SpawnsByTeam[SpawnableTeamType.ChaosInsurgency]; - } - - public class MtfSpawns : IFloatVariable - { - /// - public string Name => "{MTFSPAWNS}"; - - /// - public string Description => "Total amount of Mobile Task Force respawns."; - - /// - public float Value => MainPlugin.Handlers.SpawnsByTeam[SpawnableTeamType.NineTailedFox]; - } -} From 87f9ab4f7a8dfe3bcd7ad79dd5e556cd648c9851 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:00:44 +0200 Subject: [PATCH 047/359] make string variables their own actions --- .../VariableMimics/Strings/StrCountAction.cs | 12 + .../VariableMimics/Strings/StrLowerAction.cs | 12 + .../VariableMimics/Strings/StrRemoveAction.cs | 12 + .../Strings/StrReplaceAction.cs | 12 + .../VariableMimics/Strings/StrUpperAction.cs | 12 + ScriptedEvents/Variables/StringVariables.cs | 227 ------------------ 6 files changed, 60 insertions(+), 227 deletions(-) create mode 100644 ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs create mode 100644 ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs delete mode 100644 ScriptedEvents/Variables/StringVariables.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs new file mode 100644 index 00000000..18f44cc4 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptedEvents.Actions.VariableMimics.Strings +{ + internal class StrCountAction + { + } +} diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs new file mode 100644 index 00000000..723d5dbc --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptedEvents.Actions.VariableMimics.Strings +{ + internal class StrLowerAction + { + } +} diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs new file mode 100644 index 00000000..4eb18aa6 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptedEvents.Actions.VariableMimics.Strings +{ + internal class StrRemoveAction + { + } +} diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs new file mode 100644 index 00000000..8565b54a --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptedEvents.Actions.VariableMimics.Strings +{ + internal class StrReplaceAction + { + } +} diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs new file mode 100644 index 00000000..5e90005b --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ScriptedEvents.Actions.VariableMimics.Strings +{ + internal class StrUpperAction + { + } +} diff --git a/ScriptedEvents/Variables/StringVariables.cs b/ScriptedEvents/Variables/StringVariables.cs deleted file mode 100644 index ad70093e..00000000 --- a/ScriptedEvents/Variables/StringVariables.cs +++ /dev/null @@ -1,227 +0,0 @@ -namespace ScriptedEvents.Variables.Strings -{ -#pragma warning disable SA1402 // File may only contain a single type - using ScriptedEvents.API.Extensions; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class StringVariables : IVariableGroup - { - /// - public string GroupName => "Strings"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Index(), - new ReplaceVariable(), - new StringCountVariable(), - new StringToUpper(), - new StringToLower(), - new StringRemove(), - }; - } - - public class StringCountVariable : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{STR-COUNT}"; - - /// - public string Description => "Returns how many occurences of a string are in a given string."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variable", typeof(IStringVariable), "The variable on which the operation will be performed.", true), - new Argument("sequence", typeof(string), "The sequence which will be counted in the given string.", true), - }; - - /// - public float Value - { - get - { - // c# really has no method for this for fuck sake - static int CountOccurrences(string text, string substring) - { - int count = 0; - int index = 0; - - while ((index = text.IndexOf(substring, index)) != -1) - { - count++; - index += substring.Length; - } - - return count; - } - - string processedVar = ((IStringVariable)Arguments[0]).Value; - - return CountOccurrences(processedVar, (string)Arguments[1]); - } - } - } - - public class StringToLower : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STR-LOWER}"; - - /// - public string Description => "Returns the provided string where all UPPERCASE letters are replaced with lowercase ones."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("string", typeof(string), "The string to lowercase.", true), - }; - - /// - public string Value => Arguments[0].ToString().ToLower(); - } - - public class StringToUpper : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STR-UPPER}"; - - /// - public string Description => "Returns the provided string where all lowercase letters are replaced with UPPERCASE ones."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("string", typeof(string), "The string to UPPERCASE.", true), - }; - - /// - public string Value => Arguments[0].ToString().ToUpper(); - } - - public class StringRemove : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STR-REMOVE}"; - - /// - public string Description => "Returns the provided string where all the occurences of the specified string to remove are removed."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("mainString", typeof(string), "The string to perform the operation on.", true), - new Argument("stringToRemove", typeof(string), "The string to remove.", true), - }; - - /// - public string Value => Arguments[0].ToString().Replace(Arguments[1].ToString(), string.Empty); - } - - public class ReplaceVariable : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STR-REPLACE}"; - - /// - public string Description => "Replaces character sequneces."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variableName", typeof(IStringVariable), "The variable on which the operation will be performed.", true), - new Argument("targetSequence", typeof(string), "The sequence which will be replaced.", true), - new Argument("replacingSequence", typeof(string), "The value to replace with.", true), - }; - - /// - public string Value - { - get - { - IStringVariable processedVar = (IStringVariable)Arguments[0]; - return processedVar.String().Replace(Arguments[1].ToString(), Arguments[2].ToString()); - } - } - } - - public class Index : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STR-INDEX}"; - - /// - public string Description => "Extract a certain part of a variables value using an index."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variable", typeof(IStringVariable), "The name of the variable.", true), - new Argument("index", typeof(int), "The place from which the value should be taken.", true), - new Argument("listSplitChar", typeof(char), "The character that will split the variable into a list. Must be a 1 character only.", false), - }; - - /// - public string Value - { - get - { - IStringVariable value = (IStringVariable)Arguments[0]; - int index = (int)Arguments[1]; - string result; - - if (Arguments.Length >= 3) - { - char delimiter = (char)Arguments[2]; - - string[] resultList = value.Value.Split(delimiter); - - result = resultList[index].Trim(); - } - else - { - result = value.Value[index].ToString(); - } - - return result; - } - } - } -} From ee9fcfa2f7d3fafb62b60c1d7e2ae731c3cfe98d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:00:48 +0200 Subject: [PATCH 048/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index a966776e..b49b9b3d 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,8 +111,9 @@ - - + + + @@ -327,8 +328,6 @@ - - From 1f3a95449c7543f8e32cdad66e84e0735597fa68 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:38:39 +0200 Subject: [PATCH 049/359] Update TimeAction.cs --- .../VariableMimics/AllInOne/TimeAction.cs | 38 +++++++++++-------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs index 2a97323a..a9db75b6 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs @@ -18,18 +18,18 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, - new("TICK", "The amount of seconds since 1970."), - new("SECOND", "In range 0-59"), - new("MINUTE", "In range 0-59"), - new("HOUR", "In range 0-23"), - new("MONTH", "In range 1-12"), - new("YEAR", "The amount of years since the birth of Christ"), - new("DAYOFWEEK", "1-7 (Warning! This follows the US system, where Sunday is the first day of the week)"), - new("DAYOFMONTH", "0-31"), - new("DAYOFYEAR", "0-366"), - new("ROUNDMINUTES", "The amount of elapsed round time, in minutes."), - new("ROUNDSECONDS", "The amount of elapsed round time, in seconds."), - new("ROUNDSTART", "The amount of time remaining before the round starts. -1 if round already started.")), + new("TICK", "Returns the amount of seconds since 1970."), + new("SECOND", "Returns a number in range 0-59"), + new("MINUTE", "Returns a number in range 0-59"), + new("HOUR", "Returns a number in range 0-23"), + new("MONTH", "Returns a number in range 1-12"), + new("YEAR", "Returns the amount of years since the birth of Christ"), + new("DAYOFWEEK", "Returns a number in range 1-7 (Warning! This follows the US system, where Sunday is the first day of the week)"), + new("DAYOFMONTH", "Returns a number in range 0-31"), + new("DAYOFYEAR", "Returns a number in range 0-366"), + new("ROUNDMINUTES", "Returns the amount of elapsed round time, in minutes."), + new("ROUNDSECONDS", "Returns the amount of elapsed round time, in seconds."), + new("ROUNDSTART", "Returns the amount of time remaining before the round starts. -1 if round already started.")), }; public string[] RawArguments { get; set; } @@ -45,12 +45,20 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public ActionResponse Execute(Script script) { + static string Format(object input) + { + string str = input.ToString(); + return str.Length < 2 + ? "0" + str + : str; + } + string ret = Arguments[0].ToString().ToUpper() switch { "TICK" => ((long)(DateTime.Now - MainPlugin.Epoch).TotalSeconds).ToString(), - "SECOND" => DateTime.Now.Second.ToString(), - "MINUTE" => DateTime.Now.Minute.ToString(), - "HOUR" => DateTime.Now.Hour.ToString(), + "SECOND" => Format(DateTime.Now.Second), + "MINUTE" => Format(DateTime.Now.Minute), + "HOUR" => Format(DateTime.Now.Hour), "MONTH" => DateTime.Now.Month.ToString(), "YEAR" => DateTime.Now.Year.ToString(), "DAYOFWEEK" => (((int)DateTime.Now.DayOfWeek) + 1).ToString(), From c70c1cde9b9257eeee00d9aa05ef73e03dfa7a7b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:39:04 +0200 Subject: [PATCH 050/359] add proper srtr actions --- .../VariableMimics/Strings/StrCountAction.cs | 63 ++++++++++++++++--- .../VariableMimics/Strings/StrLowerAction.cs | 47 +++++++++++--- .../VariableMimics/Strings/StrRemoveAction.cs | 48 +++++++++++--- .../Strings/StrReplaceAction.cs | 49 ++++++++++++--- .../VariableMimics/Strings/StrUpperAction.cs | 47 +++++++++++--- ScriptedEvents/ScriptedEvents.csproj | 6 +- 6 files changed, 214 insertions(+), 46 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs index 18f44cc4..13254782 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs @@ -1,12 +1,57 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ScriptedEvents.Actions.VariableMimics.Strings +namespace ScriptedEvents.Actions { - internal class StrCountAction + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class StrCountAction : IScriptAction, IHelpInfo, IMimicsVariableAction { + /// + public string Name => "STR-COUNT"; + + /// + public string Description => "Returns the number of occurences of a string are in a given string."; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("variable", typeof(string), "The variable on which the operation will be performed.", true), + new Argument("sequence", typeof(string), "The sequence which will be counted in the given string.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + // c# really has no method for this for fuck sake + static int CountOccurrences(string text, string substring) + { + int count = 0; + int index = 0; + + while ((index = text.IndexOf(substring, index)) != -1) + { + count++; + index += substring.Length; + } + + return count; + } + + return new(true, variablesToRet: new[] { CountOccurrences((string)Arguments[0], (string)Arguments[1]).ToString() }); + } } -} +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs index 723d5dbc..8d977fb9 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs @@ -1,12 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ScriptedEvents.Actions.VariableMimics.Strings +namespace ScriptedEvents.Actions { - internal class StrLowerAction + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class StrLowerAction : IScriptAction, IHelpInfo, IMimicsVariableAction { + /// + public string Name => "STR-LOWER"; + + /// + public string Description => "Returns the provided string where all UPPERCASE letters are replaced with lowercase ones."; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("string", typeof(string), "The string to lowercase.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { Arguments[0].ToString().ToLower() }); + } } -} +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs index 4eb18aa6..7482b3f9 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs @@ -1,12 +1,42 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ScriptedEvents.Actions.VariableMimics.Strings +namespace ScriptedEvents.Actions { - internal class StrRemoveAction + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class StrRemoveAction : IScriptAction, IHelpInfo, IMimicsVariableAction { + /// + public string Name => "STR-REMOVE"; + + /// + public string Description => "Returns the provided string where all the occurences of the specified string to remove are removed."; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("mainString", typeof(string), "The string to perform the operation on.", true), + new Argument("stringToRemove", typeof(string), "The string to remove.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { ((string)Arguments[0]).Replace((string)Arguments[1], string.Empty) }); + } } -} +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs index 8565b54a..fc0b68d7 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs @@ -1,12 +1,43 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ScriptedEvents.Actions.VariableMimics.Strings +namespace ScriptedEvents.Actions { - internal class StrReplaceAction + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class StrReplaceAction : IScriptAction, IHelpInfo, IMimicsVariableAction { + /// + public string Name => "STR-REPLACE"; + + /// + public string Description => "Replaces character sequneces in a given string."; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("variableName", typeof(string), "The string on which the operation will be performed.", true), + new Argument("targetSequence", typeof(string), "The sequence which will be replaced.", true), + new Argument("replacingSequence", typeof(string), "The value to replace with.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { ((string)Arguments[0]).Replace(Arguments[1].ToString(), Arguments[2].ToString()) }); + } } -} +} \ No newline at end of file diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs index 5e90005b..6cc64260 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs @@ -1,12 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ScriptedEvents.Actions.VariableMimics.Strings +namespace ScriptedEvents.Actions { - internal class StrUpperAction + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class StrUpperAction : IScriptAction, IHelpInfo, IMimicsVariableAction { + /// + public string Name => "STR-UPPER"; + + /// + public string Description => "Returns the provided string where all lowercase letters are replaced with UPPERCASE ones."; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("string", typeof(string), "The string to UPPERCASE.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { Arguments[0].ToString().ToUpper() }); + } } -} +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index b49b9b3d..26af9bca 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -158,6 +158,11 @@ + + + + + @@ -327,7 +332,6 @@ - From 912ea2aa1365d2a9ee11bdd9ac828caabbd9551d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 13:42:44 +0200 Subject: [PATCH 051/359] Update WarheadInfoAction.cs --- .../VariableMimics/AllInOne/WarheadInfoAction.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs index 8527f1aa..b359abb7 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs @@ -19,11 +19,11 @@ public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, - new("ISDETONATED"), - new("ISOPEN"), - new("ISARMED"), - new("ISCOUNTING"), - new("DETONATIONTIME")), + new("ISDETONATED", "Returns a TRUE/FALSE value saying if the warhead is detonated."), + new("ISOPEN", "Returns a TRUE/FALSE value saying if the warhead is open."), + new("ISARMED", "Returns a TRUE/FALSE value saying if the warhead is armed."), + new("ISCOUNTING", "Returns a TRUE/FALSE value saying if the warhead is detonating."), + new("DETONATIONTIME", "Returns the amount of seconds remaining to the explosion.")), }; public string[] RawArguments { get; set; } From 50f578a33bca71819fba2f583891765c660b04a5 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 14:21:37 +0200 Subject: [PATCH 052/359] remove server info variables --- .../Variables/ServerInfoVariables.cs | 62 ------------------- 1 file changed, 62 deletions(-) delete mode 100644 ScriptedEvents/Variables/ServerInfoVariables.cs diff --git a/ScriptedEvents/Variables/ServerInfoVariables.cs b/ScriptedEvents/Variables/ServerInfoVariables.cs deleted file mode 100644 index 97295a4f..00000000 --- a/ScriptedEvents/Variables/ServerInfoVariables.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace ScriptedEvents.Variables.ServerInfo -{ - using System; -#pragma warning disable SA1402 // File may only contain a single type - - using Exiled.API.Features; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class ServerInfoVariables : IVariableGroup - { - /// - public string GroupName => "Server Info"; - - /// - public IVariable[] Variables => new IVariable[] - { - new DefaultServer(), - }; - } - - public class DefaultServer : IStringVariable, IArgumentVariable - { - /// - public string Name => "{SERVER}"; - - /// - public string Description => "All-in-one variable for server related information."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, new("IP"), new("PORT"), new("NAME"), new("MAXPLAYERS"), new("TPS"), new("VERIFIED")), - }; - - /// - public string Value - { - get - { - string mode = (string)Arguments[0]; - - return mode.ToUpper() switch - { - "IP" => Server.IpAddress, - "PORT" => Server.Port.ToString(), - "NAME" => Server.Name, - "MAXPLAYERS" => Server.MaxPlayerCount.ToString(), - "TPS" => Server.Tps.ToString(), - _ => throw new ArgumentException("No mode provided") - }; - } - } - } -#pragma warning restore SA1402 // File may only contain a single type -} From 853bb38393e236a10d04c48cb3ae3d25de681cba Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 14:21:44 +0200 Subject: [PATCH 053/359] add SERVERINFO action --- .../AllInOne/ServerInfoAction.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs new file mode 100644 index 00000000..744de2c5 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs @@ -0,0 +1,55 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class ServerInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "SERVERINFO"; + + /// + public string Description => "All-in-one action for getting server related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("IP", "Returns the IP of the server."), + new("PORT", "Returns the port of the server."), + new("NAME", "Returns the name of the server."), + new("MAXPLAYERS", "Returns the maximum amount of players the server is set to."), + new("TPS", "Returns the amount of ticks per second the server is running on.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "IP" => Server.IpAddress, + "PORT" => Server.Port.ToString(), + "NAME" => Server.Name, + "MAXPLAYERS" => Server.MaxPlayerCount.ToString(), + "TPS" => Server.Tps.ToString(), + _ => throw new ArgumentException("No mode provided") + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 310d8d462cbb93648fc8fbd68c22769b74dfff5f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 14:21:53 +0200 Subject: [PATCH 054/359] Update ActionSubgroup.cs --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 35 ++++++++++++---------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index fca2616b..cdadca2b 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -6,27 +6,27 @@ public enum ActionSubgroup { /// - /// Broadcast-related action. + /// Broadcast related action. /// Broadcast, /// - /// Cassie-related action. + /// Cassie related action. /// Cassie, /// - /// Debugging-related action. + /// Debugging related action. /// Debug, /// - /// Health-related action. + /// Health related action. /// Health, /// - /// Item-related action. + /// Item related action. /// Item, @@ -36,12 +36,12 @@ public enum ActionSubgroup Lights, /// - /// Logic action, such as IFs and STOPs. + /// Logic related action, such as IFs and STOPs. /// Logic, /// - /// Map-related action. + /// Map related action. /// Map, @@ -51,12 +51,12 @@ public enum ActionSubgroup Misc, /// - /// Player-related action. + /// Player related action. /// Player, /// - /// Round-related action. + /// Round related action. /// Round, @@ -66,33 +66,38 @@ public enum ActionSubgroup RoundRule, /// - /// Variable-related action. + /// Variable related action. /// Variable, /// - /// Yielding action. + /// Yielding related action. /// Yielding, /// - /// Server action. + /// Server related action. /// Server, /// - /// Teleportation action. + /// Teleportation related action. /// Teleportation, /// - /// Math action. + /// Math related action. /// Math, /// - /// Math action. + /// Map info related action. /// MapInfo, + + /// + /// "All In One" info related action. + /// + AllInOneInfo, } } From 253614fa9a52bd912a52cc788831894e39e1f766 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 14:21:58 +0200 Subject: [PATCH 055/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 26af9bca..9eff0753 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,6 +111,7 @@ + From 0ac83110668c5be5f9945f581239bf8a1bc6745b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:01:12 +0200 Subject: [PATCH 056/359] Update TimeAction.cs --- ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs index a9db75b6..65f02b4f 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs @@ -40,7 +40,7 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; /// public ActionResponse Execute(Script script) From 2851980b6d17e24b2d67c2b64530bc88524038da Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:01:16 +0200 Subject: [PATCH 057/359] Update WarheadInfoAction.cs --- .../Actions/VariableMimics/AllInOne/WarheadInfoAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs index b359abb7..354f4427 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs @@ -34,7 +34,7 @@ public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; /// public ActionResponse Execute(Script script) From 8b5fbb128192a20c0a2bcfe81b24d086fb5b7d55 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:01:19 +0200 Subject: [PATCH 058/359] Update WaveInfoAction.cs --- .../Actions/VariableMimics/AllInOne/WaveInfoAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs index f6f0c4e2..96dbeeb7 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs @@ -38,7 +38,7 @@ public class WaveInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; /// public ActionResponse Execute(Script script) From 8d4147edc217ff30d8207883f7ab5aab3532e9d6 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:01:21 +0200 Subject: [PATCH 059/359] Update ZonePlayersAction.cs --- .../Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs index 398f84c6..2bcbddb3 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs @@ -24,7 +24,7 @@ public class ZonePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction public object[] Arguments { get; set; } /// - public ActionSubgroup Subgroup => ActionSubgroup.Math; + public ActionSubgroup Subgroup => ActionSubgroup.Debug; /// public string Description => "Returns the players in the specified zone."; From 0b7589fb031696997bd60ba23aad35199a45fdf8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:01:23 +0200 Subject: [PATCH 060/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 9eff0753..89609f36 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -332,7 +332,6 @@ - From a4b1907c43b43cfe6446d44edd7c7c526d8a31f4 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:05:30 +0200 Subject: [PATCH 061/359] add String subgroup --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 5 +++++ .../Actions/VariableMimics/Strings/StrCountAction.cs | 2 +- .../Actions/VariableMimics/Strings/StrLowerAction.cs | 2 +- .../Actions/VariableMimics/Strings/StrRemoveAction.cs | 2 +- .../Actions/VariableMimics/Strings/StrReplaceAction.cs | 2 +- .../Actions/VariableMimics/Strings/StrUpperAction.cs | 2 +- 6 files changed, 10 insertions(+), 5 deletions(-) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index cdadca2b..aacb1907 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -99,5 +99,10 @@ public enum ActionSubgroup /// "All In One" info related action. /// AllInOneInfo, + + /// + /// String modification related action. + /// + String, } } diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs index 13254782..0101c78d 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs @@ -24,7 +24,7 @@ public class StrCountAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.String; /// public Argument[] ExpectedArguments => new[] diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs index 8d977fb9..bd50950e 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs @@ -24,7 +24,7 @@ public class StrLowerAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.String; /// public Argument[] ExpectedArguments => new[] diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs index 7482b3f9..f5db400e 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs @@ -24,7 +24,7 @@ public class StrRemoveAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.String; /// public Argument[] ExpectedArguments => new[] diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs index fc0b68d7..8e103ab9 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs @@ -24,7 +24,7 @@ public class StrReplaceAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.String; /// public Argument[] ExpectedArguments => new[] diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs index 6cc64260..ae8928f0 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs @@ -24,7 +24,7 @@ public class StrUpperAction : IScriptAction, IHelpInfo, IMimicsVariableAction public string[] Aliases => Array.Empty(); /// - public ActionSubgroup Subgroup => ActionSubgroup.MapInfo; + public ActionSubgroup Subgroup => ActionSubgroup.String; /// public Argument[] ExpectedArguments => new[] From c9e84df418a55fb67494a8863cb703ec9b8fa4cb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:10:10 +0200 Subject: [PATCH 062/359] add subgroup --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 7 ++++++- .../VariableMimics/PlayerFetch/ZonePlayersAction.cs | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index aacb1907..3f87e1f3 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -51,7 +51,7 @@ public enum ActionSubgroup Misc, /// - /// Player related action. + /// Player management related action. /// Player, @@ -100,6 +100,11 @@ public enum ActionSubgroup /// AllInOneInfo, + /// + /// Player fetching action. + /// + PlayerFetch, + /// /// String modification related action. /// diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs index 2bcbddb3..7d6ad9c6 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs @@ -24,7 +24,7 @@ public class ZonePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction public object[] Arguments { get; set; } /// - public ActionSubgroup Subgroup => ActionSubgroup.Debug; + public ActionSubgroup Subgroup => ActionSubgroup.PlayerFetch; /// public string Description => "Returns the players in the specified zone."; From a0624fb554ae3bb3debbf65d2b8bbfd1fc705efd Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:22:50 +0200 Subject: [PATCH 063/359] add THIS action --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 5 ++ .../VariableMimics/ScriptInfo/ThisAction.cs | 63 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 1 + 3 files changed, 69 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index 3f87e1f3..6300c53d 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -109,5 +109,10 @@ public enum ActionSubgroup /// String modification related action. /// String, + + /// + /// Script info related action. + /// + ScriptInfo, } } diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs new file mode 100644 index 00000000..d93fa664 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs @@ -0,0 +1,63 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class ThisAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "THIS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.ScriptInfo; + + /// + public string Description => "Returns information about the script where the action is used."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", false, + new("AUTORUN", "Returns 'TRUE' or 'FALSE' depending on if the script is set to auto-run when the round restarts."), + new("CALLER", "Returns the name of the script that called this script. 'NONE' if script was called by other means."), + new("CONTEXT", $"Returns the context in which the script was executed. Valid options are: {string.Join(", ", ((ExecuteContext[])Enum.GetValues(typeof(ExecuteContext))).Where(r => r is not ExecuteContext.None))}"), + new("DEBUG", $"Returns 'TRUE' or 'FALSE' depending on if the script is in debug mode."), + new("DURATION", $"Returns the amount of time (in seconds) the script has been running."), + new("NAME", "Returns the name of the script."), + new("PATH", "Returns the path to the script on the local directory."), + new("VARIABLES", "Returns variable names available to this script only.")), + }; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "AUTORUN" => script.HasFlag("AUTORUN").ToUpper(), + "CALLER" => script.CallerScript is not null ? script.CallerScript.ScriptName : "NONE", + "CONTEXT" => script.Context.ToString(), + "DEBUG" => script.Debug.ToUpper(), + "DURATION" => script.RunDuration.TotalSeconds.ToString(), + "NAME" => script.ScriptName, + "PATH" => script.FilePath ?? "N/A", + "VARIABLES" => script.UniqueVariables.Keys.Concat(script.UniquePlayerVariables.Keys).ToArray().Length != 0 ? string.Join(", ", script.UniqueVariables.Keys.Concat(script.UniquePlayerVariables.Keys)) : "NONE", + _ => throw new ArgumentException() + }; + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 89609f36..1a378dea 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -159,6 +159,7 @@ + From 48164fa995d8763cb932fcd0007daf0824c3d5b7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:28:48 +0200 Subject: [PATCH 064/359] add VEXISTS action --- .../ScriptInfo/VExistsAction.cs | 45 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 1 + 2 files changed, 46 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs new file mode 100644 index 00000000..8fec175c --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs @@ -0,0 +1,45 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.API.Modules; + using ScriptedEvents.Structures; + + public class VExistsAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "VEXISTS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.ScriptInfo; + + /// + public string Description => "Returns TRUE if the variable with the given name exists in the current context, else FALSE."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("variableName", typeof(string), "The name of the variable.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + string ret = VariableSystemV2.TryGetVariable((string)Arguments[0], script, out VariableResult _).ToUpper(); + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 1a378dea..ef0d69f8 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -160,6 +160,7 @@ + From 4bb75b28977c6ee088ba5f50578ae88a2b718c4d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:31:24 +0200 Subject: [PATCH 065/359] add ISRUNNING action --- .../ScriptInfo/IsRunningAction.cs | 44 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 1 + 2 files changed, 45 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs new file mode 100644 index 00000000..675a56e9 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs @@ -0,0 +1,44 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class IsRunningAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ISRUNNING"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.ScriptInfo; + + /// + public string Description => "Returns TRUE if a specific script is running, else FALSE."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("scriptName", typeof(string), "The name of the script.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + string ret = MainPlugin.ScriptModule.RunningScripts.Any(scr => scr.Key.ScriptName == (string)Arguments[0] && scr.Value.IsRunning).ToUpper(); + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index ef0d69f8..1730eefc 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -159,6 +159,7 @@ + From 405c11a3dd9b2bef1e8bc9c53615a32b82ae0745 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 15:31:43 +0200 Subject: [PATCH 066/359] Delete ScriptInfoVariables.cs --- .../Variables/ScriptInfoVariables.cs | 159 ------------------ 1 file changed, 159 deletions(-) delete mode 100644 ScriptedEvents/Variables/ScriptInfoVariables.cs diff --git a/ScriptedEvents/Variables/ScriptInfoVariables.cs b/ScriptedEvents/Variables/ScriptInfoVariables.cs deleted file mode 100644 index 69f56c37..00000000 --- a/ScriptedEvents/Variables/ScriptInfoVariables.cs +++ /dev/null @@ -1,159 +0,0 @@ -namespace ScriptedEvents.Variables.Booleans -{ - using System; -#pragma warning disable SA1402 // File may only contain a single type - using System.Linq; - - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Modules; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class ScriptInfoVariables : IVariableGroup - { - /// - public string GroupName => "Script Info"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new VariableExists(), - new IsScriptRunning(), - new This(), - }; - } - - public class This : IStringVariable, INeedSourceVariable, IArgumentVariable - { - /// - public string Name => "{THIS}"; - - /// - public string Description => "Returns information about the script."; - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", false, - new("AUTORUN", "'TRUE' or 'FALSE' depending on if the script is set to auto-run when the round restarts."), - new("CALLER", "The name of the script that called this script."), - new("CONTEXT", $"The context in which the script was executed. Valid options are: {string.Join(", ", ((ExecuteContext[])Enum.GetValues(typeof(ExecuteContext))).Where(r => r is not ExecuteContext.None))}"), - new("DEBUG", $"'TRUE' or 'FALSE' depending on if the script is in debug mode."), - new("DURATION", $"The amount of time (in seconds) the script has been running."), - new("NAME", "The name of the script."), - new("PATH", "The path to the script on the local directory."), - new("VARIABLES", "Lists variable names available to this script only.")), - }; - - /// - public string Value - { - get - { - if (Arguments.Length == 0) return Source.ScriptName; - - string mode = Arguments[0].ToUpper(); - return mode switch - { - "AUTORUN" => Source.HasFlag("AUTORUN").ToUpper(), - "CALLER" => Source.CallerScript is not null ? Source.CallerScript.ScriptName : "NONE", - "CONTEXT" => Source.Context.ToString(), - "DEBUG" => Source.Debug.ToUpper(), - "DURATION" => Source.RunDuration.TotalSeconds.ToString(), - "NAME" => Source.ScriptName, - "PATH" => Source.FilePath ?? "N/A", - "VARIABLES" => Source.UniqueVariables.Keys.Concat(Source.UniquePlayerVariables.Keys).ToArray().Length != 0 ? string.Join(", ", Source.UniqueVariables.Keys.Concat(Source.UniquePlayerVariables.Keys)) : "NONE", - _ => throw new ArgumentException("Invalid mode.", mode) - }; - } - } - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Script Source { get; set; } - } - - public class VariableExists : IBoolVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{VEXISTS}"; - - /// - public string ReversedName => "{!VEXISTS}"; - - /// - public string Description => "Whether or not the variable with the given name exists in the current context."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variableName", typeof(string), "The name of the variable.", true), - }; - - /// - public Script Source { get; set; } - - /// - public bool Value - { - get - { - if (Arguments.Length < 1) throw new ArgumentException("No variable provided"); - - if (VariableSystemV2.TryGetPlayers(RawArguments[0], Source, out _, requireBrackets: false)) - return true; - - if (VariableSystemV2.TryGetVariable(RawArguments[0], Source, out _, false, true)) - return true; - - return false; - } - } - } - - public class IsScriptRunning : IBoolVariable, IArgumentVariable - { - /// - public string Name => "{ISRUNNING}"; - - /// - public string ReversedName => "{!ISRUNNING}"; - - /// - public string Description => "Whether or not a specific script is running."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("scriptName", typeof(string), "The name of the script.", true), - }; - - /// - public bool Value - { - get - { - string scriptName = (string)Arguments[0]; - return MainPlugin.ScriptModule.RunningScripts.Any(scr => scr.Key.ScriptName == scriptName && scr.Value.IsRunning); - } - } - } -} From 6a2e9b578c9af50575cead009690fbab0ed406f0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 16:46:17 +0200 Subject: [PATCH 067/359] Delete RoundVariables.cs --- ScriptedEvents/Variables/RoundVariables.cs | 96 ---------------------- 1 file changed, 96 deletions(-) delete mode 100644 ScriptedEvents/Variables/RoundVariables.cs diff --git a/ScriptedEvents/Variables/RoundVariables.cs b/ScriptedEvents/Variables/RoundVariables.cs deleted file mode 100644 index 4cb622ed..00000000 --- a/ScriptedEvents/Variables/RoundVariables.cs +++ /dev/null @@ -1,96 +0,0 @@ -namespace ScriptedEvents.Variables.Round -{ - using System; -#pragma warning disable SA1402 // File may only contain a single type - - using Exiled.API.Features; - - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class RoundVariables : IVariableGroup - { - /// - public string GroupName => "Round"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new UptimeRound(), - new LobbyLock(), - new GeneralRound(), - }; - } - - public class UptimeRound : IFloatVariable - { - /// - public string Name => "{UPTIMEROUND}"; - - /// - public string Description => "The amount of rounds that have progressed since the server has started."; - - /// - public float Value => Round.UptimeRounds; - } - - public class LobbyLock : IBoolVariable - { - /// - public string Name => "{LOBBYLOCKED}"; - - public string ReversedName => "{!LOBBYLOCKED}"; - - /// - public string Description => "Returns the lobbylock setting status."; - - /// - public bool Value - { - get - { - return Round.IsLobbyLocked; - } - } - } - - public class GeneralRound : IBoolVariable, IArgumentVariable - { - /// - public string Name => "{ROUND}"; - - public string ReversedName => "{!ROUND}"; - - /// - public string Description => "All-in-one variable for round related information."; - - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("LOCKED", "Retruns the roundlock status."), - new("STARTED", "TRUE if round has started."), - new("INPROGRESS", "TRUE if round is in progress, neither started or ended."), - new("ENDED", "TRUE if round has ended.")), - }; - - /// - public bool Value - { - get - { - return ((string)Arguments[0]).ToUpper() switch - { - "LOCKED" => Round.IsLocked, - "STARTED" => Round.IsStarted, - "INPROGRESS" => Round.InProgress, - "ENDED" => Round.IsEnded, - _ => throw new ArgumentException("No mode provided") - }; - } - } - - public string[] RawArguments { get; set; } - - public object[] Arguments { get; set; } - } -} From f497aa50564db9d9e85664232fe837c82764772b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 16:46:22 +0200 Subject: [PATCH 068/359] Create LobbyInfoAction.cs --- .../AllInOne/LobbyInfoAction.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs new file mode 100644 index 00000000..58e84264 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs @@ -0,0 +1,51 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class LobbyInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "LOBBYINFO"; + + /// + public string Description => "All-in-one action for getting lobby related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("WAITINGTIME", "Returns the timer for waiting for players in lobby."), + new("ISACTIVE", "Returns a TRUE/FALSE value saying if the lobby is active."), + new("ISLOCKED", "Returns a TRUE/FALSE value saying if the lobby is locked.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "WAITINGTIME" => Round.LobbyWaitingTime.ToString(), + "ISACTIVE" => Round.IsLobby.ToUpper(), + "ISLOCKED" => Round.IsLobbyLocked.ToUpper(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From adb3c92700ea10fe08bab7030d1e768e33757b7e Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 16:46:24 +0200 Subject: [PATCH 069/359] Create RoundInfoAction.cs --- .../AllInOne/RoundInfoAction.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs new file mode 100644 index 00000000..34022cc6 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs @@ -0,0 +1,55 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class RoundInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ROUNDINFO"; + + /// + public string Description => "All-in-one action for getting round related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("ISLOCKED", "Returns a TRUE/FALSE value being the roundlock status."), + new("ISSTARTED", "Returns a TRUE/FALSE value saying if the round has started."), + new("ISINPROGRESS", "Returns a TRUE/FALSE value saying if the round is in progress."), + new("ISENDED", "Returns a TRUE/FALSE value saying if the round has ended."), + new("UPTIMEROUNDS", "Returns the amount of rounds that have progressed since the server has started.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "LOCKED" => Round.IsLocked.ToUpper(), + "STARTED" => Round.IsStarted.ToUpper(), + "INPROGRESS" => Round.InProgress.ToUpper(), + "ENDED" => Round.IsEnded.ToUpper(), + "UPTIMEROUNDS" => Round.UptimeRounds.ToString(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 91242aabdcf05fd1ce758bac4d12a2fd6536653c Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 16:46:26 +0200 Subject: [PATCH 070/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 1730eefc..ed9087aa 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,6 +111,8 @@ + + @@ -334,7 +336,6 @@ - From e3d5b85b2ea662f4446a8d1d436f84417b9c97dc Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 17:08:35 +0200 Subject: [PATCH 071/359] add ROLEPLAYERS action --- .../PlayerFetch/RolePlayersAction.cs | 44 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs new file mode 100644 index 00000000..1ad67714 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs @@ -0,0 +1,44 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class RolePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ROLEPLAYERS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerFetch; + + /// + public string Description => "Returns the players with the specified role."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("zone", typeof(RoleTypeId), "The role which the players should be fetched by.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { Player.List.Where(ply => ply.Role == ((RoleTypeId)Arguments[0])).ToArray() }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index ed9087aa..d69d5677 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -160,6 +160,7 @@ + @@ -335,7 +336,6 @@ - From f2b3eaaf5dd112a64c2d2839a6e6fc574a985014 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 17:08:47 +0200 Subject: [PATCH 072/359] Update RolePlayersAction.cs --- .../Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs index 1ad67714..8ef6a383 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs @@ -32,7 +32,7 @@ public class RolePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public Argument[] ExpectedArguments => new[] { - new Argument("zone", typeof(RoleTypeId), "The role which the players should be fetched by.", true), + new Argument("role", typeof(RoleTypeId), "The role which the players should be fetched by.", true), }; /// From b00bc41380285a1366cff61ae16e146a6e8392c7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 8 Sep 2024 17:10:49 +0200 Subject: [PATCH 073/359] add TEAMPLAYERS action --- .../PlayerFetch/TeamPlayersAction.cs | 44 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 1 + 2 files changed, 45 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs new file mode 100644 index 00000000..89eb51b2 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs @@ -0,0 +1,44 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class TeamPlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "TEAMPLAYERS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerFetch; + + /// + public string Description => "Returns the players from the specified team."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("team", typeof(Team), "The team which the players should be fetched by.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { Player.List.Where(ply => ply.Role.Team == ((Team)Arguments[0])).ToArray() }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index d69d5677..a659b8a0 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -161,6 +161,7 @@ + From e19d0207efc3beed4cba5a92090fbdf29849c8e0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:25:18 +0200 Subject: [PATCH 074/359] Delete ChanceVariables.cs --- ScriptedEvents/Variables/ChanceVariables.cs | 124 -------------------- 1 file changed, 124 deletions(-) delete mode 100644 ScriptedEvents/Variables/ChanceVariables.cs diff --git a/ScriptedEvents/Variables/ChanceVariables.cs b/ScriptedEvents/Variables/ChanceVariables.cs deleted file mode 100644 index b73d168a..00000000 --- a/ScriptedEvents/Variables/ChanceVariables.cs +++ /dev/null @@ -1,124 +0,0 @@ -namespace ScriptedEvents.Variables.Chance -{ - using System; - - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Interfaces; - using ScriptedEvents.Structures; -#pragma warning disable SA1402 // File may only contain a single type - using ScriptedEvents.Variables.Interfaces; - - public class ChanceVariables : IVariableGroup - { - /// - public string GroupName => "Chances"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Rand(), - }; - } - - public class Rand : IFloatVariable, IArgumentVariable, ILongDescription - { - /// - public string Name => "{RANDOM}"; - - /// - public string Description => "Returns a random number from provided range."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("type", true, - new("INT", "Will return an integer."), - new("FLOAT", "Will return a decimal (floating point) number.")), - new Argument("startNumber", typeof(string), "A starting number of the random range.", true), - new Argument("endNumber", typeof(string), "An ending number of the random range.", true), - }; - - public string LongDescription => $@"The return value will be a random number from the provided range, depending on the numbers and the type. - -If 'type' is set to 'INT': -> act PRINT My integer is {{RANDOM:INT:1:100}} -> My integer is 60 - -If 'type' is set to 'FLOAT': -> act PRINT My float is {{RANDOM:FLOAT:0:1}} -> My float is 0.35227"; - - /// - public float Value - { - get - { - float result; - string mode = Arguments[0].ToUpper(); - switch (mode) - { - case "INT": - int r1i; - int r2i; - try - { - r1i = Convert.ToInt32(Arguments[1]); - } - catch - { - throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[1])); - } - - try - { - r2i = Convert.ToInt32(Arguments[2]) + 1; - } - catch - { - throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[2])); - } - - result = UnityEngine.Random.Range(r1i, r2i); - break; - - case "FLOAT": - float r1f; - float r2f; - - try - { - r1f = Convert.ToSingle(Arguments[1]); - } - catch - { - throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[1])); - } - - try - { - r2f = Convert.ToSingle(Arguments[2]); - } - catch - { - throw new InvalidCastException(ErrorGen.Get(API.Enums.ErrorCode.InvalidNumber, Arguments[2])); - } - - result = UnityEngine.Random.Range(r1f, r2f); - break; - - default: - throw new Exception("[4562] error - you shouldnt ever see this error"); - } - - return result; - } - } - } -} From 63ec24643dd4fe11f957919b7d3db8e750aa7ce0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:32:23 +0200 Subject: [PATCH 075/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index a659b8a0..2badf755 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -329,7 +329,6 @@ - From 689ff7ce142c76889c3a0a155ec6cf12e97c72cb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:32:24 +0200 Subject: [PATCH 076/359] Update EscapesVariables.cs --- ScriptedEvents/Variables/EscapesVariables.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/Variables/EscapesVariables.cs b/ScriptedEvents/Variables/EscapesVariables.cs index 10b3b411..17c0f36f 100644 --- a/ScriptedEvents/Variables/EscapesVariables.cs +++ b/ScriptedEvents/Variables/EscapesVariables.cs @@ -1,6 +1,7 @@ #pragma warning disable SA1402 // File may only contain a single type namespace ScriptedEvents.Variables.Escapes { + using System; using System.Collections.Generic; using System.Linq; @@ -47,14 +48,13 @@ public IEnumerable Players { get { -#pragma warning disable CS8509 // Wyrażenie switch nie obsÅ‚uguje wszystkich możliwych wartoÅ›ci jego typu danych wejÅ›ciowych (nie jest kompletne). return Arguments[0].ToUpper() switch { "ALL" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD].Union(MainPlugin.Handlers.Escapes[RoleTypeId.Scientist]), "SCIENTISTS" => MainPlugin.Handlers.Escapes[RoleTypeId.Scientist], "CLASSD" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD], + _ => throw new ArgumentException() }; -#pragma warning restore CS8509 // Wyrażenie switch nie obsÅ‚uguje wszystkich możliwych wartoÅ›ci jego typu danych wejÅ›ciowych (nie jest kompletne). } } From a1c52fe6b6b5995580792f9a7c94ec35e969273f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:38:10 +0200 Subject: [PATCH 077/359] Create EscapesAction.cs --- .../PlayerFetch/EscapesAction.cs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs new file mode 100644 index 00000000..06c214dd --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs @@ -0,0 +1,56 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class EscapesAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ESCAPES"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerFetch; + + /// + public string Description => "Returns players which have escaped the facility."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("ALL", "Scientists and ClassDs which have escaped."), + new("SCIENTISTS", "Scientists which have escaped."), + new("CLASSD", "ClassDs which have escaped.")), + }; + + /// + public ActionResponse Execute(Script script) + { + Player[] ret = Arguments[0].ToUpper() switch + { + "ALL" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD].Union(MainPlugin.Handlers.Escapes[RoleTypeId.Scientist]).ToArray(), + "SCIENTISTS" => MainPlugin.Handlers.Escapes[RoleTypeId.Scientist].ToArray(), + "CLASSD" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD].ToArray(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 11a97a12dabb120b329e8df9e4b2b529a9369e65 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:38:14 +0200 Subject: [PATCH 078/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 2badf755..ab389e29 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -160,6 +160,7 @@ + From fd14e26469c8abea24e117be1d7c7135fadcbfdb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 9 Sep 2024 14:41:27 +0200 Subject: [PATCH 079/359] Delete EscapesVariables.cs --- ScriptedEvents/Variables/EscapesVariables.cs | 67 -------------------- 1 file changed, 67 deletions(-) delete mode 100644 ScriptedEvents/Variables/EscapesVariables.cs diff --git a/ScriptedEvents/Variables/EscapesVariables.cs b/ScriptedEvents/Variables/EscapesVariables.cs deleted file mode 100644 index 17c0f36f..00000000 --- a/ScriptedEvents/Variables/EscapesVariables.cs +++ /dev/null @@ -1,67 +0,0 @@ -#pragma warning disable SA1402 // File may only contain a single type -namespace ScriptedEvents.Variables.Escapes -{ - using System; - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Features; - using PlayerRoles; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class EscapesVariables : IVariableGroup - { - /// - public string GroupName => "Escapes"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Escapes(), - }; - } - - public class Escapes : IFloatVariable, IPlayerVariable, IArgumentVariable - { - /// - public string Name => "{ESCAPES}"; - - /// - public string Description => "Players which have escaped the facility."; - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("ALL", "Scientists and ClassDs which have escaped."), - new("SCIENTISTS", "Scientists which have escaped."), - new("CLASSD", "ClassDs which have escaped.")), - }; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - return Arguments[0].ToUpper() switch - { - "ALL" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD].Union(MainPlugin.Handlers.Escapes[RoleTypeId.Scientist]), - "SCIENTISTS" => MainPlugin.Handlers.Escapes[RoleTypeId.Scientist], - "CLASSD" => MainPlugin.Handlers.Escapes[RoleTypeId.ClassD], - _ => throw new ArgumentException() - }; - } - } - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - } -} From 989849da674eda873803714d669ec806a00bcd5a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 14:44:35 +0200 Subject: [PATCH 080/359] add INTERCOMINFO action --- .../AllInOne/IntercomInfoAction.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs new file mode 100644 index 00000000..188d4757 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs @@ -0,0 +1,61 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class IntercomInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "INTERCOMINFO"; + + /// + public string Description => "All-in-one action for getting intercom related information."; + + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("SPEAKER", "Returns the player who is speaking on the intercom."), + new("ISREADY", "Returns a TRUE/FALSE value saying if intercom ready to detonate."), + new("COOLDOWNLEFT", "Returns the amount of seconds of the cooldown remaining."), + new("TIMELEFT", "Returns the amount of seconds left for speaking."), + new("INUSE", "Returns a TRUE/FALSE value saying if intercom is in use already.")), + }; + + public string[] RawArguments { get; set; } + + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string mode = Arguments[0].ToUpper(); + + if (mode == "SPEAKER") + { + return new(true, variablesToRet: new[] { Intercom.Speaker is not null ? new[] { Intercom.Speaker } : Array.Empty() }); + } + + string ret = mode switch + { + "ISREADY" => (!Intercom.InUse && Intercom.RemainingCooldown <= 0).ToUpper(), + "INUSE" => Intercom.InUse.ToUpper(), + "COOLDOWNLEFT" => Intercom.RemainingCooldown.ToString(), + "TIMELEFT" => Intercom.SpeechRemainingTime.ToString(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From bb48f304090f1bfdc496163de878fd95ee92d67a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 14:44:48 +0200 Subject: [PATCH 081/359] remove item variables --- ScriptedEvents/Variables/IntercomVariables.cs | 81 ------------------- 1 file changed, 81 deletions(-) delete mode 100644 ScriptedEvents/Variables/IntercomVariables.cs diff --git a/ScriptedEvents/Variables/IntercomVariables.cs b/ScriptedEvents/Variables/IntercomVariables.cs deleted file mode 100644 index 7916f506..00000000 --- a/ScriptedEvents/Variables/IntercomVariables.cs +++ /dev/null @@ -1,81 +0,0 @@ -namespace ScriptedEvents.Variables.Intercom -{ - using System; -#pragma warning disable SA1402 // File may only contain a single type. - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Features; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class IntercomVariables : IVariableGroup - { - public string GroupName => "Intercom"; - - public IVariable[] Variables { get; } = new IVariable[] - { - new IntercomSpeaker(), - new GeneralIntercom(), - }; - } - - public class IntercomSpeaker : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{INTERCOMSPEAKER}"; - - /// - public string Description => "Gets the amount of players who are speaking on the intercom (always either 0 or 1)."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.Get(player => Intercom.Speaker == player); - } - - public class GeneralIntercom : IStringVariable, IArgumentVariable - { - /// - public string Name => "{INTERCOM}"; - - /// - public string Description => "All-in-one variable for Intercom related information."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("READY", "Is ready to detonate."), - new("COOLDOWN", "The cooldown remaining."), - new("TIMELEFT", "The time left for speaking."), - new("INUSE", "Is in use already.")), - }; - - /// - public string Value - { - get - { - string mode = (string)Arguments[0]; - - return mode.ToUpper() switch - { - "READY" => (!Intercom.InUse && Intercom.RemainingCooldown <= 0).ToString().ToUpper(), - "INUSE" => Intercom.InUse.ToString().ToUpper(), - "COOLDOWN" => Intercom.RemainingCooldown.ToString(), - "TIMELEFT" => Intercom.SpeechRemainingTime.ToString(), - _ => throw new ArgumentException("Invalid mode.", mode), - }; - } - } - } -#pragma warning restore SA1402 // File may only contain a single type. -} From 64b3873ac8e0d2289084f2930c7ea355b76378e3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 14:45:27 +0200 Subject: [PATCH 082/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index ab389e29..8b39fd71 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,6 +111,7 @@ + @@ -271,7 +272,6 @@ - @@ -331,7 +331,6 @@ - From 796efc077312dc213a8e5dc0e5522c6203a230ff Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 15:41:01 +0200 Subject: [PATCH 083/359] Create KillsAction.cs --- .../VariableMimics/Misc/KillsAction.cs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs new file mode 100644 index 00000000..1677b749 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs @@ -0,0 +1,67 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class KillsAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "KILLS"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Misc; + + /// + public string Description => "Returns the amount of kills, the amount of kills per-role or per-team."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("role", typeof(RoleTypeIdOrTeam), "The role or team to filter by. Optional.", false), + }; + + /// + public ActionResponse Execute(Script script) + { + if (Arguments.Length < 1) + return new(true, variablesToRet: new[] { MainPlugin.Handlers.Kills.Count.ToString() }); + + if (Arguments[0] is RoleTypeId rt) + { + if (MainPlugin.Handlers.Kills.TryGetValue(rt, out int amt)) + return new(true, variablesToRet: new[] { amt.ToString() }); + else + return new(true, variablesToRet: new[] { 0.ToString() }); + } + else if (Arguments[0] is Team team) + { + int total = 0; + foreach (var kills in MainPlugin.Handlers.Kills) + { + if (kills.Key.GetTeam() == team) + total += kills.Value; + } + + return new(true, variablesToRet: new[] { total.ToString() }); + } + + return new(false, "ARGPROC failed. Report this error to SE developers as soon as possible!"); + } + } +} \ No newline at end of file From f1a1ea829b1a8ae9a6d7663accfe5a7ec7f1a024 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 15:41:03 +0200 Subject: [PATCH 084/359] Delete KillsAndDeathsVariables.cs --- .../Variables/KillsAndDeathsVariables.cs | 93 ------------------- 1 file changed, 93 deletions(-) delete mode 100644 ScriptedEvents/Variables/KillsAndDeathsVariables.cs diff --git a/ScriptedEvents/Variables/KillsAndDeathsVariables.cs b/ScriptedEvents/Variables/KillsAndDeathsVariables.cs deleted file mode 100644 index 254d9840..00000000 --- a/ScriptedEvents/Variables/KillsAndDeathsVariables.cs +++ /dev/null @@ -1,93 +0,0 @@ -namespace ScriptedEvents.Variables.KillsAndDeaths -{ -#pragma warning disable SA1402 // File may only contain a single type - using System; - - using Exiled.API.Features; - - using PlayerRoles; - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Features; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class KillsAndDeathsVariables : IVariableGroup - { - /// - public string GroupName => "Kills & Deaths"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Kills(), - new ScpKills(), - }; - } - - public class Kills : IFloatVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{KILLS}"; - - /// - public string Description => "The amount of kills, the amount of kills per-role, or -1 if an invalid role type is provided."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Script Source { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("role", typeof(RoleTypeIdOrTeam), "The role or team to filter by. Optional.", false), - }; - - /// - public float Value - { - get - { - if (Arguments.Length < 1) - return MainPlugin.Handlers.Kills.Count; - - if (Arguments[0] is RoleTypeId rt) - { - if (MainPlugin.Handlers.Kills.TryGetValue(rt, out int amt)) - return amt; - else - return 0; - } - else if (Arguments[0] is Team team) - { - int total = 0; - foreach (var kills in MainPlugin.Handlers.Kills) - { - if (kills.Key.GetTeam() == team) - total += kills.Value; - } - - return total; - } - - throw new ArgumentException(ErrorGen.Get(ErrorCode.UnknownError)); - } - } - } - - public class ScpKills : IFloatVariable - { - /// - public string Name => "{SCPKILLS}"; - - /// - public string Description => "The amount of SCP-related kills."; - - /// - public float Value => Round.KillsByScp; - } -} From 8d65fab285947de97fee0c5a40bae2e6e2bb0c9a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 15:41:05 +0200 Subject: [PATCH 085/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 8b39fd71..96a8d232 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -161,6 +161,7 @@ + @@ -331,7 +332,6 @@ - From 9b60b4bceb3dfbdd51f1cc99ea7388e12aa285e9 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 23:43:54 +0200 Subject: [PATCH 086/359] Update PlayerInfoVariables.cs --- ScriptedEvents/Variables/PlayerInfoVariables.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Variables/PlayerInfoVariables.cs b/ScriptedEvents/Variables/PlayerInfoVariables.cs index 3e4be465..d258e79d 100644 --- a/ScriptedEvents/Variables/PlayerInfoVariables.cs +++ b/ScriptedEvents/Variables/PlayerInfoVariables.cs @@ -268,7 +268,7 @@ public string Value "TIER" when ply.Role is Scp079Role scp079role => scp079role.Level.ToString(), "TIER" => "NONE", "GROUP" => ply.GroupName, - "CUFFED" => ply.IsCuffed.ToUpper(), + "ISCUFFED" => ply.IsCuffed.ToUpper(), "CUSTOMINFO" or "CINFO" or "CUSTOMI" => ply.CustomInfo != string.Empty && ply.CustomInfo != null ? ply.CustomInfo : "NONE", "XSIZE" => ply.Scale.x.ToString(), "YSIZE" => ply.Scale.y.ToString(), From 438b67ce475dca42c621eb29d086871a3fea7ae3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 23:44:20 +0200 Subject: [PATCH 087/359] fix docs for AiO actions --- .../Actions/VariableMimics/AllInOne/IntercomInfoAction.cs | 3 +++ .../Actions/VariableMimics/AllInOne/LobbyInfoAction.cs | 4 ++++ .../Actions/VariableMimics/AllInOne/RoundInfoAction.cs | 4 ++++ .../Actions/VariableMimics/AllInOne/ServerInfoAction.cs | 4 ++++ ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs | 4 ++++ .../Actions/VariableMimics/AllInOne/WarheadInfoAction.cs | 4 ++++ .../Actions/VariableMimics/AllInOne/WaveInfoAction.cs | 4 ++++ 7 files changed, 27 insertions(+) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs index 188d4757..38f93d6b 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/IntercomInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class IntercomInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -26,8 +27,10 @@ public class IntercomInfoAction : IScriptAction, IHelpInfo, IMimicsVariableActio new("INUSE", "Returns a TRUE/FALSE value saying if intercom is in use already.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs index 58e84264..db04905f 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/LobbyInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class LobbyInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -16,6 +17,7 @@ public class LobbyInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting lobby related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -24,8 +26,10 @@ public class LobbyInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("ISLOCKED", "Returns a TRUE/FALSE value saying if the lobby is locked.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs index 34022cc6..d5e5c843 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class RoundInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -16,6 +17,7 @@ public class RoundInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting round related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -26,8 +28,10 @@ public class RoundInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("UPTIMEROUNDS", "Returns the amount of rounds that have progressed since the server has started.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs index 744de2c5..5530ba1a 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/ServerInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class ServerInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -16,6 +17,7 @@ public class ServerInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting server related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -26,8 +28,10 @@ public class ServerInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("TPS", "Returns the amount of ticks per second the server is running on.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs index 65f02b4f..ddfba3fb 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs @@ -7,6 +7,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -15,6 +16,7 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting time related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -32,8 +34,10 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("ROUNDSTART", "Returns the amount of time remaining before the round starts. -1 if round already started.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs index 354f4427..5cb33f3e 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WarheadInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -16,6 +17,7 @@ public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting warhead related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -26,8 +28,10 @@ public class WarheadInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("DETONATIONTIME", "Returns the amount of seconds remaining to the explosion.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs index 96dbeeb7..f2f57329 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/WaveInfoAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class WaveInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// @@ -16,6 +17,7 @@ public class WaveInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public string Description => "All-in-one action for getting wave related information."; + /// public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, @@ -30,8 +32,10 @@ public class WaveInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("RESPAWNEDPLAYERS", "Returns the players which have spawned with the last spawn wave.")), }; + /// public string[] RawArguments { get; set; } + /// public object[] Arguments { get; set; } /// From 9d1f0f8bed4c65410f6fdbee6cae9434ba1beec6 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 10 Sep 2024 23:46:48 +0200 Subject: [PATCH 088/359] style coppa --- ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs | 1 + .../Actions/VariableMimics/Math/Math_PowerAction.cs | 1 + .../Actions/VariableMimics/Math/Math_RandomAction.cs | 4 ++-- .../Actions/VariableMimics/Math/Math_RootAction.cs | 1 + .../Actions/VariableMimics/Math/Math_RoundAction.cs | 1 + ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs | 5 ++--- .../Actions/VariableMimics/PlayerFetch/EscapesAction.cs | 1 + .../Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs | 1 + .../Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs | 1 + .../Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs | 1 + .../Actions/VariableMimics/ScriptInfo/IsRunningAction.cs | 1 + .../Actions/VariableMimics/ScriptInfo/ThisAction.cs | 1 + .../Actions/VariableMimics/ScriptInfo/VExistsAction.cs | 1 + .../Actions/VariableMimics/Strings/StrCountAction.cs | 1 + .../Actions/VariableMimics/Strings/StrLowerAction.cs | 1 + .../Actions/VariableMimics/Strings/StrRemoveAction.cs | 1 + .../Actions/VariableMimics/Strings/StrReplaceAction.cs | 1 + .../Actions/VariableMimics/Strings/StrUpperAction.cs | 1 + 18 files changed, 20 insertions(+), 5 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs index 3f455699..7680703b 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_AbsAction.cs @@ -7,6 +7,7 @@ using ScriptedEvents.Structures; using UnityEngine; + /// public class Math_AbsAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs index 56aabc39..69c47bf3 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_PowerAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class Math_PowerAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs index 82ec8691..bf26fb92 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RandomAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class Math_RandomAction : IScriptAction, IHelpInfo, ILongDescription, IMimicsVariableAction { /// @@ -38,6 +39,7 @@ public class Math_RandomAction : IScriptAction, IHelpInfo, ILongDescription, IMi new Argument("endNumber", typeof(string), "An ending number of the random range.", true), }; + /// public string LongDescription => $@"The return value will be a random number from the provided range, depending on the numbers and the type. If 'type' is set to 'INT': @@ -48,8 +50,6 @@ public class Math_RandomAction : IScriptAction, IHelpInfo, ILongDescription, IMi > act PRINT My float is {{RANDOM:FLOAT:0:1}} > My float is 0.35227"; - public string WhatDoesActionReturn => "The random number generated."; - /// public ActionResponse Execute(Script script) { diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs index 4195cd2f..3e843591 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RootAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class Math_RootAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs index 3bd8b0d3..3baa0ab7 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.Structures; using UnityEngine; + /// public class Math_RoundAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs index 1677b749..794fa642 100644 --- a/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Misc/KillsAction.cs @@ -1,15 +1,14 @@ namespace ScriptedEvents.Actions { using System; - using System.Linq; - using Exiled.API.Features; using PlayerRoles; using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class KillsAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs index 06c214dd..2010689e 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/EscapesAction.cs @@ -10,6 +10,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class EscapesAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs index 8ef6a383..c40d8399 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs @@ -9,6 +9,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class RolePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs index 89eb51b2..ea719543 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs @@ -9,6 +9,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class TeamPlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs index 7d6ad9c6..9eea06e9 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs @@ -9,6 +9,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class ZonePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs index 675a56e9..0355898e 100644 --- a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/IsRunningAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class IsRunningAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs index d93fa664..a3616aef 100644 --- a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class ThisAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs index 8fec175c..dfbec578 100644 --- a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/VExistsAction.cs @@ -8,6 +8,7 @@ using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; + /// public class VExistsAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs index 0101c78d..01e30b70 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrCountAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class StrCountAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs index bd50950e..46387567 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrLowerAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class StrLowerAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs index f5db400e..7833d5c6 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrRemoveAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class StrRemoveAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs index 8e103ab9..772966f5 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrReplaceAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class StrReplaceAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// diff --git a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs index ae8928f0..cc6a4b92 100644 --- a/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Strings/StrUpperAction.cs @@ -6,6 +6,7 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; + /// public class StrUpperAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// From b23716e0ea516b6cf3eff44687c95b5247786bed Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 12:32:57 +0200 Subject: [PATCH 089/359] remove useless modes from TIME --- .../Actions/VariableMimics/AllInOne/TimeAction.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs index ddfba3fb..24f1dda3 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs @@ -28,10 +28,7 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction new("YEAR", "Returns the amount of years since the birth of Christ"), new("DAYOFWEEK", "Returns a number in range 1-7 (Warning! This follows the US system, where Sunday is the first day of the week)"), new("DAYOFMONTH", "Returns a number in range 0-31"), - new("DAYOFYEAR", "Returns a number in range 0-366"), - new("ROUNDMINUTES", "Returns the amount of elapsed round time, in minutes."), - new("ROUNDSECONDS", "Returns the amount of elapsed round time, in seconds."), - new("ROUNDSTART", "Returns the amount of time remaining before the round starts. -1 if round already started.")), + new("DAYOFYEAR", "Returns a number in range 0-366")), }; /// @@ -68,9 +65,6 @@ static string Format(object input) "DAYOFWEEK" => (((int)DateTime.Now.DayOfWeek) + 1).ToString(), "DAYOFMONTH" => DateTime.Now.Day.ToString(), "DAYOFYEAR" => DateTime.Now.DayOfYear.ToString(), - "ROUNDMINUTES" => ((float)Round.ElapsedTime.TotalMinutes).ToString(), - "ROUNDSECONDS" => ((float)Round.ElapsedTime.TotalSeconds).ToString(), - "ROUNDSTART" => Round.LobbyWaitingTime.ToString(), _ => throw new ArgumentException(), }; From 22d8bc2a477869d2cb7030e4460a8cf916c66c7b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 12:33:28 +0200 Subject: [PATCH 090/359] Update RoundInfoAction.cs --- .../VariableMimics/AllInOne/RoundInfoAction.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs index d5e5c843..5272c66c 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/RoundInfoAction.cs @@ -22,10 +22,11 @@ public class RoundInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { new OptionsArgument("mode", true, new("ISLOCKED", "Returns a TRUE/FALSE value being the roundlock status."), - new("ISSTARTED", "Returns a TRUE/FALSE value saying if the round has started."), + new("HASSTARTED", "Returns a TRUE/FALSE value saying if the round has started."), new("ISINPROGRESS", "Returns a TRUE/FALSE value saying if the round is in progress."), - new("ISENDED", "Returns a TRUE/FALSE value saying if the round has ended."), - new("UPTIMEROUNDS", "Returns the amount of rounds that have progressed since the server has started.")), + new("HASENDED", "Returns a TRUE/FALSE value saying if the round has ended."), + new("UPTIMEROUNDS", "Returns the amount of rounds that have progressed since the server has started."), + new("DURATION", "Returns the amount of seconds since the round started.")), }; /// @@ -45,11 +46,12 @@ public ActionResponse Execute(Script script) { string ret = Arguments[0].ToUpper() switch { - "LOCKED" => Round.IsLocked.ToUpper(), - "STARTED" => Round.IsStarted.ToUpper(), - "INPROGRESS" => Round.InProgress.ToUpper(), - "ENDED" => Round.IsEnded.ToUpper(), + "ISLOCKED" => Round.IsLocked.ToUpper(), + "HASSTARTED" => Round.IsStarted.ToUpper(), + "ISINPROGRESS" => Round.InProgress.ToUpper(), + "HASENDED" => Round.IsEnded.ToUpper(), "UPTIMEROUNDS" => Round.UptimeRounds.ToString(), + "DURATION" => Round.ElapsedTime.TotalSeconds.ToString(), _ => throw new ArgumentException() }; From 527bad08545fe0615a49059493793d07d19558a6 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:28:58 +0200 Subject: [PATCH 091/359] add MAPINFO action --- .../VariableMimics/AllInOne/MapInfoAction.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs new file mode 100644 index 00000000..d1251e76 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs @@ -0,0 +1,55 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class MapInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "MAPINFO"; + + /// + public string Description => "All-in-one action for getting map related information."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("SEED", "Returns the map seed."), + new("ISOVERCHARGED", "Returns a TRUE/FALSE value saying if the overcharge happened."), + new("ISDECONTAMINATED", "Returns a TRUE/FALSE value saying if the LightContainment is decontaminated."), + new("IS914ACTIVE", "Returns a TRUE/FALSE value saying if SCP-914 is currently active."), + new("ISCASSIESPEAKING", "Returns a TRUE/FALSE value saying if the cassie is currently speaking.")), + }; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string ret = Arguments[0].ToUpper() switch + { + "SEED" => Map.Seed.ToString(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 787d400febc51efa2783efd9c37830f2f8fe8117 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:29:26 +0200 Subject: [PATCH 092/359] TIMEINFO action --- .../AllInOne/{TimeAction.cs => TimeInfoAction.cs} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename ScriptedEvents/Actions/VariableMimics/AllInOne/{TimeAction.cs => TimeInfoAction.cs} (95%) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs similarity index 95% rename from ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs rename to ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs index 24f1dda3..17fd9495 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs @@ -11,7 +11,7 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "TIME"; + public string Name => "TIMEINFO"; /// public string Description => "All-in-one action for getting time related information."; @@ -20,7 +20,7 @@ public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction public Argument[] ExpectedArguments => new[] { new OptionsArgument("mode", true, - new("TICK", "Returns the amount of seconds since 1970."), + new("TICKS", "Returns the amount of seconds since 1970."), new("SECOND", "Returns a number in range 0-59"), new("MINUTE", "Returns a number in range 0-59"), new("HOUR", "Returns a number in range 0-23"), From 12d654bcaf9f33eeee2570aa55cf5db763592873 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:29:39 +0200 Subject: [PATCH 093/359] Update MainPlugin.cs --- ScriptedEvents/MainPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index 0ca44f2f..43d753b6 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -64,7 +64,7 @@ public class MainPlugin : Plugin new ConditionSamples(), }; - public static DateTime Epoch => new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + public static DateTime Epoch => new(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); public static List CustomCommands { get; } = new(); From efeed25f8f155da8dfb1608f2e1f5c14bc22f6df Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:29:50 +0200 Subject: [PATCH 094/359] Update MapVariables.cs --- ScriptedEvents/Variables/MapVariables.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index 2d63fd2e..21d0d7f1 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -167,7 +167,7 @@ public class Overcharged : IBoolVariable public string Description => "Indicates whether or not SCP-079 was successfully contained via overcharge sequence."; /// - public bool Value => Recontainer.IsContainmentSequenceSuccessful; + public bool Value => Recontainer.IsContainmentSequenceDone; } public class Generators : IFloatVariable, IArgumentVariable From 351c554fae89d115228d84cbb3035e64ceeefc5d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:29:51 +0200 Subject: [PATCH 095/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 96a8d232..f416adda 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -113,6 +113,7 @@ + From 778681a0b081d8cccec41b3c3d87902987ae7039 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:36:21 +0200 Subject: [PATCH 096/359] Create GeneratorInfoAction.cs --- .../AllInOne/GeneratorInfoAction.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/GeneratorInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/GeneratorInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/GeneratorInfoAction.cs new file mode 100644 index 00000000..9c730d17 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/GeneratorInfoAction.cs @@ -0,0 +1,61 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using Exiled.API.Enums; + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class GeneratorInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "GENERATORINFO"; + + /// + public string Description => "All-in-one action for getting generator related information."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("ENGAGED", "Returns the amount of engaged generators."), + new("ACTIVATING", "Returns the amount of activating generators."), + new("UNLOCKED", "Returns the amount of unlocked generators."), + new("OPENED", "Returns the amount of open generators."), + new("CLOSED", "Returns the amount of closed generators.")), + }; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + int ret = Arguments[0].ToUpper() switch + { + "ENGAGED" => Generator.Get(GeneratorState.Engaged).Count(), + "ACTIVATING" => Generator.Get(GeneratorState.Activating).Count(), + "UNLOCKED" => Generator.Get(GeneratorState.Unlocked).Count(), + "OPENED" => Generator.Get(GeneratorState.Open).Count(), + "CLOSED" => Generator.Get(gen => gen.IsOpen is false).Count(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret.ToString() }); + } + } +} \ No newline at end of file From ad8728fea74100ef2fd199f28638ab669c3b4bc2 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:36:24 +0200 Subject: [PATCH 097/359] Update TimeInfoAction.cs --- .../Actions/VariableMimics/AllInOne/TimeInfoAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs index 17fd9495..08633556 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/TimeInfoAction.cs @@ -8,7 +8,7 @@ using ScriptedEvents.Structures; /// - public class TimeAction : IScriptAction, IHelpInfo, IMimicsVariableAction + public class TimeInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// public string Name => "TIMEINFO"; From 6159f2d726b6898fd3d14cad8d00dc199539cdad Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:36:27 +0200 Subject: [PATCH 098/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index f416adda..0201ae70 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -111,12 +111,13 @@ + - + From 4bd1ccd392bdf5c4932852e242a445a3769a0c38 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:36:29 +0200 Subject: [PATCH 099/359] Update MapVariables.cs --- ScriptedEvents/Variables/MapVariables.cs | 109 +---------------------- 1 file changed, 4 insertions(+), 105 deletions(-) diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index 21d0d7f1..dc6d1a50 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -36,67 +36,6 @@ public class MapVariables : IVariableGroup }; } - public class Seed : IStringVariable - { - /// - public string Name => "{MAPSEED}"; - - /// - public string Description => "All-in-one variable for map related information."; - - /// - public string Value => Map.Seed.ToString(); - } - - public class CassieSpeaking : IBoolVariable - { - /// - public string Name => "{CASSIESPEAKING}"; - - /// - public string ReversedName => "{!CASSIESPEAKING}"; - - /// - public string Description => "Whether or not CASSIE is currently speaking."; - - /// - public bool Value => Cassie.IsSpeaking; - } - - public class InRoom : IFloatVariable, IArgumentVariable, IPlayerVariable - { - /// - public string Name => "{INROOM}"; - - /// - public string Description => "The amount of players in the specified room."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("roomType", typeof(RoomType), "The room to filter by.", false), - }; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - RoomType rt = (RoomType)Arguments[0]; - return Player.Get(plr => plr.CurrentRoom.Type == rt); - } - } - } - public class RandomDoor : IStringVariable, IArgumentVariable { /// @@ -140,36 +79,6 @@ public string Value } } - public class Decontaminated : IBoolVariable - { - /// - public string Name => "{DECONTAMINATED}"; - - /// - public string ReversedName => "{!DECONTAMINATED}"; - - /// - public string Description => "Whether or not Light Containment Zone has been decontaminated."; - - /// - public bool Value => Map.IsLczDecontaminated; - } - - public class Overcharged : IBoolVariable - { - /// - public string Name => "{OVERCHARGED}"; - - /// - public string ReversedName => "{!OVERCHARGED}"; - - /// - public string Description => "Indicates whether or not SCP-079 was successfully contained via overcharge sequence."; - - /// - public bool Value => Recontainer.IsContainmentSequenceDone; - } - public class Generators : IFloatVariable, IArgumentVariable { /// @@ -200,21 +109,11 @@ public float Value { get { - switch (Arguments[0].ToUpper()) + return Arguments[0].ToUpper() switch { - case "ENGAGED": - return Generator.Get(GeneratorState.Engaged).Count(); - case "ACTIVATING": - return Generator.Get(GeneratorState.Activating).Count(); - case "UNLOCKED": - return Generator.Get(GeneratorState.Unlocked).Count(); - case "OPENED": - return Generator.Get(GeneratorState.Open).Count(); - case "CLOSED": - return Generator.Get(gen => gen.IsOpen is false).Count(); - default: - throw new ScriptedEventsException($"Mode {Arguments[0]} is not ENGAGED/ACTIVATING/UNLOCKED/OPENED or CLOSED."); - } + + _ => throw new ScriptedEventsException($"Mode {Arguments[0]} is not ENGAGED/ACTIVATING/UNLOCKED/OPENED or CLOSED."), + }; } } } From d255e60e4384235d2aa7e5bf926506ce227615a0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:46:55 +0200 Subject: [PATCH 100/359] Update MapInfoAction.cs --- .../Actions/VariableMimics/AllInOne/MapInfoAction.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs index d1251e76..7ae3a9e8 100644 --- a/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/MapInfoAction.cs @@ -46,6 +46,10 @@ public ActionResponse Execute(Script script) string ret = Arguments[0].ToUpper() switch { "SEED" => Map.Seed.ToString(), + "ISOVERCHARGED" => Recontainer.IsContainmentSequenceDone.ToUpper(), + "ISDECONTAMINATED" => Map.IsLczDecontaminated.ToUpper(), + "IS914ACTIVE" => Scp914.IsWorking.ToUpper(), + "ISCASSIESPEAKING" => Cassie.IsSpeaking.ToUpper(), _ => throw new ArgumentException() }; From c5b5ed913bbbc76604bc6e1e61d2db016ccd05ca Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:46:59 +0200 Subject: [PATCH 101/359] Update MainPlugin.cs --- ScriptedEvents/MainPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/MainPlugin.cs b/ScriptedEvents/MainPlugin.cs index 43d753b6..67dc147b 100644 --- a/ScriptedEvents/MainPlugin.cs +++ b/ScriptedEvents/MainPlugin.cs @@ -77,7 +77,7 @@ public class MainPlugin : Plugin public override string Name => "ScriptedEvents"; /// - public override string Author => "Thunder and Elektryk_Andrzej"; + public override string Author => "Elektryk_Andrzej and Thunder"; /// public override Version Version => new(4, 0, 0); From 38fed3e5988eca90578117438caeec61934bea43 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:52:26 +0200 Subject: [PATCH 102/359] Create DoorStateAction.cs --- .../VariableMimics/Misc/DoorStateAction.cs | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs new file mode 100644 index 00000000..b06bb358 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs @@ -0,0 +1,50 @@ +namespace ScriptedEvents.Actions +{ + using System; + using Exiled.API.Enums; + using Exiled.API.Features.Doors; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class DoorStateAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "DOORSTATE"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Misc; + + /// + public string Description => "Returns the state of a door (either 'OPEN' or 'CLOSED')."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("door", typeof(DoorType), "The door to get the state of.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + DoorType dt = (DoorType)Arguments[0]; + Door d = Door.Get(dt); + + return d is null + ? throw new ArgumentException(ErrorGen.Get(ErrorCode.InvalidEnumGeneric, dt.ToString(), nameof(DoorType))) + : new(true, variablesToRet: new[] { (d.IsOpen ? "OPEN" : "CLOSED") }); + } + } +} \ No newline at end of file From d3c414dab0ff9a0336617a79db48d29be433cf71 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:52:29 +0200 Subject: [PATCH 103/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 0201ae70..2db89c37 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -163,6 +163,7 @@ + From 461b671ddc1a81576eedebcacd2ce4a92e0763d3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 11 Sep 2024 20:53:25 +0200 Subject: [PATCH 104/359] Update DoorStateAction.cs --- ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs index b06bb358..bb060d59 100644 --- a/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Misc/DoorStateAction.cs @@ -1,9 +1,10 @@ namespace ScriptedEvents.Actions { using System; + using Exiled.API.Enums; using Exiled.API.Features.Doors; - using PlayerRoles; + using ScriptedEvents.API.Enums; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; From e19124a3e8a0fc52cd8d2df090383fa8c09e6732 Mon Sep 17 00:00:00 2001 From: Thunder Date: Sat, 14 Sep 2024 14:45:38 -0400 Subject: [PATCH 105/359] Update README.md Pretty --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 81778423..19b25538 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ # ScriptedEvents SCP:SL Exiled plugin to create event "scripts". These scripts can be set up to run once per round, multiple times per round, or by command only. +![Repository analytics](https://repobeats.axiom.co/api/embed/1959377c83f76a4c53448880a81a55c09e6abe15.svg "Repobeats analytics image") + ## Getting Started Fair warning: This plugin is very complex and has a lot of features. However, once you understand it, the capabilities are close to endless. My best suggestion is to play around with the plugin, as that's the easiest way to learn it. Tips to get started include: * Read the documents that are generated when you first install the plugin and restart the server. Your console will tell you where they are located the first time (typically directly inside the Configs folder). From 252bc685bdc98bda5aef1e1220f7c6969a7c4c4a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:39:36 +0200 Subject: [PATCH 106/359] Create ItemInfoAction.cs --- .../VariableMimics/AllInOne/ItemInfoAction.cs | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/AllInOne/ItemInfoAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/AllInOne/ItemInfoAction.cs b/ScriptedEvents/Actions/VariableMimics/AllInOne/ItemInfoAction.cs new file mode 100644 index 00000000..0cff0836 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/AllInOne/ItemInfoAction.cs @@ -0,0 +1,86 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Features; + using Exiled.API.Features.Items; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class ItemInfoAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "ITEMINFO"; + + /// + public string Description => "All-in-one action for getting item related information from the provided item id."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("mode", true, + new("ISVALID", "Is provided item id a valid item."), + new("ISCARRIED", "Is item is in owner's inventory."), + new("SCALE", "Item's scale."), + new("WEIGHT", "Item's weight."), + new("OWNER", "Item's owner."), + new("TYPE", "Item's type.")), + new Argument("itemId", typeof(ushort), "The item id to use.", true), + }; + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public string[] Aliases => Array.Empty(); + + /// + public ActionSubgroup Subgroup => ActionSubgroup.AllInOneInfo; + + /// + public ActionResponse Execute(Script script) + { + string mode = Arguments[0].ToUpper(); + ushort id = (ushort)Arguments[1]; + + Item item = Item.Get(id); + + if (item is null) + { + if (mode == "ISVALID") + return new(true, variablesToRet: new[] { "FALSE" }); + + return new(false, $"Provided item ID '{id}' is not valid. Use the 'ISVALID' mode to verify the ID before accessing item info."); + } + + if (mode is "OWNER") + { + Player plr = item.Owner; + if (plr is null) + { + return new(true); + } + + return new(true, variablesToRet: new[] { plr }); + } + + string ret = mode switch + { + "TYPE" => item.Type.ToString(), + "ISVALID" => "TRUE", + "CARRIED" => item.IsInInventory.ToUpper(), + "SCALE" => item.Scale.ToUpper(), + "WEIGHT" => item.Weight.ToUpper(), + _ => throw new ArgumentException() + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 05274639096a2f8fc1556908811ec207346ba92f Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:40:37 +0200 Subject: [PATCH 107/359] Update Math_RoundAction.cs --- .../VariableMimics/Math/Math_RoundAction.cs | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs index 3baa0ab7..9979496c 100644 --- a/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Math/Math_RoundAction.cs @@ -32,29 +32,27 @@ public class Math_RoundAction : IScriptAction, IHelpInfo, IMimicsVariableAction /// public Argument[] ExpectedArguments => new[] { - new Argument("variable", typeof(float), "The variable to round. Requires the variable to be a number.", true), - new OptionsArgument("mode", false, new("UP"), new("DOWN"), new("NEAREST", "Default option")), + new OptionsArgument("mode", true, + new("UP"), + new("DOWN"), + new("NEAR")), + new Argument("value", typeof(float), "The number to round.", true), }; /// public ActionResponse Execute(Script script) { - float value = (float)Arguments[0]; - string result = "big fucky wucky"; + float value = (float)Arguments[1]; - switch (Arguments.Length < 2 ? "NEAREST" : Arguments[1].ToUpper()) + string res = Arguments[0].ToUpper() switch { - case "UP": - result = Mathf.Ceil(value).ToString(); break; + "UP" => Mathf.Ceil(value).ToString(), + "DOWN" => Mathf.Floor(value).ToString(), + "NEAR" => Mathf.Round(value).ToString(), + _ => throw new ArgumentException(), + }; - case "DOWN": - result = Mathf.Floor(value).ToString(); break; - - case "NEAREST": - result = Mathf.Round(value).ToString(); break; - } - - return new(true, variablesToRet: new[] { (object)result }); + return new(true, variablesToRet: new[] { res }); } } } \ No newline at end of file From ff726448becebeef0cf95c18b591c9ef74c644f7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:40:40 +0200 Subject: [PATCH 108/359] Create FilterAction.cs --- .../FilterAction.cs | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs new file mode 100644 index 00000000..f8844a69 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs @@ -0,0 +1,83 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using CustomPlayerEffects; + using Exiled.API.Enums; + using Exiled.API.Features; + using Exiled.CustomItems.API.Features; + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class FilterAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "LIMIT"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerVariableManipualtion; + + /// + public string Description => "Returns a copy of the provided players where players need to match specified criteria in order to get included in the output."; + + /// + public Argument[] ExpectedArguments => new[] + { + new OptionsArgument("type", true, + new("ROLE", "Filters by role. Use a 'RoleTypeId' type as the 'input' argument."), + new("TEAM", "Filters by team. Use a 'TeamType' type as the 'input' argument."), + new("ROOM", "Filters by room. Use a 'RoomType' type as the 'input' argument."), + new("USERID", "Filters by user id (like steam id). Use a specific user id as the 'input' argument."), + new("PLAYERID", "Filters by player id (id assigned in game). Use a specific player id as the 'input' argument."), + new("ITEM", "Filters by item in inventory. Use a 'ItemType' type as the 'input' argument."), + new("HELDITEM", "Filters by 'ItemType' in hand. Use a 'ItemType' type as the 'input' argument."), + new("GROUP", "Filters by group. Use a group name as the 'input' argument."), + new("ISSTAFF", "Filters by having RA access. Use a TRUE/FALSE value as the 'input' argument."), + new("EFFECT", "Filters by 'EffectType' the player has. Use a 'EffectType' type as the 'input' argument.")), + new Argument("players", typeof(PlayerCollection), "The players to filter.", true), + new Argument("input", typeof(string), "What to use as the filter (look at 'type' argument for guidance)", true), + }; + + /// + public ActionResponse Execute(Script script) + { + Player[] players = ((PlayerCollection)Arguments[0]).GetArray(); + string input = (string)Arguments[2]; + + IEnumerable ret = Arguments[0].ToUpper() switch + { + "ROLE" when SEParser.TryParse(input, out RoleTypeId rt, script, false) => players.Where(plr => plr.Role.Type == rt), + "TEAM" when SEParser.TryParse(input, out Team team, script, false) => players.Where(plr => plr.Role.Team == team), + "ROOM" when SEParser.TryParse(input, out RoomType room, script, false) => players.Where(plr => plr.CurrentRoom?.Type == room), + "USERID" => players.Where(plr => plr.UserId == input), + "PLAYERID" => players.Where(plr => plr.Id.ToString() == input), + "ITEM" when SEParser.TryParse(input, out ItemType item, script, false) => players.Where(plr => plr.Items.Any(i => i.Type == item)), + "ITEM" when CustomItem.TryGet(input, out CustomItem customItem) => players.Where(plr => plr.Items.Any(item => CustomItem.TryGet(item, out CustomItem customItem2) && customItem == customItem2)), + "HELDITEM" when SEParser.TryParse(input, out ItemType item, script, false) => players.Where(plr => plr.CurrentItem?.Type == item), + "HELDITEM" when CustomItem.TryGet(input, out CustomItem customItem) => players.Where(plr => CustomItem.TryGet(plr.CurrentItem, out CustomItem customItem2) && customItem == customItem2), + "GROUP" => players.Where(plr => plr.GroupName == input), + "ISSTAFF" => players.Where(plr => plr.RemoteAdminAccess == input.AsBool()), + "EFFECT" when SEParser.TryParse(input, out EffectType et, script, false) => players.Where(plr => plr.TryGetEffect(et, out StatusEffectBase seb)), + _ => throw new ArgumentException($"The provided value '{Arguments[1]}' is not a valid filter method, or the provided input '{input}' is not valid for the specified filter method."), + }; + + return new(true, variablesToRet: new[] { ret }); + } + } +} \ No newline at end of file From 6ee6336b188646a8da080e05d9b70ceb6a2fe899 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:40:43 +0200 Subject: [PATCH 109/359] Create LimitAction.cs --- .../PlayerVariableManipulation/LimitAction.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/LimitAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/LimitAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/LimitAction.cs new file mode 100644 index 00000000..ee847be3 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/LimitAction.cs @@ -0,0 +1,57 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + + using Exiled.API.Features; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class LimitAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "LIMIT"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerVariableManipualtion; + + /// + public string Description => "Returns a copy of the provided players in which the number of players is limited by the amount argument."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("players", typeof(PlayerCollection), "The players use.", true), + new Argument("amount", typeof(int), "The amount of players to limit.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + int max = (int)Arguments[1]; + List list = ((PlayerCollection)Arguments[0]).GetInnerList(); + + for (int i = 0; i < max; i++) + { + if (list.Count == 0) + break; + + list.PullRandomItem(); + } + + return new(true, variablesToRet: new[] { list.ToArray() }); + } + } +} \ No newline at end of file From 1cd3cd92981265fb662ad3bca1d83c436a6d0478 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:40:52 +0200 Subject: [PATCH 110/359] Update ActionSubgroup.cs --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index 6300c53d..7cf3305a 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -114,5 +114,10 @@ public enum ActionSubgroup /// Script info related action. /// ScriptInfo, + + /// + /// Action related to manipulating player variables. + /// + PlayerVariableManipualtion, } } From 4005614e3d175219f9c2109b0255b54f2d7db5bc Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:40:54 +0200 Subject: [PATCH 111/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 2db89c37..50c932a5 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -113,6 +113,7 @@ + @@ -169,6 +170,8 @@ + + From b4d6bcf2cf8e44affddf7414e1fd23e3cd47db4c Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:57:14 +0200 Subject: [PATCH 112/359] player action name consistency --- ScriptedEvents/Actions/RoundRule/DisablePlayerAction.cs | 2 +- ScriptedEvents/Actions/RoundRule/EnablePlayerAction.cs | 2 +- ScriptedEvents/Actions/Teleportation/TpPlayerAction.cs | 2 +- .../Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs | 2 +- .../Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs | 2 +- .../Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ScriptedEvents/Actions/RoundRule/DisablePlayerAction.cs b/ScriptedEvents/Actions/RoundRule/DisablePlayerAction.cs index f81cd6d4..925b9b05 100644 --- a/ScriptedEvents/Actions/RoundRule/DisablePlayerAction.cs +++ b/ScriptedEvents/Actions/RoundRule/DisablePlayerAction.cs @@ -14,7 +14,7 @@ public class DisablePlayerAction : IScriptAction, IHelpInfo, ILongDescription public string Name => "DISABLEPLAYER"; /// - public string[] Aliases => Array.Empty(); + public string[] Aliases => new[] { "DISABLEPLR" }; /// public string[] RawArguments { get; set; } diff --git a/ScriptedEvents/Actions/RoundRule/EnablePlayerAction.cs b/ScriptedEvents/Actions/RoundRule/EnablePlayerAction.cs index ffe43e28..20a606b0 100644 --- a/ScriptedEvents/Actions/RoundRule/EnablePlayerAction.cs +++ b/ScriptedEvents/Actions/RoundRule/EnablePlayerAction.cs @@ -17,7 +17,7 @@ public class EnablePlayerAction : IScriptAction, IHelpInfo, ILongDescription public string Name => "ENABLEPLAYER"; /// - public string[] Aliases => Array.Empty(); + public string[] Aliases => new[] { "ENABLEPLR" }; /// public string[] RawArguments { get; set; } diff --git a/ScriptedEvents/Actions/Teleportation/TpPlayerAction.cs b/ScriptedEvents/Actions/Teleportation/TpPlayerAction.cs index ce06c0bc..d91ff73b 100644 --- a/ScriptedEvents/Actions/Teleportation/TpPlayerAction.cs +++ b/ScriptedEvents/Actions/Teleportation/TpPlayerAction.cs @@ -15,7 +15,7 @@ public class TpPlayerAction : IScriptAction, IHelpInfo public string Name => "TPPLAYER"; /// - public string[] Aliases => Array.Empty(); + public string[] Aliases => new[] { "TPPLR" }; /// public string[] RawArguments { get; set; } diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs index c40d8399..619a3e92 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/RolePlayersAction.cs @@ -13,7 +13,7 @@ public class RolePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "ROLEPLAYERS"; + public string Name => "ROLEPLR"; /// public string[] Aliases => Array.Empty(); diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs index ea719543..002727ea 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/TeamPlayersAction.cs @@ -13,7 +13,7 @@ public class TeamPlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "TEAMPLAYERS"; + public string Name => "TEAMPLR"; /// public string[] Aliases => Array.Empty(); diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs index 9eea06e9..cc91ab20 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerFetch/ZonePlayersAction.cs @@ -13,7 +13,7 @@ public class ZonePlayersAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "ZONEPLAYERS"; + public string Name => "ZONEPLR"; /// public string[] Aliases => Array.Empty(); From 81c9c3813348d6ce51b17908ca82225d4a8d8d27 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:57:36 +0200 Subject: [PATCH 113/359] IEnumerable must be Player[] --- .../VariableMimics/PlayerVariableManipulation/FilterAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs index f8844a69..1db6a41d 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs @@ -77,7 +77,7 @@ public ActionResponse Execute(Script script) _ => throw new ArgumentException($"The provided value '{Arguments[1]}' is not a valid filter method, or the provided input '{input}' is not valid for the specified filter method."), }; - return new(true, variablesToRet: new[] { ret }); + return new(true, variablesToRet: new[] { ret.ToArray() }); } } } \ No newline at end of file From f90903dacf9b87277c2a4cc1dc737c585cb85596 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:57:43 +0200 Subject: [PATCH 114/359] add INDEXPLR action --- .../IndexPlayerAction.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/IndexPlayerAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/IndexPlayerAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/IndexPlayerAction.cs new file mode 100644 index 00000000..21547fe0 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/IndexPlayerAction.cs @@ -0,0 +1,55 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using Exiled.API.Features; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + using ScriptedEvents.Variables.Interfaces; + + /// + public class IndexPlayerAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "INDEXPLR"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.PlayerVariableManipualtion; + + /// + public string Description => "Returns a player inhabiting the specified index in the player variable."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("playervar", typeof(IPlayerVariable), "The name of the variable to index.", true), + new Argument("type", typeof(int), "The index from the player should be extracted.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + IEnumerable players = ((IPlayerVariable)Arguments[0]).Players; + int index = (int)Arguments[1]; + + if (index > players.Count() - 1) + throw new IndexOutOfRangeException(ErrorGen.Get(ErrorCode.IndexTooLarge, index)); + + return new(true, variablesToRet: new[] { new[] { players.ElementAt(index) } }); + } + } +} \ No newline at end of file From c9d5aa37a2f73aa6dc2ed08345d77d33b5cd501d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:57:54 +0200 Subject: [PATCH 115/359] small doc changes --- ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs b/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs index 1607bad9..bd8c4963 100644 --- a/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs +++ b/ScriptedEvents/API/APITestLab/ScriptedEventsIntegration.cs @@ -54,14 +54,13 @@ internal static class ScriptedEventsIntegration /// internal static List CustomActions { get; } = new(); -#pragma warning disable SA1629 // Documentation text should end with a period /// /// Registers a custom action. /// /// The name of the action. /// The action implementation. /// - /// Action implementation is Func>, where: + /// Action implementation is Func.>, where: /// /// Tuple - the action input, where: /// string[] - the input to the action. Usually represented by single word strings, BUT can also include multiple words in one string. @@ -70,10 +69,8 @@ internal static class ScriptedEventsIntegration /// Tuple - the action result, where: /// bool - did action execute without any errors. /// string - action response to the console when there was an error. - /// object[] - optional values to return from an action, only STRINGS or PLAYER ARRAYS, anything different will result in an ERROR. + /// object[] - optional values to return from an action, only STRINGS or PLAYER ARRAYS, anything different will result in an ERROR!!!!!!!!!!!! /// -#pragma warning restore SA1629 // Documentation text should end with a period - public static void RegisterCustomAction(string name, Func, Tuple> action) { try From 9b7a57334011152c56122b3fde8d19a7598032e3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 13:57:57 +0200 Subject: [PATCH 116/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 50c932a5..709e5629 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -171,6 +171,7 @@ + From 997fe7b6c84ce4523a23ca5bd56cabf00d3affa7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 14:21:32 +0200 Subject: [PATCH 117/359] Delete FilterVariables.cs --- ScriptedEvents/Variables/FilterVariables.cs | 198 -------------------- 1 file changed, 198 deletions(-) delete mode 100644 ScriptedEvents/Variables/FilterVariables.cs diff --git a/ScriptedEvents/Variables/FilterVariables.cs b/ScriptedEvents/Variables/FilterVariables.cs deleted file mode 100644 index bd2d8608..00000000 --- a/ScriptedEvents/Variables/FilterVariables.cs +++ /dev/null @@ -1,198 +0,0 @@ -namespace ScriptedEvents.Variables.Filters -{ -#pragma warning disable SA1402 // File may only contain a single type - using System; - using System.Collections.Generic; - using System.Linq; - - using CustomPlayerEffects; - using Exiled.API.Enums; - using Exiled.API.Features; - using Exiled.CustomItems.API.Features; - using PlayerRoles; - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Modules; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class FilterVariables : IVariableGroup - { - /// - public string GroupName => "Filters"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Max(), - new Filter(), - new GetByIndex(), - }; - } - - public class Max : IFloatVariable, IPlayerVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{LIMIT}"; - - /// - public string Description => "Creates a copy of a provided player variable, but does not copy more players than the limit provided."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("name", typeof(IPlayerVariable), "The name of the variable to select from.", true), - new Argument("amount", typeof(int), "The amount of players to select (default: 1)", false), - }; - - /// - public float Value => Players.Count(); - - /// - public Script Source { get; set; } - - /// - public IEnumerable Players - { - get - { - IEnumerable players = ((IPlayerVariable)Arguments[0]).Players; - - int max = 1; - - if (Arguments.Length > 1) - max = (int)Arguments[1]; - - List list = players.ToList(); - - for (int i = 0; i < max; i++) - { - if (list.Count == 0) - yield break; - - yield return list.PullRandomItem(); - } - } - } - } - - public class Filter : IFloatVariable, IPlayerVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{FILTER}"; - - /// - public string Description => "Filters a player variable by a certain type."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("name", typeof(IPlayerVariable), "The name of the variable to filter.", true), - new OptionsArgument("type", true, - new("ROLE", "Filter by 'RoleTypeId'."), - new("TEAM", "Filter by 'Team' type."), - new("ROOM", "Filter by 'Room' type."), - new("USERID", "Filter by user id. (steam id)"), - new("PLAYERID", "Filter by player id. (id in game)"), - new("ITEM", "Filter by 'ItemType' in inventory."), - new("HELDITEM", "Filter by 'ItemType' in hand."), - new("GROUP", "Filter by group."), - new("ISSTAFF", "Filter by having RA access."), - new("EFFECT", "Filter by 'EffectType'.")), - new Argument("input", typeof(string), "What to use as the filter (ROOM, TEAM, etc.)", true), - }; - - /// - public float Value => Players.Count(); - - /// - public Script Source { get; set; } - - /// - public IEnumerable Players - { - get - { - IEnumerable players = ((IPlayerVariable)Arguments[0]).Players; - string input = (string)Arguments[2]; - - return Arguments[1].ToString() switch - { - "ROLE" when SEParser.TryParse(input, out RoleTypeId rt, Source, false) => players.Where(plr => plr.Role.Type == rt), - "TEAM" when SEParser.TryParse(input, out Team team, Source, false) => players.Where(plr => plr.Role.Team == team), - "ROOM" when SEParser.TryParse(input, out RoomType room, Source, false) => players.Where(plr => plr.CurrentRoom?.Type == room), - "USERID" => players.Where(plr => plr.UserId == VariableSystemV2.ReplaceVariable(input, Source, false)), - "PLAYERID" => players.Where(plr => plr.Id.ToString() == VariableSystemV2.ReplaceVariable(input, Source, false)), - "ITEM" when SEParser.TryParse(input, out ItemType item, Source, false) => players.Where(plr => plr.Items.Any(i => i.Type == item)), - "ITEM" when CustomItem.TryGet(input, out CustomItem customItem) => players.Where(plr => plr.Items.Any(item => CustomItem.TryGet(item, out CustomItem customItem2) && customItem == customItem2)), - "HELDITEM" when SEParser.TryParse(input, out ItemType item, Source, false) => players.Where(plr => plr.CurrentItem?.Type == item), - "HELDITEM" when CustomItem.TryGet(input, out CustomItem customItem) => players.Where(plr => CustomItem.TryGet(plr.CurrentItem, out CustomItem customItem2) && customItem == customItem2), - "GROUP" => players.Where(plr => plr.GroupName == input), - "ISSTAFF" when VariableSystemV2.ReplaceVariable(input.ToUpper(), Source).AsBool(Source) => players.Where(plr => plr.RemoteAdminAccess), - "ISSTAFF" when !VariableSystemV2.ReplaceVariable(input.ToUpper(), Source).AsBool(Source) => players.Where(plr => !plr.RemoteAdminAccess), - "EFFECT" when SEParser.TryParse(input, out EffectType et, Source, false) => players.Where(plr => plr.TryGetEffect(et, out StatusEffectBase seb)), - _ => throw new ArgumentException($"The provided value '{Arguments[1]}' is not a valid filter method, or the provided input '{input}' is not valid for the specified filter method."), - }; - - throw new ArgumentException(ErrorGen.Get(ErrorCode.UnknownError)); - } - } - } - - public class GetByIndex : IFloatVariable, IPlayerVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{INDEXPLR}"; - - /// - public string Description => "Indexes a player variable and gets ONE player at the specified position."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("name", typeof(IPlayerVariable), "The name of the variable to index.", true), - new Argument("type", typeof(int), "The index. Number variables can be used (if they are decimal, the decimal portion will be removed)", true), - }; - - /// - public float Value => Players.Count(); - - /// - public Script Source { get; set; } - - /// - public IEnumerable Players - { - get - { - IEnumerable players = ((IPlayerVariable)Arguments[0]).Players; - int index = (int)Arguments[1]; - - if (index > players.Count() - 1) - throw new IndexOutOfRangeException(ErrorGen.Get(ErrorCode.IndexTooLarge, index)); - - return new List() { players.ToList()[index] }; // Todo: better solution (yield return didn't work??) - } - } - } -} -#pragma warning restore SA1402 // File may only contain a single type \ No newline at end of file From 0951f243e2bb305d3dd60694c56eddf8ce924c5c Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 14:21:35 +0200 Subject: [PATCH 118/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 709e5629..8eba53db 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -279,7 +279,6 @@ - From dcbb54ce52da0c97f672dc921b54cbfab2666066 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 15 Sep 2024 14:21:48 +0200 Subject: [PATCH 119/359] prepare variables for deletion --- ScriptedEvents/Variables/ItemVariables.cs | 2 +- ScriptedEvents/Variables/MapVariables.cs | 100 -------- .../Variables/PlayerInfoVariables.cs | 223 ------------------ 3 files changed, 1 insertion(+), 324 deletions(-) diff --git a/ScriptedEvents/Variables/ItemVariables.cs b/ScriptedEvents/Variables/ItemVariables.cs index 4b66a0a3..df48adb3 100644 --- a/ScriptedEvents/Variables/ItemVariables.cs +++ b/ScriptedEvents/Variables/ItemVariables.cs @@ -63,7 +63,7 @@ public class ShowItem : IStringVariable, IArgumentVariable /// public Argument[] ExpectedArguments => new[] { - new Argument("itemId", typeof(object), "The item id to use.", true), + new Argument("itemId", typeof(string), "The item id to use.", true), new OptionsArgument("mode", false, new("ISVALID", "Is provided item id a valid item."), new("CARRIED", "Is item is in owner's inventory."), diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs index dc6d1a50..ea4247d9 100644 --- a/ScriptedEvents/Variables/MapVariables.cs +++ b/ScriptedEvents/Variables/MapVariables.cs @@ -8,10 +8,6 @@ using Exiled.API.Enums; using Exiled.API.Features; using Exiled.API.Features.Doors; - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Features.Exceptions; using ScriptedEvents.Structures; using ScriptedEvents.Variables.Interfaces; @@ -23,16 +19,8 @@ public class MapVariables : IVariableGroup /// public IVariable[] Variables { get; } = new IVariable[] { - new Decontaminated(), - new Scp914Active(), - new DoorState(), - new Overcharged(), - new Generators(), new RandomRoom(), new RandomDoor(), - new InRoom(), - new CassieSpeaking(), - new Seed(), }; } @@ -79,45 +67,6 @@ public string Value } } - public class Generators : IFloatVariable, IArgumentVariable - { - /// - public string Name => "{GENERATORS}"; - - /// - public string Description => "Gets the number of generators fulfilling the requirements."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("ENGAGED"), - new("ACTIVATING"), - new("UNLOCKED"), - new("OPENED"), - new("CLOSED")), - }; - - /// - public float Value - { - get - { - return Arguments[0].ToUpper() switch - { - - _ => throw new ScriptedEventsException($"Mode {Arguments[0]} is not ENGAGED/ACTIVATING/UNLOCKED/OPENED or CLOSED."), - }; - } - } - } - public class RandomRoom : IStringVariable, IArgumentVariable { /// @@ -159,54 +108,5 @@ public string Value } } - public class Scp914Active : IBoolVariable - { - /// - public string Name => "{SCP914ACTIVE}"; - - /// - public string ReversedName => "{!SCP914ACTIVE}"; - - /// - public string Description => "Whether or not SCP-914 is currently active."; - - /// - public bool Value => Scp914.IsWorking; - } - - public class DoorState : IStringVariable, IArgumentVariable - { - /// - public string Name => "{DOORSTATE}"; - - /// - public string Description => "Reveals the state of a door (either 'OPEN' or 'CLOSED')."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("door", typeof(DoorType), "The door to get the state of.", true), - }; - - /// - public string Value - { - get - { - DoorType dt = (DoorType)Arguments[0]; - Door d = Door.Get(dt); - - return d is null - ? throw new ArgumentException(ErrorGen.Get(ErrorCode.InvalidEnumGeneric, dt.ToString(), nameof(DoorType))) - : (d.IsOpen ? "OPEN" : "CLOSED"); - } - } - } #pragma warning restore SA1402 // File may only contain a single type. } diff --git a/ScriptedEvents/Variables/PlayerInfoVariables.cs b/ScriptedEvents/Variables/PlayerInfoVariables.cs index d258e79d..d05965f2 100644 --- a/ScriptedEvents/Variables/PlayerInfoVariables.cs +++ b/ScriptedEvents/Variables/PlayerInfoVariables.cs @@ -2,18 +2,11 @@ { #pragma warning disable SA1402 // File may only contain a single type using System; - using System.Collections.Generic; using System.Linq; using Exiled.API.Features; - using Exiled.API.Features.Roles; - using Exiled.CustomItems.API.Features; - using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Features.Exceptions; - using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; using ScriptedEvents.Variables.Interfaces; @@ -25,62 +18,10 @@ public class PlayerInfoVariables : IVariableGroup /// public IVariable[] Variables { get; } = new IVariable[] { - new CommandVariable(), - new GetVariable(), new DisplayVariable(), - new GetPlayersByDataVariable(), }; } - public class GetPlayersByDataVariable : IFloatVariable, IPlayerVariable, IArgumentVariable - { - /// - public string Name => "{GETPLAYERSBYDATA}"; - - /// - public string Description => "Gets all players from a variable if their playerdata matches the required value."; - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("players", typeof(PlayerCollection), "The players variable from which the players will be fetched from.", true), - new Argument("key", typeof(string), "The key from which the value will be fetched and compared with the required value.", true), - new Argument("requiredValue", typeof(string), "The value that the player key must have in order to get included.", true), - }; - - /// - public IEnumerable Players - { - get - { - foreach (Player plr in ((PlayerCollection)Arguments[0]).GetInnerList()) - { - string key = (string)Arguments[1]; - - if (!plr.SessionVariables.TryGetValue(key, out object value)) - continue; - - if (value is not string valueString) - continue; - - if (valueString != (string)Arguments[2]) - continue; - - yield return plr; - } - } - } - - /// - public float Value => Players.Count(); - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - } - public class DisplayVariable : IStringVariable, IArgumentVariable { /// @@ -125,168 +66,4 @@ public string Value /// public object[] Arguments { get; set; } } - - public class CommandVariable : IStringVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{CMDVAR}"; - - /// - public string Description => "Converts a player variable into a format to use with commands."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("name", typeof(PlayerCollection), "The name of the player variable.", true), - }; - - /// - public Script Source { get; set; } - - /// - public string Value - { - get - { - PlayerCollection variable = (PlayerCollection)Arguments[0]; - - if (variable is IArgumentVariable) - { - throw new ArgumentException(ErrorGen.Get(ErrorCode.UnsupportedArgumentVariables, Name)); - } - - if (variable.Length == 0) - return string.Empty; - - return string.Join(".", variable.GetInnerList().Select(plr => plr.Id.ToString())); - } - } - } - - public class GetVariable : IStringVariable, IArgumentVariable, INeedSourceVariable, ILongDescription - { - /// - public string Name => "{GET}"; - - /// - public string Description => "Gets certain properties about the players in a player variable."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("name", typeof(PlayerCollection), "The player to get the info of.", true), - new SuggestedOptionsArgument("selector", false, - new("NAME", "Player's name"), - new("DPNAME", "Player's display name"), - new("UID", "Player's user id"), - new("PID", "Player's player id"), - new("ROLE", "Player's role"), - new("TEAM", "Player's team"), - new("ROOM", "Room where player is"), - new("ZONE", "Zone where player is"), - new("HP", "Player's health"), - new("ITEMCOUNT", "Amount of items in player's inventory"), - new("ITEMS", "Items in player's inventory"), - new("HELDITEM", "Item which player is holding"), - new("ISGOD", "Player's god status"), - new("POSX", "Player's X position"), - new("POSY", "Player's Y position"), - new("POSZ", "Player's Z position"), - new("TIER", "Player's tier as SCP079 (-1 if player is not SCP079)"), - new("GROUP", "Player's remote admin rank"), - new("ISCUFFED", "Is player cuffed"), - new("CUSTOMI", "Player's custom info"), - new("XSIZE", "Player's size on X axis"), - new("YSIZE", "Player's size on Y axis"), - new("ZSIZE", "Player's size on Z axis"), - new("KILLS", "Player's kills"), - new("EFFECTS", "Player's current effects"), - new("USINGNOCLIP", "Is player using noclip"), - new("CANNOCLIP", "Is player permitted to use noclip"), - new("STAMINA", "How full is players stamina"), - new("AHP", "Player's artificial hp")), - }; - - /// - public Script Source { get; set; } = null; - - /// - public string Value - { - get - { - string selector = "NAME"; - string varName = RawArguments[0]; - - if (Arguments.Length > 1) - selector = (string)Arguments[1]; - - PlayerCollection players = (PlayerCollection)Arguments[0]; - - if (players.Length > 1) - { - throw new ScriptedEventsException(ErrorGen.Generate(ErrorCode.ParameterError_TooManyPlayers, varName)); - } - else if (players.Length == 0) - { - throw new ScriptedEventsException(ErrorGen.Generate(ErrorCode.InvalidPlayerVariable, varName)); - } - - Player ply = players.FirstOrDefault(); - - return selector.ToUpper() switch - { - "NAME" => ply.Nickname, - "DISPLAYNAME" or "DPNAME" => ply.DisplayNickname, - "USERID" or "UID" => ply.UserId, - "PLAYERID" or "PID" => ply.Id.ToString(), - "ROLE" => ply.Role.Type.ToString(), - "TEAM" => ply.Role.Team.ToString(), - "ROOM" => ply.CurrentRoom.Type.ToString(), - "ZONE" => ply.Zone.ToString(), - "HP" or "HEALTH" => ply.Health.ToString(), - "ITEMCOUNT" => ply.Items.Count.ToString(), - "ITEMS" => ply.Items.Count > 0 ? string.Join("|", ply.Items.Select(item => CustomItem.TryGet(item, out CustomItem ci) ? ci.Name : item.Type.ToString())) : "NONE", - "HELDITEM" => (CustomItem.TryGet(ply.CurrentItem, out CustomItem ci) ? ci.Name : ply.CurrentItem?.Type.ToString()) ?? "NONE", - "GOD" => ply.IsGodModeEnabled.ToUpper(), - "POS" => $"{ply.Position.x} {ply.Position.y} {ply.Position.z}", - "POSX" => ply.Position.x.ToString(), - "POSY" => ply.Position.y.ToString(), - "POSZ" => ply.Position.z.ToString(), - "TIER" when ply.Role is Scp079Role scp079role => scp079role.Level.ToString(), - "TIER" => "NONE", - "GROUP" => ply.GroupName, - "ISCUFFED" => ply.IsCuffed.ToUpper(), - "CUSTOMINFO" or "CINFO" or "CUSTOMI" => ply.CustomInfo != string.Empty && ply.CustomInfo != null ? ply.CustomInfo : "NONE", - "XSIZE" => ply.Scale.x.ToString(), - "YSIZE" => ply.Scale.y.ToString(), - "ZSIZE" => ply.Scale.z.ToString(), - "KILLS" => MainPlugin.Handlers.PlayerKills.TryGetValue(ply, out int v) ? v.ToString() : "0", - "EFFECTS" when ply.ActiveEffects.Count() != 0 => string.Join(", ", ply.ActiveEffects.Select(eff => eff.name)), - "EFFECTS" => "NONE", - "USINGNOCLIP" => ply.Role is FpcRole role ? role.IsNoclipEnabled.ToUpper() : "FALSE", - "CANNOCLIP" => ply.IsNoclipPermitted.ToUpper(), - "STAMINA" => ply.Stamina.ToString(), - "ISSTAFF" => ply.RemoteAdminAccess.ToUpper(), - "AHP" => ply.ArtificialHealth.ToString(), - _ => ply.SessionVariables.ContainsKey(selector) ? ply.SessionVariables[selector].ToString() : "UNDEFINED" - }; - } - } - - /// - public string LongDescription => @"This variable is designed to only be used with a player variable containing one player."; - } } From 78871bb511275a657878a06ec09207c08c477f36 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:35:40 +0200 Subject: [PATCH 120/359] Delete ItemVariables.cs --- ScriptedEvents/Variables/ItemVariables.cs | 148 ---------------------- 1 file changed, 148 deletions(-) delete mode 100644 ScriptedEvents/Variables/ItemVariables.cs diff --git a/ScriptedEvents/Variables/ItemVariables.cs b/ScriptedEvents/Variables/ItemVariables.cs deleted file mode 100644 index df48adb3..00000000 --- a/ScriptedEvents/Variables/ItemVariables.cs +++ /dev/null @@ -1,148 +0,0 @@ -namespace ScriptedEvents.Variables.Chance -{ - using System; - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Features; - using Exiled.API.Features.Items; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Features.Exceptions; - using ScriptedEvents.Structures; -#pragma warning disable SA1402 // File may only contain a single type - using ScriptedEvents.Variables.Interfaces; - - public class ItemVariables : IVariableGroup - { - /// - public string GroupName => "Items"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new ShowItem(), - new ItemOwner(), - new RandomItem(), - }; - } - - public class RandomItem : IStringVariable - { - /// - public string Name => "{ITEM-RANDOM}"; - - /// - public string Description => "Gets the ItemType of a random item."; - - /// - public string Value - { - get - { - ItemType[] items = (ItemType[])Enum.GetValues(typeof(ItemType)); - return items[UnityEngine.Random.Range(0, items.Length)].ToString(); - } - } - } - - public class ShowItem : IStringVariable, IArgumentVariable - { - /// - public string Name => "{ITEM-INFO}"; - - /// - public string Description => "Returns more information about the item using the item id."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("itemId", typeof(string), "The item id to use.", true), - new OptionsArgument("mode", false, - new("ISVALID", "Is provided item id a valid item."), - new("CARRIED", "Is item is in owner's inventory."), - new("SCALE", "Item's scale."), - new("WEIGHT", "Item's weight."), - new("TYPE", "Item's type. Default option.")), - }; - - /// - public string Value - { - get - { - string mode = Arguments.Length > 1 ? Arguments[1].ToUpper() : "TYPE"; - string id = Arguments[0].ToString(); - - if (!ushort.TryParse(id, out ushort val)) - { - throw new ScriptedEventsException($"Provided value '{val}' is not a valid item id."); - } - - Item item = Item.Get(val); - - if (item is null) - { - if (mode == "ISVALID") return "FALSE"; - throw new ScriptedEventsException($"Provided value '{val}' is not a valid item id."); - } - - return mode switch - { - "TYPE" => item.Type.ToString(), - "ISVALID" => "TRUE", - "CARRIED" => item.IsInInventory.ToUpper(), - "SCALE" => item.Scale.ToUpper(), - "WEIGHT" => item.Weight.ToUpper(), - _ => throw new ArgumentException() - }; - } - } - } - - public class ItemOwner : IFloatVariable, IArgumentVariable, IPlayerVariable - { - /// - public string Name => "{ITEM-OWNER}"; - - /// - public string Description => "Returns the player which is the owner of the item."; - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("itemId", typeof(object), "The item id.", true), - }; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - string id = Arguments[0].ToString(); - - if (!ushort.TryParse(id, out ushort val)) - { - throw new ScriptedEventsException($"Provided value '{val}' is not a valid item id."); - } - - return new Player[] { Item.Get(val).Owner }; - } - } - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - } -} From 2c339500193bb1b66736d3c3d2891e222908e1ec Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:35:43 +0200 Subject: [PATCH 121/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 8eba53db..581e430b 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -173,6 +173,7 @@ + @@ -278,7 +279,6 @@ - From 7b00b3083e55a005cb8110f2495196f118e0361e Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:35:57 +0200 Subject: [PATCH 122/359] RandomEnums to ActionSubgroup enum --- ScriptedEvents/API/Enums/ActionSubgroup.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ScriptedEvents/API/Enums/ActionSubgroup.cs b/ScriptedEvents/API/Enums/ActionSubgroup.cs index 7cf3305a..95cbbd25 100644 --- a/ScriptedEvents/API/Enums/ActionSubgroup.cs +++ b/ScriptedEvents/API/Enums/ActionSubgroup.cs @@ -119,5 +119,10 @@ public enum ActionSubgroup /// Action related to manipulating player variables. /// PlayerVariableManipualtion, + + /// + /// Action related to retuning random Enum values. + /// + RandomEnums, } } From b7ccef112e4ec9eaead887f50a3d52e9d83a5db5 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:35:59 +0200 Subject: [PATCH 123/359] Create RandomItemAction.cs --- .../RandomEnums/RandomItemAction.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomItemAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomItemAction.cs b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomItemAction.cs new file mode 100644 index 00000000..d8dbadda --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomItemAction.cs @@ -0,0 +1,41 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using Exiled.API.Extensions; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class RandomItemAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "RANDOM-ITEM"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.RandomEnums; + + /// + public string Description => "Returns a random 'ItemType'."; + + /// + public Argument[] ExpectedArguments => Array.Empty(); + + /// + public ActionResponse Execute(Script script) + { + return new(true, variablesToRet: new[] { (Enum.GetValues(typeof(ItemType)) as ItemType[]).GetRandomValue().ToString() }); + } + } +} \ No newline at end of file From 1dba67ecc16b26d6aa991c1dabb5e1a6465017a0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:45:14 +0200 Subject: [PATCH 124/359] add RANDOM-ROOM action --- .../RandomEnums/RandomRoomAction.cs | 57 +++++++++++++++++++ ScriptedEvents/ScriptedEvents.csproj | 1 + 2 files changed, 58 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs new file mode 100644 index 00000000..233ee0c0 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs @@ -0,0 +1,57 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using Exiled.API.Enums; + using Exiled.API.Extensions; + using Exiled.API.Features; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class RandomRoomAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "RANDOM-ROOM"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.RandomEnums; + + /// + public string Description => "Returns a random 'RoomType'."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("zone", typeof(ZoneType), "A ZoneType to filter by (optional).", false), + }; + + /// + public ActionResponse Execute(Script script) + { + ZoneType filter = ZoneType.Unspecified; + + if (Arguments.Length > 0) + filter = (ZoneType)Arguments[0]; + + IEnumerable validRooms = Room.List.Where(room => room.Type != RoomType.Pocket); + + if (filter is not ZoneType.Unspecified) + validRooms = validRooms.Where(room => room.Zone.HasFlag(filter)); + + return new(true, variablesToRet: new[] { validRooms.GetRandomValue().ToString() }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 581e430b..7754a082 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -174,6 +174,7 @@ + From 379bddebaaa6de4e6e306e45a03544f2c5395462 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:56:15 +0200 Subject: [PATCH 125/359] Create RandomDoorAction.cs --- .../RandomEnums/RandomDoorAction.cs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomDoorAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomDoorAction.cs b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomDoorAction.cs new file mode 100644 index 00000000..8a8e04ac --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomDoorAction.cs @@ -0,0 +1,60 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using Exiled.API.Enums; + using Exiled.API.Extensions; + using Exiled.API.Features; + using Exiled.API.Features.Doors; + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class RandomDoorAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "RANDOM-DOOR"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.RandomEnums; + + /// + public string Description => "Returns a random 'DoorType'. Can be filtered by zone."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("zone", typeof(ZoneType), "A ZoneType to filter by (optional).", false), + }; + + /// + public ActionResponse Execute(Script script) + { + ZoneType filter = ZoneType.Unspecified; + + if (Arguments.Length > 0) + filter = (ZoneType)Arguments[0]; + + IEnumerable validDoors = Door.List; + + if (filter is not ZoneType.Unspecified) + { + validDoors = validDoors.Where(door => door.Zone.HasFlag(filter)); + } + + return new(true, variablesToRet: new[] { validDoors.GetRandomValue().Type.ToString() }); + } + } +} \ No newline at end of file From 36ed667d89b7dc1af5104e6329e406bb2c940086 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:56:17 +0200 Subject: [PATCH 126/359] Update RandomRoomAction.cs --- .../Actions/VariableMimics/RandomEnums/RandomRoomAction.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs index 233ee0c0..a09f3bab 100644 --- a/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/RandomEnums/RandomRoomAction.cs @@ -30,7 +30,7 @@ public class RandomRoomAction : IScriptAction, IHelpInfo, IMimicsVariableAction public ActionSubgroup Subgroup => ActionSubgroup.RandomEnums; /// - public string Description => "Returns a random 'RoomType'."; + public string Description => "Returns a random 'RoomType'. Can be filtered by zone."; /// public Argument[] ExpectedArguments => new[] @@ -51,7 +51,7 @@ public ActionResponse Execute(Script script) if (filter is not ZoneType.Unspecified) validRooms = validRooms.Where(room => room.Zone.HasFlag(filter)); - return new(true, variablesToRet: new[] { validRooms.GetRandomValue().ToString() }); + return new(true, variablesToRet: new[] { validRooms.GetRandomValue().Type.ToString() }); } } } \ No newline at end of file From d5af8cee24dde8006d60a8f5252292440ce75fdb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 21:56:20 +0200 Subject: [PATCH 127/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 7754a082..18de25fb 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -173,6 +173,7 @@ + From 46dc15b3c1ddd8a175b5aad25ee5004d73dcf577 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 16 Sep 2024 22:02:24 +0200 Subject: [PATCH 128/359] remove map variables --- ScriptedEvents/ScriptedEvents.csproj | 1 - ScriptedEvents/Variables/MapVariables.cs | 112 ----------------------- 2 files changed, 113 deletions(-) delete mode 100644 ScriptedEvents/Variables/MapVariables.cs diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 18de25fb..21a55d64 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -282,7 +282,6 @@ - diff --git a/ScriptedEvents/Variables/MapVariables.cs b/ScriptedEvents/Variables/MapVariables.cs deleted file mode 100644 index ea4247d9..00000000 --- a/ScriptedEvents/Variables/MapVariables.cs +++ /dev/null @@ -1,112 +0,0 @@ -namespace ScriptedEvents.Variables.Map -{ -#pragma warning disable SA1402 // File may only contain a single type. - using System; - using System.Collections.Generic; - using System.Linq; - - using Exiled.API.Enums; - using Exiled.API.Features; - using Exiled.API.Features.Doors; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class MapVariables : IVariableGroup - { - /// - public string GroupName => "Map"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new RandomRoom(), - new RandomDoor(), - }; - } - - public class RandomDoor : IStringVariable, IArgumentVariable - { - /// - public string Name => "{RANDOMDOOR}"; - - /// - public string Description => "Gets the DoorType of a random door. Can be filtered by zone."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("zone", typeof(ZoneType), "A zone to filter by (optional).", false), - }; - - /// - public string Value - { - get - { - ZoneType filter = ZoneType.Unspecified; - - if (Arguments.Length > 0) - filter = (ZoneType)Arguments[0]; - - IEnumerable validDoors = Door.List; - - if (filter is not ZoneType.Unspecified) - { - validDoors = validDoors.Where(door => door.Zone.HasFlag(filter)); - } - - List newList = validDoors.ToList(); - return newList[UnityEngine.Random.Range(0, newList.Count)].Type.ToString(); - } - } - } - - public class RandomRoom : IStringVariable, IArgumentVariable - { - /// - public string Name => "{RANDOMROOM}"; - - /// - public string Description => "Gets the RoomType of a random room. Can be filtered by zone."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("zone", typeof(ZoneType), "A zone to filter by (optional).", false), - }; - - /// - public string Value - { - get - { - ZoneType filter = ZoneType.Unspecified; - - if (Arguments.Length > 0) - filter = (ZoneType)Arguments[0]; - - IEnumerable validRooms = Room.List.Where(room => room.Type != RoomType.Pocket); - - if (filter is not ZoneType.Unspecified) - validRooms = validRooms.Where(room => room.Zone.HasFlag(filter)); - - List newList = validRooms.ToList(); - return newList[UnityEngine.Random.Range(0, newList.Count)].Type.ToString(); - } - } - } - -#pragma warning restore SA1402 // File may only contain a single type. -} From 749cf29eda112761a06b64fda700a8ff9cdf4290 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 25 Sep 2024 18:26:58 +0200 Subject: [PATCH 129/359] remove storage systems, better will come later --- .../API/Features/VariableStorage.cs | 100 ------------------ .../Actions/Variable/StorageAction.cs | 69 ------------ ScriptedEvents/Variables/MiscVariables.cs | 87 --------------- 3 files changed, 256 deletions(-) delete mode 100644 ScriptedEvents/API/Features/VariableStorage.cs delete mode 100644 ScriptedEvents/Actions/Variable/StorageAction.cs delete mode 100644 ScriptedEvents/Variables/MiscVariables.cs diff --git a/ScriptedEvents/API/Features/VariableStorage.cs b/ScriptedEvents/API/Features/VariableStorage.cs deleted file mode 100644 index 30a8aa29..00000000 --- a/ScriptedEvents/API/Features/VariableStorage.cs +++ /dev/null @@ -1,100 +0,0 @@ -namespace ScriptedEvents.API.Features -{ - using System; - using System.IO; - - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features.Exceptions; - using ScriptedEvents.Variables.Interfaces; - - /// - /// Class to save variables long-term. - /// - public static class VariableStorage - { - /// - /// Path to the variable storage folder. - /// - public static readonly string DirPath = Path.Combine(MainPlugin.BaseFilePath, MainPlugin.Configs.StorageFoldername); - - /// - /// Save variable to variable storage. - /// - /// The variable to save. - public static void Save(IConditionVariable var) - { - InternalSave(var.Name, var.String()); - } - - /// - /// Save variable to variable storage. - /// - /// The name of the variable. - /// The value of the variable. - public static void Save(string varName, string varValue) - { - InternalSave(varName, varValue); - } - - /// - /// Read from the variable storage. - /// - /// The variable name to read. - /// Variable value that has been saved before. - public static string Read(string varName) - { - try - { - varName = StripBrackets(varName); - using StreamReader reader = new(GetFilePath(varName)); - return reader.ReadLine(); - } - catch (FileNotFoundException) - { - Logger.Error($"Trying to read {varName} from storage, but it hasn't been saved in the storage folder."); - return "INVALID - VARIABLE DOESN'T EXIST"; - } - catch (Exception ex) - { - throw new Exception($"Error trying to read from storage: {ex}"); - } - } - - private static void InternalSave(string varName, string varValue) - { - try - { - varName = StripBrackets(varName); - if (!Directory.Exists(DirPath)) - { - Directory.CreateDirectory(DirPath); - Logger.Warn("Storage folder was absent; a new folder has been created."); - } - - string filePath = GetFilePath(varName); - - using StreamWriter writer = new(filePath, false, System.Text.Encoding.UTF8); - writer.WriteLine(varValue); - } - catch (UnauthorizedAccessException ex) - { - throw new ScriptedEventsException(ErrorGen.Get(ErrorCode.IOPermissionError) + $": {ex}"); - } - catch (Exception ex) - { - throw new ScriptedEventsException(ErrorGen.Get(ErrorCode.IOError) + $": {ex}"); - } - } - - private static string GetFilePath(string varName) => Path.Combine(DirPath, $"{varName}.txt"); - - private static string StripBrackets(string varName) - { - if (varName.Length >= 2 && varName[0] == '{' && varName[varName.Length - 1] == '}') - return varName.Substring(1, varName.Length - 2); - - return varName; - } - } -} diff --git a/ScriptedEvents/Actions/Variable/StorageAction.cs b/ScriptedEvents/Actions/Variable/StorageAction.cs deleted file mode 100644 index a732da46..00000000 --- a/ScriptedEvents/Actions/Variable/StorageAction.cs +++ /dev/null @@ -1,69 +0,0 @@ -namespace ScriptedEvents.Actions -{ - using System; - using System.Linq; - - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class StorageAction : IScriptAction, IHelpInfo - { - /// - public string Name => "STORE"; - - /// - public string[] Aliases => Array.Empty(); - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public ActionSubgroup Subgroup => ActionSubgroup.Variable; - - /// - public string Description => "Saves variables to long-term storage (.txt file) in the specified storage folder."; - - /// - public Argument[] ExpectedArguments => new[] - { - new OptionsArgument("mode", true, - new("LITERAL", "Saves the value as-is."), - new("PLAYER", "Saves player(s).")), - new Argument("variable", typeof(IVariable), "The variable to save.", true), - }; - - /// - public ActionResponse Execute(Script script) - { - string mode = ((string)Arguments[0]).ToUpper(); - - if (mode == "LITERAL") - { - if (!VariableSystemV2.TryGetVariable(RawArguments[1], script, out VariableResult var)) - return new(false, $"Invalid literal variable '{RawArguments[1]}' to store has been provided."); - - VariableStorage.Save(var.Variable); - } - - if (mode == "PLAYER") - { - string varName = RawArguments[1]; - - if (!VariableSystemV2.TryGetPlayers(varName, script, out PlayerCollection var)) - return new(false, "Invalid player variable to store has been provided."); - - string formattedVar = string.Join(".", var.ToList()); - VariableStorage.Save(varName, formattedVar); - } - - return new(true); - } - } -} diff --git a/ScriptedEvents/Variables/MiscVariables.cs b/ScriptedEvents/Variables/MiscVariables.cs deleted file mode 100644 index 613b29bc..00000000 --- a/ScriptedEvents/Variables/MiscVariables.cs +++ /dev/null @@ -1,87 +0,0 @@ -namespace ScriptedEvents.Variables.Misc -{ -#pragma warning disable SA1402 // File may only contain a single type - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class MiscVariables : IVariableGroup - { - /// - public string GroupName => "Miscellaneous"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new Storage(), - new Log(), - }; - } - - public class Log : IStringVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{LOG}"; - - /// - public string Description => "Shows the name of the variable with its value. Useful for quick debugging."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Script Source { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variable", typeof(IConditionVariable), "The variable.", true), - }; - - /// - public string Value - { - get - { - IConditionVariable variable = (IConditionVariable)Arguments[0]; - - return $"{variable.Name.Trim('{', '}')} = {variable.String()}"; - } - } - } - - public class Storage : IStringVariable, IArgumentVariable - { - /// - public string Name => "{STORAGE}"; - - /// - public string Description => "Retrives a variable from storage."; - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variableName", typeof(string), "The variable name to retrive.", true), - }; - - /// - public string Value - { - get - { - return VariableStorage.Read(RawArguments[0]); - } - } - } -#pragma warning restore SA1402 // File may only contain a single type. -} From e7a12d7abb391664d83e3a3797a5987db8a6389a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 25 Sep 2024 18:27:17 +0200 Subject: [PATCH 130/359] make display a action from variable --- .../Misc/DisplayPlayerAction.cs | 49 +++++++++++++ .../Variables/PlayerInfoVariables.cs | 69 ------------------- 2 files changed, 49 insertions(+), 69 deletions(-) create mode 100644 ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs delete mode 100644 ScriptedEvents/Variables/PlayerInfoVariables.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs new file mode 100644 index 00000000..c9358f5a --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs @@ -0,0 +1,49 @@ +namespace ScriptedEvents.Actions +{ + using System; + using System.Linq; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class DisplayPlayerAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "DISPLAYPLR"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Misc; + + /// + public string Description => "Returns a message where all provided players are formatted like 'playerName1, playerName2, etc'. Returns 'NONE' if player reference holds 0 players."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("players", typeof(PlayerCollection), "The players to display.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + PlayerCollection players = (PlayerCollection)Arguments[0]; + if (players.Length == 0) + { + return new(true, variablesToRet: new[] { "NONE" }); + } + + return new(true, variablesToRet: new[] { string.Join(", ", players.Select(p => p.Nickname)) }); + } + } +} \ No newline at end of file diff --git a/ScriptedEvents/Variables/PlayerInfoVariables.cs b/ScriptedEvents/Variables/PlayerInfoVariables.cs deleted file mode 100644 index d05965f2..00000000 --- a/ScriptedEvents/Variables/PlayerInfoVariables.cs +++ /dev/null @@ -1,69 +0,0 @@ -namespace ScriptedEvents.Variables.Strings -{ -#pragma warning disable SA1402 // File may only contain a single type - using System; - using System.Linq; - - using Exiled.API.Features; - - using ScriptedEvents.API.Extensions; - using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - - public class PlayerInfoVariables : IVariableGroup - { - /// - public string GroupName => "Player info"; - - /// - public IVariable[] Variables { get; } = new IVariable[] - { - new DisplayVariable(), - }; - } - - public class DisplayVariable : IStringVariable, IArgumentVariable - { - /// - public string Name => "{DISPLAY}"; - - /// - public string Description => "Displays players in a player variable."; - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("players", typeof(PlayerCollection), "The players to display.", true), - new OptionsArgument("mode", false, - new("NAME", "Display players' names. The default option"), - new("DPNAME", "Display players' display names.")), - }; - - /// - public string Value - { - get - { - PlayerCollection players = (PlayerCollection)Arguments[0]; - if (players.Length == 0) - { - return "NONE"; - } - - Func action = (Arguments.Length > 1 ? Arguments[1].ToUpper() : "NAME") switch - { - "NAME" => p => { return p.Nickname; }, - "DPNAME" => p => { return p.DisplayNickname; }, - _ => throw new ArgumentException(), - }; - return string.Join(", ", players.Select(action)); - } - } - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - } -} From 18087c0970505c96273569ba89a0511c8a0acfdb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 25 Sep 2024 18:27:27 +0200 Subject: [PATCH 131/359] fix filter action --- .../PlayerVariableManipulation/FilterAction.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs index 1db6a41d..0a12cbef 100644 --- a/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/PlayerVariableManipulation/FilterAction.cs @@ -19,7 +19,7 @@ public class FilterAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "LIMIT"; + public string Name => "FILTER"; /// public string[] Aliases => Array.Empty(); @@ -40,16 +40,16 @@ public class FilterAction : IScriptAction, IHelpInfo, IMimicsVariableAction public Argument[] ExpectedArguments => new[] { new OptionsArgument("type", true, - new("ROLE", "Filters by role. Use a 'RoleTypeId' type as the 'input' argument."), - new("TEAM", "Filters by team. Use a 'TeamType' type as the 'input' argument."), - new("ROOM", "Filters by room. Use a 'RoomType' type as the 'input' argument."), + new("ROLE", "Filters by role. Use a 'RoleTypeId' as the 'input' argument."), + new("TEAM", "Filters by team. Use a 'TeamType' as the 'input' argument."), + new("ROOM", "Filters by room. Use a 'RoomType' as the 'input' argument."), new("USERID", "Filters by user id (like steam id). Use a specific user id as the 'input' argument."), new("PLAYERID", "Filters by player id (id assigned in game). Use a specific player id as the 'input' argument."), - new("ITEM", "Filters by item in inventory. Use a 'ItemType' type as the 'input' argument."), - new("HELDITEM", "Filters by 'ItemType' in hand. Use a 'ItemType' type as the 'input' argument."), + new("ITEM", "Filters by item in inventory. Use a 'ItemType' as the 'input' argument."), + new("HELDITEM", "Filters by 'ItemType' in hand. Use a 'ItemType' as the 'input' argument."), new("GROUP", "Filters by group. Use a group name as the 'input' argument."), new("ISSTAFF", "Filters by having RA access. Use a TRUE/FALSE value as the 'input' argument."), - new("EFFECT", "Filters by 'EffectType' the player has. Use a 'EffectType' type as the 'input' argument.")), + new("EFFECT", "Filters by 'EffectType' the player has. Use a 'EffectType' as the 'input' argument.")), new Argument("players", typeof(PlayerCollection), "The players to filter.", true), new Argument("input", typeof(string), "What to use as the filter (look at 'type' argument for guidance)", true), }; From 60eb88bf582b7f9b1a70c664df1d063f7b375fe3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 25 Sep 2024 18:27:38 +0200 Subject: [PATCH 132/359] remove stored players var --- .../Variables/PlayerCountVariables.cs | 40 ------------------- 1 file changed, 40 deletions(-) diff --git a/ScriptedEvents/Variables/PlayerCountVariables.cs b/ScriptedEvents/Variables/PlayerCountVariables.cs index 502cf8d0..4d63e830 100644 --- a/ScriptedEvents/Variables/PlayerCountVariables.cs +++ b/ScriptedEvents/Variables/PlayerCountVariables.cs @@ -6,8 +6,6 @@ using Exiled.API.Features; using Exiled.API.Features.Roles; - using ScriptedEvents.API.Features; - using ScriptedEvents.Structures; using ScriptedEvents.Variables.Interfaces; public class PlayerCountVariables : IVariableGroup @@ -27,7 +25,6 @@ public class PlayerCountVariables : IVariableGroup new NonePlayer(), new Scp096Targets(), new Scp173Observers(), - new StoredPlayers(), }; } @@ -189,41 +186,4 @@ public IEnumerable Players } } } - - public class StoredPlayers : IPlayerVariable, IArgumentVariable, INeedSourceVariable - { - /// - public string Name => "{STOREDPLAYERS}"; - - /// - public string Description => "Retrieves the player variable from the variable storage."; - - /// - public IEnumerable Players - { - get - { - string playersAsString = VariableStorage.Read(RawArguments[0]); - List list = new(); - - if (SEParser.TryGetPlayers(playersAsString, null, out PlayerCollection collection, Source)) - { - return list; - } - - return collection.ToList(); - } - } - - public string[] RawArguments { get; set; } - - public object[] Arguments { get; set; } - - public Argument[] ExpectedArguments => new[] - { - new Argument("variable", typeof(string), "The variable name to retrieve players from.", true), - }; - - public Script Source { get; set; } - } } From 47716d8171575fb380efebb5e5632f80a2ffda8c Mon Sep 17 00:00:00 2001 From: andrzejki Date: Wed, 25 Sep 2024 18:27:41 +0200 Subject: [PATCH 133/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 21a55d64..26266db6 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -164,6 +164,7 @@ + @@ -189,7 +190,6 @@ - @@ -213,7 +213,6 @@ - @@ -339,9 +338,7 @@ - - From 4993f208ac7f584530ec795bfeb048a8e7cf1ea3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Sun, 29 Sep 2024 19:29:36 +0200 Subject: [PATCH 134/359] small update for V4 --- .../API/Extensions/InterfaceExtensions.cs | 13 +- .../API/Features/ArgumentProcessor.cs | 251 +++++----- .../API/Features/CoroutineHelper.cs | 3 - ScriptedEvents/API/Features/ErrorGen.cs | 27 +- ScriptedEvents/API/Features/ErrorGenV2.cs | 368 +++++++++++++++ ScriptedEvents/API/Features/Logger.cs | 2 +- ScriptedEvents/API/Features/MsgGen.cs | 5 +- ScriptedEvents/API/Features/SEParser.cs | 142 +++--- ScriptedEvents/API/Modules/ScriptModule.cs | 446 +++++++++++------- .../API/Modules/VariableSystemV2.cs | 169 +++---- .../DebugActions/DebugProcessorAction.cs | 2 - ScriptedEvents/Actions/Logic/CallAction.cs | 2 +- .../Actions/Logic/FastCallAction.cs | 2 +- ScriptedEvents/Actions/Logic/ReturnAction.cs | 3 +- ScriptedEvents/Actions/Misc/HelpAction.cs | 53 +-- ScriptedEvents/Actions/Server/ErrorAction.cs | 2 +- .../Actions/Variable/AddToAction.cs | 4 +- ScriptedEvents/Actions/Variable/BindAction.cs | 4 +- .../Actions/Variable/LocalSaveAction.cs | 2 +- ScriptedEvents/Script.cs | 2 +- ScriptedEvents/ScriptedEvents.csproj | 11 +- ScriptedEvents/Structures/VariableResult.cs | 13 +- .../Variables/CustomPlayerVariable.cs | 6 +- ScriptedEvents/Variables/CustomVariable.cs | 2 +- .../Variables/Interfaces/IArgumentVariable.cs | 25 - .../Variables/Interfaces/IBoolVariable.cs | 20 - .../Interfaces/IConditionVariable.cs | 9 - .../Variables/Interfaces/IFloatVariable.cs | 13 - .../Variables/Interfaces/IHasAliasVariable.cs | 13 - .../Variables/Interfaces/IItemVariable.cs | 13 - ...IStringVariable.cs => ILiteralVariable.cs} | 26 +- .../Variables/Interfaces/ILongVariable.cs | 13 - .../Interfaces/INeedSourceVariable.cs | 13 - .../Variables/PlayerCountVariables.cs | 127 +---- ScriptedEvents/Variables/RoleVariables.cs | 94 ++-- 35 files changed, 998 insertions(+), 902 deletions(-) create mode 100644 ScriptedEvents/API/Features/ErrorGenV2.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IArgumentVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IBoolVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IConditionVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IFloatVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IHasAliasVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/IItemVariable.cs rename ScriptedEvents/Variables/Interfaces/{IStringVariable.cs => ILiteralVariable.cs} (81%) delete mode 100644 ScriptedEvents/Variables/Interfaces/ILongVariable.cs delete mode 100644 ScriptedEvents/Variables/Interfaces/INeedSourceVariable.cs diff --git a/ScriptedEvents/API/Extensions/InterfaceExtensions.cs b/ScriptedEvents/API/Extensions/InterfaceExtensions.cs index f033a454..76980b53 100644 --- a/ScriptedEvents/API/Extensions/InterfaceExtensions.cs +++ b/ScriptedEvents/API/Extensions/InterfaceExtensions.cs @@ -9,20 +9,15 @@ public static class InterfaceExtensions { - public static string String(this IVariable variable, Script source = null, bool reversed = false) + public static string String(this IVariable variable, Script source = null) { try { switch (variable) { - case IBoolVariable @bool: - bool result = reversed ? !@bool.Value : @bool.Value; - return result.ToUpper(); - case IFloatVariable @float: - return @float.Value.ToString(); - case ILongVariable @long: - return @long.Value.ToString(); - case IStringVariable @string: + case IPlayerVariable player: + return variable.Name; + case ILiteralVariable @string: return @string.Value; default: // Shouldn't be possible throw new InvalidCastException($"{variable.Name} tried to cast to string, which resulted in an error."); diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index c14d0c00..7d78337e 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -6,7 +6,6 @@ using Exiled.API.Features; using Exiled.API.Features.Doors; - using Exiled.API.Features.Items; using PlayerRoles; using ScriptedEvents.API.Enums; @@ -30,128 +29,83 @@ public static class ArgumentProcessor /// The script source. /// If brackets are required to convert variables. /// The result of the process. - public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script source, bool requireBrackets = true) + public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script source) { - if (args is null) + void Log(string message) { - Logger.Debug("[ARGPROC] There are no raw arguments provided for this action. Ending processing.", source); - return new(true); + Logger.Debug($"[ArgumentProcessor] [Process] [{action.Name}] {message}", source); } - if (args.Length != 0) + if (args != null && args.Length > 0) { - Logger.Debug($"[ARGPROC] Arguments to process: {string.Join(", ", args)}", source); + Log($"Arguments to process: '{string.Join(", ", args)}'"); - ArgumentProcessResult processedForLoop = HandlePlayerListComprehension(args, source, out string[] strippedArgs); - if (!processedForLoop.Success) - { - Logger.Debug("[$FOR @ ARGPROC] '$FOR' action decorator parsing failed. Ending processing.", source); - return processedForLoop; - } - else + ArgumentProcessResult handledFORResult = HandleFORDecorator(args, source, out string[] strippedArgs); + if (!handledFORResult.Success) { - Logger.Debug("[$FOR @ ARGPROC] '$FOR' action decorator parsing success. Continuing processing.", source); + return handledFORResult; } args = strippedArgs; - int conditionSectionKeyword = args.IndexOf("$IF"); - if (conditionSectionKeyword != -1) - { - string[] conditionArgs = args.Skip(conditionSectionKeyword + 1).ToArray(); - args = args.Take(conditionSectionKeyword).ToArray(); - Logger.Debug($"[$IF @ ARGPROC] Evaluating condition: {string.Join(",", conditionArgs)}", source); - ConditionResponse resp = ConditionHelperV2.Evaluate(string.Join(" ", conditionArgs), source); - - if (!resp.Success) - { - Logger.Debug("[$IF @ ARGPROC] Evaluation resulted in an error. Ending processing.", source); - return new(false, true, string.Empty, resp.Message); - } - - if (!resp.Passed) - { - Logger.Debug("[$IF @ ARGPROC] Evaluation resulted in FALSE. Action shall not execute. Ending processing.", source); - return new(false); - } - else - { - Logger.Debug($"[$IF @ ARGPROC] Evaluation resulted in TRUE. Action shall execute like normal. Continuing parsing.", source); - } - } - else + ArgumentProcessResult handledIFResult = HandleIFDecorator(args, source, out string[] strippedArgs2); + if (!handledIFResult.Success) { - Logger.Debug($"[$IF @ ARGPROC] No '$IF' syntax was found. Continuing parsing.", source); + return handledIFResult; } + + args = strippedArgs2; + } + else + { + Log("No arguments were provided."); } if (expectedArguments is null || expectedArguments.Length == 0) { - Logger.Debug("[ARGPROC] There are no arguments for this action. Ending parsing.", source); + Log("This action doesnt use arguments. Ending processing."); return new(true); } - int required = expectedArguments.Count(arg => arg.Required); - - if (args.Length < required) + int requiredArguments = expectedArguments.Count(arg => arg.Required); + if (args.Length < requiredArguments) { IEnumerable args2 = expectedArguments.Select(arg => $"{(arg.Required ? "<" : "[")}{arg.ArgumentName}{(arg.Required ? ">" : "]")}"); - return new(false, true, string.Empty, ErrorGen.Get(ErrorCode.MissingArguments, action.Name, action is IAction ? "action" : "variable", required, string.Join(", ", args2))); + return new(false, true, string.Empty, ErrorGen.Get(ErrorCode.MissingArguments, action.Name, action is IAction ? "action" : "variable", requiredArguments, string.Join(", ", args2))); } - ArgumentProcessResult success = new(true); - - // raw args? aww hell nah :trollface: - List rawProcessedArgs = new(); - foreach (string arg in args) + ArgumentProcessResult success = new(true) { - if (TryProcessSmartArgument(arg, action, source, out string res, false)) - { - rawProcessedArgs.Add(res); - } - else - { - rawProcessedArgs.Add(arg); - } - } - - success.StrippedRawParameters = rawProcessedArgs.ToArray(); + StrippedRawParameters = args.ToArray(), + }; for (int i = 0; i < expectedArguments.Length; i++) { - Argument expect = expectedArguments[i]; - string input = string.Empty; + // break when we run out of args + if (args.Length <= i) break; - if (args.Length > i) - input = args[i]; - else - continue; + Argument argument = expectedArguments[i]; + string input = args[i]; - ArgumentProcessResult res = ProcessIndividualParameter(expect, input, action, source, requireBrackets); + ArgumentProcessResult res = ProcessIndividualParameter(argument, input, action, source); if (!res.Success) return res; // Throw issue to end-user success.NewParameters.AddRange(res.NewParameters); } - if (args.Length > expectedArguments.Length) - { - IEnumerable extraArgs = args.Skip(expectedArguments.Length); - foreach (string arg in extraArgs) - { - if (TryProcessSmartArgument(arg, action, source, out string saResult, true)) - { - success.NewParameters.Add(saResult); - } - else - { - success.NewParameters.Add(SEParser.ReplaceContaminatedValueSyntax(arg, source)); - } - - Logger.Debug("New parameters: " + string.Join(", ", success.NewParameters, source)); - } - } + success.NewParameters.AddRange(args + .Skip(expectedArguments.Length) + .Select( + arg => TryProcessSmartArgument( + arg.ToString(), + action, + source, + out string result, + true) + ? result + : arg)); - success.NewParameters.RemoveAll(o => o is string st && string.IsNullOrWhiteSpace(st)); + Log($"Processed action parameters: '{string.Join(", ", success.NewParameters.Select(x => x.ToString()))}'"); return success; } @@ -214,7 +168,13 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action string argument; try { - argument = source.SmartArguments[actualAction][lastNum - 1]; + var res = source.SmartArguments[actualAction][lastNum - 1](); + if (!res.Item1) + { + continue; + } + + argument = res.Item2; } catch (IndexOutOfRangeException) { @@ -256,11 +216,16 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action /// The action or variable performing the process. /// The script source. /// The output of the process. - public static ArgumentProcessResult ProcessIndividualParameter(Argument expected, string input, IScriptComponent action, Script source, bool requireBrackets = true) + public static ArgumentProcessResult ProcessIndividualParameter(Argument expected, string input, IScriptComponent action, Script source) { + void Log(string message) + { + Logger.Debug("[ArgumentProcessor] [PIP] " + message, source); + } + ArgumentProcessResult success = new(true); - source.DebugLog($"[C: {action.Name}] Param {expected.ArgumentName} needs a {expected.Type.Name}"); + Log($"Parameter '{expected.ArgumentName}' from '{action.Name}' needs a '{expected.Type.Name}'"); // Extra magic for options if (expected is OptionsArgument options) @@ -283,7 +248,7 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected } success.NewParameters.Add(input); - source?.DebugLog($"[OPTION ARG] [C: {action.Name}] Param {expected.ArgumentName} now has a processed value '{success.NewParameters.Last()}' and raw value '{input}'"); + Log($"[OPTION ARG] Parameter '{expected.ArgumentName}' now has a processed value '{success.NewParameters.Last()}' and raw value '{input}'"); return success; } @@ -303,19 +268,19 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected success.NewParameters.Add(result); break; case "Int32": // int - if (!SEParser.TryParse(input, out int intRes, source, requireBrackets)) + if (!SEParser.TryParse(input, out int intRes, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidInteger, input)); success.NewParameters.Add(intRes); break; case "Int64": // long - if (!SEParser.TryParse(input, out long longRes, source, requireBrackets)) + if (!SEParser.TryParse(input, out long longRes, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidInteger, input)); success.NewParameters.Add(longRes); break; case "Single": // float - if (!SEParser.TryParse(input, out float floatRes, source, requireBrackets)) + if (!SEParser.TryParse(input, out float floatRes, source)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidNumber, input)); success.NewParameters.Add(floatRes); @@ -327,23 +292,16 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected success.NewParameters.Add(charRes); break; - // Variable Interfaces - case "IConditionVariable": - if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable, requireBrackets)) - return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidVariable, input)); - - success.NewParameters.Add(variable.Variable); - break; case "IStringVariable": - if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable2, requireBrackets)) + if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable2)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidVariable, input)); - if (variable2.Variable is not IStringVariable strVar) + if (variable2.Variable is not ILiteralVariable strVar) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidStringVariable, input)); success.NewParameters.Add(strVar); break; case "IPlayerVariable": - if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable3, requireBrackets)) + if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable3)) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidVariable, input)); if (variable3.Variable is not IPlayerVariable playerVar) return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidPlayerVariable, input)); @@ -351,19 +309,6 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected success.NewParameters.Add(playerVar); break; - case "IItemVariable": - if (!VariableSystemV2.TryGetVariable(input, source, out VariableResult variable4, requireBrackets)) - return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidVariable, input)); - if (variable4.Variable is not IItemVariable itemVar) - - // TODO: ??? - return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidVariable, input)); - if (Item.Get(itemVar.Value) is null) - return new(false, true, expected.ArgumentName, "The provided item variable is not valid."); - - success.NewParameters.Add(itemVar); - break; - // Array Types: case "Room[]": if (!SEParser.TryGetRooms(input, out Room[] rooms, source)) @@ -386,14 +331,14 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected // Special case "PlayerCollection": - if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players, source, requireBrackets)) + if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players, source)) return new(false, true, expected.ArgumentName, players.Message); success.NewParameters.Add(players); break; case "Player": - if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players1, source, requireBrackets)) + if (!SEParser.TryGetPlayers(input, null, out PlayerCollection players1, source)) return new(false, true, expected.ArgumentName, players1.Message); if (players1.Length == 0) @@ -409,9 +354,9 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected break; case "RoleTypeIdOrTeam": - if (SEParser.TryParse(input, out RoleTypeId rtResult, source, requireBrackets)) + if (SEParser.TryParse(input, out RoleTypeId rtResult, source)) success.NewParameters.Add(rtResult); - else if (SEParser.TryParse(input, out Team teamResult, source, requireBrackets)) + else if (SEParser.TryParse(input, out Team teamResult, source)) success.NewParameters.Add(teamResult); else return new(false, true, expected.ArgumentName, ErrorGen.Get(ErrorCode.InvalidRoleTypeOrTeam, input)); @@ -430,29 +375,32 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected break; } - // Unsupported types: Parse variables in string and use that as a param (RawArguments are used for getting the raw string) - // TODO: ReplaceVariable works only when a "clean" variable is provided, meaning it doesnt work when provided things like ({PLAYERSALIVE}) - // so we need to fix that instead of calling ReplaceVariables all the time success.NewParameters.Add(SEParser.ReplaceContaminatedValueSyntax(input, source)); break; } - source?.DebugLog($"[C: {action.Name}] Param {expected.ArgumentName} has a processed value '{success.NewParameters.Last()}' and raw value '{input}'"); + Log($"Param '{expected.ArgumentName}' processed! STD value: '{success.NewParameters.Last()}' RAW value: '{input}'"); return success; } - private static ArgumentProcessResult HandlePlayerListComprehension(string[] inArgs, Script source, out string[] args) + private static ArgumentProcessResult HandleFORDecorator(string[] inArgs, Script source, out string[] args) { + void Log(string message) + { + Logger.Debug("[ArgumentProcessor] [$FOR] " + message, source); + } + args = inArgs; int loopSyntaxIndex = inArgs.IndexOf("$FOR"); if (loopSyntaxIndex == -1) { - Logger.Debug("$FOR: no syntax found.", source); return new(true); } + Log("Syntax found, continuing."); + string[] loopArgs = inArgs.Skip(loopSyntaxIndex + 1).ToArray(); args = inArgs.Take(loopSyntaxIndex).ToArray(); @@ -461,30 +409,29 @@ private static ArgumentProcessResult HandlePlayerListComprehension(string[] inAr string playerVarNameLoopingThrough = loopArgs[2]; if (inKeyword != "IN") - Logger.Warn($"$FOR: statement requires 'IN' keyword, provided '{inKeyword}'.", source); + Logger.Warn($"[$FOR DECORATOR] $FOR statement requires the 'IN' keyword (e.g. $FOR {{PLR}} IN {{PLAYERS}}). Instead of IN, '{inKeyword}' was provided.", source); List playersToLoop; if (source.PlayerLoopInfo is not null && source.PlayerLoopInfo.Line == source.CurrentLine) { playersToLoop = source.PlayerLoopInfo.PlayersToLoopThrough; - Logger.Debug("$FOR: first time init loop - copy player var", source); + Log("A loop for this action has already been initialized."); } else { if (!SEParser.TryGetPlayers(playerVarNameLoopingThrough, null, out PlayerCollection outPlayers, source)) { - Logger.Debug("$FOR: provided player variable to loop through is invalid", source); - return new(false, true, playerVarNameLoopingThrough, ErrorGen.Get(ErrorCode.InvalidPlayerVariable, playerVarNameLoopingThrough)); + return new(false, true, ErrorGenV2.InvalidPlayerVariable(playerVarNameLoopingThrough)); } playersToLoop = outPlayers.GetInnerList(); - Logger.Debug("$FOR: not first time init loop - use existing player var", source); + Log($"A loop for this action has not yet been initalized. Saved '{playerVarNameLoopingThrough}' as the players to loop through."); } if (playersToLoop.Count == 0) { - Logger.Debug("$FOR: players to loop through are 0, going to next action", source); + Log("No more players to loop through. Action will be skipped."); source.PlayerLoopInfo = null; return new(false); } @@ -500,5 +447,43 @@ private static ArgumentProcessResult HandlePlayerListComprehension(string[] inAr return new(true); } + + private static ArgumentProcessResult HandleIFDecorator(string[] inArgs, Script source, out string[] outArgs) + { + void Log(string message) + { + Logger.Debug("[ArgumentProcessor] [$IF] " + message, source); + } + + outArgs = inArgs; + + int conditionSectionKeyword = inArgs.IndexOf("$IF"); + if (conditionSectionKeyword == -1) + { + return new(true); + } + + Log($"Decorator was detected, continuing..."); + + string[] conditionArgs = inArgs.Skip(conditionSectionKeyword + 1).ToArray(); + outArgs = outArgs.Take(conditionSectionKeyword).ToArray(); + + ConditionResponse resp = ConditionHelperV2.Evaluate(string.Join(" ", conditionArgs), source); + + if (!resp.Success) + { + Log("Evaluation resulted in an error."); + return new(false, true, string.Empty, resp.Message); + } + + if (!resp.Passed) + { + Log("Evaluation resulted in FALSE. Action will be skipped."); + return new(false); + } + + Log($"Evaluation resulted in TRUE. Continuing..."); + return new(true); + } } } diff --git a/ScriptedEvents/API/Features/CoroutineHelper.cs b/ScriptedEvents/API/Features/CoroutineHelper.cs index b4f7ef58..a6578dcb 100644 --- a/ScriptedEvents/API/Features/CoroutineHelper.cs +++ b/ScriptedEvents/API/Features/CoroutineHelper.cs @@ -2,10 +2,7 @@ { using System.Collections.Generic; - using Exiled.API.Features; - using MEC; - using ScriptedEvents.Structures; public static class CoroutineHelper diff --git a/ScriptedEvents/API/Features/ErrorGen.cs b/ScriptedEvents/API/Features/ErrorGen.cs index 0125ad68..cc3cfb15 100644 --- a/ScriptedEvents/API/Features/ErrorGen.cs +++ b/ScriptedEvents/API/Features/ErrorGen.cs @@ -56,22 +56,6 @@ public static bool TryGetError(ErrorCode errorCode, out ErrorInfo errorInfo) return errorInfo.Id != 0; } - /// - /// Generates an error string given an error ID. - /// - /// Error ID. - /// Arguments for the error. - /// An error string. - public static string Generate(int errorID, params object[] arguments) - { - ErrorInfo err = GetError(errorID); - - if (err.Id == 0) - err = GetError(126); - - return string.Format(err.ToString(), arguments); - } - /// /// Generates an error string given an error code. /// @@ -88,15 +72,6 @@ public static string Generate(ErrorCode errorCode, params object[] arguments) return string.Format(err.ToString(), arguments); } - /// - /// Generates an error string given an error ID. - /// - /// Error ID. - /// Arguments for the error. - /// An error string. - [Obsolete("Use overload with enum.")] - public static string Get(int errorID, params object[] arguments) => Generate(errorID, arguments); - /// /// Generates an error string given an error code. /// @@ -116,7 +91,7 @@ internal static class ErrorList /// public static ReadOnlyCollection Errors { get; } = new List() { - new ErrorInfo( + new( 100, ErrorCode.AutoRun_Disabled, "The '{0}' script is set to run each round, but the script is disabled!", diff --git a/ScriptedEvents/API/Features/ErrorGenV2.cs b/ScriptedEvents/API/Features/ErrorGenV2.cs new file mode 100644 index 00000000..d4045b97 --- /dev/null +++ b/ScriptedEvents/API/Features/ErrorGenV2.cs @@ -0,0 +1,368 @@ +namespace ScriptedEvents.API.Features +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + using Exiled.API.Enums; + + using PlayerRoles; + using ScriptedEvents.API.Enums; + using ScriptedEvents.Structures; + + /// + /// Exposes API to generate consistent error messages throughout the entire plugin. + /// + public static class ErrorGenV2 + { + /// + /// Gets a from the given . + /// + /// Error code. + /// An object. Its will be 0 if the operation was unsuccessful. + public static ErrorInfo GetError(ErrorCode code) => + ErrorList.Errors.FirstOrDefault(err => err.Code == code); + + /// + /// Generates an error string given an error code. + /// + /// Error code. + /// Arguments for the error. + /// An error string. + public static string Generate(ErrorCode errorCode, params object[] arguments) + { + ErrorInfo err = GetError(errorCode); + + if (err.Id == 0) + err = GetError(ErrorCode.UnknownError); + + return string.Format(err.ToString(), arguments); + } + + public static string IOPermissionError() + { + return Generate(ErrorCode.IOPermissionError); + } + + public static string IOError() + { + return Generate(ErrorCode.IOError); + } + + public static string InvalidPlayerVariable(string varName) + { + return Generate(ErrorCode.InvalidPlayerVariable, varName); + } + } + + /// + /// Contains all error messages. + /// + internal static class ErrorListV2 + { + /// + /// Gets a list of all possible SE errors. + /// + public static ReadOnlyCollection Errors { get; } = new List() + { + new( + 100, + ErrorCode.AutoRun_Disabled, + "The '{0}' script is set to run each round, but the script is disabled!", + "This error occurs when a disabled script is set to run in the auto_run_scripts Exiled config. This error can be resolved by removing the script from the config option, or by enabling the script by removing its !-- DISABLED flag."), + + new ErrorInfo( + 101, + ErrorCode.AutoRun_NotFound, + "The '{0}' script is set to run each round, but the script is not found!", + "This error occurs when a script is specified to run automatically in the auto_run_scripts Exiled config, but the script cannot be found in the Scripted Events directory. This may either be due to a typo in the config, in the script name, or if the script doesn't exist. This error can be resolved by resolving any typos in the script name, by creating a script that doesn't exist, or by deleting a non-existent script from the config option."), + + new ErrorInfo( + 102, + ErrorCode.InvalidAction, + "Invalid action '{0}' detected in script '{1}'.", + "This error occurs when a script is read, and the script reader finds one or more invalid actions in the script. This error can be resolved by checking for typos in the name of the action."), + + new ErrorInfo( + 103, + ErrorCode.MultipleFlagDefs, + "Multiple definitions for the '{0}' flag detected in script {1}.", + "This error occurs when a script has multiple flag declarations (!-- [FLAG]) for the same flag. This error can be resolved by simply removing multiple declarations of the same flag -- these declarations are only necessary once per script."), + + new ErrorInfo( + 104, + ErrorCode.MultipleLabelDefs, + "Multiple definitions for the '{0}' label detected in script {1}.", + "This error occurs when a script has multiple labels (LABELNAME:) with the same name. This error can be resolved by renaming labels so that each label has a unique name."), + + new ErrorInfo( + 105, + ErrorCode.AutoRun_AdminEvent, + "The '{0}' script is set to run each round, but the script is marked as an admin event!", + "This error occurs when a script is specified to run automatically in the auto_run_scripts Exiled config, but the script is marked as an admin event via the !-- ADMINEVENT flag. Admin event scripts are not meant to be run automatically. This error can be resolved by removing the script from the auto_run_scripts config, or removing the !-- ADMINEVENT flag from the script."), + + new ErrorInfo( + 106, + ErrorCode.IOPermissionError, + "Unable to create the required ScriptedEvents directories due to a permission error. Please ensure that ScriptedEvents has proper system permissions to Exiled's Config folder.", + "This error occurs when Scripted Events is unable to initialize the required directory due to an unauthorized permission error (likely due to the PC or server machine's own antivirus software). This error can be resolved by adjusting the system's settings to allow Scripted Events to make directory changes, or creating the directories manually."), + + new ErrorInfo( + 107, + ErrorCode.IOError, + "Unable to load ScriptedEvents due to a directory error.", + "This error occurs when Scripted Events is unable to initialize the required directory due to any non-permission error. Please report this error in the Scripted Events Discord server."), + + new ErrorInfo( + 108, + ErrorCode.On_UnknownEvent, + "The specified event '{0}' in the 'On' config was not found!", + "This error occurs when an invalid event name is provided in the on Exiled config. This error can be resolved by checking for typos in the name of events and referencing Exiled's list of provided events."), + + new ErrorInfo( + 109, + ErrorCode.On_IncompatibleEvent, + "The '{0}' event is not currently compatible with the On config.", + "This error occurs when an unsupported event is present in the on Exiled config. Unfortunately, there isn't much of a solution here at the moment. Due to how the system works, events must have an event argument in order to be usable with the on config. 99% of Exiled's events DO have an event argument, but very few of them do not. These are the unsupported events.\r\n\r\nMaybe this error will be forever gone in the future!"), + + new ErrorInfo( + 110, + ErrorCode.On_DisabledScript, + "Error in 'On' handler (event: {0}): Script '{1}' is disabled!", + "This error occurs when a disabled script is present in the on Exiled config. This error can be resolved by removing the script from the config option, or by enabling the script by removing its !-- DISABLED flag."), + + new ErrorInfo( + 111, + ErrorCode.On_NotFoundScript, + "Error in 'On' handler (event: {0}): Script '{1}' cannot be found!", + "This error occurs when a script is present in the on Exiled config that is not present in the Scripted Events directory. This may either be due to a typo in the config, in the script name, or if the script doesn't exist. This error can be resolved by resolving any typos in the script name, by creating a script that doesn't exist, or by deleting a non-existent script from the config option."), + + new ErrorInfo( + 112, + ErrorCode.On_UnknownError, + "Error in 'On' handler (event: {0})", + "This error occurs when Scripted Events is unable to handle the 'on' config correctly due to an error. Please report this error in the Scripted Events Discord server."), + + new ErrorInfo( + 113, + ErrorCode.LEGACY_SafetyError, + "Script '{0}' exceeded safety limit of {1} actions per 1 second and has been force-stopped, saving from a potential crash. If this is intentional, add '!-- NOSAFETY' to the top of the script. All script loops should have a delay in them.", + "This error occurs when a script executes more actions in 1 second than what is allowed in the Exiled configs, per the max_actions_per_second configuration. This is likely an indicator that the script is trying to do too much at one time, and could be due to a loop without a yield. This error can be resolved by performing less actions per second, and adding delays (such as WAITSEC) where they wont cause issues. Additionally, the max_actions_per_second config can be raised, allowing more actions to occur per-second. Lastly, as a last-case resort, adding the !-- NOSAFETY flag to the top of a script disables this warning for that individual script."), + + new ErrorInfo( + 114, + ErrorCode.IOHelpPermissionError, + "Unable to create the help file, the plugin does not have permission to access the ScriptedEvents directory!", + "This error occurs when the HELP action is executed, however, ScriptedEvents is unable to create the documentation file due to an unauthorized permission error (likely due to the PC or server machine's own antivirus software). This error can be resolved by adjusting the system's settings to allow Scripted Events to write files, or by using the NOFILE argument in the HELP action."), + new ErrorInfo( + 115, + ErrorCode.IOHelpError, + "Error when writing to file.", + "This error occurs when the HELP action is executed, however, ScriptedEvents is unable to create the documentation file due to any non-permission error. Please report this error in the Scripted Events Discord server."), + new ErrorInfo( + 116, + ErrorCode.InvalidActionUsage, + "Invalid '{0}' action usage. Usage: {1}", + "This error occurs when an action is executed without the proper arguments. This error can be resolved by executing the action with the proper arguments, as specified in the error message.\r\n\r\n"), + + new ErrorInfo( + 117, + ErrorCode.LEGACY_InvalidActionUsage, + "Invalid '{0}' action usage.", + "This error occurs when an action is executed without the proper arguments. This error can be resolved by executing the action with the proper arguments. This error is obsolete and has been replaced with SE-116."), + + new ErrorInfo( + 118, + ErrorCode.ParameterError_Option, + "Invalid option {0} provided for the '{1}' parameter of the {2} action. This parameter expects one of the following options: {3}.", + "This error occurs when an action is executed successfully, however one of its parameters received a string value that it was not expecting. This error can be resolved by replacing the specified parameter with one of the specified options."), + + new ErrorInfo( + 119, + ErrorCode.ParameterError_Number, + "Invalid number '{0}' provided for the '{1}' parameter of the {2} action.", + "This error occurs when an action is executed successfully. However, a numerical parameter received a non-numerical value. This error can be resolved by replacing the value of the specified parameter with a numerical value."), + + new ErrorInfo( + 120, + ErrorCode.ParameterError_Condition, + "Invalid {0} condition provided in the {1} action! Condition: {2} Error type: '{3}' Message: '{4}'.", + "This error occurs when an action is executed successfully. However, a numerical parameter received a value that cannot be evaluated as numerical. This error can be resolved by replacing the specified parameter with a valid numerical value, or a valid mathematical formula."), + + new ErrorInfo( + 121, + ErrorCode.ParameterError_LessThanZeroNumber, + "Negative number '{0}' cannot be used in the '{1}' parameter of the {2} action.", + "This error occurs when an action is executed successfully. However, a numerical parameter received a less-than-zero value, which is invalid for the specified action. This error can be resolved by ensuring that the result of the numerical expression does not equal a less-than-zero value.\r\n\r\n"), + + new ErrorInfo( + 122, + ErrorCode.ParameterError_RoleType, + "Invalid {0} provided in the {1} action. '{2}' is not a valid RoleType.", + $"This error occurs when an action is executed successfully. However, a role parameter received an invalid role type. This error can be resolved by ensuring that the value of the parameter matches an internal RoleType value. A full list of valid RoleTypes (as of {DateTime.Now:g}) follows:\n{string.Join("\n", ((RoleTypeId[])Enum.GetValues(typeof(RoleTypeId))).Where(r => r is not RoleTypeId.None).Select(r => $"- [{r:d}] {r}"))}"), + + new ErrorInfo( + 123, + ErrorCode.ParameterError_Players, + "No players were found matching the given criteria ('{0}' parameter).", + "This error occurs when an action is executed successfully. However, no players were found matching the given variables. This error can be resolved by ensuring that there is at least one player match when running a script."), + + new ErrorInfo( + 124, + ErrorCode.ParameterError_Rooms, + "No rooms were found matching the given criteria '{0}' ('{1}' parameter).", + $"This error occurs when an action is executed successfully. However, no rooms were found matching the given names or IDs. This error can be resolved by ensuring that there are no typos in the name or ID of rooms. A full list of valid Room IDs (as of {DateTime.Now:g}) follows:\n{string.Join("\n", ((RoomType[])Enum.GetValues(typeof(RoomType))).Where(r => r is not RoomType.Unknown).Select(r => $"- [{r:d}] {r}"))}"), + + new ErrorInfo( + 125, + ErrorCode.ParameterError_CassieNoAnnc, + "Cannot show captions without a corresponding CASSIE announcement.", + "This error occurs when using the CASSIE and SILENTCASSIE actions, if a CASSIE caption is provided but no message is provided. This error can be resolved by ensuring that the 'message' portion of the text parameter is always provided."), + + new ErrorInfo( + 126, + ErrorCode.UnknownError, + "Unknown error", + "This error can occur if there is an action failure without a valid message. Please report this error in the Scripted Events Discord server."), + + new ErrorInfo( + 127, + ErrorCode.IOMissing, + "Critical error: Missing script path. Please reload plugin.", + "This error occurs when the Scripted Events directory is deleted while the plugin is running. Reloading the plugin usually fixes this issue."), + + new ErrorInfo( + 128, + ErrorCode.CustomCommand_NoName, + "Custom command is defined without a name.", + "This error occurs when there is a command specified in the commands Exiled config, but its name parameter is blank. This error can be resolved by simply providing a name to the command, or by removing the unfinished command structure from the config."), + + new ErrorInfo( + 129, + ErrorCode.CustomCommand_NoScripts, + "Custom command '{0}' ({1}) will not be created because it is set to run zero scripts.", + "This error occurs when there is a command specified in the commands Exiled config, but its run parameter is non-existent or empty. Custom commands must have at least one script set to run in order for the command to be created. As such, this error can be resolved by adding a script to run when the command is executed, or by removing the unfinished command structure from the config."), + + new ErrorInfo( + 130, + ErrorCode.MissingArguments, + "The '{0}' {1} requires {2} argument(s) ({3})", + "This error occurs when an action or variable is used with an insufficient amount of arguments. Most actions require arguments, separated by spaces, such as 'LOG TEST'. Likewise, some variables require arguments, separated by :, such as '{FILTER:PLAYERS:ROLE:ClassD}'. This error can be resolved by supplying the proper amount of arguments."), + + new ErrorInfo( + 131, + ErrorCode.LEGACY_InvalidPlayerVariable, + "The provided value '{0}' is not a valid variable or has no associated players.", + "This error occurs when a variable requires another player variable as an argument, but that other variable is not a valid variable. This error will also occur if the variable is valid, but is not a variable that contains players. This error can be resolved by providing a valid variable that contains players."), + + new ErrorInfo( + 132, + ErrorCode.InvalidVariable, + "The provided value '{0}' is not a valid variable.", + "This error occurs when a variable requires another variable as an argument, but that other variable is not a valid variable. This error can be resolved by providing a valid variable."), + + new ErrorInfo( + 133, + ErrorCode.InvalidPlayerVariable, + "The provided variable '{0}' has no associated players.", + "This error occurs when a variable requires another player variable as an argument, but the other variable is not a variable that contains players. This error can be resolved by providing a valid variable that contains players."), + + new ErrorInfo( + 134, + ErrorCode.InvalidInteger, + "The provided value '{0}' is not a valid integer or variable containing an integer.", + "This error occurs when a variable requires a variable that must be an integer, or a variable containing an integer. However, the provided variable is not an integer or a valid integer variable."), + + new ErrorInfo( + 135, + ErrorCode.IndexTooLarge, + "The provided index '{index}' is greater than the size of the player collection.", + "This error only occurs in the {INDEXVAR} variable. It occurs when the index provided is larger than the list it is trying to index. As an example, this error will occur if you try to get the 5th player from a variable containing only two players."), + + new ErrorInfo( + 136, + ErrorCode.CustomCommand_MultCooldowns, + "Custom command '{0}' ({1}) will not be created because it has multiple cooldowns set to a value other than -1. Only one cooldown can have a value other than -1.", + "This error only occurs if both the cooldown and player_cooldown settings are set to a value other than -1 in a custom command. Only one cooldown type may have a value of -1."), + + new ErrorInfo( + 137, + ErrorCode.InvalidNumber, + "The provided value '{0}' is not a valid number or variable containing a number.", + "This error occurs when a variable requires a variable that must be a number, or a variable containing a number. However, the provided variable is not a number or a valid number variable."), + + new ErrorInfo( + 138, + ErrorCode.UnsupportedArgumentVariables, + "Argument variables are not supported in the '{0}' variable. Please use a custom variable instead.", + $"This error occurs when a variable expects a variable as one of its arguments. However, the provided variable is a variable with arguments, which is not supported. This error can be resolved by using a custom variable in its place."), + + new ErrorInfo( + 139, + ErrorCode.ScriptJumpFailed, + "Failed to jump to {0}, '{1}' value is not a valid label.", + $"This error occurs when an invalid label or keyword is provided for an action that jumps to labels."), + + new ErrorInfo( + 140, + ErrorCode.VariableReplaceError, + "Error replacing the {0} variable: {1}", + "This error occurs when an error occurred while replacing a variable. Please report this error in the Scripted Events Discord server."), + + new ErrorInfo( + 141, + ErrorCode.UnknownActionError, + "Ran into an error while running '{0}' action (please report to developer)", + "This error occurs when there was an unexpected error in an action. Please report this error in the Scripted Events Discord server."), + + new ErrorInfo( + 142, + ErrorCode.InvalidDoor, + "'{0}' is not a valid door input.", + "This error occurs when an input to target in-game doors was expected, but the input was invalid. This error can be resolved by using a proper door input, such as 'ALL', a ZoneType/RoomType, or the name/ID of a door."), + + new ErrorInfo( + 143, + ErrorCode.InvalidLift, + "'{0} is not a valid lift input.", + "This error occurs when an input to target in-game lift was expected, but the input was invalid. This error can be resolved by using a proper lift input, such as 'ALL' or the name/ID of a door."), + + new ErrorInfo( + 144, + ErrorCode.InvalidEnumGeneric, + "Provided value '{0}' is not a valid {1} input. See all options by running 'shelp {1}' in the server console.", + "This error occurs when an input to a specific enum was expected, but the input was invalid. This error can be resolved by using a valid enum input. All valid enum inputs can be seen by running 'shelp ' in the server console."), + + new ErrorInfo( + 145, + ErrorCode.InvalidStringVariable, + "Provided variable '{0}' is not a valid string variable.", + "This error occurs when a string variable was expected, but is not provided. This error can be resolved by providing a valid string variable."), + + new ErrorInfo( + 146, + ErrorCode.InvalidCharacter, + "Provided value '{0}' is not a valid character.", + "This error occurs when a single character input was expected, but the input is not a valid character. This error can be resolved by providing a valid character."), + + new ErrorInfo( + 147, + ErrorCode.InvalidRoleTypeOrTeam, + "Provided value '{0}' is not a valid RoleTypeId or Team.", + $"This error occurs when a RoleTypeId or Team input was expected, but the input is not either. This error can be resolved by providing a valid RoleTypeId or Team. A full list of valid RoleTypeId IDs (as of {DateTime.Now:g}) follows:\n{string.Join("\n", ((RoleTypeId[])Enum.GetValues(typeof(RoleTypeId))).Where(r => r is not RoleTypeId.None).Select(r => $"- [{r:d}] {r}"))}\n A full list of valid Team IDs (as of {DateTime.Now:g}) follows:\n{string.Join("\n", ((Team[])Enum.GetValues(typeof(Team))).Select(r => $"- [{r:d}] {r}"))}"), + + new ErrorInfo( + 148, + ErrorCode.InvalidBoolean, + "Provided value '{0}' is not a valid boolean input.", + "This error occurs when a single boolean input was expected, but the input is not a valid boolean. This error can be resolved by providing a valid boolean input. Valid inputs are as follows: 'TRUE', 'T', 'FALSE', 'F', 'YES', 'Y', 'NO', 'N'."), + + new ErrorInfo( + 149, + ErrorCode.ParameterError_TooManyPlayers, + "Provided player variable '{0}' contains too many players for propper execution.", + "This error occurs when an action or a variable has a strict limit on how many players can be provided in order for propper execution. Read the action or variable documentation to learn more about the specifications."), + }.AsReadOnly(); + } +} diff --git a/ScriptedEvents/API/Features/Logger.cs b/ScriptedEvents/API/Features/Logger.cs index 17a5d2f2..550bddf8 100644 --- a/ScriptedEvents/API/Features/Logger.cs +++ b/ScriptedEvents/API/Features/Logger.cs @@ -71,7 +71,7 @@ public static void ScriptError(string message, Script source, bool fatal = false break; default: - Warn(message); + Error(message); break; } } diff --git a/ScriptedEvents/API/Features/MsgGen.cs b/ScriptedEvents/API/Features/MsgGen.cs index 84c58b4f..2c76f417 100644 --- a/ScriptedEvents/API/Features/MsgGen.cs +++ b/ScriptedEvents/API/Features/MsgGen.cs @@ -41,10 +41,7 @@ public static class MsgGen { typeof(RoomType), "RoomType (ID / Number)" }, { typeof(IVariable), "Variable" }, { typeof(IPlayerVariable), "Player Variable" }, - { typeof(IConditionVariable), "Condition Variable" }, - { typeof(IStringVariable), "String (Message/Text) Variable" }, - { typeof(IFloatVariable), "Numerical Variable" }, - { typeof(ILongVariable), "Numerical Variable" }, + { typeof(ILiteralVariable), "Literal (Raw Text) Variable" }, { typeof(RoleTypeIdOrTeam), "RoleTypeId (ID / Number) OR Team (ID / Number)" }, { typeof(object), "Any Type" }, }; diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 956338a7..336d2836 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Text; + using System.Text.RegularExpressions; using Exiled.API.Enums; using Exiled.API.Features; @@ -11,7 +13,6 @@ using Exiled.API.Features.Roles; using Exiled.CustomItems.API.Features; using PlayerRoles; - using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; @@ -324,61 +325,41 @@ void Log(string msg) /// The input string. /// The script source. /// The variables used within the string. - public static string[] IsolateValueSyntax(string input, Script source, bool includeAccessors = true) + public static (Match[] variables, Match[] dynamicActions, Match[] accessors) IsolateValueSyntax(string input, Script source, bool captureVariables = true, bool captureDynActs = true, bool captureAccessors = true) { void Log(string msg) { Logger.Debug($"[SEParser] [IsolateValueSyntax] {msg}", source); } - Log($"Isolating values from '{input}'"); - List result = ListPool.Pool.Get(); + Match[] variables = null; + Match[] dynamicActions = null; + Match[] accessors = null; - int inputLength = input.Length; - for (int i = 0; i < inputLength; i++) - { - char openingSymbol = input[i]; - char closingSymbol; - - switch (openingSymbol) - { - case '{': - closingSymbol = '}'; break; - case '<': - if (!includeAccessors) continue; - closingSymbol = '>'; break; - default: - continue; - } - - int index = input.IndexOf(closingSymbol, i + 1); - if (index == -1) - { - break; - } - - bool hasSpace = false; - for (int j = i + 1; j < index; j++) - { - if (input[j] == ' ') - { - hasSpace = true; - break; - } - } + Log($"Isolating value syntaxes from: '{input}'"); - if (hasSpace) - { - continue; - } + // Add @words pattern if enabled + if (captureVariables) + { + variables = Regex.Matches(input, @"@\S+").Cast().ToArray(); + Log($"Retreived {variables.Length} variables."); + } - string variable = input.Substring(i, index - i + 1); + // Add {multiple words} pattern if enabled + if (captureDynActs) + { + dynamicActions = Regex.Matches(input, @"\{[^{}\s]*\}").Cast().ToArray(); + Log($"Retreived {dynamicActions.Length} dynamic actions."); + } - Log($"Extracted a value '{variable}'"); - result.Add(variable); + // Add pattern if enabled + if (captureAccessors) + { + accessors = Regex.Matches(input, @"<[^<>\s]*>").Cast().ToArray(); + Log($"Retreived {accessors.Length} accessors."); } - return ListPool.Pool.ToArrayReturn(result); + return (variables, dynamicActions, accessors); } public static bool TryGetAccessor(string input, Script source, out string result) @@ -579,6 +560,32 @@ void Log(string msg) result = ply.ArtificialHealth.ToString(); break; + case "IS096TARGET": + result = "FALSE"; + foreach (Player p in Player.Get(RoleTypeId.Scp096)) + { + if ((p.Role as Scp096Role).Targets.Contains(ply)) + { + result = "TRUE"; + break; + } + } + + break; + + case "ISWATCHING173": + result = "FALSE"; + foreach (Player p in Player.Get(RoleTypeId.Scp173)) + { + if ((p.Role as Scp173Role).ObservingPlayers.Contains(ply)) + { + result = "TRUE"; + break; + } + } + + break; + default: result = ply.SessionVariables.ContainsKey(parts[1]) ? ply.SessionVariables[parts[1]].ToString() @@ -604,45 +611,22 @@ void Log(string msg) Logger.Debug($"[SEParser] [RCVS] {msg}", source); } - string[] values = IsolateValueSyntax(input, source); + var values = IsolateValueSyntax(input, source); + StringBuilder output = new(input); - foreach (string value in values) + foreach (Match accssr in values.accessors) { - Log("Isolated value syntax: " + value); - - if (VariableSystemV2.TryGetVariable(value, source, out VariableResult vresult)) - { - if (!vresult.ProcessorSuccess) - { - Logger.Warn($"Variable '{vresult.Variable.Name}' argument error: {vresult.Message}", source); - continue; - } - - try - { - input = input.Replace(value, vresult.String(source, vresult.Reversed)); - } - catch (InvalidCastException e) - { - Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, e.Message), source); - } - catch (Exception e) - { - Logger.Warn(ErrorGen.Get(ErrorCode.VariableReplaceError, vresult.Variable.Name, source?.Debug == true ? e : e.Message), source); - } - - Log("Value syntax was successfully replaced."); - continue; - } + output.Replace(accssr.Value, "PLACEHOLDER", accssr.Index, accssr.Length); + } - if (TryGetAccessor(value, source, out string aresult)) - { - input = input.Replace(value, aresult); - Log("Value syntax was successfully replaced."); - continue; - } + foreach (Match dynact in values.dynamicActions) + { + output.Replace(dynact.Value, "PLACEHOLDER", dynact.Index, dynact.Length); + } - Log($"Value syntax {value} cannot be replaced (perhaps a formatting issue?)"); + foreach (Match varbl in values.variables) + { + output.Replace(varbl.Value, "PLACEHOLDER", varbl.Index, varbl.Length); } return input; diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index cdab616c..d97c1f13 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -2,7 +2,6 @@ namespace ScriptedEvents.API.Modules { using System; using System.Collections.Generic; - using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; @@ -26,6 +25,9 @@ namespace ScriptedEvents.API.Modules using ScriptedEvents.Structures; + using Logger = Features.Logger; + using LogType = Enums.LogType; + /// /// A helper class to read and execute scripts, and register actions, as well as providing useful API for individual actions. /// @@ -74,23 +76,11 @@ public override void GenerateFiles() File.WriteAllText(Path.Combine(MainPlugin.BaseFilePath, "README.txt"), new About().Contents); } - catch (UnauthorizedAccessException e) - { - Logger.Error(ErrorGen.Get(ErrorCode.IOPermissionError) + $": {e}"); - return; - } catch (Exception e) { - Logger.Error(ErrorGen.Get(ErrorCode.IOError) + $": {e}"); + Logger.Error(ErrorGenV2.IOError() + $": {e}"); return; } - - // Welcome message :) - // 3s delay to show after other console spam - Timing.CallDelayed(6f, () => - { - Logger.Warn($"Thank you for installing Scripted Events! View the README file located at {Path.Combine(MainPlugin.BaseFilePath, "README.txt")} for information on how to use and get the most out of this plugin."); - }); } public override void Init() @@ -141,6 +131,11 @@ public void OnWaitingForPlayers() Logger.Warn(ErrorGen.Get(ErrorCode.AutoRun_NotFound, scr.ScriptName)); } } + + if (ShouldGenerateFiles) + { + Logger.Info($"Thank you for installing Scripted Events! View the README file located at {Path.Combine(MainPlugin.BaseFilePath, "README.txt")} for information on how to use and get the most out of this plugin."); + } } /// @@ -225,7 +220,7 @@ public Script ReadScript(string scriptName, ICommandSender executor, bool suppre bool inMultilineComment = false; Script script = new(); - void DebugLog(string message) + void Log(string message) { Logger.Debug($"[ScriptModule] [ReadScript] {message}", script); } @@ -275,20 +270,6 @@ void DebugLog(string message) string keyword = structureParts[0].RemoveWhitespace(); - // labels - if (keyword.EndsWith(":")) - { - string labelName = line.Remove(keyword.Length - 1, 1).RemoveWhitespace(); - - if (!script.Labels.ContainsKey(labelName)) - script.Labels.Add(labelName, currentline); - else if (!suppressWarnings) - Logger.Warn(ErrorGen.Get(ErrorCode.MultipleLabelDefs, labelName, scriptName)); - - addActionNoArgs(new NullAction($"{labelName} LABEL")); - continue; - } - // function labels if (keyword == "->") { @@ -322,17 +303,82 @@ void DebugLog(string message) if (script.SmartArguments.ContainsKey(lastAction)) { - script.SmartArguments[lastAction] = script.SmartArguments[lastAction].Append(value).ToArray(); + script.SmartArguments[lastAction] = script.SmartArguments[lastAction].Append(() => new(true, value)).ToArray(); } else { - script.SmartArguments[lastAction] = new[] { value }; + script.SmartArguments[lastAction] = new Func>[] { () => new(true, value) }; } addActionNoArgs(new NullAction($"SMART ARG")); continue; } + if (keyword == "//::") + { + if (actionList.Count == 0) + { + Logger.Log("'//::' (smart extractor) syntax can't be used if there isn't any action above it.", LogType.Warning, script, currentline + 1); + continue; + } + + string actionName = structureParts[1]; + string[] actionArgs = structureParts.Skip(2).ToArray(); + + // TODO: implement for external actions + if (!TryGetActionType(actionName, out Type actionType1)) + { + Logger.Warn(ErrorGen.Get(ErrorCode.InvalidAction, actionName, scriptName), script); + continue; + } + + IAction actionToExtract = Activator.CreateInstance(actionType1) as IAction; + + Tuple ActionWrapper() + { + if (actionToExtract is ITimingAction) + { + return new(false, "Action is a timing action, which cannot be used with smart extractors."); + } + + if (!TryRunAction(script, actionToExtract, out ActionResponse resp, out float? delay, actionArgs)) + { + return new(false, resp.Message); + } + + if (resp == null || resp.ResponseVariables.Length == 0) + { + return new(false, "Action did not return any values to use."); + } + + if (resp.ResponseVariables.Length > 1) + { + Log("Action returned more than 1 value. Using the first one as default."); + } + + object value = resp.ResponseVariables[0]; + + if (value is not string) + { + return new(false, "Action returned a value that is not a string."); + } + + return new(true, value as string); + } + + if (script.SmartArguments.ContainsKey(lastAction)) + { + script.SmartArguments[lastAction] = script.SmartArguments[lastAction].Append(ActionWrapper).ToArray(); + } + else + { + script.SmartArguments[lastAction] = new Func>[] { ActionWrapper }; + } + + addActionNoArgs(new NullAction($"SMART EXTR")); + continue; + } + // flags if (keyword == "!--") { @@ -352,6 +398,20 @@ void DebugLog(string message) continue; } + // labels + if (keyword.EndsWith(":")) + { + string labelName = line.Remove(keyword.Length - 1, 1).RemoveWhitespace(); + + if (!script.Labels.ContainsKey(labelName)) + script.Labels.Add(labelName, currentline); + else if (!suppressWarnings) + Logger.Warn(ErrorGen.Get(ErrorCode.MultipleLabelDefs, labelName, scriptName)); + + addActionNoArgs(new NullAction($"{labelName} LABEL")); + continue; + } + // extractor int indexOfExtractor = line.IndexOf("::"); string[] resultVariableNames = Array.Empty(); @@ -360,17 +420,21 @@ void DebugLog(string message) { string variablesSection = line.Substring(0, indexOfExtractor); string actionSection = line.Substring(indexOfExtractor + 2).TrimStart(); - DebugLog($"[ExtractorSyntax] Variables section: {variablesSection}"); - DebugLog($"[ExtractorSyntax] Action section: {actionSection}"); + Log($"[ExtractorSyntax] Variables section: {variablesSection}"); + Log($"[ExtractorSyntax] Action section: {actionSection}"); - resultVariableNames = SEParser.IsolateValueSyntax(variablesSection, script, false); + resultVariableNames = SEParser.IsolateValueSyntax(variablesSection, script, true, false, false).variables.Select(arg => arg.Value).ToArray(); if (resultVariableNames.Length != 0) { - DebugLog($"[ExtractorSyntax] Variables found before the syntax: {string.Join(", ", resultVariableNames)}"); + Log($"[ExtractorSyntax] Variables found before the syntax: {string.Join(", ", resultVariableNames)}"); structureParts = actionSection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(part => part.Trim()).ToList(); keyword = structureParts[0]; } + else + { + Logger.Warn("The extraction operator `::` has been used, but no variable names were specified to contain extracted values.", script); + } } keyword = keyword.ToUpper(); @@ -416,7 +480,7 @@ void DebugLog(string message) script.OriginalActionArgs[newAction] = structureParts.Skip(1).Select(str => str.RemoveWhitespace()).ToArray(); script.ResultVariableNames[newAction] = resultVariableNames; - DebugLog($"Queuing action {keyword}, {string.Join(", ", script.OriginalActionArgs[newAction])}"); + Log($"Queuing action {keyword}, {string.Join(", ", script.OriginalActionArgs[newAction])}"); // Obsolete check if (newAction.IsObsolete(out string obsoleteReason) && !suppressWarnings && !script.SuppressWarnings) @@ -459,7 +523,7 @@ void DebugLog(string message) script.Sender = executor; - DebugLog($"Debug script read successfully. Name: {script.ScriptName} | Actions: {script.Actions.Count(act => act is not NullAction)} | Flags: {string.Join(" ", script.Flags)} | Labels: {string.Join(" ", script.Labels)} | Comments: {script.Actions.Count(action => action is NullAction @null && @null.Type is "COMMENT")}"); + Log($"Debug script read successfully. Name: {script.ScriptName} | Actions: {script.Actions.Count(act => act is not NullAction)} | Flags: {string.Join(" ", script.Flags)} | Labels: {string.Join(" ", script.Labels)} | Comments: {script.Actions.Count(action => action is NullAction @null && @null.Type is "COMMENT")}"); return script; } @@ -475,10 +539,38 @@ public void RunScript(Script scr, bool dispose = true) if (scr.Disabled) throw new DisabledScriptException(scr.ScriptName); - CoroutineHandle handle = Timing.RunCoroutine(RunScriptInternal(scr, dispose), $"SCRIPT_{scr.UniqueId}"); + CoroutineHandle handle = Timing.RunCoroutine(SafeRunCoroutine(RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); RunningScripts.Add(scr, handle); } + // chatgpt made this amazing thing + public IEnumerator SafeRunCoroutine(IEnumerator coroutine) + { + while (true) + { + object current; + try + { + // Continue running the original coroutine + if (coroutine.MoveNext()) + { + current = coroutine.Current; + } + else + { + yield break; + } + } + catch (Exception e) + { + Logger.Error($"A coroutine error has been caught!\n{e.Message}\n{e.StackTrace}"); + yield break; + } + + yield return (float)current; + } + } + /// /// Reads and runs a script. /// @@ -634,13 +726,99 @@ internal void RegisterActions(Assembly assembly) MainPlugin.Info($"Assembly '{assembly.GetName().Name}' has registered {i} actions."); } + public static bool TryRunAction(Script scr, IAction action, out ActionResponse actResp, out float? delay, string[] originalActionArgs = null) + { + actResp = null; + delay = null; + + void Log(string message) + { + Logger.Debug("[ScriptModule] [TryRunAction] " + message, scr); + } + + if (action is NullAction nullAction) + { + Log($"Null action type: {nullAction.Type}"); + return true; + } + + if (scr.IfActionBlocksExecution && action is not IIgnoresIfActionBlock) + { + Log("Action was skipped; the IF block resulted in FALSE and action does not terminate IF blocks."); + return true; + } + + if (originalActionArgs == null) + { + // Process Arguments + if (scr.OriginalActionArgs.TryGetValue(action, out string[] xxx)) + { + originalActionArgs = xxx; + } + else + { + Log("Action does not have any arguments provided."); + } + } + + ArgumentProcessResult res = ArgumentProcessor.Process(action.ExpectedArguments, originalActionArgs, action, scr); + if (res.Errored) + { + string message = (res.FailedArgument != string.Empty ? $"[Argument: {res.FailedArgument}] " : string.Empty) + res.Message; + actResp = new(false, message); + return false; + } + + if (!res.Success) + { + Log("Action will not be ran. " + actResp.Message != null ? actResp.Message : string.Empty); + return true; + } + + action.Arguments = res.NewParameters.ToArray(); + action.RawArguments = res.StrippedRawParameters; + + switch (action) + { + case ITimingAction timed: + Log($"Running {action.Name} action (timed)..."); + delay = timed.Execute(scr, out actResp); + break; + case IScriptAction scriptAction: + Log($"Running {action.Name} action..."); + actResp = scriptAction.Execute(scr); + break; + default: + Log($"Action is not runnable."); + return true; + } + + if (delay.HasValue) + { + Log($"Action '{action.Name}' is delaying the script. Length of delay: {delay.Value}"); + } + + if (!actResp.Success) + { + return false; + } + + Log($"{action.Name} has successfully executed."); + return true; + } + /// /// Internal coroutine to run the script. /// /// The script to run. /// Coroutine iterator. - private IEnumerator RunScriptInternal(Script scr, bool dispose = true) + public IEnumerator RunScriptInternal(Script scr, bool dispose = true) { + void Log(string message) + { + Logger.Debug("[ScriptModule] [RunScriptInternal] " + message, scr); + } + MainPlugin.Info($"Started running the '{scr.ScriptName}' script."); yield return Timing.WaitForOneFrame; @@ -648,190 +826,102 @@ private IEnumerator RunScriptInternal(Script scr, bool dispose = true) scr.IsRunning = true; scr.RunDate = DateTime.Now; - Stopwatch runTime = Stopwatch.StartNew(); int lines = 0; int successfulLines = 0; for (; scr.CurrentLine < scr.Actions.Length; scr.NextLine()) { - Logger.Debug("-----------", scr); - Logger.Debug($"Current Line: {scr.CurrentLine + 1}", scr); - if (!scr.Actions.TryGet(scr.CurrentLine, out IAction action) || action == null) - { - Logger.Debug("There is no runnable action on this line. Skipping...", scr); - continue; - } - - Logger.Debug($"Fetched action '{action.Name}'", scr); - if (action is NullAction nullAction) + if (!scr.HasFlag("NOSAFETY")) { - Logger.Debug($"Null action type: {nullAction.Type}", scr); + yield return Timing.WaitForOneFrame; } - if (scr.IfActionBlocksExecution && action is not IIgnoresIfActionBlock) + if (!scr.Actions.TryGet(scr.CurrentLine, out IAction action) || action == null) { - Logger.Debug("Action was skipped; the IF statement resulted in FALSE and action is not 'ITerminatesIfAction'", scr); + Log("There is no runnable action on this line. Skipping..."); continue; } - Logger.Debug("Action was not skipped by an IF statement.", scr); - + lines++; + Log("-> Running action " + action.Name); ActionResponse resp; - float? delay = null; - // Process Arguments - if (scr.OriginalActionArgs.TryGetValue(action, out string[] originalArgs)) + if (!TryRunAction(scr, action, out resp, out float? delay)) { - ArgumentProcessResult res = ArgumentProcessor.Process(action.ExpectedArguments, originalArgs, action, scr); - if (res.Errored) + Log("Action failed."); + if (resp != null && resp.Message.Length > 0) { - Logger.ScriptError((res.FailedArgument != string.Empty ? $"[Argument: {res.FailedArgument}] " : string.Empty) + res.Message, scr); - break; + Logger.ScriptError(resp.Message, scr, true); } - if (!res.Success) - { - Logger.Debug("Action was skipped; the argument processor did not return 'success' as true.", scr); - continue; - } - else - { - Logger.Debug("Action was not skipped; the argument processor returned 'success' as true.", scr); - } + continue; + } - action.Arguments = res.NewParameters.ToArray(); - action.RawArguments = res.StrippedRawParameters; + if (resp == null) + { + continue; } - try + Log("Action success."); + + if (resp.ResponseFlags.HasFlag(ActionFlags.StopEventExecution)) + break; + + successfulLines++; + + if (!string.IsNullOrEmpty(resp.Message)) { - switch (action) + string message = $"[Script: {scr.ScriptName}] [Line: {scr.CurrentLine + 1}] [Action: {action.Name}] {resp.Message}"; + switch (scr.Context) { - case ITimingAction timed: - Logger.Debug($"Running {action.Name} action (timed)...", scr); - delay = timed.Execute(scr, out resp); - break; - case IScriptAction scriptAction: - Logger.Debug($"Running {action.Name} action...", scr); - resp = scriptAction.Execute(scr); + case ExecuteContext.RemoteAdmin: + Player.Get(scr.Sender)?.RemoteAdminMessage(message, true, MainPlugin.Singleton.Name); break; default: - Logger.Debug($"Skipping line (no runnable action on line)", scr); - continue; + Logger.Info(message); + break; } } - catch (ScriptedEventsException seException) - { - string message = $"[Script: {scr.ScriptName}] [L: {scr.CurrentLine + 1}] {seException.Message}"; - Logger.ScriptError(message, scr); - continue; - } - catch (Exception e) + if (resp.ResponseVariables == null) { - string message = $"[Script: {scr.ScriptName}] [L: {scr.CurrentLine + 1}] {ErrorGen.Get(ErrorCode.UnknownActionError, action.Name)}:\n{e}"; - Logger.ScriptError(message, scr); - continue; } - if (!resp.Success) + if (!scr.ResultVariableNames.TryGetValue(action, out string[] variableNames)) { - Logger.Debug($"{action.Name} [Line: {scr.CurrentLine + 1}]: FAIL", scr); - if (resp.ResponseFlags.HasFlag(ActionFlags.FatalError)) - { - string message = $"[{action.Name}] Fatal action error! {resp.Message}"; - Logger.ScriptError(message, scr, fatal: true); - - break; - } - else if (!scr.SuppressWarnings) - { - string message = $"[{action.Name}] Action error! {resp.Message}"; - Logger.ScriptError(message, scr); - } + continue; } - else - { - Logger.Debug($"{action.Name} [Line: {scr.CurrentLine + 1}]: SUCCESS", scr); - successfulLines++; - if (resp.ResponseVariables != null && scr.ResultVariableNames.TryGetValue(action, out string[] variableNames)) + foreach (var zipped in resp.ResponseVariables.Zip(variableNames, (variable, name) => (variable, name))) + { + switch (zipped.variable) { - foreach (var zipped in resp.ResponseVariables.Zip(variableNames, (variable, name) => (variable, name))) - { - switch (zipped.variable) - { - case Player[] plrVar: - Logger.Debug($"Action {action.Name} is adding a player variable as '{zipped.name}'.", scr); - scr.UniquePlayerVariables.Add(zipped.name, new(zipped.name, string.Empty, plrVar.ToList())); - break; - - case string strVar: - Logger.Debug($"Action {action.Name} is adding a variable as '{zipped.name}'.", scr); - scr.UniqueVariables.Add(zipped.name, new(zipped.name, string.Empty, strVar)); - break; - - default: - try - { - scr.UniqueVariables.Add(zipped.name, new(zipped.name, string.Empty, zipped.variable.ToString())); - } - catch (InvalidCastException) - { - Logger.ScriptError($"Action {action.Name} returned a value of an illegal type '{zipped.variable.GetType()}', which cannot be casted back to string. Please report this to the developer.", scr); - } - - break; - } - } - } + case Player[] plrVar: + Log($"Action {action.Name} is adding a player variable as '{zipped.name}'."); + scr.UniquePlayerVariables.Add(zipped.name, new(zipped.name, string.Empty, plrVar.ToList())); + break; - if (!string.IsNullOrEmpty(resp.Message)) - { - string message = $"[Script: {scr.ScriptName}] [L: {scr.CurrentLine + 1}] [{action.Name}] Response: {resp.Message}"; - switch (scr.Context) - { - case ExecuteContext.RemoteAdmin: - Player.Get(scr.Sender)?.RemoteAdminMessage(message, true, MainPlugin.Singleton.Name); - break; - default: - Logger.Info(message); - break; - } - } + case string strVar: + Log($"Action {action.Name} is adding a variable as '{zipped.name}'."); + scr.UniqueVariables.Add(zipped.name, new(zipped.name, string.Empty, strVar)); + break; - if (delay.HasValue) - { - Logger.Debug($"Action '{action.Name}' on line {scr.CurrentLine + 1} delaying script. Length of delay: {delay.Value}", scr); - yield return delay.Value; + default: + Logger.ScriptError($"Action '{action.Name}' returned a value of an illegal type '{zipped.variable.GetType()}', which is not supported. Report this error to the developers.", scr); + scr.UniqueVariables.Add(zipped.name, new(zipped.name, string.Empty, zipped.variable.ToString())); + break; } } - - lines++; - - if (resp.ResponseFlags.HasFlag(ActionFlags.StopEventExecution)) - break; - - if (!scr.HasFlag("NOSAFETY")) - { - yield return Timing.WaitForOneFrame; - } } - scr.DebugLog("-----------"); - scr.DebugLog($"Script {scr.ScriptName} concluded. Total time '{runTime.Elapsed:mm':'ss':'fff}', Executed '{successfulLines}/{lines}' ({Math.Round((float)successfulLines / lines * 100)}%) actions successfully"); + Log("-----------"); + Log($"Script concluded!"); MainPlugin.Info($"Finished running script {scr.ScriptName}."); - scr.DebugLog("-----------"); + Log("-----------"); scr.IsRunning = false; - if (scr.HasFlag("LOOP")) - { - scr.DebugLog("Re-running looped script."); - ReadAndRun(scr.ScriptName, scr.Sender); // so that it re-reads the content of the text file. - } - - scr.DebugLog("Removing script from running scripts."); + Log("Removing script from running scripts."); RunningScripts.Remove(scr); if (dispose) diff --git a/ScriptedEvents/API/Modules/VariableSystemV2.cs b/ScriptedEvents/API/Modules/VariableSystemV2.cs index a3f61e87..06e797d8 100644 --- a/ScriptedEvents/API/Modules/VariableSystemV2.cs +++ b/ScriptedEvents/API/Modules/VariableSystemV2.cs @@ -5,7 +5,6 @@ using System.Linq; using Exiled.API.Features; - using Exiled.API.Features.Pools; using ScriptedEvents.API.Extensions; using ScriptedEvents.API.Features; @@ -114,137 +113,115 @@ public static void ClearVariables() DefinedPlayerVariables.Clear(); } - /// - /// Gets a variable. - /// - /// The input string. - /// The script source. - /// If brackets are required to parse the variable. - /// If processing is to be skipped. - /// A tuple containing the variable and whether or not it's a reversed boolean value. - public static VariableResult GetVariable(string name, Script source, bool requireBrackets = true, bool skipProcessing = false) + public static VariableResult InternalGetVariable(string initName, Script source) { - DebugLog($"[GetVariable] Getting the '{name}' variable.", source); - - // Do this here so individual files dont have to do it anymore - if (!requireBrackets) + void Log(string message) { - name = name.Replace("{", string.Empty).Replace("}", string.Empty); - name = $"{{{name}}}"; - } - - string variableName; - List argList = ListPool.Pool.Get(); - - string[] arguments = name.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); - if (arguments.Length == 1) - { - variableName = arguments[0]; - } - else - { - variableName = arguments[0] + "}"; - foreach (string argument in arguments.Skip(1)) - { - string arg = argument; - if (arg.EndsWith("}")) arg = arg.Replace("}", string.Empty); - argList.Add(arg); - DebugLog($"[GetVariable] Formatted argument '{argument} to '{arg}'", source); - } + DebugLog("[VariableSystem] [InternalGetVariable] " + message, source); } - variableName = variableName.ToUpper(); - - DebugLog($"[GetVariable] Attempting to retrieve variable '{variableName}' with args '{string.Join(", ", argList)}'", source); + string name = initName.ToUpper(); - Tuple result = new(null, false); - - bool foundVar = false; foreach (IVariableGroup group in Groups) { foreach (IVariable variable in group.Variables) { - if (variable.Name.ToUpper() == variableName && variable is IConditionVariable condition) - { - result = new(condition, false); - foundVar = true; - } - else if (variable is IBoolVariable boolVariable && boolVariable.ReversedName.ToUpper() == variableName) + if (variable.Name.ToUpper() != name) { - result = new(boolVariable, true); - foundVar = true; + continue; } + + Log($"Variable {initName} is a predefined SE variable."); + return new(true, variable); } } - if (!foundVar) - DebugLog("[GetVariable] The variable provided is not a variable predefined by ScriptedEvents.", source); - else - DebugLog("[GetVariable] Variable provided is a variable defined by ScriptedEvents.", source); - - if (DefinedVariables.TryGetValue(variableName, out CustomVariable customValue)) - result = new(customValue, false); - - if (DefinedPlayerVariables.TryGetValue(variableName, out CustomPlayerVariable customPlayerValue)) - result = new(customPlayerValue, false); + if (DefinedVariables.TryGetValue(name, out CustomVariable customValue)) + { + Log($"Variable {initName} is a global literal variable."); + return new(true, customValue); + } - if (source is not null && source.UniqueVariables.TryGetValue(variableName, out CustomVariable uniqueValue)) - result = new(uniqueValue, false); + if (DefinedPlayerVariables.TryGetValue(name, out CustomPlayerVariable customPlayerValue)) + { + Log($"Variable {initName} is a global player variable."); + return new(true, customPlayerValue); + } - if (source is not null && source.UniquePlayerVariables.TryGetValue(variableName, out CustomPlayerVariable uniquePlayerValue)) - result = new(uniquePlayerValue, false); + if (source.UniqueVariables.TryGetValue(name, out CustomVariable uniqueValue)) + { + Log($"Variable {initName} is a local literal variable."); + return new(true, uniqueValue); + } - if (result.Item1 is not null) + if (source.UniquePlayerVariables.TryGetValue(name, out CustomPlayerVariable uniquePlayerValue)) { - if (result.Item1 is IArgumentVariable argSupport) - { - DebugLog("[GetVariable] Variable provided has arguments.", source); - argSupport.RawArguments = argList.ToArray(); + Log($"Variable {initName} is a local player variable."); + return new(true, uniquePlayerValue); + } - if (!skipProcessing) - { - ArgumentProcessResult processResult = ArgumentProcessor.Process(argSupport.ExpectedArguments, argSupport.RawArguments, result.Item1, source, false); + Log($"No variable matches the provided name '{initName}'."); + return new(false, null, $"The variable name '{initName}' (checked by '{name}') does not match any SE predefined, global or local variable."); + } - DebugLog($"[GetVariable] Variable argument processing completed. Success: {processResult.Success} | Message: {processResult.Message ?? "N/A"}", source); + public static VariableResult InternalGetDynamicVariable(string initName, Script source) + { + return new(true, null); + } - if (!processResult.Success) - return new(false, result.Item1, processResult.Message, result.Item2); + /// + /// Gets a variable. + /// + /// The input string. + /// The script source. + /// A tuple containing the variable and whether or not it's a reversed boolean value. + public static VariableResult GetVariable(string name, Script source) + { + void Log(string message) + { + DebugLog("[GetVariable] " + message, source); + } - argSupport.Arguments = processResult.NewParameters.ToArray(); - } - else - { - DebugLog("[GetVariable] Argument processing skipped. Arguments and RawArguments will not be processed", source); - } - } + Log($"Getting the '{name}' variable."); - if (result.Item1 is INeedSourceVariable sourcePls) - { - sourcePls.Source = source; - } + if (name.StartsWith("@")) + { + Log($"'{name}' is a standard variable since '@' is the first token."); + return InternalGetVariable(name, source); } - else + else if (name.CountOccurrences('{') + name.CountOccurrences('}') == 0) { - return new(true, null, $"Unknown variable '{variableName}' provided.", false); + return new(false, null, + $"'{name}' is not a variable. No start token '@' or brackets '{{}}' detected."); } - ListPool.Pool.Return(argList); - DebugLog($"[GetVariable] Returning the variable value as {result.Item1}", source); - return new(true, result.Item1, string.Empty, result.Item2); + return new(false, null); + + /* + * add support for dynacts later + if (name.CountOccurrences('{') != 1 || name.CountOccurrences('}') != 1) + { + return new(false, null, + $"The amount of opening ({{) and closing (}}) brackets in the variable '{name}' should be 1 each, but there are '{name.CountOccurrences('{')}' opening and '{name.CountOccurrences('}')}' closing brackets."); + } + + if (name.First() != '{' || name.Last() != '}') + { + return new(false, null, + $"The opening ({{) and closing (}}) brackets in the variable '{name}' should be first and last accordingly, but theyre not."); + } + */ } - public static bool TryGetVariable(string name, Script source, out VariableResult result, bool requireBrackets = true, bool skipProcessing = false) + public static bool TryGetVariable(string name, Script source, out VariableResult result, bool skipProcessing = false) { - DebugLog($"[TryGetVariable] Trying to get the '{name}' variable", source); - result = GetVariable(name, source, requireBrackets, skipProcessing); + result = GetVariable(name, source); if (result.Variable is null) { - DebugLog($"[TryGetVariable] Fail! Was unable to get the '{name}' variable.", source); return false; } - DebugLog($"[TryGetVariable] Success! The '{name}' variable was successfully extracted.", source); return true; } diff --git a/ScriptedEvents/Actions/DebugActions/DebugProcessorAction.cs b/ScriptedEvents/Actions/DebugActions/DebugProcessorAction.cs index 35a40244..8ebb12dd 100644 --- a/ScriptedEvents/Actions/DebugActions/DebugProcessorAction.cs +++ b/ScriptedEvents/Actions/DebugActions/DebugProcessorAction.cs @@ -2,8 +2,6 @@ { using System; - using Exiled.API.Features; - using ScriptedEvents.API.Enums; using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; diff --git a/ScriptedEvents/Actions/Logic/CallAction.cs b/ScriptedEvents/Actions/Logic/CallAction.cs index 96612b45..bea5d6c3 100644 --- a/ScriptedEvents/Actions/Logic/CallAction.cs +++ b/ScriptedEvents/Actions/Logic/CallAction.cs @@ -84,7 +84,7 @@ public class CallAction : IHelpInfo, ITimingAction continue; } - if (VariableSystemV2.TryGetVariable(varName, script, out VariableResult result, requireBrackets: true) && result.ProcessorSuccess) + if (VariableSystemV2.TryGetVariable(varName, script, out VariableResult result) && result.ProcessorSuccess) { calledScript.AddVariable($"{{ARG{arg}}}", "Variable created using the CALL action.", result.String()); diff --git a/ScriptedEvents/Actions/Logic/FastCallAction.cs b/ScriptedEvents/Actions/Logic/FastCallAction.cs index 6d6e2cbd..12d24a8a 100644 --- a/ScriptedEvents/Actions/Logic/FastCallAction.cs +++ b/ScriptedEvents/Actions/Logic/FastCallAction.cs @@ -79,7 +79,7 @@ public ActionResponse Execute(Script script) continue; } - if (VariableSystemV2.TryGetVariable(varName, script, out VariableResult var, requireBrackets: true)) + if (VariableSystemV2.TryGetVariable(varName, script, out VariableResult var)) { calledScript.AddVariable($"{{ARG{arg}}}", "Variable created using the CALL action.", var.String()); diff --git a/ScriptedEvents/Actions/Logic/ReturnAction.cs b/ScriptedEvents/Actions/Logic/ReturnAction.cs index b41ca4c2..40bbadbb 100644 --- a/ScriptedEvents/Actions/Logic/ReturnAction.cs +++ b/ScriptedEvents/Actions/Logic/ReturnAction.cs @@ -6,9 +6,8 @@ using ScriptedEvents.API.Interfaces; using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; - using ScriptedEvents.Variables.Interfaces; - public class ReturnAction : IScriptAction, ILogicAction, IHelpInfo, IArgumentVariable + public class ReturnAction : IScriptAction, ILogicAction, IHelpInfo { /// public string Name => "RETURN"; diff --git a/ScriptedEvents/Actions/Misc/HelpAction.cs b/ScriptedEvents/Actions/Misc/HelpAction.cs index edb0d9d2..41f0bd31 100644 --- a/ScriptedEvents/Actions/Misc/HelpAction.cs +++ b/ScriptedEvents/Actions/Misc/HelpAction.cs @@ -309,64 +309,23 @@ Interested in helping others learn the plugin? Let {MainPlugin.Singleton.Author} if (VariableSystemV2.TryGetVariable(text, script, out VariableResult res2, skipProcessing: true)) { valid = true; - IConditionVariable variable = res2.Variable; + IVariable variable = res2.Variable; sb.AppendLine("=== VARIABLE ==="); sb.AppendLine($"Name: {variable.Name}"); sb.AppendLine($"Description: {variable.Description}"); - sb.AppendLine($"Stores Players: {(variable is IPlayerVariable ? "YES" : "NO")}"); - - if (variable is IArgumentVariable argSupport1) - { - sb.AppendLine($"Usage: {variable.Name.Substring(0, variable.Name.Length - 1)}:{string.Join(":", argSupport1.ExpectedArguments.Select(arg => arg.ArgumentName.ToUpper()))}}}"); - } - else - { - sb.AppendLine($"Usage: {variable.Name}"); - } + sb.AppendLine($"Usage: {variable.Name}"); sb.Append("Variable Type: "); switch (variable) { - case IBoolVariable @bool: - sb.AppendLine("Boolean (true/false)"); + case IPlayerVariable @float: + sb.AppendLine("Player variable (stores player objects)"); break; - case ILongVariable @long: - case IFloatVariable @float: - sb.AppendLine("Numerical"); + case ILiteralVariable @string: + sb.AppendLine("Literal variable (stores raw text)"); break; - case IStringVariable @string: - sb.AppendLine("String (Text)"); - break; - } - - if (variable is IArgumentVariable argSupport) - { - sb.AppendLine(); - sb.AppendLine("Arguments:"); - - foreach (Argument arg in argSupport.ExpectedArguments) - { - string[] chars = arg.Required ? new[] { "<", ">" } : new[] { "[", "]" }; - sb.AppendLine(); - sb.AppendLine($"{chars[0]}{arg.ArgumentName}{chars[1]}"); - sb.AppendLine($" Required: {(arg.Required ? "YES" : "NO")}"); - sb.AppendLine($" Type: {arg.TypeString}"); - sb.AppendLine($" {arg.Description}"); - - if (arg is OptionsArgument options) - { - sb.AppendLine($" Valid options for this argument:"); - foreach (Option option in options.Options) - { - if (option.Description is null || option.Description.RemoveWhitespace() == string.Empty) - sb.AppendLine($" - '{option.Name}'"); - else - sb.AppendLine($" - '{option.Name}' - {option.Description}"); - } - } - } } sb.AppendLine(); diff --git a/ScriptedEvents/Actions/Server/ErrorAction.cs b/ScriptedEvents/Actions/Server/ErrorAction.cs index 03e03997..1cfbd586 100644 --- a/ScriptedEvents/Actions/Server/ErrorAction.cs +++ b/ScriptedEvents/Actions/Server/ErrorAction.cs @@ -37,7 +37,7 @@ public class ErrorAction : IScriptAction, IHelpInfo /// public ActionResponse Execute(Script script) { - Logger.ScriptError(Arguments.JoinMessage(0), script); + Logger.ScriptError(Arguments.JoinMessage(0), script, true); return new(true); } } diff --git a/ScriptedEvents/Actions/Variable/AddToAction.cs b/ScriptedEvents/Actions/Variable/AddToAction.cs index 7d2acc1b..12438fae 100644 --- a/ScriptedEvents/Actions/Variable/AddToAction.cs +++ b/ScriptedEvents/Actions/Variable/AddToAction.cs @@ -33,14 +33,14 @@ public class AddToAction : IScriptAction, IHelpInfo /// public Argument[] ExpectedArguments => new[] { - new Argument("variableName", typeof(IStringVariable), "The string variable.", true), + new Argument("variableName", typeof(ILiteralVariable), "The string variable.", true), new Argument("value", typeof(string), "The value to add. Math is supported.", true), }; /// public ActionResponse Execute(Script script) { - IStringVariable var = (IStringVariable)Arguments[0]; + ILiteralVariable var = (ILiteralVariable)Arguments[0]; string input = Arguments.JoinMessage(1); input = $"{var.Value} {input}"; diff --git a/ScriptedEvents/Actions/Variable/BindAction.cs b/ScriptedEvents/Actions/Variable/BindAction.cs index bb193c7b..d0df71ad 100644 --- a/ScriptedEvents/Actions/Variable/BindAction.cs +++ b/ScriptedEvents/Actions/Variable/BindAction.cs @@ -34,14 +34,14 @@ public class BindAction : IScriptAction, IHelpInfo public Argument[] ExpectedArguments => new[] { new Argument("newVariableName", typeof(string), "The name of the new variable.", true), - new Argument("oldVariable", typeof(IConditionVariable), "The value of the variable.", false), + new Argument("oldVariable", typeof(IVariable), "The value of the variable.", false), }; /// public ActionResponse Execute(Script script) { string newVarName = RawArguments[0]; - IConditionVariable oldVar = (IConditionVariable)Arguments[1]; + IVariable oldVar = (IVariable)Arguments[1]; if (oldVar is IPlayerVariable oldPlayerVar) { diff --git a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs b/ScriptedEvents/Actions/Variable/LocalSaveAction.cs index 826a2f95..018a87ee 100644 --- a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs +++ b/ScriptedEvents/Actions/Variable/LocalSaveAction.cs @@ -32,7 +32,7 @@ public class LocalSaveAction : IScriptAction, IHelpInfo public Argument[] ExpectedArguments => new[] { new Argument("variableName", typeof(string), "The name of the new variable. Braces will be added automatically if not provided.", true), - new Argument("value", typeof(object), "The value to store. Math is supported.", false), + new Argument("value", typeof(object), "The value to store. Math is supported.", true), }; /// diff --git a/ScriptedEvents/Script.cs b/ScriptedEvents/Script.cs index 36f308d4..9ea30c66 100644 --- a/ScriptedEvents/Script.cs +++ b/ScriptedEvents/Script.cs @@ -197,7 +197,7 @@ public Script() /// /// Gets or sets the smart arguments for specified action. /// - public Dictionary SmartArguments { get; set; } = new(); + public Dictionary>[]> SmartArguments { get; set; } = new(); /// /// Gets or sets the names under which to create variables as result of an successful action. diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 26266db6..a5d4ea4c 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -208,6 +208,7 @@ + @@ -277,11 +278,7 @@ - - - - - + @@ -348,10 +345,6 @@ - - - - diff --git a/ScriptedEvents/Structures/VariableResult.cs b/ScriptedEvents/Structures/VariableResult.cs index f59eeddf..278cc8ea 100644 --- a/ScriptedEvents/Structures/VariableResult.cs +++ b/ScriptedEvents/Structures/VariableResult.cs @@ -14,11 +14,9 @@ public class VariableResult /// Whether or not the argument processing was successful. /// The newly retrieved variable. /// The error message, if is . - /// Whether or not the boolean variable was reversed. - public VariableResult(bool success, IConditionVariable variable, string message = "", bool reversed = false) + public VariableResult(bool success, IVariable variable, string message = "") { ProcessorSuccess = success; - Reversed = reversed; Message = message; Variable = variable; } @@ -28,11 +26,6 @@ public VariableResult(bool success, IConditionVariable variable, string message /// public bool ProcessorSuccess { get; } - /// - /// Gets a value indicating whether or not the boolean variable is reversed. - /// - public bool Reversed { get; } - /// /// Gets the error message, if is . /// @@ -41,8 +34,8 @@ public VariableResult(bool success, IConditionVariable variable, string message /// /// Gets the variable. Will be null if variable was not found. /// - public IConditionVariable Variable { get; } + public IVariable Variable { get; } - public string String(Script source = null, bool reversed = false) => Variable.String(source, reversed); + public string String(Script source = null) => Variable.String(source); } } diff --git a/ScriptedEvents/Variables/CustomPlayerVariable.cs b/ScriptedEvents/Variables/CustomPlayerVariable.cs index 576e23cc..d41d75f7 100644 --- a/ScriptedEvents/Variables/CustomPlayerVariable.cs +++ b/ScriptedEvents/Variables/CustomPlayerVariable.cs @@ -1,12 +1,11 @@ namespace ScriptedEvents.Variables { using System.Collections.Generic; - using System.Linq; using Exiled.API.Features; using ScriptedEvents.Variables.Interfaces; - public class CustomPlayerVariable : IFloatVariable, IPlayerVariable + public class CustomPlayerVariable : IPlayerVariable { /// /// Initializes a new instance of the class. @@ -34,9 +33,6 @@ public CustomPlayerVariable(string name, string description, List value) /// public string Description { get; } - /// - public float Value => Players.Where(p => p.IsConnected).Count(); - /// public IEnumerable Players => PlayerList; diff --git a/ScriptedEvents/Variables/CustomVariable.cs b/ScriptedEvents/Variables/CustomVariable.cs index 3059e3a3..59e505b3 100644 --- a/ScriptedEvents/Variables/CustomVariable.cs +++ b/ScriptedEvents/Variables/CustomVariable.cs @@ -2,7 +2,7 @@ { using ScriptedEvents.Variables.Interfaces; - public class CustomVariable : IStringVariable + public class CustomVariable : ILiteralVariable { /// /// Initializes a new instance of the class. diff --git a/ScriptedEvents/Variables/Interfaces/IArgumentVariable.cs b/ScriptedEvents/Variables/Interfaces/IArgumentVariable.cs deleted file mode 100644 index 82c2cc69..00000000 --- a/ScriptedEvents/Variables/Interfaces/IArgumentVariable.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - using ScriptedEvents.Structures; - - /// - /// Represents a variable that supports arguments. - /// - public interface IArgumentVariable - { - /// - /// Gets or sets the variable raw arguments. - /// - public string[] RawArguments { get; set; } - - /// - /// Gets or sets the variable arguments. - /// - public object[] Arguments { get; set; } - - /// - /// Gets the expected arguments. - /// - public Argument[] ExpectedArguments { get; } - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IBoolVariable.cs b/ScriptedEvents/Variables/Interfaces/IBoolVariable.cs deleted file mode 100644 index e7a9008c..00000000 --- a/ScriptedEvents/Variables/Interfaces/IBoolVariable.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a conditional variable that has a boolean result. - /// - public interface IBoolVariable : IConditionVariable - { - /// - /// Gets the variable name that will flip the if used. - /// - public string ReversedName { get; } - - /// - /// Gets a value indicating the boolean value of this variable. - /// -#pragma warning disable SA1623 // Property summary documentation should match accessors - public bool Value { get; } -#pragma warning restore SA1623 // Property summary documentation should match accessors - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IConditionVariable.cs b/ScriptedEvents/Variables/Interfaces/IConditionVariable.cs deleted file mode 100644 index 87d18b4c..00000000 --- a/ScriptedEvents/Variables/Interfaces/IConditionVariable.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a variable that can be used in conditions. - /// - public interface IConditionVariable : IVariable - { - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IFloatVariable.cs b/ScriptedEvents/Variables/Interfaces/IFloatVariable.cs deleted file mode 100644 index 3222c5b7..00000000 --- a/ScriptedEvents/Variables/Interfaces/IFloatVariable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a conditional variable that has a float result. - /// - public interface IFloatVariable : IConditionVariable - { - /// - /// Gets the float value of this variable. - /// - public float Value { get; } - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IHasAliasVariable.cs b/ScriptedEvents/Variables/Interfaces/IHasAliasVariable.cs deleted file mode 100644 index a132e57e..00000000 --- a/ScriptedEvents/Variables/Interfaces/IHasAliasVariable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a variable with an alias. - /// - public interface IHasAliasVariable : IConditionVariable - { - /// - /// Gets the variable alias. - /// - public string Alias { get; } - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IItemVariable.cs b/ScriptedEvents/Variables/Interfaces/IItemVariable.cs deleted file mode 100644 index 0956197e..00000000 --- a/ScriptedEvents/Variables/Interfaces/IItemVariable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a conditional variable that has a boolean result. - /// - public interface IItemVariable : IConditionVariable - { - /// - /// Gets XXXX. - /// - public ushort Value { get; } - } -} diff --git a/ScriptedEvents/Variables/Interfaces/IStringVariable.cs b/ScriptedEvents/Variables/Interfaces/ILiteralVariable.cs similarity index 81% rename from ScriptedEvents/Variables/Interfaces/IStringVariable.cs rename to ScriptedEvents/Variables/Interfaces/ILiteralVariable.cs index 75e1252a..a0eb1931 100644 --- a/ScriptedEvents/Variables/Interfaces/IStringVariable.cs +++ b/ScriptedEvents/Variables/Interfaces/ILiteralVariable.cs @@ -1,13 +1,13 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a conditional variable that has a string result. - /// - public interface IStringVariable : IConditionVariable - { - /// - /// Gets the string value of this variable. - /// - public string Value { get; } - } -} +namespace ScriptedEvents.Variables.Interfaces +{ + /// + /// Represents a conditional variable that has a string result. + /// + public interface ILiteralVariable : IVariable + { + /// + /// Gets the string value of this variable. + /// + public string Value { get; } + } +} diff --git a/ScriptedEvents/Variables/Interfaces/ILongVariable.cs b/ScriptedEvents/Variables/Interfaces/ILongVariable.cs deleted file mode 100644 index 1c3e0c32..00000000 --- a/ScriptedEvents/Variables/Interfaces/ILongVariable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Represents a conditional variable that has a float result. - /// - public interface ILongVariable : IConditionVariable - { - /// - /// Gets the long value of this variable. - /// - public long Value { get; } - } -} diff --git a/ScriptedEvents/Variables/Interfaces/INeedSourceVariable.cs b/ScriptedEvents/Variables/Interfaces/INeedSourceVariable.cs deleted file mode 100644 index 02f7fef6..00000000 --- a/ScriptedEvents/Variables/Interfaces/INeedSourceVariable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ScriptedEvents.Variables.Interfaces -{ - /// - /// Indicates a variable that requests its script source to be stored as a property of the variable. - /// - public interface INeedSourceVariable - { - /// - /// Gets or sets the source that is executing this variable. - /// - public Script Source { get; set; } - } -} diff --git a/ScriptedEvents/Variables/PlayerCountVariables.cs b/ScriptedEvents/Variables/PlayerCountVariables.cs index 4d63e830..61d3454f 100644 --- a/ScriptedEvents/Variables/PlayerCountVariables.cs +++ b/ScriptedEvents/Variables/PlayerCountVariables.cs @@ -5,7 +5,6 @@ using System.Linq; using Exiled.API.Features; - using Exiled.API.Features.Roles; using ScriptedEvents.Variables.Interfaces; public class PlayerCountVariables : IVariableGroup @@ -19,171 +18,81 @@ public class PlayerCountVariables : IVariableGroup new AllPlayers(), new AllNpcs(), new PlayersAlive(), - new PlayersDead(), new Humans(), new Staff(), new NonePlayer(), - new Scp096Targets(), - new Scp173Observers(), }; } - public class AllPlayers : IFloatVariable, IPlayerVariable + public class AllPlayers : IPlayerVariable { /// - public string Name => "{PLAYERS}"; + public string Name => "@PLAYERS"; /// - public string Description => "The amount of players in the server."; - - /// - public float Value => Players.Count(); + public string Description => "Returns all players on the server."; /// public IEnumerable Players => Player.List; } - public class AllNpcs : IFloatVariable, IPlayerVariable + public class AllNpcs : IPlayerVariable { /// - public string Name => "{NPCS}"; - - /// - public string Description => "The amount of NPCs in the server."; + public string Name => "@NPCS"; /// - public float Value => Players.Count(); + public string Description => "Returns all NPCs on the server."; /// public IEnumerable Players => Npc.List; } - public class PlayersAlive : IFloatVariable, IPlayerVariable + public class PlayersAlive : IPlayerVariable { /// - public string Name => "{PLAYERSALIVE}"; - - /// - public string Description => "The amount of alive players in the server."; + public string Name => "@PLAYERSALIVE"; /// - public float Value => Players.Count(); + public string Description => "Returns all alive players on the server."; /// public IEnumerable Players => Player.List.Where(p => p.IsAlive); } - public class PlayersDead : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{PLAYERSDEAD}"; - - /// - public string Description => "The amount of dead players in the server."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players => Player.List.Where(p => p.IsDead); - } - - public class Humans : IFloatVariable, IPlayerVariable + public class Humans : IPlayerVariable { /// - public string Name => "{HUMANS}"; + public string Name => "@HUMANS"; /// - public string Description => "The amount of humans that are currently alive."; - - /// - public float Value => Players.Count(); + public string Description => "Returns all humans that are currently alive (humans as in a human role, not not NPCs)."; /// public IEnumerable Players => Player.List.Where(p => p.IsHuman); } - public class Staff : IFloatVariable, IPlayerVariable + public class Staff : IPlayerVariable { /// - public string Name => "{SERVERSTAFF}"; - - /// - public string Description => "The amount of staff on the server (RA access)"; + public string Name => "@STAFF"; /// - public float Value => Players.Count(); + public string Description => "Returns all staff on the server (RA access)"; /// public IEnumerable Players => Player.Get(player => player.RemoteAdminAccess); } - public class NonePlayer : IFloatVariable, IPlayerVariable + public class NonePlayer : IPlayerVariable { /// - public string Name => "{NONE}"; - - /// - public string Description => "Will always be an empty variable with no players."; + public string Name => "@NONE"; /// - public float Value => 0; + public string Description => "Returns an empty player variable."; /// public IEnumerable Players => Enumerable.Empty(); } - - public class Scp096Targets : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{SCP096TARGETS}"; - - /// - public string Description => "The amount of players that are being targeted by an SCP-096."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - List list = new(); - foreach (Player ply in Player.Get(PlayerRoles.RoleTypeId.Scp096)) - { - list.AddRange((ply.Role as Scp096Role).Targets); - } - - return list; - } - } - } - - public class Scp173Observers : IFloatVariable, IPlayerVariable - { - /// - public string Name => "{SCP173OBSERVERS}"; - - /// - public string Description => "The amount of players that are looking at SCP-173."; - - /// - public float Value => Players.Count(); - - /// - public IEnumerable Players - { - get - { - List list = new(); - foreach (Player ply in Player.Get(PlayerRoles.RoleTypeId.Scp173)) - { - list.AddRange((ply.Role as Scp173Role).ObservingPlayers); - } - - return list; - } - } - } } diff --git a/ScriptedEvents/Variables/RoleVariables.cs b/ScriptedEvents/Variables/RoleVariables.cs index 51d5b755..84104656 100644 --- a/ScriptedEvents/Variables/RoleVariables.cs +++ b/ScriptedEvents/Variables/RoleVariables.cs @@ -48,112 +48,91 @@ public IVariable[] Variables } } - public class Guards : IFloatVariable, IPlayerVariable + public class Guards : IPlayerVariable { /// - public string Name => "{GUARDS}"; + public string Name => "@GUARDS"; /// - public string Description => "The amount of facility guards alive. Equivalent to {FACILITYGUARD}"; - - /// - public float Value => Players.Count(); + public string Description => "Returns players playing as facility guards. Equivalent to @FACILITYGUARDS"; /// public IEnumerable Players => Player.Get(RoleTypeId.FacilityGuard); } - public class MtfAndGuards : IFloatVariable, IPlayerVariable + public class MtfAndGuards : IPlayerVariable { /// - public string Name => "{MTFANDGUARDS}"; - - /// - public string Description => "The amount of facility guards & MTF alive."; + public string Name => "@MTFANDGUARDS"; /// - public float Value => Players.Count(); + public string Description => "Returns players playing as facility guards & MTF."; /// public IEnumerable Players => Player.Get(Team.FoundationForces); } - public class Scps : IFloatVariable, IPlayerVariable + public class Scps : IPlayerVariable { /// - public string Name => "{SCPS}"; + public string Name => "@SCPS"; /// - public string Description => "The amount of SCPs alive."; - - /// - public float Value => Players.Count(); + public string Description => "Returns players playing as SCPs."; /// public IEnumerable Players => Player.Get(Team.SCPs); } - public class Mtf : IFloatVariable, IPlayerVariable + public class Mtf : IPlayerVariable { /// - public string Name => "{MTF}"; + public string Name => "@MTF"; /// - public string Description => "The amount of MTF alive."; - - /// - public float Value => Players.Count(); + public string Description => "Returns players playing as MTF."; /// public IEnumerable Players => Player.Get(ply => ply.Role.Team is Team.FoundationForces && ply.Role.Type is not RoleTypeId.FacilityGuard); } - public class Chaos : IFloatVariable, IPlayerVariable + public class Chaos : IPlayerVariable { /// - public string Name => "{CI}"; - - /// - public string Description => "The amount of Chaos Insurgency alive."; + public string Name => "@CI"; /// - public float Value => Players.Count(); + public string Description => "Returns players playing as Chaos Insurgency."; /// public IEnumerable Players => Player.Get(Team.ChaosInsurgency); } - public class SerpentsHand : IFloatVariable, IPlayerVariable + public class SerpentsHand : IPlayerVariable { /// - public string Name => "{SH}"; + public string Name => "@SH"; /// - public string Description => "The amount of Serpent's Hand alive (always 0 if the plugin is not installed)."; - - /// - public float Value => Players.Count(); + public string Description => "Returns players playing as the Serpent's Hand (always 0 if the plugin is not installed)."; /// public IEnumerable Players => Player.Get(player => player.SessionVariables.ContainsKey("IsSH")); } - public class UIU : IFloatVariable, IPlayerVariable + public class UIU : IPlayerVariable { /// - public string Name => "{UIU}"; + public string Name => "@UIU"; /// - public string Description => "The amount of UIU alive (always 0 if the plugin is not installed)."; - - /// - public float Value => Players.Count(); + public string Description => "Returns players playing as the UIU squad (always 0 if the plugin is not installed)."; /// public IEnumerable Players => Player.Get(player => player.SessionVariables.ContainsKey("IsUIU")); } - public class RoleTypeVariable : IFloatVariable, IPlayerVariable + public class RoleTypeVariable : IPlayerVariable { public RoleTypeVariable() { @@ -168,13 +147,34 @@ public RoleTypeVariable(RoleTypeId rt) public RoleTypeId RoleType { get; } /// - public string Name => $"{{{RoleType.ToString().ToUpper()}}}"; + public string Name + { + get + { + string role = $"{RoleType.ToString().ToUpper()}"; - /// - public string Description => $"The amount of {RoleType} alive."; + if (role.EndsWith("TCH")) + { + role += "ES"; + } + else if (role.EndsWith("MAN")) + { + role = role.Substring(0, role.Length - 3) + "MEN"; + } + else if (role == "NONE") + { + } + else + { + role += "S"; + } + + return "@" + role; + } + } /// - public float Value => Players.Count(); + public string Description => $"Returns players playing as the '{RoleType}' role."; /// public IEnumerable Players => Player.Get(RoleType); From eb72a4f45dfc51314cbb1642ac38c35008e63a81 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:03:29 +0200 Subject: [PATCH 135/359] LocalSave -> Local --- .../{LocalSaveAction.cs => LocalAction.cs} | 114 ++++++++---------- 1 file changed, 49 insertions(+), 65 deletions(-) rename ScriptedEvents/Actions/Variable/{LocalSaveAction.cs => LocalAction.cs} (64%) diff --git a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs b/ScriptedEvents/Actions/Variable/LocalAction.cs similarity index 64% rename from ScriptedEvents/Actions/Variable/LocalSaveAction.cs rename to ScriptedEvents/Actions/Variable/LocalAction.cs index 018a87ee..0060feaa 100644 --- a/ScriptedEvents/Actions/Variable/LocalSaveAction.cs +++ b/ScriptedEvents/Actions/Variable/LocalAction.cs @@ -1,65 +1,49 @@ -namespace ScriptedEvents.Actions -{ - using System; - - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Interfaces; - using ScriptedEvents.Structures; - - public class LocalSaveAction : IScriptAction, IHelpInfo - { - /// - public string Name => "LOCAL"; - - /// - public string[] Aliases => Array.Empty(); - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public ActionSubgroup Subgroup => ActionSubgroup.Variable; - - /// - public string Description => "Saves a new variable. Saved variables can be used in THIS script only, and are reset when the round ends."; - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("variableName", typeof(string), "The name of the new variable. Braces will be added automatically if not provided.", true), - new Argument("value", typeof(object), "The value to store. Math is supported.", true), - }; - - /// - public ActionResponse Execute(Script script) - { - string varName = RawArguments[0]; - if (Arguments.Length < 2) - { - script.AddVariable(varName, "User-defined variable.", string.Empty); - return new(true); - } - - string input = Arguments.JoinMessage(1); - - try - { - float value = ConditionHelperV2.Math(input); - script.AddVariable(varName, "User-defined variable.", value.ToString()); - return new(true); - } - catch - { - } - - script.AddVariable(varName, "User-defined variable.", input); - - return new(true); - } - } -} +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class LocalAction : IScriptAction, IHelpInfo + { + /// + public string Name => "LOCAL"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Variable; + + /// + public string Description => "Saves a new variable. Saved variables can be used in THIS script only, and are reset when the round ends."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("variableName", typeof(string), "The name of the new variable. The name must have the '@' prefix.", true), + new Argument("value", typeof(object), "The value to store. Math is supported.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + string varName = RawArguments[0]; + string input = Arguments.JoinMessage(1); + input = SEParser.ReplaceContaminatedValueSyntax(input, script); + + script.AddVariable(varName, string.Empty, input); + return new(true); + } + } +} From f82a0ee1b90792ce58c3d61b8d6b8aee6d48fb02 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:04:35 +0200 Subject: [PATCH 136/359] optimize TryProcessSmartArgument, improve Process --- .../API/Features/ArgumentProcessor.cs | 77 ++++++++----------- 1 file changed, 31 insertions(+), 46 deletions(-) diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index 7d78337e..eb4ee779 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Text.RegularExpressions; using Exiled.API.Features; using Exiled.API.Features.Doors; @@ -93,17 +94,17 @@ void Log(string message) success.NewParameters.AddRange(res.NewParameters); } - success.NewParameters.AddRange(args - .Skip(expectedArguments.Length) - .Select( - arg => TryProcessSmartArgument( - arg.ToString(), - action, - source, - out string result, - true) - ? result - : arg)); + success.NewParameters.AddRange(args.Skip(expectedArguments.Length).Select(arg => + { + if (TryProcessSmartArgument(arg, action, source, out string saRes, true)) + { + return saRes; + } + else + { + return SEParser.ReplaceContaminatedValueSyntax(arg, source); + } + }).ToArray()); Log($"Processed action parameters: '{string.Join(", ", success.NewParameters.Select(x => x.ToString()))}'"); @@ -129,45 +130,28 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action return false; } - bool skipAddingTrailingNumber = false; - for (int i = 0; i < input.Length; i++) - { - char c = input[i]; - if (skipAddingTrailingNumber) - { - skipAddingTrailingNumber = false; - continue; - } - - result += c; - - if (c != '#') - { - continue; - } + // Regex pattern to match '#' followed by a digit + Regex regex = new(@"#(\d)"); + result = input; // Start with input as the base result - Logger.Debug($"[SMART ARG PROC] Found '#' syntax at index {i}", source); + var matches = regex.Matches(input); - int lastNum; - try - { - lastNum = (int)char.GetNumericValue(input[i + 1]); - } - catch (IndexOutOfRangeException) - { - continue; - } + foreach (Match match in matches) + { + int index = match.Index; - if (lastNum == -1) + // Try to parse the number after '#' + if (!int.TryParse(match.Groups[1].Value, out int lastNum) || lastNum < 1) { continue; } - Logger.Debug($"[SMART ARG PROC] Found a index '{lastNum}' behind the '#'", source); + Logger.Debug($"[SMART ARG PROC] Found '#' syntax with index '{lastNum}' at position {index}", source); string argument; try { + // Fetch smart argument based on index var res = source.SmartArguments[actualAction][lastNum - 1](); if (!res.Item1) { @@ -189,6 +173,7 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action if (processForVariables) { + // Process variables if necessary argument = SEParser.ReplaceContaminatedValueSyntax(argument, source); if (ConditionHelperV2.TryMath(argument, out MathResult mathRes)) @@ -197,11 +182,10 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action } } - result = result.Substring(0, result.Length - 1); - - result += argument; + // Replace the '#' with the processed argument + result = result.Replace(match.Value, argument); didSomething = true; - skipAddingTrailingNumber = true; + Logger.Debug($"[SMART ARG PROC] Success! Smart arg used correctly. Result: {result}", source); } @@ -220,12 +204,13 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected { void Log(string message) { - Logger.Debug("[ArgumentProcessor] [PIP] " + message, source); + if (!source.Debug) return; + Logger.Debug($"[ArgumentProcessor] [PIP] [{action.Name}] " + message, source); } ArgumentProcessResult success = new(true); - Log($"Parameter '{expected.ArgumentName}' from '{action.Name}' needs a '{expected.Type.Name}'"); + Log($"Parameter '{expected.ArgumentName}' needs a '{expected.Type.Name}' type."); // Extra magic for options if (expected is OptionsArgument options) @@ -409,7 +394,7 @@ void Log(string message) string playerVarNameLoopingThrough = loopArgs[2]; if (inKeyword != "IN") - Logger.Warn($"[$FOR DECORATOR] $FOR statement requires the 'IN' keyword (e.g. $FOR {{PLR}} IN {{PLAYERS}}). Instead of IN, '{inKeyword}' was provided.", source); + Logger.Warn($"[$FOR DECORATOR] $FOR statement requires the 'IN' keyword (e.g. $FOR {{PLR}} IN {{PLAYERS}}). Instead of 'IN', '{inKeyword}' was provided.", source); List playersToLoop; From b6e90c3bdcb45789cb7e856c851ffb3fa16ac38b Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:04:49 +0200 Subject: [PATCH 137/359] optimize IsolateValueSyntax --- ScriptedEvents/API/Features/SEParser.cs | 48 +++++++++++-------------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 336d2836..425b173e 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -327,38 +327,27 @@ void Log(string msg) /// The variables used within the string. public static (Match[] variables, Match[] dynamicActions, Match[] accessors) IsolateValueSyntax(string input, Script source, bool captureVariables = true, bool captureDynActs = true, bool captureAccessors = true) { - void Log(string msg) - { - Logger.Debug($"[SEParser] [IsolateValueSyntax] {msg}", source); - } - - Match[] variables = null; - Match[] dynamicActions = null; - Match[] accessors = null; + var empty = Array.Empty(); + Match[] variables = empty; + Match[] dynamicActions = empty; + Match[] accessors = empty; - Log($"Isolating value syntaxes from: '{input}'"); - - // Add @words pattern if enabled - if (captureVariables) + if (captureVariables && input.Length >= 2) { variables = Regex.Matches(input, @"@\S+").Cast().ToArray(); - Log($"Retreived {variables.Length} variables."); } - // Add {multiple words} pattern if enabled - if (captureDynActs) + if (captureDynActs && input.Length >= 3) { dynamicActions = Regex.Matches(input, @"\{[^{}\s]*\}").Cast().ToArray(); - Log($"Retreived {dynamicActions.Length} dynamic actions."); } - // Add pattern if enabled - if (captureAccessors) + if (captureAccessors && input.Length >= 3) { accessors = Regex.Matches(input, @"<[^<>\s]*>").Cast().ToArray(); - Log($"Retreived {accessors.Length} accessors."); } + Logger.Debug($"[SEParser] [IsolateValueSyntax] From '{input}' retreived: {variables.Length} VARS >< {dynamicActions.Length} DNCTS >< {accessors.Length} ACSRS", source); return (variables, dynamicActions, accessors); } @@ -601,35 +590,40 @@ void Log(string msg) /// Replaces all the occurrences of a value syntax in a string with regular text. /// /// The string to perform the replacements on. - /// The script that is currently running to replace values. + /// The script that is currently running to replace values. /// The modified string. /// This is intended for strings that contain both regular text and value syntax. Otherwise, see . - public static string ReplaceContaminatedValueSyntax(string input, Script source) + public static string ReplaceContaminatedValueSyntax(string input, Script script) { void Log(string msg) { - Logger.Debug($"[SEParser] [RCVS] {msg}", source); + Logger.Debug($"[SEParser] [RCVS] {msg}", script); } - var values = IsolateValueSyntax(input, source); + var values = IsolateValueSyntax(input, script); StringBuilder output = new(input); foreach (Match accssr in values.accessors) { - output.Replace(accssr.Value, "PLACEHOLDER", accssr.Index, accssr.Length); + output.Replace(accssr.Value, "", accssr.Index, accssr.Length); } foreach (Match dynact in values.dynamicActions) { - output.Replace(dynact.Value, "PLACEHOLDER", dynact.Index, dynact.Length); + output.Replace(dynact.Value, "{DYNACT}", dynact.Index, dynact.Length); } foreach (Match varbl in values.variables) { - output.Replace(varbl.Value, "PLACEHOLDER", varbl.Index, varbl.Length); + if (!VariableSystemV2.TryGetVariable(varbl.Value, script, out VariableResult res) || res.Variable is null) + { + continue; + } + + output.Replace(varbl.Value, res.Variable.String(), varbl.Index, varbl.Length); } - return input; + return output.ToString(); } } } \ No newline at end of file From 8cdce121562629ba3753e3d0e676ce7487ecac7d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:04:51 +0200 Subject: [PATCH 138/359] Update Script.cs --- ScriptedEvents/Script.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ScriptedEvents/Script.cs b/ScriptedEvents/Script.cs index 9ea30c66..6baec550 100644 --- a/ScriptedEvents/Script.cs +++ b/ScriptedEvents/Script.cs @@ -170,14 +170,14 @@ public Script() public bool IfActionBlocksExecution { get; set; } = false; /// - /// Gets or sets a of variables that are unique to this script. + /// Gets a of variables that are unique to this script. /// - public Dictionary UniqueVariables { get; set; } + public Dictionary UniqueVariables { get; private set; } /// - /// Gets or sets a of player variables that are unique to this script. + /// Gets a of player variables that are unique to this script. /// - public Dictionary UniquePlayerVariables { get; set; } + public Dictionary UniquePlayerVariables { get; private set; } /// /// Gets a of coroutines run by this script. From e45ec5a2f888b295653dcf460475efc207eba3da Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:04:55 +0200 Subject: [PATCH 139/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index a5d4ea4c..366320bc 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -189,7 +189,7 @@ - + From af71e2a8219f7d8c9136503d811c0cbc5537e6f3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:22:54 +0200 Subject: [PATCH 140/359] IsDebug ad IsDisabled --- ScriptedEvents/API/Extensions/InterfaceExtensions.cs | 6 +++--- ScriptedEvents/API/Features/Logger.cs | 2 +- ScriptedEvents/API/Modules/ScriptModule.cs | 6 +++--- ScriptedEvents/Actions/Misc/HelpAction.cs | 2 +- .../Actions/VariableMimics/ScriptInfo/ThisAction.cs | 2 +- ScriptedEvents/Commands/MainCommand/ReadScript.cs | 2 +- ScriptedEvents/Script.cs | 6 +++--- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ScriptedEvents/API/Extensions/InterfaceExtensions.cs b/ScriptedEvents/API/Extensions/InterfaceExtensions.cs index 76980b53..df9d7859 100644 --- a/ScriptedEvents/API/Extensions/InterfaceExtensions.cs +++ b/ScriptedEvents/API/Extensions/InterfaceExtensions.cs @@ -25,12 +25,12 @@ public static string String(this IVariable variable, Script source = null) } catch (InvalidCastException e) { - Logger.Warn(source?.Debug == true ? e.ToString() : e.Message, source); + Logger.Warn(source?.IsDebug == true ? e.ToString() : e.Message, source); } catch (Exception e) { - Logger.Warn(source?.Debug == true ? e.ToString() : e.Message, source); - return source?.Debug == true ? e.ToString() : e.Message; + Logger.Warn(source?.IsDebug == true ? e.ToString() : e.Message, source); + return source?.IsDebug == true ? e.ToString() : e.Message; } return "ERROR"; diff --git a/ScriptedEvents/API/Features/Logger.cs b/ScriptedEvents/API/Features/Logger.cs index 550bddf8..e721ff4f 100644 --- a/ScriptedEvents/API/Features/Logger.cs +++ b/ScriptedEvents/API/Features/Logger.cs @@ -30,7 +30,7 @@ public static void Log(string message, LogType logType, Script script = null, in LogInternal.Info(message); break; case LogType.Debug: - if (script is not null && script.Debug) + if (script is not null && script.IsDebug) script.DebugLog(message); else LogInternal.Debug(message); diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index d97c1f13..e8f31fe9 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -533,10 +533,10 @@ Tuple ActionWrapper() /// /// The script to run. /// If , the script will be disposed after finishing execution. - /// If is . + /// If is . public void RunScript(Script scr, bool dispose = true) { - if (scr.Disabled) + if (scr.IsDisabled) throw new DisabledScriptException(scr.ScriptName); CoroutineHandle handle = Timing.RunCoroutine(SafeRunCoroutine(RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); @@ -578,7 +578,7 @@ public IEnumerator SafeRunCoroutine(IEnumerator coroutine) /// The executor that is running the script. Can be null. /// Whether to dispose of the script as soon as execution is finished. /// The script was not found. - /// If is . + /// If is . /// The script object. public Script ReadAndRun(string scriptName, ICommandSender executor, bool dispose = true) { diff --git a/ScriptedEvents/Actions/Misc/HelpAction.cs b/ScriptedEvents/Actions/Misc/HelpAction.cs index 41f0bd31..d249452b 100644 --- a/ScriptedEvents/Actions/Misc/HelpAction.cs +++ b/ScriptedEvents/Actions/Misc/HelpAction.cs @@ -378,7 +378,7 @@ Interested in helping others learn the plugin? Let {MainPlugin.Singleton.Author} sb.AppendLine($"=== ERROR CODE ==="); sb.AppendLine($"ID: SE-{info.Id}"); - if (script is not null && script.Debug) + if (script is not null && script.IsDebug) sb.AppendLine($"Internal ID: {info.Code}"); sb.AppendLine(info.Info); diff --git a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs index a3616aef..bc9a518c 100644 --- a/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/ScriptInfo/ThisAction.cs @@ -51,7 +51,7 @@ public ActionResponse Execute(Script script) "AUTORUN" => script.HasFlag("AUTORUN").ToUpper(), "CALLER" => script.CallerScript is not null ? script.CallerScript.ScriptName : "NONE", "CONTEXT" => script.Context.ToString(), - "DEBUG" => script.Debug.ToUpper(), + "DEBUG" => script.IsDebug.ToUpper(), "DURATION" => script.RunDuration.TotalSeconds.ToString(), "NAME" => script.ScriptName, "PATH" => script.FilePath ?? "N/A", diff --git a/ScriptedEvents/Commands/MainCommand/ReadScript.cs b/ScriptedEvents/Commands/MainCommand/ReadScript.cs index f5483904..2010efa3 100644 --- a/ScriptedEvents/Commands/MainCommand/ReadScript.cs +++ b/ScriptedEvents/Commands/MainCommand/ReadScript.cs @@ -61,7 +61,7 @@ public bool Execute(ArraySegment arguments, ICommandSender sender, out s return false; } - if (scr.Disabled) + if (scr.IsDisabled) { Logger.Warn($"Note: The {scr.ScriptName} script is disabled, and cannot be executed until the DISABLE flag is removed. Script contents still shown below."); } diff --git a/ScriptedEvents/Script.cs b/ScriptedEvents/Script.cs index 6baec550..391653e7 100644 --- a/ScriptedEvents/Script.cs +++ b/ScriptedEvents/Script.cs @@ -127,12 +127,12 @@ public Script() /// /// Gets a value indicating whether or not the script is enabled. /// - public bool Disabled => HasFlag("DISABLE"); + public bool IsDisabled => HasFlag("DISABLE"); /// /// Gets a value indicating whether or not the script is running in debug mode. /// - public bool Debug => HasFlag("DEBUG") || MainPlugin.Configs.Debug; + public bool IsDebug => HasFlag("DEBUG") || MainPlugin.Configs.Debug; /// /// Gets a value indicating whether or not the script is marked as an admin-event (CedMod compatibility). @@ -275,7 +275,7 @@ public bool JumpToFunctionLabel(string keyword) /// The input to Logger. public void DebugLog(string input) { - if (Debug) + if (IsDebug) Log.Send($"[{MainPlugin.Singleton.Name}] {input}", LogLevel.Debug, ConsoleColor.Green); } From 9e0747153b9a53f06b861f250e50c7786ccf1b5e Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:23:12 +0200 Subject: [PATCH 141/359] optimize ArgumentProcessor logger --- .../API/Features/ArgumentProcessor.cs | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index eb4ee779..1f6c1c5e 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -27,21 +27,22 @@ public static class ArgumentProcessor /// The expected arguments. /// The provided arguments. /// The action or variable performing the process. - /// The script source. + /// The script source. /// If brackets are required to convert variables. /// The result of the process. - public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script source) + public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script script) { void Log(string message) { - Logger.Debug($"[ArgumentProcessor] [Process] [{action.Name}] {message}", source); + if (!script.IsDebug) return; + Logger.Debug($"[ArgumentProcessor] [Process] [{action.Name}] {message}", script); } if (args != null && args.Length > 0) { Log($"Arguments to process: '{string.Join(", ", args)}'"); - ArgumentProcessResult handledFORResult = HandleFORDecorator(args, source, out string[] strippedArgs); + ArgumentProcessResult handledFORResult = HandleFORDecorator(args, script, out string[] strippedArgs); if (!handledFORResult.Success) { return handledFORResult; @@ -49,7 +50,7 @@ void Log(string message) args = strippedArgs; - ArgumentProcessResult handledIFResult = HandleIFDecorator(args, source, out string[] strippedArgs2); + ArgumentProcessResult handledIFResult = HandleIFDecorator(args, script, out string[] strippedArgs2); if (!handledIFResult.Success) { return handledIFResult; @@ -88,7 +89,7 @@ void Log(string message) Argument argument = expectedArguments[i]; string input = args[i]; - ArgumentProcessResult res = ProcessIndividualParameter(argument, input, action, source); + ArgumentProcessResult res = ProcessIndividualParameter(argument, input, action, script); if (!res.Success) return res; // Throw issue to end-user success.NewParameters.AddRange(res.NewParameters); @@ -96,13 +97,13 @@ void Log(string message) success.NewParameters.AddRange(args.Skip(expectedArguments.Length).Select(arg => { - if (TryProcessSmartArgument(arg, action, source, out string saRes, true)) + if (TryProcessSmartArgument(arg, action, script, out string saRes, true)) { return saRes; } else { - return SEParser.ReplaceContaminatedValueSyntax(arg, source); + return SEParser.ReplaceContaminatedValueSyntax(arg, script); } }).ToArray()); @@ -204,7 +205,7 @@ public static ArgumentProcessResult ProcessIndividualParameter(Argument expected { void Log(string message) { - if (!source.Debug) return; + if (!source.IsDebug) return; Logger.Debug($"[ArgumentProcessor] [PIP] [{action.Name}] " + message, source); } @@ -369,11 +370,12 @@ void Log(string message) return success; } - private static ArgumentProcessResult HandleFORDecorator(string[] inArgs, Script source, out string[] args) + private static ArgumentProcessResult HandleFORDecorator(string[] inArgs, Script script, out string[] args) { void Log(string message) { - Logger.Debug("[ArgumentProcessor] [$FOR] " + message, source); + if (!script.IsDebug) return; + Logger.Debug("[ArgumentProcessor] [$FOR] " + message, script); } args = inArgs; @@ -394,18 +396,18 @@ void Log(string message) string playerVarNameLoopingThrough = loopArgs[2]; if (inKeyword != "IN") - Logger.Warn($"[$FOR DECORATOR] $FOR statement requires the 'IN' keyword (e.g. $FOR {{PLR}} IN {{PLAYERS}}). Instead of 'IN', '{inKeyword}' was provided.", source); + Logger.Warn($"[$FOR DECORATOR] $FOR statement requires the 'IN' keyword (e.g. $FOR {{PLR}} IN {{PLAYERS}}). Instead of 'IN', '{inKeyword}' was provided.", script); List playersToLoop; - if (source.PlayerLoopInfo is not null && source.PlayerLoopInfo.Line == source.CurrentLine) + if (script.PlayerLoopInfo is not null && script.PlayerLoopInfo.Line == script.CurrentLine) { - playersToLoop = source.PlayerLoopInfo.PlayersToLoopThrough; + playersToLoop = script.PlayerLoopInfo.PlayersToLoopThrough; Log("A loop for this action has already been initialized."); } else { - if (!SEParser.TryGetPlayers(playerVarNameLoopingThrough, null, out PlayerCollection outPlayers, source)) + if (!SEParser.TryGetPlayers(playerVarNameLoopingThrough, null, out PlayerCollection outPlayers, script)) { return new(false, true, ErrorGenV2.InvalidPlayerVariable(playerVarNameLoopingThrough)); } @@ -417,27 +419,28 @@ void Log(string message) if (playersToLoop.Count == 0) { Log("No more players to loop through. Action will be skipped."); - source.PlayerLoopInfo = null; + script.PlayerLoopInfo = null; return new(false); } Player player = playersToLoop.FirstOrDefault(); playersToLoop.Remove(player); - source.AddPlayerVariable(newPlayerVarName, string.Empty, new[] { player }); + script.AddPlayerVariable(newPlayerVarName, string.Empty, new[] { player }); - source.PlayerLoopInfo = new(source.CurrentLine, playersToLoop); + script.PlayerLoopInfo = new(script.CurrentLine, playersToLoop); - source.Jump(source.CurrentLine); + script.Jump(script.CurrentLine); return new(true); } - private static ArgumentProcessResult HandleIFDecorator(string[] inArgs, Script source, out string[] outArgs) + private static ArgumentProcessResult HandleIFDecorator(string[] inArgs, Script script, out string[] outArgs) { void Log(string message) { - Logger.Debug("[ArgumentProcessor] [$IF] " + message, source); + if (!script.IsDebug) return; + Logger.Debug("[ArgumentProcessor] [$IF] " + message, script); } outArgs = inArgs; @@ -453,7 +456,7 @@ void Log(string message) string[] conditionArgs = inArgs.Skip(conditionSectionKeyword + 1).ToArray(); outArgs = outArgs.Take(conditionSectionKeyword).ToArray(); - ConditionResponse resp = ConditionHelperV2.Evaluate(string.Join(" ", conditionArgs), source); + ConditionResponse resp = ConditionHelperV2.Evaluate(string.Join(" ", conditionArgs), script); if (!resp.Success) { From eebf0b2049b5ad38aa1ac8f6310aeea05872818d Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:27:01 +0200 Subject: [PATCH 142/359] optimize log system for VariableSystemV2 --- .../API/Modules/VariableSystemV2.cs | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/ScriptedEvents/API/Modules/VariableSystemV2.cs b/ScriptedEvents/API/Modules/VariableSystemV2.cs index 06e797d8..d6a3f254 100644 --- a/ScriptedEvents/API/Modules/VariableSystemV2.cs +++ b/ScriptedEvents/API/Modules/VariableSystemV2.cs @@ -113,11 +113,12 @@ public static void ClearVariables() DefinedPlayerVariables.Clear(); } - public static VariableResult InternalGetVariable(string initName, Script source) + public static VariableResult InternalGetVariable(string initName, Script script) { void Log(string message) { - DebugLog("[VariableSystem] [InternalGetVariable] " + message, source); + if (!script.IsDebug) return; + DebugLog("[InternalGetVariable] " + message, script); } string name = initName.ToUpper(); @@ -148,13 +149,13 @@ void Log(string message) return new(true, customPlayerValue); } - if (source.UniqueVariables.TryGetValue(name, out CustomVariable uniqueValue)) + if (script.UniqueVariables.TryGetValue(name, out CustomVariable uniqueValue)) { Log($"Variable {initName} is a local literal variable."); return new(true, uniqueValue); } - if (source.UniquePlayerVariables.TryGetValue(name, out CustomPlayerVariable uniquePlayerValue)) + if (script.UniquePlayerVariables.TryGetValue(name, out CustomPlayerVariable uniquePlayerValue)) { Log($"Variable {initName} is a local player variable."); return new(true, uniquePlayerValue); @@ -173,13 +174,14 @@ public static VariableResult InternalGetDynamicVariable(string initName, Script /// Gets a variable. /// /// The input string. - /// The script source. + /// The script source. /// A tuple containing the variable and whether or not it's a reversed boolean value. - public static VariableResult GetVariable(string name, Script source) + public static VariableResult GetVariable(string name, Script script) { void Log(string message) { - DebugLog("[GetVariable] " + message, source); + if (!script.IsDebug) return; + DebugLog("[GetVariable] " + message, script); } Log($"Getting the '{name}' variable."); @@ -187,7 +189,7 @@ void Log(string message) if (name.StartsWith("@")) { Log($"'{name}' is a standard variable since '@' is the first token."); - return InternalGetVariable(name, source); + return InternalGetVariable(name, script); } else if (name.CountOccurrences('{') + name.CountOccurrences('}') == 0) { @@ -229,31 +231,38 @@ public static bool TryGetVariable(string name, Script source, out VariableResult /// Attempts to get a of s based on the input variable. /// /// The variable. - /// The source script. + /// The source script. /// The players found. If the operation was not successful, this will contain the error reason. /// If brackets are required to parse variables. /// Whether or not players were found. /// This should be used for variables where is . Otherwise, use . /// - public static bool TryGetPlayers(string name, Script source, out PlayerCollection players, bool requireBrackets = true) + public static bool TryGetPlayers(string name, Script script, out PlayerCollection players, bool requireBrackets = true) { - DebugLog($"[TryGetPlayers] Trying to fetch {name} variable. [requireBrackets {requireBrackets}]", source); - if (TryGetVariable(name, source, out VariableResult result, requireBrackets) && result.ProcessorSuccess) + void Log(string msg) + { + if (!script.IsDebug) return; + DebugLog("[TryGetPlayers] " + msg, script); + } + + Log($"Trying to fetch {name} variable. [requireBrackets {requireBrackets}]"); + + if (TryGetVariable(name, script, out VariableResult result, requireBrackets) && result.ProcessorSuccess) { if (result.Variable is IPlayerVariable plrVariable) { players = new(plrVariable.Players.ToList()); - DebugLog($"[TryGetPlayers] Fetch was successful!", source); + Log($"Fetch was successful!"); return true; } else { - DebugLog($"[TryGetPlayers] Fetch was unsuccessful! Variable fetched is not a player variable.", source); + Log($"Fetch was unsuccessful! Variable fetched is not a player variable."); } } else { - DebugLog($"[TryGetPlayers] Fetch was unsuccessful! {result.Message}", source); + Log($"Fetch was unsuccessful! {result.Message}"); } players = new(null, false, result?.Message ?? "Invalid variable provided."); From c45d77759b166235f387a2dd8e4331ec0f4b3d12 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:44:11 +0200 Subject: [PATCH 143/359] rename LOCAL to SAVE --- .../Variable/{LocalAction.cs => SaveAction.cs} | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) rename ScriptedEvents/Actions/Variable/{LocalAction.cs => SaveAction.cs} (55%) diff --git a/ScriptedEvents/Actions/Variable/LocalAction.cs b/ScriptedEvents/Actions/Variable/SaveAction.cs similarity index 55% rename from ScriptedEvents/Actions/Variable/LocalAction.cs rename to ScriptedEvents/Actions/Variable/SaveAction.cs index 0060feaa..093be9fb 100644 --- a/ScriptedEvents/Actions/Variable/LocalAction.cs +++ b/ScriptedEvents/Actions/Variable/SaveAction.cs @@ -4,14 +4,13 @@ using ScriptedEvents.API.Enums; using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; using ScriptedEvents.API.Interfaces; using ScriptedEvents.Structures; - public class LocalAction : IScriptAction, IHelpInfo + public class SaveAction : IScriptAction, IHelpInfo, IReturnValueAction { /// - public string Name => "LOCAL"; + public string Name => "SAVE"; /// public string[] Aliases => Array.Empty(); @@ -26,24 +25,20 @@ public class LocalAction : IScriptAction, IHelpInfo public ActionSubgroup Subgroup => ActionSubgroup.Variable; /// - public string Description => "Saves a new variable. Saved variables can be used in THIS script only, and are reset when the round ends."; + public string Description => "Returns the value that was provided, but in a variable form."; /// public Argument[] ExpectedArguments => new[] { - new Argument("variableName", typeof(string), "The name of the new variable. The name must have the '@' prefix.", true), - new Argument("value", typeof(object), "The value to store. Math is supported.", true), + new Argument("value", typeof(object), "The value to store.", true), }; /// public ActionResponse Execute(Script script) { - string varName = RawArguments[0]; - string input = Arguments.JoinMessage(1); - input = SEParser.ReplaceContaminatedValueSyntax(input, script); + string input = Arguments.JoinMessage(); - script.AddVariable(varName, string.Empty, input); - return new(true); + return new(true, variablesToRet: new[] { input }); } } } From b9e0ac602695cd1d28c4bebbe682622e1e8c3d01 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:44:18 +0200 Subject: [PATCH 144/359] remove TEMP --- .../Actions/Variable/TempVariableAction.cs | 62 ------------------- 1 file changed, 62 deletions(-) delete mode 100644 ScriptedEvents/Actions/Variable/TempVariableAction.cs diff --git a/ScriptedEvents/Actions/Variable/TempVariableAction.cs b/ScriptedEvents/Actions/Variable/TempVariableAction.cs deleted file mode 100644 index cd709b2f..00000000 --- a/ScriptedEvents/Actions/Variable/TempVariableAction.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace ScriptedEvents.Actions -{ - using System; - - using ScriptedEvents.API.Enums; - using ScriptedEvents.API.Extensions; - using ScriptedEvents.API.Features; - using ScriptedEvents.API.Interfaces; - using ScriptedEvents.API.Modules; - using ScriptedEvents.Structures; - - public class TempVariableAction : IScriptAction, IHelpInfo - { - /// - public string Name => "TEMP"; - - /// - public string[] Aliases => Array.Empty(); - - /// - public string[] RawArguments { get; set; } - - /// - public object[] Arguments { get; set; } - - /// - public ActionSubgroup Subgroup => ActionSubgroup.Variable; - - /// - public string Description => "Saves a new variable with a name of '{@}'. If a provided argument is ONLY a player variable, then it will be copied. Else it will saved as a literal variable and math operations will be performed."; - - /// - public Argument[] ExpectedArguments => new[] - { - new Argument("value", typeof(object), "The value to store. Can be a player variable. Math is supported (when applicable).", true), - }; - - /// - public ActionResponse Execute(Script script) - { - if (VariableSystemV2.TryGetPlayers(RawArguments[0], script, out PlayerCollection players, true) && RawArguments.Length == 1) - { - script.AddPlayerVariable("{@}", string.Empty, players.GetInnerList()); - return new(true); - } - - string input = Arguments.JoinMessage().Replace("\\n", "\n"); - - try - { - float value = ConditionHelperV2.Math(input); - script.AddVariable("{@}", string.Empty, value.ToString()); - return new(true); - } - catch - { - script.AddVariable("{@}", string.Empty, input); - return new(true); - } - } - } -} \ No newline at end of file From 8bb7d1f61783f52420d6dbb078409b092b15893a Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:44:28 +0200 Subject: [PATCH 145/359] fix override bug --- ScriptedEvents/API/Modules/ScriptModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index e8f31fe9..ff4c85db 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -904,7 +904,7 @@ void Log(string message) case string strVar: Log($"Action {action.Name} is adding a variable as '{zipped.name}'."); - scr.UniqueVariables.Add(zipped.name, new(zipped.name, string.Empty, strVar)); + scr.AddVariable(zipped.name, string.Empty, strVar); break; default: From b7df5ed4a8d8e65911158b8a922b8601d26e0ac8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 20:44:31 +0200 Subject: [PATCH 146/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index 366320bc..b1116e8e 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -189,8 +189,7 @@ - - + From 6df82618225af7e27925ebc6a7029ac460416cc3 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 21:53:32 +0200 Subject: [PATCH 147/359] add EVAL action --- ScriptedEvents/Actions/Variable/EvalAction.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 ScriptedEvents/Actions/Variable/EvalAction.cs diff --git a/ScriptedEvents/Actions/Variable/EvalAction.cs b/ScriptedEvents/Actions/Variable/EvalAction.cs new file mode 100644 index 00000000..4a1e3ce8 --- /dev/null +++ b/ScriptedEvents/Actions/Variable/EvalAction.cs @@ -0,0 +1,51 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Features; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + public class EvalAction : IScriptAction, IHelpInfo, IReturnValueAction + { + /// + public string Name => "EVAL"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Variable; + + /// + public string Description => "Returns an evaluated value that was provided (does math and boolean algebra if applicable)."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("value", typeof(object), "The value to store.", true), + }; + + /// + public ActionResponse Execute(Script script) + { + string input = Arguments.JoinMessage(); + input = SEParser.ReplaceContaminatedValueSyntax(input, script); + + if (ConditionHelperV2.TryMath(input, out var condition)) + { + return new(true, variablesToRet: new[] { condition.Result.ToUpper() }); + } + + return new(true, variablesToRet: new[] { input }); + } + } +} From e801e99724dea39e683d30fe5b6d613c732ead96 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 21:53:40 +0200 Subject: [PATCH 148/359] Update ArgumentProcessor.cs --- ScriptedEvents/API/Features/ArgumentProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index 1f6c1c5e..afa5362b 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -467,7 +467,7 @@ void Log(string message) if (!resp.Passed) { Log("Evaluation resulted in FALSE. Action will be skipped."); - return new(false); + return new(false, false); } Log($"Evaluation resulted in TRUE. Continuing..."); From 67ef8b3d93f43b16c57189809af547d397ad84a0 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 21:53:48 +0200 Subject: [PATCH 149/359] fix null reference --- ScriptedEvents/API/Modules/ScriptModule.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index ff4c85db..b7464248 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -539,7 +539,7 @@ public void RunScript(Script scr, bool dispose = true) if (scr.IsDisabled) throw new DisabledScriptException(scr.ScriptName); - CoroutineHandle handle = Timing.RunCoroutine(SafeRunCoroutine(RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); + CoroutineHandle handle = Timing.RunCoroutine((RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); RunningScripts.Add(scr, handle); } @@ -771,7 +771,7 @@ void Log(string message) if (!res.Success) { - Log("Action will not be ran. " + actResp.Message != null ? actResp.Message : string.Empty); + Log("Action will not be ran. " + res.Message != null ? res.Message : string.Empty); return true; } @@ -857,6 +857,11 @@ void Log(string message) continue; } + if (delay.HasValue) + { + yield return delay.Value; + } + if (resp == null) { continue; From 130b33ee333786f359fb7ec0b21bdfea2bd6d436 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 21:53:51 +0200 Subject: [PATCH 150/359] Update ScriptedEvents.csproj --- ScriptedEvents/ScriptedEvents.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/ScriptedEvents/ScriptedEvents.csproj b/ScriptedEvents/ScriptedEvents.csproj index b1116e8e..5433cfa9 100644 --- a/ScriptedEvents/ScriptedEvents.csproj +++ b/ScriptedEvents/ScriptedEvents.csproj @@ -187,6 +187,7 @@ + From 53734097ac0155b62aa8f792d900e0c8348cc3d8 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Mon, 30 Sep 2024 21:54:12 +0200 Subject: [PATCH 151/359] Update ScriptModule.cs --- ScriptedEvents/API/Modules/ScriptModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/API/Modules/ScriptModule.cs b/ScriptedEvents/API/Modules/ScriptModule.cs index b7464248..e7f770d8 100644 --- a/ScriptedEvents/API/Modules/ScriptModule.cs +++ b/ScriptedEvents/API/Modules/ScriptModule.cs @@ -539,7 +539,7 @@ public void RunScript(Script scr, bool dispose = true) if (scr.IsDisabled) throw new DisabledScriptException(scr.ScriptName); - CoroutineHandle handle = Timing.RunCoroutine((RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); + CoroutineHandle handle = Timing.RunCoroutine(SafeRunCoroutine(RunScriptInternal(scr, dispose)), $"SCRIPT_{scr.UniqueId}"); RunningScripts.Add(scr, handle); } From 21d94f28cd26ce04d5f1ada30340a4fc51326776 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:08:12 +0200 Subject: [PATCH 152/359] EVAL condition num to string bool representation --- ScriptedEvents/Actions/Variable/EvalAction.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/Actions/Variable/EvalAction.cs b/ScriptedEvents/Actions/Variable/EvalAction.cs index 4a1e3ce8..fc3cb31e 100644 --- a/ScriptedEvents/Actions/Variable/EvalAction.cs +++ b/ScriptedEvents/Actions/Variable/EvalAction.cs @@ -40,9 +40,9 @@ public ActionResponse Execute(Script script) string input = Arguments.JoinMessage(); input = SEParser.ReplaceContaminatedValueSyntax(input, script); - if (ConditionHelperV2.TryMath(input, out var condition)) + if (ConditionHelperV2.TryMath(input, out var res)) { - return new(true, variablesToRet: new[] { condition.Result.ToUpper() }); + return new(true, variablesToRet: new[] { res.Result == 1f ? "TRUE" : "FALSE" }); } return new(true, variablesToRet: new[] { input }); From c1959336472b4794aad6a27dabbbef777595bfe7 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:08:27 +0200 Subject: [PATCH 153/359] DISPLAYPLR -> DISPLAY --- .../Actions/VariableMimics/Misc/DisplayPlayerAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs index c9358f5a..3d9fa4c7 100644 --- a/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs +++ b/ScriptedEvents/Actions/VariableMimics/Misc/DisplayPlayerAction.cs @@ -11,7 +11,7 @@ public class DisplayPlayerAction : IScriptAction, IHelpInfo, IMimicsVariableAction { /// - public string Name => "DISPLAYPLR"; + public string Name => "DISPLAY"; /// public string[] Aliases => Array.Empty(); From 9eaaaa0b4f74f9bbf9bdabef2e63ff2edcfa96cb Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:08:32 +0200 Subject: [PATCH 154/359] add LEN action --- .../VariableMimics/Misc/PlayerLenAction.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 ScriptedEvents/Actions/VariableMimics/Misc/PlayerLenAction.cs diff --git a/ScriptedEvents/Actions/VariableMimics/Misc/PlayerLenAction.cs b/ScriptedEvents/Actions/VariableMimics/Misc/PlayerLenAction.cs new file mode 100644 index 00000000..8e1d1ac0 --- /dev/null +++ b/ScriptedEvents/Actions/VariableMimics/Misc/PlayerLenAction.cs @@ -0,0 +1,39 @@ +namespace ScriptedEvents.Actions +{ + using System; + + using ScriptedEvents.API.Enums; + using ScriptedEvents.API.Interfaces; + using ScriptedEvents.Structures; + + /// + public class PlayerLenAction : IScriptAction, IHelpInfo, IMimicsVariableAction + { + /// + public string Name => "LEN"; + + /// + public string[] Aliases => Array.Empty(); + + /// + public string[] RawArguments { get; set; } + + /// + public object[] Arguments { get; set; } + + /// + public ActionSubgroup Subgroup => ActionSubgroup.Misc; + + /// + public string Description => "Returns a number saying how many players are contained inside the specified variable."; + + /// + public Argument[] ExpectedArguments => new[] + { + new Argument("players", typeof(PlayerCollection), "The players.", true), + }; + + /// + public ActionResponse Execute(Script script) => new(true, variablesToRet: new[] { ((PlayerCollection)Arguments[0]).Length.ToString() }); + } +} \ No newline at end of file From 90a29cb9c1c45808b720c1ecd841261161493716 Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:08:55 +0200 Subject: [PATCH 155/359] add processForDecorators param --- .../API/Features/ArgumentProcessor.cs | 26 +++++++------------ 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/ScriptedEvents/API/Features/ArgumentProcessor.cs b/ScriptedEvents/API/Features/ArgumentProcessor.cs index afa5362b..d8f96b4c 100644 --- a/ScriptedEvents/API/Features/ArgumentProcessor.cs +++ b/ScriptedEvents/API/Features/ArgumentProcessor.cs @@ -30,7 +30,7 @@ public static class ArgumentProcessor /// The script source. /// If brackets are required to convert variables. /// The result of the process. - public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script script) + public static ArgumentProcessResult Process(Argument[] expectedArguments, string[] args, IScriptComponent action, Script script, bool processForDecorators = true) { void Log(string message) { @@ -38,7 +38,7 @@ void Log(string message) Logger.Debug($"[ArgumentProcessor] [Process] [{action.Name}] {message}", script); } - if (args != null && args.Length > 0) + if (args != null && args.Length > 0 && processForDecorators) { Log($"Arguments to process: '{string.Join(", ", args)}'"); @@ -58,6 +58,10 @@ void Log(string message) args = strippedArgs2; } + else if (!processForDecorators) + { + Log("Action is not supposed to have decorators."); + } else { Log("No arguments were provided."); @@ -97,7 +101,7 @@ void Log(string message) success.NewParameters.AddRange(args.Skip(expectedArguments.Length).Select(arg => { - if (TryProcessSmartArgument(arg, action, script, out string saRes, true)) + if (TryProcessSmartArgument(arg, action, script, out string saRes)) { return saRes; } @@ -119,9 +123,8 @@ void Log(string message) /// The action or variable performing the process. /// The script source. /// The resulting string. Empty if method returns false. - /// TShould fetched values from smart params be processed. /// The output of the process. - public static bool TryProcessSmartArgument(string input, IScriptComponent action, Script source, out string result, bool processForVariables) + public static bool TryProcessSmartArgument(string input, IScriptComponent action, Script source, out string result) { result = string.Empty; bool didSomething = false; @@ -172,17 +175,6 @@ public static bool TryProcessSmartArgument(string input, IScriptComponent action Logger.Debug($"[SMART ARG PROC] Index '{lastNum}' is valid", source); - if (processForVariables) - { - // Process variables if necessary - argument = SEParser.ReplaceContaminatedValueSyntax(argument, source); - - if (ConditionHelperV2.TryMath(argument, out MathResult mathRes)) - { - argument = mathRes.Result.ToString(); - } - } - // Replace the '#' with the processed argument result = result.Replace(match.Value, argument); didSomething = true; @@ -239,7 +231,7 @@ void Log(string message) } // smart action arguments - if (TryProcessSmartArgument(input, action, source, out string saResult, true)) + if (TryProcessSmartArgument(input, action, source, out string saResult)) { input = saResult; } From a200fc79e32ae020f5ec8623f35493407f790afc Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:09:11 +0200 Subject: [PATCH 156/359] add TryGetDynamicAction to SEParser --- ScriptedEvents/API/Features/SEParser.cs | 94 ++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/ScriptedEvents/API/Features/SEParser.cs b/ScriptedEvents/API/Features/SEParser.cs index 425b173e..2f68ec99 100644 --- a/ScriptedEvents/API/Features/SEParser.cs +++ b/ScriptedEvents/API/Features/SEParser.cs @@ -14,6 +14,7 @@ using Exiled.CustomItems.API.Features; using PlayerRoles; using ScriptedEvents.API.Extensions; + using ScriptedEvents.API.Interfaces; using ScriptedEvents.API.Modules; using ScriptedEvents.Structures; @@ -351,6 +352,85 @@ public static (Match[] variables, Match[] dynamicActions, Match[] accessors) Iso return (variables, dynamicActions, accessors); } + public static bool TryGetDynamicAction(string input, Script script, out T output) + { + if (typeof(T) != typeof(string) && typeof(T) != typeof(Player[])) + { + throw new ArgumentException(typeof(T).FullName); + } + + // "{LIMIT:@PLAYERS:2}" + input = input.Trim(); + output = default; + + if (!input.StartsWith("{") || !input.EndsWith("}")) + { + return false; + } + + // "LIMIT:@PLAYERS:2 + input = input.Substring(1, input.Length - 1); + + // ["LIMIT", "@PLAYERS", "2"] + string[] parts = input.Split(new[] { ':' }); + + // "LIMIT" + string actionName = parts[0]; + + // ["@PLAYERS", "2"] + string[] arguments = parts.Skip(1).ToArray(); + + if (!MainPlugin.ScriptModule.TryGetActionType(actionName, out Type actionType1)) + { + return false; + } + + IAction actionToExtract = Activator.CreateInstance(actionType1) as IAction; + + if (actionToExtract is ITimingAction) + { + // Logger.Log($"{actionToExtract.Name} is a timing action, which cannot be used with smart extractors.", LogType.Warning, script, currentline + 1); + return false; + } + + if (actionToExtract is not IReturnValueAction) + { + // Logger.Log($"{actionToExtract.Name} action does not return any values, therefore can't be used with smart accessors.", LogType.Warning, script, currentline + 1); + return false; + } + + if (!ScriptModule.TryRunAction(script, actionToExtract, out ActionResponse resp, out float? _, arguments)) + { + return false; + } + + if (resp == null || resp.ResponseVariables.Length == 0) + { + return false; + } + + if (resp.ResponseVariables.Length > 1) + { + // Log("Action returned more than 1 value. Using the first one as default."); + } + + object value = resp.ResponseVariables[0]; + + if (value is not string) + { + return false; + } + + output = value switch + { + string s => (T)(object)s, + Player[] players => (T)(object)players, + _ => throw new InvalidOperationException("Unsupported type") + }; + + return true; + } + public static bool TryGetAccessor(string input, Script source, out string result) { void Log(string msg) @@ -605,12 +685,22 @@ void Log(string msg) foreach (Match accssr in values.accessors) { - output.Replace(accssr.Value, "", accssr.Index, accssr.Length); + if (!TryGetAccessor(accssr.Value, script, out string res)) + { + continue; + } + + output.Replace(accssr.Value, res, accssr.Index, accssr.Length); } foreach (Match dynact in values.dynamicActions) { - output.Replace(dynact.Value, "{DYNACT}", dynact.Index, dynact.Length); + if (!TryGetDynamicAction(dynact.Value, script, out string res)) + { + continue; + } + + output.Replace(dynact.Value, res, dynact.Index, dynact.Length); } foreach (Match varbl in values.variables) From 1646756aa6712300365b4962eb5f579ffff7b3aa Mon Sep 17 00:00:00 2001 From: andrzejki Date: Tue, 1 Oct 2024 21:10:16 +0200 Subject: [PATCH 157/359] make scripts scan only once on startup --- .../API/Modules/EventScriptModule.cs | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/ScriptedEvents/API/Modules/EventScriptModule.cs b/ScriptedEvents/API/Modules/EventScriptModule.cs index 80c6067b..d650ef29 100644 --- a/ScriptedEvents/API/Modules/EventScriptModule.cs +++ b/ScriptedEvents/API/Modules/EventScriptModule.cs @@ -85,7 +85,15 @@ public void BeginConnections() CurrentEventData = new(); CurrentCustomEventData = new(); - foreach (Script scr in MainPlugin.ScriptModule.ListScripts()) + var scripts = MainPlugin.ScriptModule.ListScripts(); + RegisterEventScripts(scripts); + MainPlugin.ScriptModule.RegisterAutorunScripts(scripts); + foreach (var script in scripts) script.Dispose(); + } + + public void RegisterEventScripts(List