カスタム ブロックを定義する

ブロックはプログラミングに使用します。これらは、テキストベースのプログラミング言語で式とステートメントを表します。

ブロックとそのパーツの詳細については、ビジュアル グロサリーをご覧ください。

ブロック定義

ブロック定義では、ブロックのパズルピースの接続とフィールドを指定します。ブロックの外観とスタイルのほとんどは、他の方法で指定します。ブロックが変換される文字列(通常はコード)は、ブロックコード生成ツールとして定義されます。

単純なブロックを定義する最も簡単な方法は、JSON を使用することです。

このコード スニペットは、次と前の接続と、距離のフィールド 1 つを持つ「前方に移動」ブロックを定義しています。

// Create the definition.
const definitions = Blockly.common.createBlockDefinitionsFromJsonArray([
  {
    // The type is like the "class name" for your block. It is used to construct
    // new instances. E.g. in the toolbox.
    type: 'my_custom_block',
    // The message defines the basic text of your block, and where inputs or
    // fields will be inserted.
    message0: 'move forward %1',
    args0: [
      // Each arg is associated with a %# in the message.
      // This one gets substituted for %1.
      {
        // The type specifies the kind of input or field to be inserted.
        type: 'field_number',
        // The name allows you to reference the field and get its value.
        name: 'FIELD_NAME',
      }
    ],
    // Adds an untyped previous connection to the top of the block.
    previousStatement: null,
    // Adds an untyped next connection to the bottom of the block.
    nextStatement: null,
  }
]);

// Register the definition.
Blockly.common.defineBlocks(definitions);

前進するためのブロック

ブロックを定義してツールボックスに追加する方法については、カスタム ブロックの概要をご覧ください。