User Tools

Site Tools


ru:tutorial:commands

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
Next revisionBoth sides next revision
ru:tutorial:commands [2020/10/01 10:40] – created magicsweetru:tutorial:commands [2022/03/03 12:50] furnygo
Line 1: Line 1:
-====== Создание команда ======+====== Создание команды ======
  
 Создание команд позволяет разработчику наращивать функционал и способ воздействия с пользователем через, собственно, команды. Создание команд позволяет разработчику наращивать функционал и способ воздействия с пользователем через, собственно, команды.
-Это руководство расскажет как регистрировать команды и общую инофрмацию о структуре Brigadier.+Это руководство расскажет как регистрировать команды и общую информацию о структуре Brigadier.
  
 Примечание: Весь код, описанный здесь, написан для 1.14.4. Что-то может быть изменено в yarn, но большая часть кода всё ещё применима и там. Примечание: Весь код, описанный здесь, написан для 1.14.4. Что-то может быть изменено в yarn, но большая часть кода всё ещё применима и там.
Line 12: Line 12:
 С исходным кодом Brigadier вы можете ознакомиться тут: https://github.com/Mojang/brigadier С исходным кодом Brigadier вы можете ознакомиться тут: https://github.com/Mojang/brigadier
  
-===== Что такое команда? =====+===== Что такое "команда"? =====
  
-Brigadier requires you specify the ''Command'' to be run"commandis a fairly loose term within brigadierbut typically it means an exit point of the command treeThis is where the code is executed for your command+Brigadier требует описание ''команды'' чтобы её исполнятьНа самом деле, "командаэто довольно неточный термин, если мы говорим о Brigadier, но обычно он означает конечную точку для командыт.е. то место, где исполняется ваш код
-''Command'' is a functional interfaceThe command has a generic type of ''S'' which defines the type of the command sourceThe command source provides some context in which a command was ranIn Minecraft, this is typically a ''ServerCommandSource'' which can represent a servera command blockrcon connectiona player or an entity.+''Command'' - это функциональный интерфейсКоманда имеет подтип ''S'', где ''S'' - это источник командыИсточник команды может предоставить некий "контекст" для неёВ Minecraft обычно используется ''ServerCommandSource'', что представляет сервер, командный блоксоединение RCONигрока или сущность.
  
-The single method in ''Command''''run(CommandContext<S>)'' takes a ''CommandContext<S>'' as the sole parameter and returns an integerThe command context holds your command source of ''S'' and allows you to obtain argumentslook at the parsed command nodes and see the input used in this command.+Единственный метод в ''Command'' ''run(CommandContext<S>)'' принимает один параметр ''CommandContext<S>'' и возвращает целое числоКонтекст команды (CommandContext) типа ''S'' содержит в себе ''S'', позволяет увидеть используемые аргументыработать с обработанными аргументами и посмотреть на непосредственный ввод пользователя.
  
-A command can be implemented in several ways as shown below:+Вы можете создать команду несколькими образами, которые написаны ниже:
  
-**__As a lambda__**+**__Как лямбда-выражение__**
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 Command<Object> command = context -> { Command<Object> command = context -> {
Line 28: Line 28:
 </code> </code>
  
-**__As an anonymous class__**+**__Как анонимный класс__**
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 Command<Object> command = new Command<Object>() { Command<Object> command = new Command<Object>() {
Line 38: Line 38:
 </code> </code>
  
-**__Implemented as a class__**+**__Как часть класса__**
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 final class XYZCommand implements Command<Object> { final class XYZCommand implements Command<Object> {
Line 48: Line 48:
 </code> </code>
  
-**__As a method reference__**+**__Как обращение к методу__**
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 void registerCommand() { void registerCommand() {
-    // Ignore this for nowwe will explain it next.+    // Не обращайте вниманиемы объясним про это далее.
     dispatcher.register(CommandManager.literal("foo"))     dispatcher.register(CommandManager.literal("foo"))
-        .executes(this::execute); // This refers to the "executemethod below.+        .executes(this::execute); // Это относится к приведённому ниже методу "выполнить".
 } }
  
Line 62: Line 62:
  
  
-The ''run(CommandContext)'' method can throw a ''CommandSyntaxException'', but this is covered later in the tutorial+Метод ''run(CommandContext)'' может произвести исключение ''CommandSyntaxException'', это будет объяснено далее в руководстве
  
-The integer can be considered the result of the commandIn Minecraft, the result can correspond to the power of a redstone comparator feeding from a command block or the value that will be passed the chain command block the command block is facingTypically negative values mean a command has failed and will do nothing. A result of ''0'' means the command has passed. Positive values mean the command was successful and did something.+Возвращаемое число можно понимать как результат командыВ Minecraft результатом может являться силой сигнала красного камнякоторый выдаёт командный блок или число, которое будет передано в следующий цепной командный блокОбычно отрицательное число значит что команда не выполнена и что-то пошло не по плану, ''0'' что команда прошла, положительные числа - что выполнена и что-то произошло 
  
-===== A basic command =====+===== Простейшая команда =====
  
-Below is a command that contains no arguments:+Ниже вы можете увидеть команду, без аргументов:
  
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
Line 78: Line 78:
 </code> </code>
  
-''CommandManager.literal("foo")'' tells brigadier this command has one node**literal** called ''foo''. +''CommandManager.literal("foo")'' даёт brigadier'у понятьчто у команды только одна ветвь, это **буквальный ввод** foo. Чтобы команда была выполненанужно ввести ''/foo''Если введено ''/Foo'', ''/FoO'', ''/FOO'', ''/fOO'' или ''/fooo'', команда не будет считаться верной.
-To execute this commandone must type ''/foo''If ''/Foo'', ''/FoO'', ''/FOO'', ''/fOO'' or ''/fooo'' is typed insteadthe command will not run.+
  
-==== A sub command ====+===== Статические импорты ===== 
 +Вы можете вводить ''CommandManager.literal("foo")'' каждый раз, когда хотите создать литерал. Это работает, но вы можете статически импортировать аргументы и сократить оператор до ''literal("foo")''. Это также работает для получения значения аргумента. Это сокращает ''StringArgumentType.getString(ctx, "string")'' до ''getString(ctx, "string")''
 +Это также работает для собственных типов аргументов Minecraft.
  
-To add a sub command, you register the first literal node of the command normally.+И ваш импорт будет выглядеть примерно так: 
 +<code java [enable_line_numbers="true"]> 
 +// getString(ctx, "string"
 +import static com.mojang.brigadier.arguments.StringArgumentType.getString; 
 +// word() 
 +import static com.mojang.brigadier.arguments.StringArgumentType.word; 
 + // literal("foo"
 +import static net.minecraft.server.command.CommandManager.literal; 
 + // argument("bar"word()) 
 +import static net.minecraft.server.command.CommandManager.argument; 
 +// Импортировать всё 
 +import static net.minecraft.server.command.CommandManager.*; 
 +</code> 
 + 
 +Примечание: Пожалуйста, убедитесь, что вы используете ''literal'' и ''argument'' из CommandManager, иначе у вас могут возникнуть проблемы с дженериками при попытке компиляции. 
 + 
 +Аргументы Brigadier по умолчанию находятся в ''com.mojang.brigadier.arguments'' 
 + 
 +Аргументы Minecraft находятся в разделе ''net.minecraft.command.arguments''
 +CommandManager находится в ''net.minecraft.server.command'' 
 + 
 +===== Подкоманда ===== 
 + 
 +Чтобы добавить команде подкоманду, сначала необходимо зарегистрировать ветвь с буквальным вводом.
  
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
Line 89: Line 113:
 </code> </code>
  
-In order to have a sub commandone needs to append the next node to the existing nodeThis is done use the ''then(ArgumentBuilder)'' method which takes in an ''ArgumentBuilder''.+В целомчтобы получить подкоманду, нужно расширить текущую ветвь следующей, уже существующей ветвьюЭто можно сделать с помощью метода ''then(ArgumentBuilder)'' который принимает в себя ''ArgumentBuilder''.
  
-This creates the command ''foo <bar>'' as shown below.+То, что показано ниже, создаёт команду ''foo <bar>'':
  
 <code java [enable_line_numbers="true", highlight_lines_extra="2"]> <code java [enable_line_numbers="true", highlight_lines_extra="2"]>
Line 99: Line 123:
 </code> </code>
  
-It is advised to indent your code as you add nodes to the commandUsually the indentation corresponds to how many nodes deep one is on the command treeThe new line also makes it visible that another node is being addedThere 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 ''/foo bar'' in gamethe command will fail to runThis is because there is no code for the game to execute when all the required arguments have been metTo fix thisyou need to tell the game what to run when the command is being executed using the ''executes(Command)'' method. Below is how the command should look as an example.+Скорее всего, если вы наберете ''/foo bar'' в игрекоманда не будет выполненаЭто происходит потому, что нет кода для игры, который выполнялся бы после выполнения всех требуемых аргументовЧтобы исправить этовам нужно указать игре, что запускать, когда выполняется команда, используя метод ''executes(Command)''Ниже в качестве примера показано, как должна выглядеть команда:
  
 <code java [enable_line_numbers="true", highlight_lines_extra="3,4,5,6,7"]> <code java [enable_line_numbers="true", highlight_lines_extra="3,4,5,6,7"]>
Line 117: Line 141:
 </code> </code>
  
-===== Registering the commands =====+===== Регистрация команд =====
  
-Registering commands is done by registering a callback using the ''CommandRegistrationCallback''For information on registering callbacksplease see the [[tutorial:callbacks|callbacks article]].+Регистрация команд выполняется путем регистрации обратного вызова с помощью ''CommandRegistrationCallback''Для получения информации о регистрации обратных вызововознакомьтесь с [[ru:tutorial:callbacks|статьёй об обратных вызовах]].
  
-The event should be registered in your mod's initializerThe callback has two parametersThe ''CommmandDispatcher<S>'' is used to registerparse and execute commands. ''S'' is the type of command source the command dispatcher supportsThe second parameter is a boolean which identifies the type of server the commands are being registeredon is an ''dedicated'' or ''integrated'' (false) server.+Событие должно быть зарегистрировано в инициализаторе вашего модаОбратный вызов имеет два параметра. ''CommmandDispatcher<S>'' используется для регистрациианализа и выполнения команд. ''S'' i- это тип источника команд, который поддерживает диспетчер командВторой параметр - это логическое значение, которое определяет тип сервера, на котором регистрируются командыЭто может быть ''dedicated'' (выделенный) или ''integrated''(интегрированный) (false) сервер:
  
  
Line 135: Line 159:
 </code> </code>
  
-Inside your lambdamethod reference or whatever you have chosenyou will register your commands.+Внутри вашего лямбда-выраженияссылки на метод или чего бы вы ни выбрализарегистрируете свои команды:
  
 <code java [enable_line_numbers="true", highlight_lines_extra="5,6,7,8"]> <code java [enable_line_numbers="true", highlight_lines_extra="5,6,7,8"]>
Line 151: Line 175:
 </code> </code>
  
-If desiredyou can make sure a command is only registered on a dedicated server by checking the ''dedicated'' flag+При желании вы можете убедитьсячто команда зарегистрирована только на выделенном сервере, установив флажок ''dedicated''(выделенный):
  
  
Line 167: Line 191:
 </code> </code>
  
-And vice versa+И наоборот:
  
 <code java [enable_line_numbers="true", highlight_lines_extra="5,6,7"]> <code java [enable_line_numbers="true", highlight_lines_extra="5,6,7"]>
Line 182: Line 206:
 </code> </code>
  
-===== 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 ''EntityArgumentType'' which represents the in-game entity selectors ''@a, @r, @p, @e[type=!player, limit=1, distance=..2]'', or an ''NbtTagArgumentType'' that parses stringified nbt (snbt) and verifies that the input is the correct syntax. +
- +
-**TODO:** Go into more detail on how to use arguments +
- +
-===== Static Imports ===== +
-You could type out ''CommandManager.literal("foo")'' every time you want to create a literal. This works, but you can statically import the arguments and shorten the statement to ''literal("foo")''. This also works for getting the value of an argument. This shortens ''StringArgumentType.getString(ctx, "string")'' to ''getString(ctx, "string")''+
-This also works for Minecraft's own argument types. +
- +
-And your imports would look something like this: +
-<code java [enable_line_numbers="true"]> +
-// getString(ctx, "string"+
-import static com.mojang.brigadier.arguments.StringArgumentType.getString; +
-// word() +
-import static com.mojang.brigadier.arguments.StringArgumentType.word; +
- // literal("foo"+
-import static net.minecraft.server.command.CommandManager.literal; +
- // argument("bar", word()) +
-import static net.minecraft.server.command.CommandManager.argument; +
-// Import everything +
-import static net.minecraft.server.command.CommandManager.*; +
-</code> +
- +
-Note: Please be sure you use the ''literal'' and ''argument'' from CommandManager or you may have issues with generics when trying to compile. +
- +
-Brigadier's default arguments are at ''com.mojang.brigadier.arguments''+
  
-Minecraft's arguments are in ''net.minecraft.command.arguments''+Аргументы в Brigadier как анализируют, так и проверяют на ошибки любые введенные аргументы. 
-CommandManager is in ''net.minecraft.server.command''+Minecraft создает некоторые специальные типы аргументов для собственного использования, такие как ''EntityArgumentType'', который представляет внутриигровые селекторы сущностей ''@a, @r, @p, @e[type=!player, limit=1, distance=..2]'', или ''NbtTagArgumentType'', который анализирует строковый nbt (snbt) и проверяет правильность ввода синтаксиса.
  
-====== Advanced concepts ======+**Будет сделано позже:** Подробнее о том, как использовать аргументы.
  
-Below are links to the articles about more complex concepts used in brigadier.+====== Дополнительные концепции ======
  
-^ Page                                                           ^ Description                                                                     ^ +Ниже приведены ссылки на статьи о более сложных концепциях, используемых в Brigadier.
-| [[tutorials:commands:requirements|Requirements]]               | Only allow users to execute commands in certain scenarios                     | +
-| [[tutorials:commands:exceptions  |Exceptions]]                 | Fail execution of a command with a descriptive message and in certain contexts. |                                                                   +
-| [[tutorials:commands:suggestions |Suggestions]]                | Suggesting input to be sent to the client.                                      | +
-| [[tutorials:commands:redirects_aliases|Redirects (Aliases)]]   | Allow use of aliases to execute commands.                                       | +
-| [[tutorials:commands:redirects_chaining|Redirects (Chaining)]] | Allow commands to have repeating elements and flags.                            | +
-| [[tutorials:commands:argument_types|Custom Argument Types]]    | Parse your own arguments and return your own types.                             |+
  
-**TODO:** Sections are being moved to sub categories and will be added to their respective articles as they are migrated.+^ Страница                                                           ^ Описание                                                                     ^ 
 +| [[ru:tutorial:commands:requirements|Условия]]| Разрешать пользователям выполнять команды только в определенных сценариях.| 
 +| [[ru:tutorial:commands:exceptions|Исключения]]| Сбой выполнения команды с описательным сообщением и в определенных контекстах.|                                                                   
 +| [[ru:tutorial:commands:suggestions|Предложения]]| Предложение входных данных для отправки клиенту.| 
 +| [[ru:tutorial:commands:redirects_aliases|Редиректы (Разные вариации)]]| Разрешить использование разновидностей команд.| 
 +| [[ru:tutorial:commands:redirects_chaining|Редиректы (Цепочки)]]| Разрешить командам иметь повторяющиеся элементы и флаги.| 
 +| [[ru:tutorial:commands:argument_types|Свои типы аргументов]]| Анализируйте свои аргументы и возвращайте свои типы.|
  
-====== FAQ ======+====== Часто задаваемые вопросы ======
  
-===== Why does my command not compile =====+===== Почему моя команда не компилируется? =====
  
-There are two immediate possibilities for why this could occur.+Есть две непосредственные возможности того, почему это могло произойти.
  
-==== Catch or throw a CommandSyntaxException ====+==== Поймать или вызвать исключение CommandSyntaxException ====
  
-The solution to this issue is to make the run or suggest methods throw a CommandSyntaxException. Don't worrybrigadier will handle the exceptions and output the proper error message.+Решение этой проблемы состоит в том, чтобы заставить методы run или suggest вызывать исключение CommandSyntaxException. Не волнуйтесьBrigadier обработает исключения и выдаст соответствующее сообщение об ошибке.
  
-==== Issues with generics ====+==== Проблемы с дженериками ====
  
-You may have an issue with generic types once in a whileVerify you are using ''CommandManager.literal(...)'' or ''CommandManager.argument(...)'' instead ''LiteralArgumentBuilder'' or ''RequiredArgumentBuilder''.+Время от времени у вас могут возникать проблемы с типами дженерикаУбедитесь, что вы используете ''CommandManager.literal(...)'' или ''CommandManager.argument(...)'' вместо ''LiteralArgumentBuilder'' или ''RequiredArgumentBuilder''.
  
-===== Can I register client side commands? =====+===== Могу ли я зарегистрировать команды на стороне клиента? =====
  
-Fabric doesn't currently support client side commandsThere is a [[https://github.com/CottonMC/ClientCommands|third-party mod]] by the Cotton team that adds this functionality.+Fabric в настоящее время не поддерживает команды на стороне клиентаСуществует [[https://github.com/CottonMC/ClientCommands|сторонний мод]] от команды Cotton, которая добавляет эту функциональность.
  
-===== Dark Arts =====+===== "Темные искусства" =====
  
-A few things we don't recommendbut are possible.+Несколько вещейкоторые мы не рекомендуем, но которые возможны.
  
-==== Can I register commands in runtime? ====+==== Могу ли я регистрировать команды во время выполнения? ====
  
-You can do this but it is not recommendedYou would get the ''CommandManager'' from the server and add anything commands you wish to it'''CommandDispatcher''.+Вы можете это сделать, но это не рекомендуетсяВы получите ''CommandManager'' с сервера и добавите любые команды, которые пожелаете, в его ''CommandDispatcher''.
  
-After that you need to send the command tree to every player again using ''sendCommandTree(ServerPlayerEntity)''This is required because the client locally caches the command tree it receives during login (or when operator packets are sentfor local completions rich error messages.+После этого вам нужно снова отправить дерево команд каждому игроку, используя ''sendCommandTree(ServerPlayerEntity)''Это необходимо, поскольку клиент локально кэширует дерево команд, которое он получает во время входа в систему (или при отправке пакетов операторадля локальных завершений и сообщений об ошибках.
  
-==== Can I unregister commands in runtime? ====+==== Могу ли я отменить регистрацию команд во время выполнения? ====
  
-You can also do thishowever it is much less stable than registering commands and could cause unwanted side effectsTo keep things simpleyou need to use reflection on brigadier and remove the nodesAfter thisyou need to send the command tree to every player again using ''sendCommandTree(ServerPlayerEntity)''If you don't send the updated command treethe client may think a command still existseven though the server will fail execution.+Вы также можете сделать этооднако это гораздо менее стабильно, чем регистрация команд, и может вызвать нежелательные побочные эффектыЧтобы все было простовам нужно использовать отражение для бригадира и удалить узлыПосле этого вам нужно снова отправить дерево команд каждому игрокуиспользуя ''sendCommandTree(ServerPlayerEntity)''Если вы не отправите обновленное дерево команд, клиент может подуматьчто команда все еще существуетдаже если сервер завершит выполнение с ошибкой.
  
 ---- ----
  
-====== Sorry for the mess ======+====== Со временем уберётся ======
  
 **__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