You are on page 1of 42

Introduction to Blockly

Blockly 简介
CS Education Should Start With Kids

“计算机普及要从娃娃抓起 ” 邓小平,1984
How to Teach Kids Coding
For many parents ...

Kid’s screen time is always a dilemma


Edutainment with Visual Programming

OzoBot Dash & Dot

Scratch Blocks Blockly Games Sphero

寓教于乐 * 图形化编程
Blockly App Demo: code.org
Blockly App Demo: OzoBlockly
Blockly App Demo: App Inventor
More Apps Built with Blockly
Blockly An Open Source Library
for Building Visual Programming Editor

Cross-platform
➢ Web, Android, iOS
➢ Chrome, Firefox, Safari, Opera, and IE.
Exportable code
➢ JavaScript, Python, PHP, Lua, Dart
Highly customizable and Extensible
➢ Custom blocks and code generation
International
➢ 40+ languages, including RTL support

100% Client Library


➢ No server-side dependency
Scratch Blocks
Scratch A new generation of graphical blocks
➢ Launched in 2007 by MIT Media Lab for designing creative interface
➢ A Creative Learning Community
➢ 11M Registered Users

Scratch Blocks
➢ Launched in 2016 at Google I/O
➢ Collaboration between Google and MIT
➢ A Fork of Blockly at LLK Repo
➢ Tailored for Creative Young Learners
Build Blockly App
OutlineEditor
Blockly Blocks
Toolbox

Blockly
Programs

Workspace
Configure
Outline
Blockly App Block Definitions JavaScript Generator

Python Generator
Blockly Editor

Blockly Core libraries PHP Generator

Web, Android, iOS Lua Generator

App Configuration for


Workspace & Toolbox Dart Generator
Inject Blockly <script src="blockly_compressed.js"></script>
<script src="blocks_compressed.js"></script>
<script src="msg/js/en.js"></script>
<script>
window.onload = function() {
var workspace = Blockly.inject('blocklyDiv', {
media: 'media/',
toolbox: document.getElementById('toolbox')
});
}
</script>
<div id="blocklyDiv" style="height: 400px; width: 600px;"></div>
<xml id="toolbox" style="display: none">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="math_number"></block>
<block type="math_arithmetic"></block>
</xml>
Resize <div id="blocklyDiv" style="position: absolute"></div>

Workspace var overlayBlocklyWorkspace = function() {


var src = document.getElementById('blocklyDiv');
var dst = document.getElementById('targetDiv');
var e = dst, x = 0, y = 0;
do {
x += e.offsetLeft; y += e.offsetTop; e = e.offsetParent;
} while (e);
src.style.left = x + 'px'; src.style.top = y + 'px';
src.style.width = dst.offsetWidth + 'px';
src.style.height = dst.offsetHeight + 'px';
};

window.onload = function() {
overlayBlocklyWorkspace();
window.addEventListener('resize', overlayBlocklyWorkspace);
var workspace = Blockly.inject('blocklyDiv', …);
}
Save
Workspace
// Export blocks in workspace in XML
var dom = Blockly.Xml.workspaceToDom(workspace);

var xml_text = Blockly.Xml.domToText(dom);

// Import blocks into workspace from XML


var dom = Blockly.Xml.textToDom(xml_text);

Blockly.Xml.domToWorkspace(dom, workspace);
Configure
Toolbox <xml id="toolbox" style="display: none">
<category name="Control">
<block type="controls_if"></block>
<block type="controls_whileUntil"></block>
<block type="controls_for">
</category>

<category name="Logic">
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_boolean"></block>
</category>
</xml>
Create
Variables <category name="Variables" custom="VARIABLE"></category>
Define <category name="Functions" custom="PROCEDURE"></category>
Functions
Block <block type="controls_for">
<value name="FROM">
Groups <shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
<value name="TO">
<shadow type="math_number">
<field name="NUM">10</field>
</shadow>
</value>
<value name="BY">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
</block>
Code <script src="blockly_compressed.js"></script>
Generation <script src="blocks_compressed.js"></script>

<-- Add code generator: language_compressed.js -->


<-- language: javascript, python, php, lua, dart -->
<script src="javascript_compressed.js"></script>
<script>
var workspace = Blockly.inject('blocklyDiv', ...);

function myUpdateFunction(event) {
// Call Blockly.Language.workspaceToCode(...) to generate code
var code = Blockly.JavaScript.workspaceToCode(workspace);
document.getElementById(myCodeViewer).value = code;
}

// Update generated code in realtime


workspace.addChangeListener(myUpdateFunction);
</script>
Create Custom Blocks
Block <script src="blockly_compressed.js"></script>
<script src="my_blocks.js"></script>
Definition
// my_blocks.js: a custom block definition in JSON
var myMathChangeBlock = {
"message0": "change %1 by %2",
"args0": [
{"type": "field_variable", "name": "VAR", "variable": "item"},
{"type": "input_value", "name": "DELTA", "check": "Number"}
],
"colour": 230
... ...
};

// Add a new block and register it with the name “my_math_change”


Blockly.Blocks['my_math_change'] = {
init: function() {
this.jsonInit(myMathChangeBlock);
}
}
Block
Connections
var math_change_block = {

"message0": "change %1 by %2",


"args0": [
{"type": "field_variable", "name": "VAR", "variable": "item"},
{"type": "input_value", "name": "DELTA", "check": "Number"}
],
"previousStatement": null,
"nextStatement": null,
};
Block var math_change_block = {
Input & Output "message0": "change %1 by %2",
"args0": [
{"type": "field_variable", "name": "VAR", "variable": "item"},
{"type": "input_value", "name": "DELTA", "check": "Number"}
],
... ...
};

var math_number_block = {
"output": "Number",
... ...
};
External vs var loop = {
Inline Inputs "inputInlines": false,
... ...
};

External Inputs Inline Inputs


Block Colour

var math_change_block = {
"colour": 230
... ...
};

● Blockly uses HSV colour model


● Saturation and Value are fixed
● Configure block colour by Hue (0 ~ 360)
Help & Tooltip var my_math_change_block = {
"args0": [
{"type": "field_variable", "name": "VAR", "variable": "item"},
{"type": "input_value", "name": "DELTA", "check": "Number"}
],
"helpUrl": "http://online.help.for.my_math_change.block"
"tooltip" : "... static tooltip ..."
};

Blockly.Blocks['my_math_change'] = {
init: function() {
this.jsonInit(my_math_change_block);
// Assign 'this' to a variable to be used in the closure below.
var thisBlock = this;
// Set tooltip dynamically.
this.setTooltip(function() {
return 'Add a number to variable "%1".'.replace('%1',
thisBlock.getFieldValue('VAR'));
});
}
}
Code var my_math_change_block = {
Generator "message0": "change %1 by %2",
"args0": [
{"type": "field_variable", "name": "VAR", "variable": "item"},
{"type": "input_value", "name": "DELTA", "check": "Number"}
],
... ...
}

Blockly.JavaScript['my_math_change'] = function(block) {
// Add to a variable in place.
var delta = Blockly.JavaScript.valueToCode(
block, 'DELTA', Blockly.JavaScript.ORDER_ADDITION) || '0';
var name = Blockly.JavaScript.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
return name + ' = ' + '(typeof ' + name + ' == \'number\' ? '
+ name + ' : 0) + ' + delta + ';\n';
};
Outline
Blockly
Developer Tool
Blockly for Android and iOS
Developer Preview

Rendering library
➢ Full native versions for Android and iOS
➢ Feature complete, though bugs exist
Configuration
➢ XML toolbox same format as web
➢ Layout specific to each platform
Custom blocks
➢ Uses JSON block definitions
Work in Progress
➢ Functions, Mutators, i18n, undo/redo, UI
customization
public class MyActivity extends AbstractBlocklyActivity {
Blockly
for Android @Override protected String getToolboxContentsXmlPath() {
return "default/toolbox.xml";
}

@Override protected List<String> getBlockDefinitionsJsonPaths() {


return Arrays.asList(
"default/list_blocks.json",
"default/logic_blocks.json",
……
);
}

@Override protected List<String> getGeneratorsJsPaths() {


return Arrays.asList(
"my_javascript_generator.js",
……
);
}

}
Blockly for iOS
// Add WorkbenchViewController to an existing UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Create editor
let workbenchViewController = WorkbenchViewController(style: .defaultStyle)
// Add editor to this view controller
addChildViewController(workbenchViewController)
view.addSubview(workbenchViewController.view)
workbenchViewController.view.frame = view.bounds
workbenchViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
workbenchViewController.didMove(toParentViewController: self)
}
// Create a workbench editor
Blockly for iOS let workbenchViewController = WorkbenchViewController(style: .defaultStyle)
let blockFactory = BlockFactory()
// Load a block factory with the default blocks
blockFactory.load(fromDefaultFiles: .allDefault)
// Load custom blocks from JSON files
// blockFactory.load(fromJSONPaths: ["my_blocks.json"])
do {
// Load toolbox configuration from `toolbox.xml`
if let toolboxFile = Bundle.main.path(forResource: "toolbox", ofType: "xml") {
let toolboxXML = try String(contentsOfFile: toolboxFile,
encoding: String.Encoding.utf8)
let toolbox = try Toolbox.makeToolbox(xmlString: toolboxXML, factory: blockFactory)
// Load the toolbox into the workbench
try workbenchViewController.loadToolbox(toolbox)
} else {
print("Could not load 'toolbox.xml'")
}
} catch let error {
// Handle error
}
Outline
Android and
iOS Examples
Blockly for Android
● https://github.com/google/blockly-android
● https://developers.google.cn/blockly/guides/get-started/android

Blockly for iOS


● https://github.com/google/blockly-ios
● https://developers.google.cn/blockly/guides/get-started/ios
Google Programs for CS Education
CS4HS
Outline

● CS professional development for teachers

● App Inventor tool and hands-on practice

● Awards: $12,000 each

● 40K Teachers, 1M Students, 40 Countries

● https://www.cs4hs.com/
RISE Awards
Outline

● Grants of $10,000 ~ $25,000

● For non-profit organizations

● Connects awardees with Google expertise

● For Details: https://goo.gl/BnUY98


CS First
Outline
● Free online materials for CS Club

● Involve block-based coding using Scratch

● Targeted at students in grades 4th-8th (ages 9-14)

● Can be tailored to fit your schedule and needs

● Are themed to attract students with varied interests

● https://www.cs-first.com
Outline
Q&A
Resources and Links

● Blockly Developer Site: https://developers.google.cn/blockly/


● Blockly for web: https://github.com/google/blockly
● Blockly for iOS: https://github.com/google/blockly-ios
● Blockly for Android: https://github.com/google/blockly-android
● Scratch Blocks: https://github.com/llk/scratch-blocks
● Blockly Developer Tools:
https://blockly-demo.appspot.com/static/demos/blockfactory/index.html
● Contact: Peng Yang (yangpeng@google.com)

You might also like