ru:tutorial:commands
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
ru:tutorial:commands [2020/10/01 10:40] – created magicsweet | ru:tutorial:commands [2022/03/03 12:50] – furnygo | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Создание команда ====== | + | ====== Создание команды ====== |
Создание команд позволяет разработчику наращивать функционал и способ воздействия с пользователем через, собственно, | Создание команд позволяет разработчику наращивать функционал и способ воздействия с пользователем через, собственно, | ||
- | Это руководство расскажет как регистрировать команды и общую инофрмацию о структуре Brigadier. | + | Это руководство расскажет как регистрировать команды и общую информацию о структуре Brigadier. |
Примечание: | Примечание: | ||
Line 12: | Line 12: | ||
С исходным кодом Brigadier вы можете ознакомиться тут: https:// | С исходным кодом Brigadier вы можете ознакомиться тут: https:// | ||
- | ===== Что такое команда? | + | ===== Что такое |
- | Brigadier | + | Brigadier |
- | A '' | + | '' |
- | The single method in '' | + | Единственный метод в '' |
- | A command can be implemented in several ways as shown below: | + | Вы можете создать команду несколькими образами, |
- | **__As a lambda__** | + | **__Как лямбда-выражение__** |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Command< | Command< | ||
Line 28: | Line 28: | ||
</ | </ | ||
- | **__As an anonymous class__** | + | **__Как анонимный класс__** |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Command< | Command< | ||
Line 38: | Line 38: | ||
</ | </ | ||
- | **__Implemented as a class__** | + | **__Как часть класса__** |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
final class XYZCommand implements Command< | final class XYZCommand implements Command< | ||
Line 48: | Line 48: | ||
</ | </ | ||
- | **__As a method reference__** | + | **__Как обращение к методу__** |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
void registerCommand() { | void registerCommand() { | ||
- | // Ignore this for now, we will explain it next. | + | // Не обращайте внимание, мы объясним про это далее. |
dispatcher.register(CommandManager.literal(" | dispatcher.register(CommandManager.literal(" | ||
- | .executes(this:: | + | .executes(this:: |
} | } | ||
Line 62: | Line 62: | ||
- | The '' | + | Метод |
- | The integer can be considered the result of the command. In Minecraft, | + | Возвращаемое число можно понимать как результат команды. В Minecraft |
- | ===== A basic command | + | ===== Простейшая команда |
- | Below is a command that contains no arguments: | + | Ниже вы можете увидеть команду, |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 78: | Line 78: | ||
</ | </ | ||
- | '' | + | '' |
- | To execute this command, one must type ''/ | + | |
- | ==== A sub command | + | ===== Статические импорты |
+ | Вы можете вводить '' | ||
+ | Это также работает для собственных типов аргументов Minecraft. | ||
- | To add a sub command, | + | И ваш импорт будет выглядеть примерно так: |
+ | <code java [enable_line_numbers=" | ||
+ | // getString(ctx, | ||
+ | import static com.mojang.brigadier.arguments.StringArgumentType.getString; | ||
+ | // word() | ||
+ | import static com.mojang.brigadier.arguments.StringArgumentType.word; | ||
+ | // literal(" | ||
+ | import static net.minecraft.server.command.CommandManager.literal; | ||
+ | // argument(" | ||
+ | import static net.minecraft.server.command.CommandManager.argument; | ||
+ | // Импортировать всё | ||
+ | import static net.minecraft.server.command.CommandManager.*; | ||
+ | </ | ||
+ | |||
+ | Примечание: | ||
+ | |||
+ | Аргументы Brigadier по умолчанию находятся в '' | ||
+ | |||
+ | Аргументы Minecraft находятся в разделе '' | ||
+ | CommandManager находится в '' | ||
+ | |||
+ | ===== Подкоманда ===== | ||
+ | |||
+ | Чтобы добавить команде подкоманду, | ||
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 89: | Line 113: | ||
</ | </ | ||
- | In order to have a sub command, one needs to append the next node to the existing node. This is done use the '' | + | В целом, чтобы получить подкоманду, |
- | This creates the command | + | То, что показано ниже, создаёт команду |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 99: | Line 123: | ||
</ | </ | ||
- | It is advised to indent your code as you add nodes to the command. Usually the indentation corresponds to how many nodes deep one is on the command tree. The new line also makes it visible that another node is being added. There are alternative styles to formatting the tree command that are shown later on in this tutorial. | + | Рекомендуется делать отступы в вашем коде при добавлении узлов в команду. Обычно отступ соответствует количеству глубоких узлов в дереве команд. Новая строка также делает видимым, |
- | **So let's try running the command** | + | **Итак, давайте попробуем выполнить команду** |
- | Most likely if you typed ''/ | + | Скорее всего, если вы наберете |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 117: | Line 141: | ||
</ | </ | ||
- | ===== Registering the commands | + | ===== Регистрация команд |
- | Registering commands is done by registering a callback using the '' | + | Регистрация команд выполняется путем регистрации обратного вызова с помощью |
- | The event should be registered in your mod's initializer. The callback has two parameters. The '' | + | Событие должно быть зарегистрировано в инициализаторе вашего мода. Обратный вызов имеет два параметра. '' |
Line 135: | Line 159: | ||
</ | </ | ||
- | Inside your lambda, method reference or whatever you have chosen, you will register your commands. | + | Внутри вашего лямбда-выражения, ссылки на метод или чего бы вы ни выбрали, зарегистрируете свои команды: |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 151: | Line 175: | ||
</ | </ | ||
- | If desired, you can make sure a command is only registered on a dedicated server by checking the '' | + | При желании вы можете убедиться, что команда зарегистрирована только на выделенном сервере, |
Line 167: | Line 191: | ||
</ | </ | ||
- | And vice versa | + | И наоборот: |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
Line 182: | Line 206: | ||
</ | </ | ||
- | ===== Arguments | + | ===== Аргументы |
- | + | ||
- | Arguments in Brigadier both parse and error check any inputted arguments. | + | |
- | Minecraft creates some special argument types for it's own use such as the '' | + | |
- | + | ||
- | **TODO:** Go into more detail on how to use arguments | + | |
- | + | ||
- | ===== Static Imports ===== | + | |
- | You could type out '' | + | |
- | This also works for Minecraft' | + | |
- | + | ||
- | And your imports would look something like this: | + | |
- | <code java [enable_line_numbers=" | + | |
- | // getString(ctx, | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.getString; | + | |
- | // word() | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.word; | + | |
- | // literal(" | + | |
- | import static net.minecraft.server.command.CommandManager.literal; | + | |
- | // argument(" | + | |
- | import static net.minecraft.server.command.CommandManager.argument; | + | |
- | // Import everything | + | |
- | import static net.minecraft.server.command.CommandManager.*; | + | |
- | </ | + | |
- | + | ||
- | Note: Please be sure you use the '' | + | |
- | + | ||
- | Brigadier' | + | |
- | Minecraft' | + | Аргументы в Brigadier как анализируют, |
- | CommandManager is in '' | + | Minecraft |
- | ====== Advanced concepts ====== | + | **Будет сделано позже: |
- | Below are links to the articles about more complex concepts used in brigadier. | + | ====== Дополнительные концепции ====== |
- | ^ Page ^ Description | + | Ниже приведены ссылки на статьи о более сложных концепциях, |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | **TODO:** Sections are being moved to sub categories and will be added to their respective articles as they are migrated. | + | ^ Страница |
+ | | [[ru:tutorial: | ||
+ | | [[ru: | ||
+ | | [[ru: | ||
+ | | [[ru: | ||
+ | | [[ru: | ||
+ | | [[ru: | ||
- | ====== | + | ====== |
- | ===== Why does my command not compile | + | ===== Почему моя команда не компилируется? |
- | There are two immediate possibilities for why this could occur. | + | Есть две непосредственные возможности того, почему это могло произойти. |
- | ==== Catch or throw a CommandSyntaxException ==== | + | ==== Поймать или вызвать исключение |
- | The solution to this issue is to make the run or suggest | + | Решение этой проблемы состоит в том, чтобы заставить методы |
- | ==== Issues with generics | + | ==== Проблемы с дженериками |
- | You may have an issue with generic types once in a while. Verify you are using '' | + | Время от времени у вас могут возникать проблемы с типами дженерика. Убедитесь, |
- | ===== Can I register client side commands? ===== | + | ===== Могу ли я зарегистрировать команды на стороне клиента? ===== |
- | Fabric | + | Fabric |
- | ===== Dark Arts ===== | + | ===== " |
- | A few things we don't recommend, but are possible. | + | Несколько вещей, которые мы не рекомендуем, |
- | ==== Can I register commands in runtime? ==== | + | ==== Могу ли я регистрировать команды во время выполнения? ==== |
- | You can do this but it is not recommended. You would get the '' | + | Вы можете это сделать, |
- | After that you need to send the command tree to every player again using '' | + | После этого вам нужно снова отправить дерево команд каждому игроку, |
- | ==== Can I unregister commands in runtime? ==== | + | ==== Могу ли я отменить регистрацию команд во время выполнения? ==== |
- | You can also do this, however it is much less stable than registering commands and could cause unwanted side effects. To keep things simple, you need to use reflection on brigadier and remove the nodes. After this, you need to send the command tree to every player again using '' | + | Вы также можете сделать это, однако это гораздо менее стабильно, |
---- | ---- | ||
- | ====== | + | ====== |
**__Currently this article is being migrated, so things may be a mess. Below is are the parts of the article that are yet to be migrated to the new format.__** | **__Currently this article is being migrated, so things may be a mess. Below is are the parts of the article that are yet to be migrated to the new format.__** |
ru/tutorial/commands.txt · Last modified: 2022/03/03 13:27 by furnygo