Изменения

Материал из Chaotic Onyx
Перейти к навигацииПерейти к поиску
м
Строка 1: Строка 1:  +
{{Устарело}}
 
''Это 4 глава перевода оригинального руководства по Dream Maker от разработчиков.''
 
''Это 4 глава перевода оригинального руководства по Dream Maker от разработчиков.''
   Строка 5: Строка 6:  
[http://www.byond.com/docs/guide/chap04.html Оригинальная 4 глава руководства на английском языке]
 
[http://www.byond.com/docs/guide/chap04.html Оригинальная 4 глава руководства на английском языке]
   −
= Глава 4: Verbs =
+
{{Заготовка}}
   −
''It might be only a dream after all, part and parcel of this magic house of dreams.'' -- L.M. Montgomery, Anne's House of Dreams
+
= Глава 4: Действия verb =
   −
Players have several ways to interact with their world. They can move around with the arrow keys, select objects with the mouse, and type commands (or select them from a menu). In DM, the commands you define for players to use are called verbs. They form a sort of player language.
+
''В конце концов, это может быть всего лишь сон. Только часть и лишь один слой этого пристанища грез.'' — Л.М. Монтогомери, Пристанище снов Анны.
   −
== Defining a Verb ==
+
У игроков есть несколько способов взаимодействовать с окружающим миром: они могут передвигаться с помощью стрелок на клавиатуре, выбирать объекты с помощью мыши и вводить команды (или выбирать их в меню). В DM команда, которую вы создаете для использования игроками, называется ''verb'' (''действие''). Они составляют язык общения игроков с сервером.
   −
Verbs are always attached to some object. This is done by putting the verb inside the object definition. This object is called the source of the verb. The simplest case, is a verb attached to the player's mob.
+
== Создание действия ==
 +
 
 +
Действия всегда задаются для объектов путем определения этого действия внутри описания объекта. Такой объект называют ''источником действия'' (''source''). Примитивный случай: действие, привязанное к существу игрока.
    
  mob
 
  mob
Строка 20: Строка 23:  
           density = 0  //now we can walk through walls!
 
           density = 0  //now we can walk through walls!
   −
This example defines a verb called intangible. A player who has executed this command can walk through other dense objects like walls.
+
Этот пример описывает действие ''"нематериальный"'' (''intangible''). Игрок, который использует его, получает возможность передвигаться сквозь материальные объекты, вроде стен.
   −
As you can see, the definition goes inside a node called verb and is followed by parentheses. The name of the verb itself (like any node) follows the same rules as an object type name. It is case sensitive, consists of letters, digits, and underscores, and must not start with a digit.
+
Как вы, наверное, заметили, определение записывается под узлом ''verb'' и сопровождается круглыми скобками. Само название действия, как и любой другой узел в вашей программе, должно удовлетворять некоторым условиям: оно чувствительно к регистру, может состоять из букв, цифр и подчеркиваний, а также не должно начинаться с цифры.
   −
== Setting Verb Properties ==
+
== Свойства описания действия ==
   −
Just as with object types, you can override the actual name of the verb (as seen by the user) to overcome the limitations of the node name. This is done with the set command. Example:
+
Также, как и с объектами, вы можете задать новое имя для действия (видимое пользователем), чтобы обойти ограничения для названий узлов. Это можно сделать с помощью специальной команды:
    
  obj/lamp/verb/Break()
 
  obj/lamp/verb/Break()
Строка 32: Строка 35:  
     luminosity = 0
 
     luminosity = 0
   −
The reason the verb node could not be directly specified in lowercase is that there is a reserved word break that prevents this. Capitalization is a simple way to avoid conflicts with reserved words because they never begin with a capital letter. (If you are curious about the meaning of break hang on until chapter 6.)
+
Причина того, что этот узел не может быть задан в нижнем регистре, лежит в том, что слово ''break'' зарезервировано. Озаглавливание - простой способ избежать конфликта с зарезервированным словом, поскольку они никогда не начинаются с большой буквы. ''Если вас озадачило значение ''break'', дождитесь 6 главы.''
   −
Notice the condensed style using slashes in place of stair-step indentation. The use of the set command distinguishes between an assignment of the object's name and an assignment of the verb's name. Also note that the name assignment is said to take place at compile-time rather than run-time. Otherwise, like the assignment of luminosity, it would not happen until the verb was executed by the player.
+
Обратите внимание на использование множества слешей, заместо разделения отступами. Команда ''set'' по-разному используется для присвоения имен объектов и действий. Также заметьте, что присвоение имени происходит скорее во время компиляции, чем во время работы программы, хотя оно и не должно происходить до тех пор, пока игрок не вызовет действие, как и изменение переменной освещения, например.
   −
There are other properties of a verb that can be configured using the set command. They are presented in the following list.
+
Также существуют и другие свойства действий, описанные в следующем списке:
   −
* name
+
• '''name''' - как вы уже поняли, название действия, видимое пользователем. По умолчанию, оно соответствует названию узла действия, с заменой нижних подчеркиваний на пробелы.
As you have already seen, this is the name of the verb as seen by the user. It defaults to the node name with any underscores replaced by spaces.
     −
* desc
+
• '''desc''' - описание действия. Игроки могут увидеть его, если введут название действия и нажмут F1 или просто наведут указатель мыши на это действие в меню. Синтаксис описания стандартный, но если вы захотите изменить способ появления новых аргументов, то вы можете сделать это в скобочках в начале текста. Смотри страницу [4.5.1] для примера.
A description of the verb. Players can see this by typing the verb name and pressing F1. Another way is to hold the mouse over it in the verb panel. The syntax is described for you, by default, but if you wish to override the way individual arguments appear, you can do so inside parentheses at the beginning of the text. See page [4.5.1] for an example.
     −
* category
+
• '''category''' - действия могут группироваться по категориям, имена для которых вы задаете этим свойством. Категории появляются на панели действий.
Verbs can be grouped by assigning a category name of your choosing. They will show up accordingly in the verb panels.
     −
* hidden
+
• '''hidden''' - может принимать значения 1 или 0, чтобы определить скрытые действия. Такие действия не появляются на панели или в меню. Как вариант облегченной версии спрятанных действий, вы можете начать их название с точки. Тогда они будут работать как скрытые, но появятся в меню, если ввести точку. Вы можете, например, использовать их, чтобы задать кучу социальных действий, которыми вы не хотели бы захламлять меню.
This is 1 or 0 to indicate if the verb is secret. A hidden verb will not appear in the panels and will not be expanded on the command line. As a slight variation of this, verbs beginning with a dot are like hidden verbs except they expand once at least the dot has been typed. You might, for example, have a large number of social commands that you don't want cluttering up the normal verb menus. In that case you would probably want to use the dot prefix to hide them.
     −
* src
+
• '''src''' - описывает, где вы определяете отношения между пользователем и источником действия. Влияет на то, кто имеет контроль к действию. Смотри объяснение в следующей секции.
This is where you define the relationship between the user and the source of the verb. The effect is to control who has access to the verb. See the explanation in the next section.
      +
== Доступ к действиям ==
   −
== Verb Accessibility ==
+
Одни из самых важных аспектов действий - это то, к чему они прикреплены и кто их может использовать. Действие ''"нематериальный"'', которое мы рассматривали ранее в этой главе, прикреплено к существу и доступно только для игрока, который управляет этим существом. Вы можете использовать свое собственное действие нематериальности, а другие игроки могут использовать свои, такие же действия, но вы не можете использовать их друг за друга.
   −
One of the most important aspects of a verb is what it is attached to and who may use it. The intangibility verb seen earlier in this chapter is attached to a mob and accessible to the mob's player alone. You can use your own intangibility verb and other people can use their own intangibility verbs, but you can't use each other's verbs. If you could, it would be possible to turn each other intangible.
+
Конечно, в некоторых случаях, вы захотите разрешить людям использовать действия друг друга. Чтобы это сделать, вам нужно будет переписать стандартные настройки доступа. Перед тем, как приступить к этому, вам нужно понять как работают настройки по умолчанию.
   −
Of course, in some cases, you might actually want people to be able to use each other's verbs. To do that, you need to override the default accessibility settings. Before we get into that, you need to understand how the defaults work.
+
Когда действие прикреплено к существу, автоматические настройки ставятся в положение ''src = usr''. Это означает, что источник действия (''source'') должен быть эквивалентен тому, кто использует это действие (''user''). Никто больше не может их использовать или даже видеть. Этот оператор использует две предопределенные переменные: '''src''' обращается к объекту, который хранит действие, источнику (''source''), а '''usr''' обращается к существу, которое использует действие (''user'').
   −
When a verb is attached to a mob, the default accessibility setting is set src = usr. That means the source of the verb must be equal to the user of the verb. Nobody else is allowed to use it (or even see it). This statement makes use of two special pre-defined variables. The variable src refers to the object containing the verb--that is, the source object. The variable usr refers to the mob (of the player) who is using the verb.
+
Это самое обычное действие, которое позволяет людям превращать друг друга в картошку:
 
  −
Here is a commonly used verb which allows people to turn each other into potatoes.
      
  mob/verb/make_potato()
 
  mob/verb/make_potato()
Строка 70: Строка 67:  
     icon = 'potato.dmi'
 
     icon = 'potato.dmi'
   −
Instead of the default accessibility (src = usr) this verb uses src in view(). That means anyone within view of the user can be turned into a potato. The view procedure computes a list of everything which is visible to the user.
+
Вместо стандартных настроек доступа (''src = usr''), это действие использует ''src in view()''. Это означает, что любой в поле зрения пользователя может быть превращен в картошку. Процедура ''view'' возвращает список всего, что находится в поле зрения того, кто ее использует.
   −
Also note that in this example an underscore was used in the name of the verb. This will be automatically converted into a space in the name of the command. However, when the user types it in, a `-' will be inserted on the command line instead of a space. That is because spaces are only allowed on the command line between arguments or inside of quotes. The user doesn't have to worry--the substitution of a dash happens automatically.
+
Также обратите внимание на то, что в имени действия использовалось нижнее подчеркивание. Оно автоматически превратится в пробел в имени команды. Однако, если пользователь хочет ввести эту команду, то ему нужно вводить дефис ''"-"'', а не пробел. Это связанно с тем, что пробелы в командной строке могут использоваться только между аргументами или внутри ковычек. Пользователю не стоит волноваться, замена дефисов происходит автоматически.
   −
Consider instead a verb that is attached to an obj.
+
Теперь рассмотрим действие, привязанное к объекту:
    
  obj/torch/verb/extinguish()
 
  obj/torch/verb/extinguish()
Строка 80: Строка 77:  
     luminosity = 0
 
     luminosity = 0
   −
The verb extinguish in this example causes a torch to stop shining. It again makes use of the view instruction, but this time an additional parameter is specified to limit the range. In this case, the range is 1, so the torch must be in the user's turf or an adjacent one for the verb to be accessible. Somebody standing across the room will not be able to extinguish the torch.
+
<div style="width: 30%; float: right; border: 1px solid #AAAAAA; padding: 10px; margin: 10px; background-color: #FFFFDD">
 +
<p style="font-weight: bold; text-align: center"><font style="font-size: 25px">Мам, смотри, без рук!</font><br>(и другие способы избежать набора...)</p>
 +
Вам не нужно волноваться об игроках, которым приходится набирать длинные команды. Dream Seeker предусматривает множество удобных путей облегчить жизнь пальцам пользователей. Вот несколько способов использовать вышеупомянутое действие тушения факела:
   −
Try this example on a suitable map with some torches scattered about. If you move up to a torch and type "extinguish torch" it will go out (see figure 4.5).
+
# Ввести ''"extinguish torch"''.
 +
# Ввести первую пару букв команды, например, "ex" и нажать пробел, чтобы автодополнить ввод. Если что, Dream Seeker укажет вам на двусмысленность специальным окном.
 +
# Кликнуть по "extinguish" на панели действий.
 +
# Щелкнуть правой кнопкой мыши по факелу, чтобы вывести контекстное меню и выбрать требуемое действие.
 +
</div>
 +
Действие ''extinguish'' в этом примере заставляет факел потухнуть. Мы опять используем ''view'', но на этот раз вместе с дополнительным параметром, которое указывает на дальность действия. В этом случае, с дальностью 1, факел должен быть или на том же месте, что и существо, использующее действие, или на соседней клетке. Кто-нибудь в другом конце комнаты не получит доступа к этому действию и потушить факел не сможет.
   −
----
+
Опробуйте этот пример на подходящей карте с несколькими факелами, разбросанными вокруг. Если вы подойдете к факелу и наберете ''"extinguish torch"'' - он потухнет (смотри вставку).
   −
Figure 4.5: Look Ma, no hands! (and other ways to avoid typing...)
+
Вы могли заметить тонкую разницу между действием тушения и нематериальности, которое мы описывали ранее. В одном случае нам нужно ввести лишь "instangible", а в другом "extinguish torch". Дело в том, что в первом случае нам не нужно указывать источник действия поскольку он итак понятен, а во втором нужно.
   −
You need not worry about players having to deal with typing lengthy commands. Dream Seeker provides many convenient ways to ease the burden on the users' fingers. For example, there are several methods for a player to access the aforementioned extinguish torch verb:
+
=== Неявный источник против Явного ===
   −
Type "extinguish torch".
+
Предположим, что кто-то исповедует религию, в которой молиться необходимо в непосредственной близости от факела. Мы не хотим команду ''"pray torch"'', а хотим просто ''"pray"''. Другими словами мы хотим использовать неявный источник, вместо явного.
Type the first few letters of the command, for instance, "ex" and then hit the spacebar to expand the command. Dream Seeker will fill in the remaining letters, indicating ambiguity on-screen.
  −
Click on the "extinguish" entry in the on-screen verb panels.
  −
Right-click on the torch to pull up a context-menu from which the extinguish verb may be selected.
     −
----
+
Используем мы явный или неявный источник - зависит от того, как заданы параметры ''src''. Если ''src'' однозначно определен (например, вы написали ''src=usr'' или даже ''src=view(1)''), компьютер автоматически будет использовать доступный источник. С другой стороны, если ''src'' не определен, а просто ограничен определенным списком (например, ''src in view(1)''), то пользователю придется указать источник самому, даже если в списке всего один пункт. Так мы можем контролировать синтаксис вводимой команды.
   −
You may have noticed a subtle difference between the extinguish verb and the intangible verb seen earlier. In one case we just had to type "intangible" and in the other "extinguish torch". In the first case we didn't have to specify the verb source and in the second case we did. The term for this difference is an implicit versus an explicit source.
+
Вернемся к примеру факела, включающего молитвы. Раз мы хотим неявный источник, то нам нужно использовать оператор ''"="'', а не ''"in"'', чтобы ограничить варианты для компьютера.
 
  −
 
  −
=== Explicit versus Implicit Source ===
  −
 
  −
Suppose one practices a religion in which praying must be done in the vicinity of a torch. We don't want the command to be "pray torch" but just "pray". In other words, we want an implicit source, not an explicit one.
  −
 
  −
Whether the source syntax is implicit or explicit depends on how the src setting is specified. If src is assigned (e.g. set src=usr or even set src=view(1)) the computer automatically picks the source from the available possibilities. On the other hand, if src is not assigned but just limited to anything in a list (e.g. set src in view(1)) it is up to the user to specify the source--even if there is only one choice. This gives the designer control over the command syntax.
  −
 
  −
Return to the example of torch enabled prayers. Since we want an implicit source, we use = to assign the source rather than in, which would merely limit it.
      
  obj/torch/verb/pray()
 
  obj/torch/verb/pray()
Строка 112: Строка 104:  
     //God fills in this part!
 
     //God fills in this part!
   −
In general, one uses an implicit source when the mere presence of an object gives the user some ability that is otherwise independent of the source object. Another case (like set src=usr) is when the source object is always unique. Verbs in this latter case are called private verbs because they are only accessible to the mob itself.
+
В основном, неявное определение источника используют, когда лишь присутствие предмета дает пользователю новые способности, которые, в общем-то не зависят от того, какой конкретно объект их дает. Также их используют, когда объект-источник всегда один и тот же (например, как ''src=usr''). Действия из последнего случая называют личными действия, поскольку они доступны только самому существу.
   −
=== Default Accessibility ===
+
=== Доступ по умолчанию ===
    
For convenience, verbs attached to different object types have different default accessibilities. These are summarized in figure 4.6.
 
For convenience, verbs attached to different object types have different default accessibilities. These are summarized in figure 4.6.
   −
Figure 4.6: Default Verb Accessibilities
+
<div style="width: 30%; float: right; border: 1px solid #AAAAAA; padding: 10px; margin: 10px; background-color: #FFFFDD">
 
+
<p style="font-weight: bold; text-align: center"><font style="font-size: 25px">Настройки действий по умолчанию</font></p>
mob src = usr
+
:'''mob'''    src = usr
obj src in usr
+
:'''obj'''    src in usr
turf src = view(0)
+
:'''turf'''  src = view(0)
area src = view(0)
+
:'''area'''  src = view(0)
 +
</div>
    
Note that the default obj accessibility is really an abbreviation for src in usr.contents, which means the contents (or inventory) of the user's mob. As you shall see later on, the in operator always treats the right-hand side as a list--hence usr is treated as usr.contents in this context.
 
Note that the default obj accessibility is really an abbreviation for src in usr.contents, which means the contents (or inventory) of the user's mob. As you shall see later on, the in operator always treats the right-hand side as a list--hence usr is treated as usr.contents in this context.
Строка 135: Строка 128:     
Abracadabra!
 
Abracadabra!
      
=== Possible Access Settings ===
 
=== Possible Access Settings ===

Навигация