简体   繁体   中英

How can you use the code generated by Blockly?

Google's Blockly seems to be an interesting tool to make educational software and games to help kids learn programming better.

Though google has a documentation for the same for developers but its very short and not of much help(for rookie developers) and there are very less tutorial to learn the same.

So my question is that in the code generator section inside Blockly you can click on python/javascript tabs to see the code for whatever blocks you have placed but how to get that code.I mean how to execute that code say send it over a wifi using websockets or something.

Can anyone help me getting a better understanding of the same!

I'm not an expert at Blockly but maybe this will be useful.

To more directly answer your question, the Blocks you drop on the workspace have code behind them that is used by the Generators (JavaScrip, PHP...) to create your desired output code. The Generator routine is called by adding a button outside the Blockly div tag. There are many ways to do this but to keep things simple, assume you have the following:

<div id="blocklyDiv">

...followed by a button

<button onclick="run()"> RunMe </button>

Then in script you need to have a function that responds to the button onclick event.

<scrip>

var run = function(){
    Blockly.JavaScript.addReservedWords('code');
    var code = Blockly.JavaScript.workspaceToCode(workspace);

    // now what do you do want to do with code...?
    alert(code);
}

</script>

The Blockly documentation is very thin at best... but they do suggest the generated code is tested within try/catch code block. This will allow you to know if the blocks you defined in the Blockly editor produced valid or buggy code. So after you have the code as shown above try the following in place of the alert(code) above.

try {
    eval(code);
    // passed the test, now what...
    alert(code);
} catch (e) {
    // failed so show the error
    alert(e);
}

If the JavaScript eval() command does not produce an error the next line of code will execute. If an error was found do to a bug in the way you build your blocks an error event will be fired and the catch statement will execute (not the alert that follows the eval command). The parameter "e" will then be displayed with the alert(e) statement. From there you will have to debug your blocks and try again.

One other thing, I am using the JavaScript generator in the above sample. Not sure how the other languages test their code but I assume there are similar ways to invoke a try/catch environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM