Create an Extension for a Sprite

Background

This tutorial uses an API-type extension as an example to describe how to use Extension Builder of mBlock 5. You can create an extension a sprite simply by a few steps.

Our task is to enable the stage to display one sentence for the execution of each block.

图片

Basic Principle

On mBlock 5, when you click to execute a block, a js program is executed. Creating an executable block is not as difficult as you think.

Use an API provided by Hitokoto as an example. By analying the API document , we can find that the following API request can be used to obtain a sentence from the source of animation:(You can copy the following statement to a browser to view the result. If the API you use cannot be connected, a cross-domain problem may occur.)

Note: The API used in this example is in Chinese. You can use any API in English when creating your own extension.

https://v1.hitokoto.cn/?c=a&encode=json

The result is shown as follows:

{
  "id": 84,
  "hitokoto": "因为无法再见面,所以要笑着说再见。",
  "type": "a",
  "from": "AIR",
  "creator": "Sai",
  "created_at": "1468605909"
}

We can define the request process in the execution program of a block, and the result is returned after the execution.

Extension Creation Procedure

Step 1: Sign in to Extension Builder.

Visit https://ext.mblock.cc.

Note: If you do not have an Extension Builder account, you can simply sign up one. The account can be used in all Makeblock product systems, including the mBlock community, mBlock 5 on mobile terminals, mBlock 5 on PCs, and mBlock 5 webpages. With the account, you can synchronize your projects and use the AI services of mBlock 5.

图片

Step 2: Create an extension.

After signing in to Extension Builder, choose My Plugin > My Extension in the navigation tree on the left side.

Note: On Extension Builder, My Device refer to specific hardware devices, distinguished from sprites; and My Extension refer to extensions that must be used in combination with hardware devices or sprite.

In this development example, we click Add extension, instead of Add device, to create an enhaced extension for a sprite.

图片

Step 3: Enter basic information.

图片

After enterng the basic information, click OK.

The extension list is displayed, and you can click the extension name to enter the editing page.

图片

Step 4: Set the category and blocks.

Click Add category to set the category.

The Extension category dialog box is displayed for you to enter the information. You can use the default ID.

图片

Step 5: Design blocks.

图片

As shown in the preceding figure, we need three blocks, where the sentence source block is used to initiate an HTTP request, the show sentence and show sentence source blocks are used to display the result of the request.

Design the "sentence source" block

Refer to https://v1.hitokoto.cn/?c=a&encode=json. The parameter can be set to one of the following: animation, comic, game, novel, Myself, Internet, or other.

Click + at the bottom of Blocks list to add a block.

图片

Step 6: Complete the live mode handler settings and common code settings.

Live mode handler settings

After defining the description and parameter, we can define the specific action of the block. Click the Live mode handler settings tab, the following area is displayed. Double-click the black box to enter the specific execution program of the block.

图片

Extension Builder has encapsulated the execution interface, and so we need only to enter the corresponding js execution code in the braces. Extension Builder supports the es6 and es7 syntaxes. We can use async or other syntax.

async (args, app, device, block) => {
    const { origin } = args;  // args.origin indicating to obtain the value of the drop-down list box
    await getYiYanOfCategory(origin);
}

We can see the function getYiYanOfCategory. Where does it come from? The following describes a useful configuration item Common code settings. Common code settings

Click the Common code settings tab, as shown in the following figure.

图片

Double-click to edit the code. You can define the global variables and global functions that can be directly invoked in other js configuration items of Extension Builder. The getYiYanOfCategory function we see in Live mode handler settings is defined in this area. The complete code is shown in the following:

var yiYanResult = {
    hitokoto: '',
    from:''
};
const request = async (opts = {}) => {
    const host = 'https://v1.hitokoto.cn/';
    const { method, body, headers } = opts;
    var url = host + opts['url'];
    try {
        if (!navigator.onLine) {
            console.log('Poor network~~~~')
        }
        let req = {
            // POST request by default
            method: method ? method : 'POST',
            headers: new Headers(),
        }
        // Add the request parameter in body if POST request
        if (method == 'POST') {
            Object.assign({}, req, { body: JSON.stringify(body) })
        }
        const res = await fetch(url, req);
        return res.json()
    } catch (err) {
        console.log(err.toString())
    }
}
const getYiYanOfCategory = async (category) => {
    return await request({
        url: `?/c=${category}&encode=json`,
        method: 'GET'
    })
}

Step 7: Define the result return blocks.

Based on step 6, we can use yiYanResult to store the content obtained by the API and return the content in blocks.

Configure the blocks.

图片

Live mode handler settings

图片

The code is as follows. The execution of the block is to return a value.

(app, device, block) => {
    return yiYanResult['hitokoto']
}

Test and commissioning

Way 1: Click "Preview" in the upper right corner of Extension Builder

图片

A preview window is displayed. We can see the extension we created. If no extension appears, check whether the accound used to sign in mBlock 5 is the same as that used in Extension Builder.

图片

You can also right-click the title bar and choose to check your code as in a common brower.

图片

Way 2: Download the extension to your computer and drag it to mBlock 5 to use it

Summary

You may find that creating an extension is not as difficult as you think before. After you master how to create extensions, you can create more interesting ones. You can also refer to Share Extension to create your extension homepage, where you can introduce your extensions, describe how to use them, and discuss your ideas with other users.

Download extension package

Download Extension Package

More Tutorials

results matching ""

    No results matching ""