Scratch3.0二次开发(1)--环境搭建与生成python等其它语言代码

781 阅读2分钟

项目要求能将积木块儿转换成其它语言代码,网上搜了一大圈文章,讲的都是大致思路,不太详细,绕了一些弯路,故在此记录一下生成代码的详细步骤,希望有此需求的人少绕弯路,转载文章请注明出处,谢谢!!!

搭建环境

官方文档写的非常清楚,并给了一个例子deom

积木块儿转Python等其它语言

  1. scratch-blocks基于blockly开发,blockly中是支持将积木块儿转换成其它语言代码的,scratch-blocks中也支持,只是将generators相关文件删除了,github中有分支删除记录,所以我们要做的就是将这一部分代码重新放回到scratch-blocks中

  2. generators文件夹放到scratch-blocks目录下

  3. scratch-blocks中跟生成代码相关的文件有

    • scratch-blocks/core/generator.js
    • scratch-blocks/build.py
    • scratch-blocks/generators/*.js
  4. 在scratch-blocks/build文件夹下增加gen_generators.js文件,只放这一行代码

goog.provide('Blockly.Generator');
  1. 修改build.py,在build.py中增加gen_generator方法并在run方法中调用,将generators相关文件打包进去
### build.py
 def gen_generator(self, language):
    target_filename = language + "_compressed.js"
    # Define the parameters for the POST request.
    params = [
        ("compilation_level", "SIMPLE_OPTIMIZATIONS"),
      ]

    # Read in all the source files.
    # Add Blockly.Generator to be compatible with the compiler.
    params.append(("js_file", os.path.join("build", "gen_generators.js")))

    filenames = glob.glob(
        os.path.join("generators", language, "*.js"))
    filenames.insert(0, os.path.join("generators", language + ".js"))
    for filename in filenames:
      params.append(("js_file", filename))
    filenames.insert(0, "[goog.provide]")

    # Remove Blockly.Generator to be compatible with Blockly.
    remove = "var Blockly={Generator:{}};"
    self.do_compile(params, target_filename, filenames, remove)
  1. 在scratch-blocks目录下执行 npm run prepublish 进行打包部署,打包成功后scratch-blocks中会出现language + "_compressed.js"文件
  2. 在scratch-gui中引用,找到scratch-gui/src/lib/blocks.js,以python为例就是
import 'scratch-blocks/python_compressed';
  1. 最后进行调用,找到scratch-gui/src/containers/blocks.jsx,增加workspaceToCode方法,并在binAll中绑定,最后对this.workspace增加监听事件,监听积木块变化
### 对应语言生成代码调用
 workspaceToCode () {
        let code;
        try {
            const generatorName = 'Python';
            code = this.ScratchBlocks[generatorName].workspaceToCode(this.workspace);
            console.log(code)
        } catch (e) {
            code = e.message;
        }
        return code;
    }
### workspace监听
 this.workspace.addChangeListener(this.workspaceToCode)

generators相关文件

  1. generators/python.js 注册Python语言生成模块
  2. generators/python/*.js 文件中的每一个方法都对应一个积木块,将积木转换成其他语言

参考博主文章

  1. 按键伤人 这篇文章可以说是很详细了,但是少了gen_generator方法和最后的引用调用
  2. 取个昵称就那么难这篇文章讲了如何写generators/python/*.js中的方法
  3. 取个昵称就那么难这篇文章讲了blocks的类型和如何自定义一个block