main.js 3.11 KB
/**
 * @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",
  });
})();