A .net core interpreter for blockly programs.
Via nuget:
PM> Install-Package IronBlock
or
> dotnet add package IronBlock
Firstly, in JavaScript save your blockly workspace as an XML file:
var xml = Blockly.Xml.workspaceToDom(workspace);
The blockly code demo allows you to view the XML of your workspace.
The XML will look something like this:
<xml>
<block type="text_print">
<value name="TEXT">
<shadow type="text">
<field name="TEXT">Hello World</field>
</shadow>
</value>
</block>
</xml>
You'll need to pass this XML to you server using an Ajax call or similar.
// create a parser
var parser = new Parser();
// add the standard blocks to the parser
parser.AddStandardBlocks();
// parse the xml file to create a workspace
var workspace = parser.Parse(xml);
// run the workspace
var output = workspace.Evaluate();
// "Hello World"
Blockly has a block designer, allowing you to create your own blocks very easily.
Custom block can be created in C# by inheriting IBlock
:
public class MyCustomBlock : IBlock
{
public override object Evaluate(Context context)
{
// read a field
var myField = this.Fields.Get("MY_FIELD");
// evaluate a value
var myValue = this.Values.Evaluate("MY_VALUE", context);
// evaluate a statement
var myStatement = this.Statements.Get($"MY_STATEMENT");
myStatement.Evaluate(context); // evaluate your statement
// if your block returns a value, simply `return myValue`
// if your block is part of a statment, and another block runs after it, call
base.Evaluate(context);
return null;
}
}
You can then register your block and run it:
var parser = new Parser();
parser.AddBlock<MyCustomBlock>("my_custom_block");
var workspace = parser.Parse(xml);
workspace.Evaluate();
MIT