Материал из Скретч Вики

< Участник:Gohoski

SandCastleIcon.png Эта статья содержит ссылки на веб-сайты или программы, не доверенные командой Скретча или предоставляемые Википедией. Помните о безопасности при пользовании Интернетом, так как мы не можем гарантировать безопасность других сайтов.
Эта статья или раздел документирует текущую версию Скретча (3.0). Для данной статьи о Скретч 2.0 см. Участник:Gohoski/Черновик (2.0). Для статьи о Скретч 1.4 см. Участник:Gohoski/Черновик (1.4).

Хоть и Скретч может показаться сложным для некоторых пользователей, некоторые скретчеры создают модификации или моды программы, чтобы добавить больше функций или блоков, настроить графический интерфейс (UI) или улучшить производительность. Скретч 3.0 был разработан на языке программирования JavaScript.

Перед тем, как начать

Требования

Программное обеспечение

Перед тем, как начать модифицировать Скретч, установите следующее ПО на Ваш компьютер:

  • Git: Git позволяет клонировать (скачать) исходный код Скретч 3.0 и, если Вы хотите, опубликовать свою модификацию в репозиторий, доступный всем.
  • Node.js: Node.js — это фреймворк, позволяющий выполнять JavaScript-код в командной строке и включает в себя пакетный менеджер NPM.
  • Редактор кода (необязательно): Модификация Скретча может быть сделана в текстовом редакторе вроде «Блокнота», однако мод легче писать с помощью редактора кода, по типу Visual Studio Code или IntelliJ IDEA.
  • Python 2 (необязательно): Если Ваш мод добавляет новые блоки, Вам понадобится Python 2.
Информация.png Scratch Blocks is incompatible with Python 3.x. Use Python 2.x instead.Шаблон:Cite post
  • Java Compiler (optional): Scratch Blocks requires Java to build. Although there is an online compiler, it can cause problems.Шаблон:Cite post
  • Windows Subsystem for Linux (optional): If using Windows, running the commands in a Linux environment will help prevent errors.[1]

Knowledge

Additionally you should have some knowledge of the following:

  • JavaScript
  • React (JavaScript library)
  • HTML
  • CSS
  • NPM
  • Git

How Scratch 3.0 is organized

Основная статья: Scratch Source Code#Scratch 3.0
Scratch 3.0 program repository sections.png

Scratch 3.0 is designed in a modular way. Every part is a different repository on GitHub.

As you add functionality to your mod, your mod's folder will contain a sub-folder for each component. For example, your mod may look like this:

scratch_mod
    scratch-gui
        ...
    scratch-vm
        ...
    scratch-blocks
        ...

Most mods will only require modifications to Scratch GUI, Scratch Blocks, and Scratch VM.

Getting Started

Create a new folder for your mod. Before making any changes, the source code for at least Scratch GUI will need to be downloaded its dependencies will need to be installed.

Adding a component to your mod

Open a terminal from your mod's folder, run the command <syntaxhighlight lang="bash">git clone https://github.com/llk/scratch-*.git</syntaxhighlight> replacing the asterisk with the component's name, for example, scratch-gui. When cloning scratch-gui, it is recommended to add <syntaxhighlight lang="bash">--depth=1</syntaxhighlight> to the end of the cloning command since the Git history contains large files.

This will clone (download) the source code for the that component into into a new folder with the same name. The command will take some time to complete.

After the command completes, run <syntaxhighlight lang="bash">cd scratch-*</syntaxhighlight> to switch to the component's folder and then <syntaxhighlight lang="bash">npm install</syntaxhighlight> to install the dependencies.

Opening the GUI

The development version of the Scratch 3.0 editor

Clone and install the dependencies for scratch-gui.

From the Scratch GUI folder, run <syntaxhighlight lang="bash">npm start</syntaxhighlight> and open localhost:8601 in a browser. You should see your mod running! The editor will automatically reload whenever any changes are made to your mod if the terminal is left open.

Setting up Scratch Blocks

Setting up Scratch Blocks is a little different from the other components since it requires Python, Java and Google's closure library to compile and must be re-compiled every time a change is made. After cloning it, run ln -s $(npm root)/google-closure-library ../closure-library to download the closure library into a new sub-folder of the mod's main folder.

You can safely ignore most warnings, but if <syntaxhighlight lang="bash" inline>npm install</syntaxhighlight> fails with an error, delete the closure-library folder's contents and extract the March 2019 release into it instead.

Run <syntaxhighlight lang="bash">npm run prepublish</syntaxhighlight> when changes are made to Scratch Blocks to re-compile it so that they are reflected by the GUI.

Linking other components

To link other components, start by cloning and installing them, then run <syntaxhighlight lang="bash">npm link</syntaxhighlight> from the component's folder and <syntaxhighlight lang="bash">npm link scratch-*</syntaxhighlight> from the GUI folder. This removes the original dependency inside the GUI and replaces it with a reference to the new component's folder.

Adding or Changing a Block

Шаблон:Expand

Before adding or changing any blocks, Scratch Blocks and Scratch VM will need to be linked to the GUI.

Changing a block in Scratch Blocks

To change or create a block, open scratch-blocks/blocks_vertical which contains a file for each block category. Each file contains the code defining each block in that category, for example, the move (10) steps block looks like this: <syntaxhighlight lang="js">//Motion.js Blockly.Blocks['motion_movesteps'] = {

 /**
  * Block to move steps.
  * @this Blockly.Block
  */
 init: function() {
   this.jsonInit({
     "message0": Blockly.Msg.MOTION_MOVESTEPS,
     "args0": [
       {
         "type": "input_value",
         "name": "STEPS"
       }
     ],
     "category": Blockly.Categories.motion,
     "extensions": ["colours_motion", "shape_statement"]
   });
 }

};</syntaxhighlight> To change a block's label, open scratch-blocks/msg/messages.js and find the block, for example, the move (10) steps block looks like this: <syntaxhighlight lang="js">Blockly.Msg.MOTION_MOVESTEPS = 'move %1 steps';</syntaxhighlight>

Adding the block to the GUI

To add a block to the GUI or change its location or default values, open scratch-gui/src/lib/make-toolbox-xml.js and find the block, for example, the move (10) steps block: <syntaxhighlight lang="js"><block type="motion_movesteps">

 <value name="STEPS">
   <shadow type="math_number">
     <field name="NUM">10</field>
   </shadow>
 </value>

</block></syntaxhighlight>

Changing a block's behavior

To change a block's behavior or add a new one, find the block's category under scratch-vm/src/blocks, for example, scratch3_motion.js.

To change a block's behavior, find the function for the block you want to change. For example, the move (10) steps block looks like this: <syntaxhighlight lang="js">moveSteps (args, util) {

 const steps = Cast.toNumber(args.STEPS);
 const radians = MathUtil.degToRad(90 - util.target.direction);
 const dx = steps * Math.cos(radians);
 const dy = steps * Math.sin(radians);
 util.target.setXY(util.target.x + dx, util.target.y + dy);

}</syntaxhighlight> To add a new block, add an entry for it in the <syntaxhighlight lang="js" inline>getPrimitives</syntaxhighlight> function, and map it to a new function. <syntaxhighlight lang="js">class Scratch3MotionBlocks { getPrimitives () {

   return {
       motion_movesteps: this.moveSteps,
       //Other blocks
   };

};</syntaxhighlight>

Building and Releasing

To build scratch 3.0, in the GUI folder, run <syntaxhighlight lang="bash">npm run build</syntaxhighlight> Then, open scratch-gui/build/index.html in your browser. Scratch 3.0 mod should be running on its own without any localhost server running.

You can upload the contents of the build folder to whatever hosting service you want (GitHub Pages, Firebase Hosting, etc), or your own server, and share your mod on Scratch!

See Also

References

  1. Ошибка цитирования Неверный тег <ref>; для сносок modding_topic не указан текст

External Links


Cookie-файлы помогают нам предоставлять наши услуги. Используя наши сервисы, вы соглашаетесь с использованием cookie-файлов.