translate items/nodes_items_crafting

This commit is contained in:
Andrey Stepanov 2024-11-29 09:58:25 +05:00
parent 25abb55ed3
commit b36834d1dc
Signed by: Koldun
GPG Key ID: 53DE683337F5D25F

View File

@ -1,51 +1,52 @@
--- ---
title: Nodes, Items, and Crafting title: Блоки, предметы и крафт
layout: default layout: default
root: ../.. root: ../..
idx: 2.1 idx: 2.1
description: Learn how to register node, items, and craft recipes using register_node, register_item, and register_craft. description: Вы узнаете как зарегистрировать новый блок, предмет или рецепт с помощью register_node, register_item и register_craft.
redirect_from: /en/chapters/nodes_items_crafting.html redirect_from: /ru/chapters/nodes_items_crafting.html
--- ---
## Introduction <!-- omit in toc --> ## Введение <!-- omit in toc -->
Registering new nodes and craftitems, and creating craft recipes, are Регистрация новых блоков, ингредиентов и рецептов встречается практически
basic requirements for many mods. во всех модах.
- [What are Nodes and Items?](#what-are-nodes-and-items) - [Что такое Блоки и Предметы?](#what-are-nodes-and-items)
- [Registering Items](#registering-items) - [Регистрация предметов](#registering-items)
- [Item Names](#item-names) - [Названия предметов](#item-names)
- [Item Aliases](#item-aliases) - [Псевдонимы](#item-aliases)
- [Textures](#textures) - [Текстуры](#textures)
- [Registering a basic node](#registering-a-basic-node) - [Регистрация простого блока](#registering-a-basic-node)
- [Crafting](#crafting) - [Рецепты](#crafting)
- [Shaped](#shaped) - [Shaped](#shaped)
- [Shapeless](#shapeless) - [Shapeless](#shapeless)
- [Cooking and Fuel](#cooking-and-fuel) - [Cooking и Fuel](#cooking-and-fuel)
- [Groups](#groups) - [Группы](#groups)
- [Tools, Capabilities, and Dig Types](#tools-capabilities-and-dig-types) - [Инструменты, Возможности, and Способы ломания](#tools-capabilities-and-dig-types)
## What are Nodes and Items? ## Что такое Блоки и Предметы?
Nodes, craftitems, and tools are all Items. An item is something that could be Все блоки и инструменты также являются Предметами. Предмет — это то,
found in an inventory - even if it isn't possible through normal gameplay. что может лежать в инвентаре (даже если правила игры это запрещают).
A node is an item that can be placed or be found in the world. Every position Блок — это Предмет, который может быть поставлен или найден в мире. В каждом
in the world must be occupied with one and only one node - seemingly blank вокселе мира всегда находится один и только один блок (пустое место — это,
positions are usually air nodes. обычно, блок воздуха).
A craftitem can't be placed and is only found in inventories or as a dropped item Обычные предметы (не блоки) не могут быть поставлены в мире, а могут только
in the world. находиться в инвентаре или выпадать в мир.
A tool is like a craftitem but has the ability to wear. As you use the tool, the Инструмент похож на обычный предмет, но его можно использовать. Когда вы
wear bar goes down until the tool breaks. Tools can also never be stacked. In используете инструмент, шкала его прочности уменьшается до тех пор, пока он
the future, it's likely that craftitems and tools will merge into one type of не сломается. Инструменты не могут быть сгруппированы в стак. В будущем,
item, as the distinction between them is rather artificial. возможно, Инструменты не будут выделяться в отдельный тип, поскольку различие
между ними и обычными предметами довольно условное.
## Registering Items ## Регистрация предметов
Item definitions consist of an *item name* and a *definition table*. Объявление предмета состоит из *названия* и *аттрибутов*.
The definition table contains attributes that affect the behaviour of the item. В аттрибутах записаны различные параметры, влияющие на поведение предмета.
```lua ```lua
core.register_craftitem("modname:itemname", { core.register_craftitem("modname:itemname", {
@ -54,63 +55,60 @@ core.register_craftitem("modname:itemname", {
}) })
``` ```
### Item Names ### Названия предметов
Every item has an item name used to refer to it, which should be in the У каждого предмета есть название для обращения к нему, которое должно иметь
following format: следующий формат:
modname:itemname modname:itemname
The modname is the name of the mod in which the item is registered, and the item `modname` — это имя мода, в котором предмет зарегистрирован, а `itemname` — это
name is the name of the item itself. The item name should be relevant to what название самого предмета. Название предмета должно быть уникальным и должно
the item is and can't already be registered. отражать его суть.
Both `modname` and `itemname` should only contain lowercase letters, numbers, Для написания `modname` и `itemname` используются только строчные буквы
and underscores. английского алфавита, цифры и подчёркивания.
### Item Aliases ### Псевдонимы
Items can also have *aliases* pointing to their name. An *alias* is a У предметов могут быть *псевдонимы*. Игровой движок работает с псевдонимами
pseudo-item name that results in the engine treating any occurrences of the предметов как будто это сами предметы. Псевдонимы используются в двух случаях:
alias as if it were the item name. There are two main common uses of this:
* Renaming removed items to something else. * Чтобы переименовать удалённые предметы на что нибудь другое. На карте или
There may be unknown nodes in the world and in inventories if an item is в инвентаре могут появится *неизвестные блоки* (unknown nodes), если
removed from a mod without any corrective code. просто удалить предмет из мода без исправления кода.
* Adding a shortcut. `/giveme dirt` is easier than `/giveme default:dirt`. * Для сокращения названий. Команда `/giveme dirt` получается короче,
чем `/giveme default:dirt`.
Registering an alias is pretty simple. A good way to remember the order of the Зарегистрировать псевдоним очень просто. Нужно запомнить правильный порядок
arguments is `from → to` where *from* is the alias and *to* is the target. аргументов `from → to`, гле *from* — это псевдоним, а *to* — это сам предмет.
```lua ```lua
core.register_alias("dirt", "default:dirt") core.register_alias("dirt", "default:dirt")
``` ```
Mods need to make sure to resolve aliases before dealing directly with item names, Моды должны всегд разименовывать псевдонимы перед тем как работать с именем
as the engine won't do this. предмета, потому что движок сам этого не делает. Но это довольно просто:
This is pretty simple though:
```lua ```lua
itemname = core.registered_aliases[itemname] or itemname itemname = core.registered_aliases[itemname] or itemname
``` ```
### Textures ### Текстуры
Textures should be placed in the textures/ folder with names in the format Файлы текстур нужно класть в папку textures/ и давать имена в следующем
`modname_itemname.png`.\\ формате: `modname_itemname.png`.\\
JPEG textures are supported, but they do not support transparency and are generally Можно использовать текстуры в формате JPEG, но они не поддерживают прозрачность
bad quality at low resolutions. и, обычно, плохо выглядят при низком разрешении. Лучше использовать формат PNG.
It is often better to use the PNG format.
Textures in Minetest are usually 16 by 16 pixels. They can be any resolution, Обычно, текстуры в Minetest имеют размер 16 на 16 пикселей. Вообще, разрешение
but it is recommended that they are in the order of 2, for example, 16, 32, 64, может быть любым, но рекомендуется использовать значения степени двойки,
or 128. This is because other resolutions may not be supported correctly on например 16, 32, 64 или 128. В противном случае они могут вызвать проблемы
older devices, especially phones, resulting in degraded performance. с производительностью на старых компьютерах и особенно телефонах.
## Registering a basic node ## Регистрация простого блока
Registering nodes is similar to registering items, just with a different Блоки регистрируются так же, как и предметы, только другой функцией:
function:
```lua ```lua
core.register_node("mymod:diamond", { core.register_node("mymod:diamond", {
@ -121,18 +119,18 @@ core.register_node("mymod:diamond", {
}) })
``` ```
Node definitions can contain any property in an item definition, and also При объявлении блока в список аттрибутов добавляются дополнительные свойства,
contain additional properties specific to nodes. характерные для блоков.
The `tiles` property is a table of texture names the node will use. Свойство `tiles` — это таблица с именами текстур этого блока.
When there is only one texture, this texture is used on every side. Если указана только одна текстура, она используется для всех сторон блока.
To give a different texture per-side, supply the names of 6 textures in this order: Если нужно указать разные текстуры для сторон, то они должны быть перечислены
в следующем порядке:
up (+Y), down (-Y), right (+X), left (-X), back (+Z), front (-Z). сверху (+Y), снизу (-Y), справа (+X), слева (-X), сзади (+Z), спереди (-Z).
(+Y, -Y, +X, -X, +Z, -Z) (+Y, -Y, +X, -X, +Z, -Z)
Remember that +Y is upwards in Minetest, as is the convention with Запомните, что +Y это верх в Minetest, как и в большинстве других игр.
most 3D computer games.
```lua ```lua
core.register_node("mymod:diamond", { core.register_node("mymod:diamond", {
@ -148,34 +146,33 @@ core.register_node("mymod:diamond", {
is_ground_content = true, is_ground_content = true,
groups = {cracky = 3}, groups = {cracky = 3},
drop = "mymod:diamond_fragments" drop = "mymod:diamond_fragments"
-- ^ Rather than dropping diamond, drop mymod:diamond_fragments -- ^ Выпадает не сам алмаз, а mymod:diamond_framgents
}) })
``` ```
The `is_ground_content` attribute allows caves to be generated over the stone. Свойство `is_ground_content` позволяет генерировать пещеры в каменной толще.
This is essential for any node which may be placed during map generation underground. Это важно для всех блоков, которые должны появляться под землёй в процессе
Caves are cut out of the world after all the other nodes in an area have generated. генерации карты. Пещеры прорезаются после того, как будут сгенерированы все
остальные блоки в данной области.
## Crafting ## Рецепты
There are several types of crafting recipe available, indicated by the `type` Существует несколько типов рецептов, которые указываются через свойство `type`.
property.
* shaped - Ingredients must be in the correct position. * shaped — Ингредиенты должны быть сложены в правильном порядке.
* shapeless - It doesn't matter where the ingredients are, * shapeless — Порядок ингредиентов не важен, важно лишь их наличие
just that there is the right amount. и количество.
* cooking - Recipes for the furnace to use. * cooking — Можно приготовить в печи.
* fuel - Defines items which can be burned in furnaces. * fuel — Может быть топливом для печи.
* tool_repair - Defines items which can be tool repaired. * tool_repair — Можно отремонтировать инструментом.
Craft recipes are not items, so they do not use Item Names to uniquely Рецепты крфта — это не предметы, и поэтому им не нужно указывать имя.
identify themselves.
### Shaped ### Shaped
Shaped recipes are when the ingredients need to be in the right shape or Для рецептов `shaped` важно расположение ингредиентов в сетке крафта.
pattern to work. In the example below, the fragments need to be in a В примере ниже фрагменты нужно расположить в форме стула, чтобы рецепт
chair-like pattern for the craft to work. сработал:
```lua ```lua
core.register_craft({ core.register_craft({
@ -189,11 +186,10 @@ core.register_craft({
}) })
``` ```
One thing to note is the blank column on the right-hand side. Обратите внимание на пустую колонку в правой части.
This means that there *must* be an empty column to the right of the shape, otherwise Так обозначается, что *должна* быть пустая колонка справа, иначе рецепт
this won't work. не будет работать.
If this empty column shouldn't be required, then the empty strings can be left Если пустая колонка не требуется, постые строки можно не указывать:
out like so:
```lua ```lua
core.register_craft({ core.register_craft({
@ -206,13 +202,13 @@ core.register_craft({
}) })
``` ```
The type field isn't actually needed for shaped crafts, as shaped is the Свойство type можно не указывать, потому что все рецепты по умолчанию
default craft type. считаются shaped.
### Shapeless ### Shapeless
Shapeless recipes are a type of recipe which is used when it doesn't matter В рецептах `shapeless` не важно расположение ингредиентов, они просто должны
where the ingredients are placed, just that they're there. быть.
```lua ```lua
core.register_craft({ core.register_craft({
@ -226,10 +222,10 @@ core.register_craft({
}) })
``` ```
### Cooking and Fuel ### Cooking и Fuel
Recipes with the type "cooking" are not made in the crafting grid, Рецепты типа `cooking` предназначены не для сетки крафта, а для приготовления
but are cooked in furnaces, or other cooking tools that might be found in mods. в различных типах печей.
```lua ```lua
core.register_craft({ core.register_craft({
@ -240,18 +236,17 @@ core.register_craft({
}) })
``` ```
The only real difference in the code is that the recipe is just a single item, Единственное отличие в коде такого рецепта заключается в том, что поле recipe —
compared to being in a table (between braces). это просто одно свойство, а не таблица. Кроме того, в таких рецептах можно
They also have an optional "cooktime" parameter which указывать свойство "cooktime", в котором задаётся время приготовления.
defines how long the item takes to cook. По умоланию, оно равно 3.
If this is not set, it defaults to 3.
The recipe above works when the coal block is in the input slot, Указанный выше рецепт работает, когда во входной слот печи кладут блок угля,
with some form of fuel below it. а в слот топлива — какое-нибудь топливо. Через 10 секунд на выходе получается
It creates diamond fragments after 10 seconds! кусочек алмаза.
This type is an accompaniment to the cooking type, as it defines Рецепты типа `fuel` дополняют рецепты типа `cooking`. Они указывают, что
what can be burned in furnaces and other cooking tools from mods. можно использовать в качестве топлива в печах.
```lua ```lua
core.register_craft({ core.register_craft({
@ -261,24 +256,25 @@ core.register_craft({
}) })
``` ```
They don't have an output like other recipes, but they have a burn time У таких рецептов нет свойства output, но есть свойство burntime, определяющее
which defines how long they will last as fuel in seconds. время горения предмета в печи (в секнудах). В данном примере алмаз получается
So, the diamond is good as fuel for 300 seconds! хорошим топливом, потому что он горит целых 300 секунд!
## Groups ## Группы
Items can be members of many groups and groups can have many members. Предметы можно объединять в группы, и в группах может быть множество предметов.
Groups are defined using the `groups` property in the definition table Принадлежность к группе указывается с помощью аттрибута `groups` в таблице
and have an associated value. аттрибутов.
```lua ```lua
groups = {cracky = 3, wood = 1} groups = {cracky = 3, wood = 1}
``` ```
There are several reasons you use groups. Есть несколько причин указывать группы.
Firstly, groups are used to describe properties such as dig types and flammability. Во первых, группы позволяют указать такие свойства, как способ ломания блока
Secondly, groups can be used in a craft recipe instead of an item name to allow и его горючесть.
any item in the group to be used. Во вторых, в рецептах крафта в качестве ингредиентов можно указывать группы
вместо конкретных предметов.
```lua ```lua
core.register_craft({ core.register_craft({
@ -289,37 +285,36 @@ core.register_craft({
``` ```
## Tools, Capabilities, and Dig Types ## Инструменты, Возможности, и Способы ломания
Dig types are groups which are used to define how strong a node is when dug Способы ломания — это группы, которые обозначают, насколько блок устойчив
with different tools. к разным типам инструментов.
A dig type group with a higher associated value means the node is easier Чем большее значение задано группе, тем проще сломать блок данным видом
and quicker to cut. инструмента.
It's possible to combine multiple dig types to allow the more efficient use Можно комбинировать несколько способов ломания, чтобы позволить игрокам
of multiple types of tools. эффективнее использовать разные виды инструментов.
A node with no dig types cannot be dug by any tools. Если не указать никакой из способов ломания, блок нельзя будет сломать.
| Group | Best Tool | Description | | Группа | Инструмент | Описание |
|--------|-----------|-------------| |-------------------------|------------|--------------------------------------------------------------------------------------|
| crumbly | spade | Dirt, sand | | crumbly | лопата | Земля, песок |
| cracky | pickaxe | Tough (but brittle) stuff like stone | | cracky | кирка | Твердый (но хрупкий) материал. Например, камень. |
| snappy | *any* | Can be cut using fine tools;<br>e.g. leaves, smallplants, wire, sheets of metal | | snappy | *любой* | Можно сломать чем угодно. Например, листья, неболшие растения, проволока. |
| choppy | axe | Can be cut using a sharp force; e.g. trees, wooden planks | | choppy | топор | Можно разрубить. Например, деревья, доски. |
| fleshy | sword | Living things like animals and the player.<br>This could imply some blood effects when hitting. | | fleshy | меч | Живые объекты, такие как животные или игроки.<br>Могут быть эффекты крови при ударе. |
| explody | ? | Especially prone to explosions | | explody | ? | Может взрываться |
| oddly_breakable_by_hand | *any* | Torches and such - very quick to dig | | oddly_breakable_by_hand | *любой* | Факелы и подобные быстро ломаемые вещи |
Every tool has a tool capability. У каждого инструмента есть Возможности — это список типов ломания
A capability includes a list of supported dig types, and associated properties с соответствующими свойствами, такими как время ломания и степень износа.
for each type such as dig times and the amount of wear. Кроме того, можно указывать максимально допустимую прочность блоков, которые
Tools can also have a maximum supported hardness for each type, which makes можно ломать данным инструментом. Таким образом можно запретить ломать твёрдые
it possible to prevent weaker tools from digging harder nodes. блоки слишком простыми инструментами. Обычно, всем инструментам указывают все
It's very common for tools to include all dig types in their capabilities, возможные способы ломания, делая неподходящие способы сильно неэффективными.
with the less suitable ones having very inefficient properties. Если игрок пытается сломать блок инструментом, не поддерживающим такой тип
If the item a player is currently wielding doesn't have an explicit tool блоков, то будет применяться свойство рук, а не инструмента.
capability, then the capability of the current hand is used instead.
```lua ```lua
core.register_tool("mymod:tool", { core.register_tool("mymod:tool", {
@ -340,6 +335,6 @@ core.register_tool("mymod:tool", {
}) })
``` ```
Groupcaps is the list of supported dig types for digging nodes. `groupcaps` — это список поддерживаемых Способов ломания.
Damage groups are for controlling how tools damage objects, which will be `damage_groups` позволяет указать, каким образом инструмент повреждает блок,
discussed later in the Objects, Players, and Entities chapter. это будет описано позже в главе "Объекты, Игроки и Сущности".