84 lines
2.2 KiB
JavaScript
84 lines
2.2 KiB
JavaScript
// Example addon: adds a "My Robot" toolbox category with two custom blocks.
|
|
//
|
|
// To use: click "Addons" in the toolbar, upload this file, and the
|
|
// "My Robot" category will appear in the toolbox.
|
|
|
|
// --- Block definitions ---
|
|
api.Blockly.Blocks['robot_drive'] = {
|
|
init() {
|
|
this.appendDummyInput()
|
|
.appendField('drive')
|
|
.appendField(new api.Blockly.FieldDropdown([
|
|
['forward', 'FORWARD'],
|
|
['backward', 'BACKWARD'],
|
|
['left', 'LEFT'],
|
|
['right', 'RIGHT'],
|
|
['stop', 'STOP'],
|
|
]), 'DIRECTION');
|
|
this.appendValueInput('SPEED')
|
|
.setCheck('Number')
|
|
.appendField('speed');
|
|
this.setInputsInline(true);
|
|
this.setPreviousStatement(true, null);
|
|
this.setNextStatement(true, null);
|
|
this.setColour(45);
|
|
this.setTooltip('Drive the robot in a direction at a given speed');
|
|
},
|
|
};
|
|
|
|
api.Blockly.Blocks['robot_beep'] = {
|
|
init() {
|
|
this.appendValueInput('TIMES')
|
|
.setCheck('Number')
|
|
.appendField('beep');
|
|
this.appendDummyInput()
|
|
.appendField('times');
|
|
this.setInputsInline(true);
|
|
this.setPreviousStatement(true, null);
|
|
this.setNextStatement(true, null);
|
|
this.setColour(45);
|
|
this.setTooltip('Make the robot beep');
|
|
},
|
|
};
|
|
|
|
// --- Code generators ---
|
|
api.pythonGenerator.forBlock['robot_drive'] = function (block) {
|
|
const dir = block.getFieldValue('DIRECTION');
|
|
const speed = api.pythonGenerator.valueToCode(
|
|
block, 'SPEED', api.pythonGenerator.ORDER_NONE
|
|
) || '0';
|
|
return `robot.drive("${dir.toLowerCase()}", ${speed})\n`;
|
|
};
|
|
|
|
api.pythonGenerator.forBlock['robot_beep'] = function (block) {
|
|
const times = api.pythonGenerator.valueToCode(
|
|
block, 'TIMES', api.pythonGenerator.ORDER_NONE
|
|
) || '1';
|
|
return `robot.beep(${times})\n`;
|
|
};
|
|
|
|
// --- Register toolbox category ---
|
|
api.registerCategories([
|
|
{
|
|
kind: 'category',
|
|
name: 'My Robot',
|
|
colour: '45',
|
|
contents: [
|
|
{
|
|
kind: 'block',
|
|
type: 'robot_drive',
|
|
inputs: {
|
|
SPEED: { shadow: { type: 'math_number', fields: { NUM: 100 } } },
|
|
},
|
|
},
|
|
{
|
|
kind: 'block',
|
|
type: 'robot_beep',
|
|
inputs: {
|
|
TIMES: { shadow: { type: 'math_number', fields: { NUM: 3 } } },
|
|
},
|
|
},
|
|
],
|
|
},
|
|
]);
|