Skip to content

Commit

Permalink
feat: delay instruction
Browse files Browse the repository at this point in the history
  • Loading branch information
hfrances committed Apr 1, 2024
1 parent 0ec571e commit eb6e1dc
Show file tree
Hide file tree
Showing 18 changed files with 727 additions and 372 deletions.
451 changes: 237 additions & 214 deletions SequentialScript.Test/CustomData/Resources.Designer.cs

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions SequentialScript.Test/CustomData/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@
<data name="TestComments" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>TestComments.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="TestDelay" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>TestDelay.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="TestDependences" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>TestDependences.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
Expand Down
5 changes: 5 additions & 0 deletions SequentialScript.Test/CustomData/TestDelay.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[OPEN]
run
Block -> Some Action /NoCheck /Key1:Value /Key2:"Value with spaces" /Key3:"Value with special characters :/"
Delay 3000
as @action
2 changes: 1 addition & 1 deletion SequentialScript.Test/CustomData/TestHydrogen.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ as @thrusters_disabled
run
Hydrogen Example (Status LCD) -> Set /Index:-1 /Background:YELLOW /Text:Connecting...
Hydrogen Example (Piston) -> Extend
as piston_extended
as @piston_extended

when @piston_extended
run
Expand Down
38 changes: 38 additions & 0 deletions SequentialScript.Test/InstructionParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,43 @@ public void TestHydrogen()
commands = IngameScript.InstructionParser.Parse(CustomData.Resources.TestHydrogen);
commands.ToString();
}

[TestMethod]
public void TestDelay()
{
IDictionary<string, IngameScript.ICommandInstruction> commands;
var expected = new Dictionary<string, IngameScript.ICommandInstruction>()
{
{ "OPEN", new IngameScript.InstructionCommand {
CommandName = "OPEN",
Body = new Dictionary<string, IngameScript.InstructionBlock> {
{ "@action", new IngameScript.InstructionBlock {
Alias = "@action",
PreviousAlias = new string[] { },
Instructions = new []{ new IngameScript.Instruction {
BlockName = "Block",
ActionName = "Some Action",
Arguments = new Dictionary<string, string> {
{ "NoCheck", "" },
{ "Key1", "Value" },
{ "Key2", "Value with spaces" },
{ "Key3", "Value with special characters :/" }
},
IsValid = true,
}, new IngameScript.Instruction {
BlockName = null,
ActionName = "DELAY",
Arguments = new Dictionary<string, string> { { "TIME", "3000" } },
IsValid = true,
}},
} }
}.Values
}}
};

commands = IngameScript.InstructionParser.Parse(CustomData.Resources.TestDelay);
InstrucionAssert.AreEqual(expected, commands);
}

}
}
1 change: 1 addition & 0 deletions SequentialScript.Test/SequentialScript.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="CustomData\TestDelay.txt" />
<Content Include="CustomData\TestHydrogen.txt" />
<Content Include="CustomData\TestArguments.txt" />
<Content Include="CustomData\TestComments.txt" />
Expand Down
2 changes: 1 addition & 1 deletion SequentialScript/Instructions.readme
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
R e a d m e
-----------

V1.1-alpha.6
V1.2-alpha
See more information in the following link:
https://github.com/space-engineers-hf/SequentialScript
109 changes: 82 additions & 27 deletions SequentialScript/Instructions/InstructionParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,40 +125,52 @@ private static InstructionCommand CreateCommand(System.Text.RegularExpressions.M
.Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("//")) // Ignore empty lines and comments.
.Select((line, index) =>
{
Instruction instruction = null;
// Remove comments
var lineComments = line.Split(new[] { "//" }, StringSplitOptions.None);
var lineWithoutComments = lineComments.First();
// Take BlockName and ActionName
var lineItems = lineWithoutComments.Trim().Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries);
string blockName = null, actionName = null;
bool isValid;
var lineWithoutComments = lineComments.First().Trim();
if (lineItems.Length > 0)
// Create instruction.
if (lineWithoutComments.Contains("->"))
{
blockName = lineItems[0].Trim();
// Instruction of IMyTerminalBlock -> Action
instruction = CreateInstruction(lineWithoutComments);
}
if (lineItems.Length > 1)
else
{
actionName = lineItems[1].Trim();
}
isValid = lineItems.Length == 2;
// Arguments
var arguments = GetArguments(actionName);
// Script reserved instructions.
var lineItems = lineWithoutComments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var command = lineItems.FirstOrDefault();
if (command == null)
{
instruction = null;
}
else if (command.Equals("DELAY", StringComparison.OrdinalIgnoreCase))
{
instruction = CreateInstructionDelay(lineItems);
}
if (instruction == null)
{
instruction = new Instruction
{
BlockName = null,
ActionName = null,
Arguments = null,
IsValid = false
};
}
}
return new
{
Line = index + 1,
BlockName = blockName,
ActionName = arguments[""].Trim(),
Arguments = arguments.Where(x => !string.IsNullOrEmpty(x.Key)).ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase),
IsValid = isValid
Instruction = instruction,
};
})
;

var invalid = actions.Where(x => !x.IsValid);
var invalid = actions.Where(x => !x.Instruction.IsValid);
if (invalid.Any())
{
throw new SyntaxException(
Expand Down Expand Up @@ -197,13 +209,7 @@ private static InstructionCommand CreateCommand(System.Text.RegularExpressions.M
{
Alias = alias,
PreviousAlias = previousActionsMatch.Select(x => x.Alias),
Instructions = actions.Select(x => new Instruction
{
BlockName = x.BlockName,
ActionName = x.ActionName,
Arguments = x.Arguments,
IsValid = x.IsValid
})
Instructions = actions.Select(x => x.Instruction)
});
}
}
Expand Down Expand Up @@ -237,6 +243,55 @@ private static InstructionCommand CreateCommand(System.Text.RegularExpressions.M
return result;
}

private static Instruction CreateInstruction(string lineWithoutComments)
{
// Take BlockName and ActionName
var lineItems = lineWithoutComments.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries);
string blockName = null, actionName = null;
bool isValid;

if (lineItems.Length > 0)
{
blockName = lineItems[0].Trim();
}
if (lineItems.Length > 1)
{
actionName = lineItems[1].Trim();
}
isValid = lineItems.Length == 2;

// Arguments
var arguments = GetArguments(actionName);

// Return
return new Instruction
{
BlockName = blockName,
ActionName = arguments[""].Trim(),
Arguments = arguments.Where(x => !string.IsNullOrEmpty(x.Key)).ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase),
IsValid = isValid
};
}

private static Instruction CreateInstructionDelay(string[] lineItems)
{
string timeString = null;

if (lineItems.Length >= 1)
{
timeString = lineItems[1];
}
return new Instruction
{
BlockName = null,
ActionName = "DELAY",
Arguments = new Dictionary<string, string>() {
{ "TIME", timeString }
},
IsValid = true
};
}

private static ConditionCommandInstruction CreateConditionCommand(System.Text.RegularExpressions.Match commandMatch)
{
ConditionCommandInstruction result = null;
Expand Down
4 changes: 2 additions & 2 deletions SequentialScript/MDK/MDK.options.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
-->
<MDKVersion>1.4.14</MDKVersion>
<MDKTrimTypes>
<Enabled>no</Enabled>
<Enabled>yes</Enabled>
</MDKTrimTypes>
<MDKMinify>
<Level>StripComments</Level>
<Level>Lite</Level>
</MDKMinify>
<MDKIgnore>
<Folder>mdk</Folder>
Expand Down
13 changes: 10 additions & 3 deletions SequentialScript/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ partial class Program : MyGridProgram
static readonly UpdateFrequency UPDATE_FREQUENCY = UpdateFrequency.Update10; // Update1, Update10, Update100
static readonly int UPDATE_TICKS = 0; // Very slow mode multiplier (for debug)


/* ----------------------------------------------------------------------------------- */
/* --- ¡¡¡IMPORTANT!!! Do not change anything below this line. --- */
/* ----------------------------------------------------------------------------------- */

#endregion

DateTime _momento;
Expand Down Expand Up @@ -76,7 +81,9 @@ public void Main(string argument, UpdateType updateSource)
.OfType<InstructionCommand>()
.SelectMany(cmd => cmd.Body)
.SelectMany(body => body.Instructions)
.Select(instruction => instruction.BlockName);
.Where(instruction => instruction.BlockName != null)
.Select(instruction => instruction.BlockName)
.Distinct();

AdvancedEcho($"Building dictionary", append: true);
_blocksDictionary = Helper.CreateBlockDictionary(blockNames, _terminalBlocks, _terminalGroups);
Expand Down Expand Up @@ -283,7 +290,7 @@ void EndCycle()

void AdvancedEchoReset()
{
_momento = DateTime.Now;
_momento = DateTime.UtcNow;
}

void AdvancedEcho(string message, bool append = false)
Expand All @@ -297,7 +304,7 @@ void AdvancedEcho(string message, bool append = false)
builder.Append(value);
message = builder.ToString();
}
message = $"| Elapsed {(DateTime.Now - _momento).TotalMilliseconds:00}ms |\n{message}";
message = $"| Elapsed {(DateTime.UtcNow - _momento).TotalMilliseconds:00}ms |\n{message}";

Echo(message);
if (DEBUG_IN_SCREEN)
Expand Down
3 changes: 3 additions & 0 deletions SequentialScript/SequentialScript.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,11 @@
<AdditionalFiles Include="Instructions.readme" />
<AdditionalFiles Include="thumb.png" />
<AdditionalFiles Include="MDK\whitelist.cache" />
<Compile Include="Tasks\ITaskAction.cs" />
<Compile Include="Tasks\TaskAction.cs" />
<Compile Include="Tasks\Task.cs" />
<Compile Include="Tasks\TaskActionDelay.cs" />
<Compile Include="Tasks\TaskEnums.cs" />
<Compile Include="Tasks\Tasks.cs" />
</ItemGroup>
<Import Project="..\..\CommonScript\CommonScript\CommonScript.projitems" Label="Shared" />
Expand Down
52 changes: 52 additions & 0 deletions SequentialScript/Tasks/ITaskAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI.Ingame;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using VRage;
using VRage.Collections;
using VRage.Game;
using VRage.Game.Components;
using VRage.Game.GUI.TextPanel;
using VRage.Game.ModAPI.Ingame;
using VRage.Game.ModAPI.Ingame.Utilities;
using VRage.Game.ObjectBuilders.Definitions;
using VRageMath;

namespace IngameScript
{
interface ITaskAction
{

string ActionKey { get; }

/// <summary>
/// Gets or sets if this task action must be checked during "<see cref="Tasks.TaskStatusMode.Condition"/>" validation.
/// </summary>
bool IsCommandCondition { get; set; }

/// <summary>
/// Gets or sets when this task started or null if it has not started yet.
/// </summary>
DateTime? StartTime { get; set; }

/// <summary>
/// Starts the task.
/// </summary>
void Execute();

/// <summary>
/// Checks if this task has been ended.
/// </summary>
/// <param name="mode"></param>
/// <param name="momento"></param>
/// <param name="debug"></param>
bool Check(TaskStatusMode mode, DateTime? momento = null, StringBuilder debug = null);

}
}
2 changes: 1 addition & 1 deletion SequentialScript/Tasks/Task.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class Task

public string Alias { get; set; }
public IEnumerable<Task> PreviousTasks { get; set; }
public IEnumerable<TaskAction> Actions { get; set; }
public IEnumerable<ITaskAction> Actions { get; set; }

public bool IsRunning { get; set; }
public bool IsDone { get; set; }
Expand Down
Loading

0 comments on commit eb6e1dc

Please sign in to comment.