Blockly字典积木开发

24 阅读5分钟

Blockly字典积木开发

今天出一期关于Blockly字典积木开发的教程,废话不多说,上代码

字典积木

文件积木借鉴mixly部分文件积木,python代码可以参考www.runoob.com/python/pyth…

一:构建积木

1,涉及要修改得文件(blocks,dicts这个是要自己创建) 2,blocks文件引入dicts文件,并在export导出积木 在这里插入图片描述

dicts代码

/**
 * @license
 * Copyright 2012 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

// Former goog.module ID: Blockly.libraryBlocks.dicts
import type {Block} from '../core/block.js';
import type {BlockSvg} from '../core/block_svg.js';
import type {Workspace} from '../core/workspace.js';
import type {Connection} from '../core/connection.js';
import {Msg} from '../core/msg.js';
import {Align} from '../core/inputs/align.js';
import {MutatorIcon} from '../core/icons/mutator_icon.js';
import {
  createBlockDefinitionsFromJsonArray,
  defineBlocks,
} from '../core/common.js';
import * as xmlUtils from '../core/utils/xml.js';

declare global {
  interface Window {
    Blockly: any; // 或者更精确的类型
  }
}
/**
 * A dictionary of the block definitions provided by this module.
 */
export const blocks = createBlockDefinitionsFromJsonArray([
  {
    type: "dicts_keys",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: "Dicts",
    message0: "%{BKY_DICTS_KEYS}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "dicts_get",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_DICTS_GET}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
    ],
  },
  {
    type: "dicts_get_default",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_DICTS_GET_DEFAULT}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
      { type: "input_value", name: "DEFAULT" },
    ],
  },
  {
    type: "dicts_add_or_change",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    previousStatement: null,
    nextStatement: null,
    message0: "%{BKY_DICTS_ADD_OR_CHANGE}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
      { type: "input_value", name: "VALUE1" },
    ],
  },
  {
    type: "dicts_delete",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    previousStatement: null,
    nextStatement: null,
    message0: "%{BKY_DICTS_DELETE}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
    ],
  },
  {
    type: "dicts_pop",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_DICTS_POP}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
    ],
  },
  {
    type: "dicts_setdefault",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    previousStatement: null,
    nextStatement: null,
    message0: "%{BKY_DICTS_SETDEFAULT}",
    args0: [
      { type: "input_value", name: "VALUE", check: "Dicts" },
      { type: "input_value", name: "KEY", check: "String" },
      { type: "input_value", name: "DEFAULT" },
    ],
  },
  {
    type: "dicts_clear",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    previousStatement: null,
    nextStatement: null,
    message0: "%{BKY_DICTS_CLEAR}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "dicts_values",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_DICTS_VALUES}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "dicts_length",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: "Number",
    message0: "%{BKY_DICTS_LENGTH}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "dicts_deldict",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    previousStatement: null,
    nextStatement: null,
    message0: "%{BKY_DICTS_DELDICT}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "dicts_todict",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: "Dicts",
    message0: "%{BKY_DICTS_TODICT}",
    args0: [{ type: "input_value", name: "VALUE" }],
  },
  {
    type: "dicts_to_json",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_DICTS_TO_JSON}",
    args0: [{ type: "input_value", name: "VALUE", check: "Dicts" }],
  },
  {
    type: "json_to_dicts",
    style: "dicts_blocks",
    helpUrl: "",
    tooltip: "",
    inputsInline: true,
    output: null,
    message0: "%{BKY_JSON_TO_DICTS}",
    args0: [{ type: "input_value", name: "VALUE" }],
  },
])

/**
 * Type of a 'dicts_create_with' block.
 */
export type CreateWithBlock = Block & DictsCreateWithMixin;
interface DictsCreateWithMixin extends DictsCreateWithMixinType  {
  itemCount_: number;
};
type DictsCreateWithMixinType  = typeof DICTS_CREATE_WITH;
const DICTS_CREATE_WITH = {
  /**
   * Block for creating a dicts with any number of elements of any type.
   */
  init: function(this: CreateWithBlock) {
    this.setHelpUrl('');
    this.setStyle('dicts_blocks');
    this.itemCount_ = 3;
    this.updateShape_();
    this.setOutput(true, 'Dicts');
    this.setInputsInline(true);
    this.setMutator(
      new MutatorIcon(['dicts_create_with_item'], this as unknown as BlockSvg)
    )
    this.setTooltip('');
  },
  /**
   * Create XML to represent dicts inputs.
   * Backwards compatible serialization implementation.
   */
  mutationToDom: function(this: CreateWithBlock): Element {
    const container = xmlUtils.createElement('mutation');
    container.setAttribute('items', String(this.itemCount_));
    return container;
  },
  /**
   * Parse XML to restore the dicts inputs.
   * Backwards compatible serialization implementation.
   *
   * @param xmlElement XML storage element.
   */
  domToMutation: function(this: CreateWithBlock, xmlElement: Element) {
    const items = xmlElement.getAttribute('items');
    if (!items) throw new TypeError('element did not have items');
    this.itemCount_ = parseInt(items, 10)
    this.updateShape_();
  },
  /**
   * Returns the state of this block as a JSON serializable object.
   *
   * @returns The state of this block, ie the item count.
   */
  saveExtraState: function (this: CreateWithBlock): {itemCount: number} {
    return {
      'itemCount': this.itemCount_,
    };
  },
  /**
   * Applies the given state to this block.
   *
   * @param state The state to apply to this block, ie the item count.
   */
  loadExtraState: function (this: CreateWithBlock, state: AnyDuringMigration) {
    this.itemCount_ = state['itemCount'];
    this.updateShape_();
  },
  /**
   * Populate the mutator's dialog with this block's components.
   * 
   * @param workspace Mutator's workspace.
   * @returns Root block in mutator.
   */
  decompose: function(
    this: CreateWithBlock,
    workspace: Workspace,
  ): ContainerBlock {
    const containerBlock = workspace.newBlock(
      'dicts_create_with_container'
    ) as ContainerBlock;
    (containerBlock as BlockSvg).initSvg();
    let connection = containerBlock.getInput('STACK')!.connection;
    for (let i = 0; i < this.itemCount_; i++) {
      const itemBlock = workspace.newBlock(
        'dicts_create_with_item'
      ) as ItemBlock;
      (itemBlock as BlockSvg).initSvg();
      if (!itemBlock.previousConnection) {
        throw new Error('itemBlock has no previousConnection')
      }
      connection!.connect(itemBlock.previousConnection)
      connection = itemBlock.nextConnection;
    }
    return containerBlock;
  },
  /**
   * Reconfigure this block based on the mutator dialog's components.
   * 
   * @param containerBlock Root block in mutator.
   */
  compose: function(this: CreateWithBlock, containerBlock: Block) {
    let itemBlock: ItemBlock | null = containerBlock.getInputTargetBlock(
      'STACK'
    ) as ItemBlock;
    // Count number of inputs.
    const connections: Connection[] = [];
    while (itemBlock) {
      if (itemBlock.isInsertionMarker()) {
        itemBlock = itemBlock.getNextBlock() as ItemBlock | null;
        continue;
      }
      connections.push(itemBlock.valueConnection_ as Connection);
      itemBlock = itemBlock.getNextBlock() as ItemBlock | null;
    }
    // Disconnect any children that don't belong.
    for (let i = 0; i < this.itemCount_; i++) {
      const connection = this.getInput('ADD' + i)!.connection!.targetConnection;
      if (connection && !connections.includes(connection)) {
        connection.disconnect();
      }
    }
    this.itemCount_ = connections.length;
    this.updateShape_();
    // Reconnect any child blocks.
    for (let i = 0; i < this.itemCount_; i++) {
      connections[i]?.reconnect(this, 'ADD' + i)
    }
  },
  /**
   * Store pointers to any connected child blocks.
   *
   * @param containerBlock Root block in mutator.
   */
  saveConnections: function(this: CreateWithBlock, containerBlock: Block) {
    let itemBlock: ItemBlock | null = containerBlock.getInputTargetBlock(
      'STACK',
    ) as ItemBlock;
    let i = 0;
    while(itemBlock) {
      if (itemBlock.isInsertionMarker()) {
        itemBlock = itemBlock.getNextBlock() as ItemBlock | null;
        continue;
      }
      const input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input?.connection!.targetConnection as Connection;
      itemBlock = itemBlock.getNextBlock() as ItemBlock | null;
      i++;
    }
  },
  /**
   * Modify this block to have the correct number of inputs.
   */
  updateShape_: function(this: CreateWithBlock) {
    if (this.itemCount_ && this.getInput('EMPTY')) {
      this.removeInput('EMPTY');
    } else if (!this.itemCount_ && ! this.getInput('EMPTY')) {
      this.appendDummyInput('EMPTY')
        .appendField(
          Msg['DICTS_CREATE_EMPTY_TITLE']
        );
    }

    let keyNames = [];
    let Blockly = window.Blockly || {};
    for (let i = 0 ; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        keyNames.push(this.getFieldValue("KEY" + i))
        const input = this.appendValueInput('ADD' + i)
        if (i === 0) {
          input.appendField(Msg['DICTS_CREATE_WITH_INPUT_WITH'])
        }
        input.setCheck(null)
          .setAlign(Align.RIGHT)
          .appendField(
            new Blockly.FieldTextInput(
              (keyNames.length > i
                ? keyNames[i]
                : i == 0
                ? '"key"'
                : '"key' + (i + 1) + '"') || '"key"'
            ),
            "KEY" + i
          )
          .appendField(":")
      }
    }

    // Remove deleted inputs.
    for (let i = this.itemCount_; this.getInput('ADD' + i); i++) {
      this.removeInput('ADD' + i);
    }
  }
};
blocks['dicts_create_with'] = DICTS_CREATE_WITH;

/** type for a 'dicts_creat_with_item' block. */
type ItemBlock = Block & ItemMutator
interface ItemMutator extends ItemMutatorType {
  valueConnection_?: Connection;
}
type ItemMutatorType = typeof DICTS_CREATE_WITH_ITEM
const DICTS_CREATE_WITH_ITEM = {
  /**
   * Mutator block for adding items.
   */
  init: function(this: ItemBlock) {
    this.setStyle('dicts_blocks');
    this.appendDummyInput()
      .appendField(Msg['DICTS_ELEMENT']);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
}
blocks['dicts_create_with_item'] = DICTS_CREATE_WITH_ITEM;

/** Type for a 'dicts_create_with_container' block. */
type ContainerBlock = Block & ContainerMutator
interface ContainerMutator extends ContainerMutatorType {}
type ContainerMutatorType = typeof DICTS_CREATE_WITH_CONTAINER
const DICTS_CREATE_WITH_CONTAINER = {
  /**
   * Mutator block from dicts container.
   */
  init: function(this: ContainerBlock) {
    this.setStyle('dicts_blocks');
    this.appendDummyInput()
      .appendField(Msg['DICTS_CREATE_WITH_CONTAINER']);
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
}
blocks['dicts_create_with_container'] = DICTS_CREATE_WITH_CONTAINER;

defineBlocks(blocks);

至此字典积木已经完成,看一下效果图 在这里插入图片描述

二:构建python

1,涉及要修改得文件(python,dicts这个是要自己创建) 2,python文件引入dicts文件,并在export导出python代码 在这里插入图片描述

dicts代码

/**
 * @license
 * Copyright 2012 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @file Generating Python for list blocks.
 */

// Former goog.module ID: Blockly.Python.dicts
import type {Block} from '../../core/block.js';
import type {CreateWithBlock} from '../../blocks/dicts.js';
import type {PythonGenerator} from './python_generator.js';
import {Order} from './python_generator.js';

export function dicts_create_with(
  block: Block,
  generator: PythonGenerator,
): [string, Order] {
  // Create a dicts with any number of elements of any type.
  const createWithBlock = block as CreateWithBlock;
  const elements = new Array(createWithBlock.itemCount_);
  let keys = null;
  for (let i = 0; i < createWithBlock.itemCount_; i++) {
    keys = block.getFieldValue('KEY' + i)
    elements[i] = keys + ':' + (generator.valueToCode(block, 'ADD' + i, Order.NONE) || 0);
  }
  
  let code = '{' + elements.join(', ') + '}'
  return [code, Order.COLLECTION];
}

export function dicts_keys(block: Block, generator: PythonGenerator) : [string, Order] { 
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `${VALUE}.keys()`
  return [code, Order.ATOMIC]
}

export function dicts_get(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';

  let code = `${VALUE}[${KEY}]`
  return [code, Order.ATOMIC]
}

export function dicts_get_default(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';
  let DEFAULT = generator.valueToCode(block, 'DEFAULT', Order.NONE) || '0';

  let code = `${VALUE}.get(${KEY}, ${DEFAULT})`
  return [code, Order.ATOMIC]
}

export function dicts_add_or_change(block: Block, generator: PythonGenerator)  {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';
  let VALUE1 = generator.valueToCode(block, 'VALUE1', Order.NONE) || '0';

  let code = `${VALUE}[${KEY}] = ${VALUE1}\n`
  return code
}

export function dicts_delete(block: Block, generator: PythonGenerator)  {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';

  let code = `del ${VALUE}[${KEY}]\n`
  return code
}

export function dicts_pop(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';

  let code = `${VALUE}.pop(${KEY})`
  return [code, Order.ATOMIC]
}

export function dicts_setdefault(block: Block, generator: PythonGenerator)  {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
  let KEY = generator.valueToCode(block, 'KEY', Order.NONE) || '0';
  let DEFAULT = generator.valueToCode(block, 'DEFAULT', Order.NONE) || '0';

  let code = `${VALUE}.setdefault(${KEY}, ${DEFAULT})\n`
  return code
}

export function dicts_clear(block: Block, generator: PythonGenerator)  {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `${VALUE}.clear()\n`
  return code
}

export function dicts_values(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `${VALUE}.values()`
  return [code, Order.ATOMIC]
}

export function dicts_length(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `len(${VALUE})`
  return [code, Order.ATOMIC]
}

export function dicts_deldict(block: Block, generator: PythonGenerator)  {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `del ${VALUE}\n`
  return code
}

export function dicts_todict(block: Block, generator: PythonGenerator) : [string, Order] {
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  return [`dict(${VALUE})`, Order.ATOMIC]
}

export function dicts_to_json(block: Block, generator: PythonGenerator) : [string, Order] {
  (generator as AnyDuringMigration).definitions_['import_json'] = 'import json'
  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `json.dumps(${VALUE})`
  return [code, Order.ATOMIC]
}

export function json_to_dicts(block: Block, generator: PythonGenerator) : [string, Order] {
  (generator as AnyDuringMigration).definitions_['import_json'] = 'import json'

  let VALUE = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';

  let code = `json.loads(${VALUE})`
  return [code, Order.ATOMIC]
}

至此文件python已经完成,看一下效果图 在这里插入图片描述 总结:字典属于python基础代码,开发起来难度也不大