main.js
3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.require('Blockly.FieldIconDropDown');
(function () {
let currentButton;
function handlePlay(event) {
loadWorkspace(event.target); // 加载被点击的按钮的工作区
let code = javascript.javascriptGenerator.workspaceToCode(Blockly.getMainWorkspace());
code += 'MusicMaker.play();';// 先加载生成音乐的代码,再添加播放音乐的代码
try {
eval(code); // 执行生成的代码
} catch (error) {
console.log(error);
}
}
function save(button) {
// Add code for saving the behavior of a button.
button.blocklySave = Blockly.serialization.workspaces.save(Blockly.getMainWorkspace());//保存特定按钮的工作区的状态
}
function handleSave() {
document.body.setAttribute('mode', 'edit');
save(currentButton);
}
function loadWorkspace(button) {
const workspace = Blockly.getMainWorkspace(); // 获取主工作区
if (button.blocklySave) {
Blockly.serialization.workspaces.load(button.blocklySave, workspace); // 加载特定按钮的工作区的状态
} else {
workspace.clear(); // 清空工作区
}
}
function enableEditMode() {
document.body.setAttribute('mode', 'edit');
document.querySelectorAll('.button').forEach((btn) => {
btn.removeEventListener('click', handlePlay);
btn.addEventListener('click', enableBlocklyMode);
});
}
function enableMakerMode() {
document.body.setAttribute('mode', 'maker');
document.querySelectorAll('.button').forEach((btn) => {
btn.addEventListener('click', handlePlay);
btn.removeEventListener('click', enableBlocklyMode);
});
}
function enableBlocklyMode(e) {
document.body.setAttribute('mode', 'blockly');
currentButton = e.target;
loadWorkspace(currentButton);
}
document.querySelector('#edit').addEventListener('click', enableEditMode);
document.querySelector('#done').addEventListener('click', enableMakerMode);
document.querySelector('#save').addEventListener('click', handleSave);
enableMakerMode();
const toolbox = { // 工具箱
'kind': 'flyoutToolbox',
'contents': [
{
'kind': 'block',
'type': 'controls_repeat_ext', // 循环块
'inputs': {
'TIMES': {
'shadow': {
'type': 'math_number',
'fields': {
'NUM': 5
}
}
}
}
},
{
'kind': 'block',
'type': 'play_sound' // 播放声音块
},
{
'kind': 'block',
'type': 'ZE3P_led_set_color', // 块类型
'inputs': {
'COLOR': {
'shadow': {
'type': 'ZE3P_led', // 影子块类型
'fields': {
'COLOR': 'Red' // 影子块中的字段值
}
}
}
}
}
]
};
Blockly.inject('blocklyDiv', { // 注入到blocklyDiv中
toolbox: toolbox,
scrollbars: false,
horizontalLayout: true,
toolboxPosition: "end",
});
})();