<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="ru">
	<id>https://wiki.ss13.ru/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=IXVI</id>
	<title>Animus - Вклад участника [ru]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.ss13.ru/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=IXVI"/>
	<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%A1%D0%BB%D1%83%D0%B6%D0%B5%D0%B1%D0%BD%D0%B0%D1%8F:%D0%92%D0%BA%D0%BB%D0%B0%D0%B4/IXVI"/>
	<updated>2026-04-19T08:48:45Z</updated>
	<subtitle>Вклад участника</subtitle>
	<generator>MediaWiki 1.35.9</generator>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_food/Bay12&amp;diff=19807</id>
		<title>Обсуждение:Guide to food/Bay12</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_food/Bay12&amp;diff=19807"/>
		<updated>2015-12-04T11:14:34Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Ещё один клоун, сука! Призываю Рецея! [[Участник:Alexix|Alexix]] ([[Обсуждение участника:Alexix|обсуждение]]) 11:30, 29 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
Сам ты пармизан [[Участник:Alexix|Alexix]] ([[Обсуждение участника:Alexix|обсуждение]]) 13:31, 4 декабря 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
От пармижаны слышу [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 15:14, 4 декабря 2015 (MSK)&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Roboticist&amp;diff=19729</id>
		<title>Roboticist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Roboticist&amp;diff=19729"/>
		<updated>2015-11-28T17:40:36Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Подсказки */ Какие такие же картинки, коопер?&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobrob.png]]&amp;lt;br&amp;gt;[[Roboticist|Роботехник]]&lt;br /&gt;
|'''Доступ:''' Robotics; Technical Storage; Maintenance &lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Engineer|Главный Инженер]], [[Research Director|Директор по Исследованиям]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Захватывать власть своей армией киборгов, [http://www.youtube.com/watch?v=C4cfo0f88Ug не забывая показывать им, кто в доме хозяин.]&lt;br /&gt;
&lt;br /&gt;
'''Гайды:''' [[Guide to Robotic|Гайд по Роботехнике]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Возиться с машинами намного проще, чем управлять людьми, достаточно действовать логично, чтобы добиться успеха. С людьми так не получается.''&amp;lt;br/&amp;gt;'''''Колин Пауэлл'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Работа Роботехника заключается в создании и обслуживании кибернетических систем, а также создании различных ботов и мехов.&lt;br /&gt;
== Отдел роботехники ==&lt;br /&gt;
&lt;br /&gt;
[[File:Roboticist.jpg|250px|thumb|Отдел робототехники, царство технологий.]]&lt;br /&gt;
&lt;br /&gt;
'''Ваш рабочий отсек из технической составляющей будет оборудован:'''&lt;br /&gt;
*Мусорным баком [[File:Disposal_Bin.png]]; &lt;br /&gt;
*Несколькими зарядными станциями для киборгов [[File:CyborgRecharger.png]] и мехов [[File:Recharge_Port.gif]];&lt;br /&gt;
*Фабрикаторами [[File:Exofab.png]]; &lt;br /&gt;
*Связующей R&amp;amp;D консолью, к которой будет подключен принтер плат [[File:Circuit_imprinter.png]];&lt;br /&gt;
*Небольшой хирургической комнатой. &lt;br /&gt;
'''Для работы вам выдадут:'''&lt;br /&gt;
*Несколько стаков металла (каждый стак по 50 листов)[[File:Metal.png]] и одним неполным стаком пласталя (10-20 листов)[[File:Metal_r.png]]; &lt;br /&gt;
*Немного улучшенных батареек питания [[File:Power_cell.png]] и зарядным устройством для них;&lt;br /&gt;
*Флеш-устройства [[Файл:Flash.png]] и сенсоры [[File:Prox_Sensor.png]]; &lt;br /&gt;
*Несколько мотков проводов [[File:CableCoils.png]], &lt;br /&gt;
*Топливный танкер [[File:Fueltank.png]];&lt;br /&gt;
*Парочку интерфейсов MMI [[File:MMI_empty.png]];&lt;br /&gt;
*А так же пустые аптечки и ящики из-под инструментов.&lt;br /&gt;
'''Разумеется, в хирургической части будет полный набор медицинских инструментов.'''&lt;br /&gt;
&lt;br /&gt;
==Эффективный механизм работы==&lt;br /&gt;
У вас есть два основных направления: кибернизация и постройка мехов. В первое время у вас не будет &amp;quot;клиентов&amp;quot; на кибернизацию, но всё же стоит построить парочку кибер-каркасов и заняться сборкой меха [[Guide_to_Robotics#A.P.L.U._Ripley|Рипли]] [[File:Ripley_new.png]]. &lt;br /&gt;
&lt;br /&gt;
Наличие у шахтёров [[File:Ripley_new.png]] с полным комплектов инструментов ([[File:Exosuit_drill.png]] бур простой\улучшенный, [[File:Hydraulic_clamp.png]] гидравлическая рука и [[File:Mech_scaner.png]] шахтёрский сканер) принесёт хорошую выгоду, подарив вам взамен алмазы, золото, серебро и так далее. &lt;br /&gt;
&lt;br /&gt;
'''Помните:''' Рипли ускорит работу шахтёров, а значит и эффективность работы Исследовательского Отдела.&lt;br /&gt;
&lt;br /&gt;
[[Guide_to_Robotics#Medibot|Медботы]] [[File:Medibot.png]], [[Guide_to_Robotics#Cleanbot|Клинботы]] [[File:Cleanbot.png]], [[Guide_to_Robotics#Floorbot|Флурботы]] [[File:Floorbot.png]] - ваши верные помощники. Ещё одно маленькое направление в вашей работе, которое не требует особых затрат, зато значительно окупает потерю времени.&lt;br /&gt;
Не стоит забывать, что есть ещё два бота, а именно [[Guide_to_Robotics#Securitron|Секьюритоны]] [[File:Securitron.png]] и [[Guide_to_Robotics#ED-209|ED-209]] [[File:ED-209.png]], но эта парочка требует снаряжение, недоступное вам изначально. Свяжитесь с [[Warden|Варденом]] или [[Head of Security|Начальником Службы Безопасности]] и договоритесь о нескольких тазерах, бронежилетах и касках. Поверьте, они не должны вам отказать.&lt;br /&gt;
&lt;br /&gt;
==Что можно, а что нельзя==&lt;br /&gt;
'''Можно и нужно:'''&lt;br /&gt;
*[[Файл:Standard_cyborg.png]] Создавать каркасы для будущих киборгов.&lt;br /&gt;
*Стараться кибернизировать опасных личностей, вместо их казни.&lt;br /&gt;
*Обрезать LawSync (синхронизацию законов) и сбрасывать законы киборгу при сбое ИИ.&lt;br /&gt;
*[[Файл:Floorbot.png]] Собирать полезных ботов и отпускать их гулять по станции.&lt;br /&gt;
*[[Файл:Drone_animated.gif]] Создавать дронов, чтобы безнадёжно умершие игроки смогли вернуться в игру и чинить станцию.&lt;br /&gt;
*[[Файл:RoboticsControlConsole.png]] Собрать собственноручно контроль-консоли для мехов и киборгов.&lt;br /&gt;
*[[Файл:R%26D_console.png]] Не забывать периодически синхронизировать свою R&amp;amp;D консоль.&lt;br /&gt;
'''Нельзя:'''&lt;br /&gt;
*[[Файл:%2BMMI.png]] Вставлять MMI в каркас киборга не убедившись, что мозг проявляет активность. Будет неприятно, если вы создадите киборга-апатика.&lt;br /&gt;
*Взрывать всех киборгов лишь потому, что одного из них обработали е-магом [[File:Emag.png]].&lt;br /&gt;
*Немедля взрывать всех киборгов при малейшем [[AI_Malfunction|сбое ИИ]]. Вместо этого, разберите вашу консоль &amp;quot;Robotics Control&amp;quot; [[Файл:RoboticsControlConsole.png]] и переместите её куда-нибудь, где нет камер, так, чтобы вы могли блокировать киборгов и превращать их в верных союзников в борьбе против [[AI_Malfunction|сбойного ИИ]].&lt;br /&gt;
*Пытаться собрать мех, не оценив количество материалов, которое у вас есть.&lt;br /&gt;
*Использовать военные экзоскелеты с полным вооружением. Никто не говорит, что вам запрещено это делать, но с логической точки зрения это неправильно.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
'''Для ботов:'''&lt;br /&gt;
*Любому боту можно дать собственное имя, подписав его ручкой перед завершением его сборки. Это полезно для их отслеживания, иначе все они будут иметь базовое название &amp;quot;Medibot&amp;quot;.&lt;br /&gt;
*Цвет медбота зависит от цвета аптечки, которую вы возьмёте за основу.&lt;br /&gt;
*Фактически, можно взять любого бота вместе с собой, но только в виде несобранного корпуса и руки\сенсора (зависит от последней стадии сборки бота)&lt;br /&gt;
*У любого бота есть свой интерфейс и настраиваемые параметры, среди которых есть примитивная функция включения\выключения, смена режима патрулирования, система безопасности, а так же настройка специальных функций у определённых видов ботов. &lt;br /&gt;
*Выключение системы безопасности повлияет на работу и поведение бота: &lt;br /&gt;
**[[File:Securitron.png]] начнёт арестовывать всех подряд;&lt;br /&gt;
**[[File:Cleanbot.png]] начнёт использовать для очистки пола безвредную, но крайне неприятную пену, на которой можно подскользнуться;&lt;br /&gt;
**[[File:Medibot.png]] начнёт колоть людям то, что задаст сам пользователь (необходимо вставить пробирку с нужным веществом).&lt;br /&gt;
'''Для мехов:'''&lt;br /&gt;
*Во всех мехах присутствует система проверки по ДНК. Это своеобразный замок и, поверьте, эта функция защитит ваши мехи от нехороших людей.&lt;br /&gt;
*Шприцепушку [[File:Sgun.png]] можно зарядить целиком и за один раз, если воспользоваться коробкой со шприцами. Успешный тык по коробке гарантирует полный &amp;quot;магазин&amp;quot;.&lt;br /&gt;
'''Общее:'''&lt;br /&gt;
*Модификация фабрикатора [[File:Exofab.png]] существенно уменьшает потребление ресурсов и время на постройку, повышая общую эффективность. &lt;br /&gt;
Производство [[Guide_to_Robotics#A.P.L.U._Ripley|Рипли]] [[File:Ripley_new.png]] и [[Guide_to_Robotics#Odysseus|Одиссея]] [[File:Odysseus.png]] не будет затратным без апгрейда, но более продвинутые боевые мехи, вроде [[Guide_to_Robotics#Gygax|Гигакса]] [[File:Gygax.png]], [[Guide_to_Robotics#Durand|Дюранда]] [[File:Durand.png]],  [[Guide_to_Robotics#Phazon|Фазона]] [[File:Phazon.png]] и [[Guide_to_Robotics#H.O.N.K.|H.O.N.K.]] [[File:Honk.png]] потребуют много серебра, золота, плазмы, алмазов и даже бананиума, поэтому в таком случае апгрейд отлично сэкономит ваши материалы и нервы шахтёров.&lt;br /&gt;
*Модификация последней стадии для зарядных кибер-станций [[File:CyborgRecharger.png]] упростит вам задачу, ведь теперь зарядники будут чинить ваших киборгов.&lt;br /&gt;
*Вы не должны забивать фабрикаторы [[File:Exofab.png]] всем металлом, который у вас есть. Оставьте как минимум один стак для сборки мехов.&lt;br /&gt;
*Флеши[[Файл:Flash.png]] в вашем случае - не оружие самозащиты, а деталь для сборки киборгов. Не раздавайте их кому попало.&lt;br /&gt;
*Постарайтесь собрать корпус  Рипли [[File:Ripley_new.png]] в самом начале смены, ведь если вам попадутся здравые учёные, то платы вы заполучите невероятно быстро.&lt;br /&gt;
*Если вы увидели киборга в вашем отсеке, то внимательно осмотрите его, ведь они приходят лишь в том случае, если им нужно заменить батарею, сменить модуль или просто починить.&lt;br /&gt;
*Если [[AI Malfunction|ИИ сбойный]], то необходимо воспользоваться необходимой консолью в офисе Исследовательского Директора, чтобы уничтожить напрямую связанных с ИИ киборгов. Консоль [[Файл:RoboticsControlConsole.png]] &amp;quot;Robotics Сontrol&amp;quot; - ваш верный друг и товарищ в битве с ошалевшими машинами.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chief_Medical_Officer&amp;diff=19727</id>
		<title>Chief Medical Officer</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chief_Medical_Officer&amp;diff=19727"/>
		<updated>2015-11-28T17:31:40Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; |Описание&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobcmed.png]]&amp;lt;br&amp;gt;[[Chief Medical Officer|Глава медперсонала]]&lt;br /&gt;
|'''Доступ:''' Medbay; Bridge&lt;br /&gt;
'''Подчинение:''' [[Captain]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Контроль медицинского персонала&lt;br /&gt;
&lt;br /&gt;
'''Руководства:''' [[Chain of Command]], [[Guide to Medicine]], [[Guide to Virology]], [[Guide to Genetics]], [[Chemist|Guide to Drugs]], [[Guide to Surgery]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Мы ведь не знаем, что внутри у щенка и что он чувствует. Может, это тоже притворство.''&amp;lt;br/&amp;gt;'''''Исаак Айзимов, &amp;quot;Я Робот&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Chief Medical Officer's Office.png|frame|Ваш офис]]&lt;br /&gt;
&lt;br /&gt;
== [https://www.youtube.com/watch?v=xxPDnCx0Ju0 Доктор Айболит] ==&lt;br /&gt;
Поздравляем! Вы назначены на должность главы всего медицинского персонала станции! Что может быть лучше, чем лечить людей? Правильно, [https://www.youtube.com/watch?v=MfXiBtXNJGo быть начальником тех, кто лечит людей]! А что может быть лучше, чем быть просто начальником тех, кто лечит людей? Правильно - делать это на станции, оборудованной по последнему слову техники, такой как наша Станция 13. Она абсолютно безопасна для своих обитателей, так что, скорее всего вся ваша работа будет заключаться в обработке небольших царапин и ожогов. Но и это будет увлекательно в окружении тщательно подобранных исполнительных и доброжелательных работников. Так что ваша смена пройдет абсолютно спокойно. Но всё равно следует прочитать должностные инструкции, чтобы было что рассказать внукам.&lt;br /&gt;
&lt;br /&gt;
== Медицина ==&lt;br /&gt;
'''Статьи по теме:''' [[Guide to Medicine]].&lt;br /&gt;
&lt;br /&gt;
Учитывая количество [[Medical Doctor|высококлассных врачей]], нанимающихся в корпорацию НаноТрасен, скорее всего ваши обязанности будут заключаться в управлении, а не непосредственной работе с пациентами. Однако, при неудачном стечении обстоятельств (то есть почти всегда) вы должны быть готовы самостоятельно выполнять часть работы ваших подчиненных. Поэтому рекомендуется сразу собрать себе медицинский пояс с самыми необходимыми препаратами. С собой лучше всегда носить анализатор здоровья или переключить свой ПДА в режим анализатора. Также вы должны проконтролировать выполнение следующих пунктов:&lt;br /&gt;
&lt;br /&gt;
*В начале смены криокамеры должны быть включены и настроены. Часто это значит, что вам придётся сделать это самостоятельно, до прибытия прочего персонала.&lt;br /&gt;
&lt;br /&gt;
*В любой момент времени в приёмной должен сидеть работник. Никому не будет приятно прийти в медотсек с ранением и наткнуться там только на закрытую дверь и несколько собратьев по несчастью.&lt;br /&gt;
&lt;br /&gt;
*Также всегда должно быть хотя бы два врача, готовых сорваться на выезд. Это добавит благодарных клиентов и, в идеале, лишит генетиков части работы.&lt;br /&gt;
&lt;br /&gt;
*Удостоверьтесь, что рассеянные хирурги не прихватили с собой пару инструментов из операционной. Ситуация, когда человеку нужно срочно вырезать аппендицит, а скальпель непонятно где, может плохо закончиться.&lt;br /&gt;
&lt;br /&gt;
*Этот пункт не обязателен, но работать будет гораздо удобнее, если перед сменой настроить медицинского робота. Наполните его трикордразином и отправьте в приёмную.&lt;br /&gt;
&lt;br /&gt;
== Химия ==&lt;br /&gt;
'''Основная статья:''' [[Chemist|Guide to Chemistry]]&lt;br /&gt;
&lt;br /&gt;
В отличие от врачей, [[Chemist|химики]] часто оказываются в дефиците, так что вам, скорее всего, придётся посвятить химии часть своего времени. Так или иначе, нужно следить за запасами базовых медикаментов (инапровалин, келотан, дексалин, анти-токсин) и своевременно их пополнять. Также неплохая идея иметь в запасе трикордразин. В целом, нужно подстраиваться под текущую ситуацию (например, если на станции пожар, не помешает дермалин, а если генетики сильно напортачили – то риеталин). Не помешает и раздать главам баночки с таблетками на случай внештатного происшествия. Помимо вышеперечисленного, химики могут заниматься чем угодно, исключая разве что наркотики или боевые гранаты, но тщательно отобранные сотрудники вряд ли будут делать что-то подобное.&lt;br /&gt;
&lt;br /&gt;
== Генетика ==&lt;br /&gt;
'''Статьи по теме:''' [[Guide to Genetics]].&lt;br /&gt;
&lt;br /&gt;
[[Geneticist|Генетики]] подчиняются не только вам, но и [[Research Director|руководителю исследований]]. Скорее всего вам придётся использовать этот отдел разве что для лечения генетических заболеваний и мутаций, которые нередко возникают у инженеров из-за работы с сингулярностью. Конечно, генетики также могут и клонировать погибших членов экипажа, но наши квалифицированные медики не дадут никому умереть. Также на случай ЧП рекомендуется хранить записи генов хотя бы самых важных людей на станции (конечно же вас в первую очередь).&lt;br /&gt;
&lt;br /&gt;
'''''Важно! Главный врач занимается координацией лечения пострадавшего персонала. Хоть вас и учили пользоваться генетическими консолями для излечения разнообразных генетических болезней, вам всё-равно не стоит пытаться исследовать гены и открывать новые мутации - оставьте это баловство [[Research Director|директору по исследованиям]] и [[Geneticist|генетикам]], а сами займитесь действительно полезной работой.'''''&lt;br /&gt;
&lt;br /&gt;
== Вирусология ==&lt;br /&gt;
'''Статьи по теме:''' [[Guide to Virology]].&lt;br /&gt;
&lt;br /&gt;
Тут всё просто. Если [[Virologist|вирусологов]] нет – не заморачивайтесь вообще по поводу этого отсека (''хотя регулярные проверки не помешают, ведь пустой отсек на отшибе – удобное место для того, чтобы всяким глупым ассистентам там скрываться от своей работы''). Если вирусологи есть – заходите иногда, проверяйте, что отсек чист, шлюз закрыт, а обезьяны в клетке. В случае, если они просят вашим доступом открыть им ящик с вирусами, убедитесь в их компетентности, попросив изготовить вакцину от гриппа или простуды. Вот и все, что вы должны делать с этим отсеком, кроме случаев эпидемий, конечно, когда вы должны произвести вакцину и распространить её по станции или проследить чтобы это сделали вирусологи.&lt;br /&gt;
&lt;br /&gt;
== Чистота - залог здоровья ==&lt;br /&gt;
Ещё одна важная вещь – поддерживайте в отсеке чистоту. Пол, залитый кровью и блевотиной может послужить развитию ужасных заболеваний или появлению грызунов, насекомых и назойливых инспекторов. Остальные, вероятно, будут слишком заняты, так что проследить за этим придётся вам. На наших станциях есть замечательные уборщики, которые всегда готовы помочь вам и отмыть отсек до сияющей белизны. Химики вполне могут изготовить чистящее средство, а в особо запущенных случаях – и чистящую гранату. Так же неплохо с самого начала смены заказать у робототехника одного робота-уборщика.&lt;br /&gt;
&lt;br /&gt;
== Администрирование ==&lt;br /&gt;
Не стоит забывать что вы, всё-таки, глава. Поэтому вам нужно участвовать в принятии важных решений относительно станции и собраниях командного состава. Вы, вместе с [[Chief Engineer|главным инженером]] и [[Research Director|директором по исследованиям]], имеете самое низкое звание среди всех глав, но в маловероятной ситуации, что вы единственный из начальства на станции, вам придётся взять на себя командование. Также вам придётся решать, принимать ли в отдел новых сотрудников (не забывайте устраивать им проверки), ставить свою печать на заказах квартирмейстеру от вашего персонала, а также на бумагах с данными о вскрытии, заказах в химию и прочих документах. Учитывая безопасность станции, именно в администрировании будет заключаться большая часть вашей работы.&lt;br /&gt;
&lt;br /&gt;
=== ВРЕМЯ КОММУНИЗМА ===&lt;br /&gt;
Медбей - худшее место для нахождения при мятеже, и высоки шансы того, что вашу голову оторвут первой. Если люди странно себя ведут или начинают дебоширить, вооружите себя ''хоть чем-то'' как можно скорее, будьте готовы убежать из медбея в ''любое время''. Ваша телескопическая дубинка - лучший способ самозащиты, вы можете держать обездвиженным одного врага, но абсолютно бессильны против групп, а если кто-то выбьет её из рук, то вероятность остаться с головой крайне мала. Гипоспрей хороший выбор: помните, двадцать единиц хлоралгидрата усыпит любого надолго. Прочие возможные оружия, такие как огнетушитель, топор с мостика, пульверизатор со смазкой дадут выиграть вам время. Используйте шприцемёт для обороны на расстоянии.&lt;br /&gt;
Люди видят вас слабым, вы хорошая цель для предателя, жаждущему доступ на мостик. Будьте осторожны.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Заправьте в ваш гипоспрей salbumatol или epinephrine. Теперь, когда вы увидите умирающего человека просто используйте гипоспрей на нем. В чате появится сообщение, схожее с тем, когда [[Changeling|перевёртыш]] питается жизнью человека. Таким образом, люди вокруг будут считать что '''ОБОЖЕМОЙ СМО ПЕРЕВЕРТЫШ, ДОСТАВАЙТЕ ОГНЕМЕТ!!!'''. И это весело.&lt;br /&gt;
* Переместите Crew Monitoring Console из вашего кабинета в ординаторскую, и [[Medical_Doctor|простые смертные]] смогут пользоваться ею.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Luna]]&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Virologist&amp;diff=19718</id>
		<title>Virologist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Virologist&amp;diff=19718"/>
		<updated>2015-11-28T17:15:29Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Ага, молодец, а теперь верни орфографические и пунктуационные правки, нахуя ты откатил версию? Совсем обнаглел?&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobvir.png]]&amp;lt;br&amp;gt;[[Virologist|Вирусолог]]&lt;br /&gt;
|'''Доступ:''' Virology; Medbay&lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Medical Officer]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Изучать болезни и методы их лечения&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Virology]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''“Всё всегда стоит труда.''&amp;lt;br/&amp;gt;'''''Альберт Камю, &amp;quot;Чума&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Поздравляем''', доктор!&amp;lt;br&amp;gt; Вы были выбраны для изучения различных типов вирусов и изготовления вакцин от них. Так что надевайте свои латексные перчатки и дыхательную маску, пришло время исследовать заболевания!&lt;br /&gt;
&lt;br /&gt;
==Добро пожаловать==&lt;br /&gt;
[[File:Vir.PNG|right|thumb|Вирусология.]]&lt;br /&gt;
В отличии от Роберта Невилла, героя книги '''&amp;quot;Я - Легенда&amp;quot;''', вам не нужно будет искать приключений на свою задницу для лечения заболеваний. ''Наверное.'' Вас будет мучать скука, и вероятно так будет постоянно. Просто убедитесь что '''[[Chemist|химик]]''' или '''[[Chief Medical Officer|главврач]]''' есть поблизости, или же вы будете не в состоянии вылечить редкие заболевания и скорее всего получите очередную эпидемию.&lt;br /&gt;
&lt;br /&gt;
==Экипировка и оборудование==&lt;br /&gt;
Как и всякий высококлассный специалист, вы располагаете большим количеством снаряжения.&lt;br /&gt;
&lt;br /&gt;
===Средства индивидуальной защиты===&lt;br /&gt;
Начнем с необходимого для '''вашего''' выживания - с экипировки. Она позволит не испытывать на себе все &amp;quot;прелести&amp;quot; объектов ваших исследований.&lt;br /&gt;
*[[File:Sterilemask.png]] '''Марлевая повязка''', [[File:Brmask.png]] '''Дыхательная маска''' или [[File:Gas mask.png]] '''Противогаз''' и [[File:AirTank.png]] '''Дыхательный баллон'''&lt;br /&gt;
Всё это защитит ваши дыхательные пути, а следовательно и вас от болезней, распространяющихся воздушно-капельным путем.&lt;br /&gt;
&lt;br /&gt;
*[[File:jumpsuit_virology.png]] '''Костюм''', [[File:labcoat_virology.png]] '''Лабораторный халат''', [[File:LGloves.png]] '''Латексные перчатки''', [[File:White_shoes.png]] '''Ботинки'''&lt;br /&gt;
Эти средства защищают от болезней, передающихся при контакте. Конечно, не только одежда медицинского персонала предоставляет подобную защиту, но и любая другая закрывающая кожу. Не просто так вирусологи древности закутывались в плащи и одевали маски!&lt;br /&gt;
&lt;br /&gt;
*[[File:Biosuit_virology.png]] '''Костюм биологической защиты''' с [[File:Biohood_virology.png]] '''капюшоном'''&lt;br /&gt;
В сочетании с остальными СИЗ дает абсолютную защиту от болезней, независимо от их способа передачи. Ни бактериальные, ни вирусные, ни протозойные, ни грибковые возбудители не проникнут через такой костюм (по крайней мере не должны, если это все же произошло - составляйте рекламацию).&lt;br /&gt;
&lt;br /&gt;
===Оборудование===&lt;br /&gt;
Комплектация вашей лаборатории зависит от [http://http://wiki.ss13.ru/index.php?title=Категория:Builds поставщика] оборудования вашей станции, так что этот вопрос будет подробно рассмотрен в соответствующих руководствах: [[Guide to Virology]], [[Guide to Virology/tgstation13]], [[Guide to Virology/vg]].&lt;br /&gt;
&lt;br /&gt;
===Прочее снаряжение===&lt;br /&gt;
*[[File:Health Analyzer.png]] '''[[Medical_Doctor#Как пользоваться анализатором здоровья|Анализатор здоровья]]''',  [[File:MED HUD.png]] '''Очки с медицинским интерфейсом'''&lt;br /&gt;
Для своевременного обнаружения инфицированных. &lt;br /&gt;
&lt;br /&gt;
*[[File:Virus_dish.png]] '''Чашечка с вирусом'''&lt;br /&gt;
Ёмкость для хранения и перемещения культур вирусов.&lt;br /&gt;
&lt;br /&gt;
*[[File:Vial.png]] '''Пробирка'''&lt;br /&gt;
Используется для выделения вирусов или антител из образцов крови в центрифуге.&lt;br /&gt;
&lt;br /&gt;
*[[File:Beaker.png]] '''Мензурка''', [[File:Syringe.png]] '''Шприц''', [[File:dropper.png]] '''Пипетка'''&lt;br /&gt;
Используются для перемещения жидкостей из одной емкости в другую.&lt;br /&gt;
&lt;br /&gt;
*[[Файл:Space Cleaner.png]] '''Распылитель с космоочистителем'''&lt;br /&gt;
Для очистки лаборатории от различных загрязнений, когда нахождение в ней всякого [[Janitor|неавторизованного персонала]] нежелательно.&lt;br /&gt;
&lt;br /&gt;
*[[File:Hand Labeler.png]] '''Ручной этикетировщик'''&lt;br /&gt;
Поможет не запутаться во всех этих колбах и пробирках.&lt;br /&gt;
&lt;br /&gt;
===Заражение обезьян===&lt;br /&gt;
Это ваша работа. Возьмите образец вируса, вколите в макаку и наблюдайте. Вылечите ее, когда вам потребуется.&lt;br /&gt;
&lt;br /&gt;
Если вы беспокоитесь об обезьянках, и не хотите иметь кучу заражённых приматов в загоне, возьмите одну и переведите её в свой &amp;quot;карцер&amp;quot;. Работайте над ней здесь. Это можно использовать как хранение всех вакцин в одном существе. &lt;br /&gt;
&lt;br /&gt;
Возьмите образец крови уже выздоровевшей от вируса обезьяны, перелейте ее в пробирку и поместите в PANDEMIC. Сделайте вакцину. Ура. Поздравляем! Вы нашли вакцину! &lt;br /&gt;
&lt;br /&gt;
Можно узнать метод лечения используя PANDEMIC, или воссоздать культуру вируса, если оная еще есть в крови, для [[Traitor|предателя]] или ваших нужд.&lt;br /&gt;
&lt;br /&gt;
===ЭКИПАЖ ЗАБОЛЕЛ!===&lt;br /&gt;
Если вы СЛУЧАЙНО заразили кого-то вирусом, то вам ничего не остаётся, кроме как объявить карантин и начать работу над вакциной. Обязательно вакцинируйте себя после создания лекарства. &amp;lt;s&amp;gt;Может быть, вы успеете, прежде чем орды больных ворвутся к вам по вашу душу.&amp;lt;/s&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===СОЗДАЙТЕ ПАНДЕМИЮ!===&lt;br /&gt;
Вы можете создать свою собственную болезнь. Прочтите [[Guide_to_Virology|руководство]].&lt;br /&gt;
==== Симбиоз ====&lt;br /&gt;
Вирусы не всегда плохие. Поработав, вы сможете создать вирус, убирающий нужду в еде, регенерацию здоровья. Согласуйте с [[Chief_Medical_Officer|CMO]] выпуск вируса и убедитесь что он не вредный, иначе к вам всё-таки ворвутся.&lt;br /&gt;
&lt;br /&gt;
==Тифозная Мэри==&lt;br /&gt;
Будучи предателем, вы можете найти эту работу весьма полезной. Убедитесь, что поблизости есть начальство, которое может открыть для вас ящик с вирусами, или использовать особое снаряжение Синдиката на нём чтобы открыть его самому. Болезнь, поражающая мозг, кажется является лучшим способом взвинтить экипаж, и если люди будут интересоваться, почему вы не выходите из лаборатории, пробормочете что-то невнятное (в то время как хороший вирусолог уже давно бы их вылечил).&lt;br /&gt;
Выпускание вируса на волю является хорошим способом посеять панику и хаос на станции, являясь удобным прикрытием для Вашей предательской деятельности. В качестве дополнительного бонуса, лечение болезни и ликвидация его следов на станции - хороший способ получить одобрение со стороны руководства, что полезно для вашего алиби. Возьмите за правило, защитить себя самого от заражения важнее всего.&lt;br /&gt;
Помните, если вы будете выпускать вирусы, не являясь агентом Синдиката, '''вы можете получить бан'''.&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Virologist&amp;diff=19716</id>
		<title>Virologist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Virologist&amp;diff=19716"/>
		<updated>2015-11-28T16:53:55Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobvir.png]]&amp;lt;br&amp;gt;[[Virologist|Вирусолог]]&lt;br /&gt;
|'''Доступ:''' Virology; Medbay&lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Medical Officer]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Изучать болезни и методы их лечения&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Virology]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''“Всё всегда стоит труда.''&amp;lt;br/&amp;gt;'''''Альберт Камю, &amp;quot;Чума&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Поздравляем''', доктор!&amp;lt;br&amp;gt; Вы были выбраны для изучения различных типов вирусов и изготовления вакцин от них. Так что надевайте свои латексные перчатки и дыхательную маску, пришло время исследовать заболевания!&lt;br /&gt;
&lt;br /&gt;
==Добро пожаловать==&lt;br /&gt;
[[File:Vir.PNG|right|thumb|Вирусология.]]&lt;br /&gt;
В отличии от Роберта Невилла, героя книги '''&amp;quot;Я - Легенда&amp;quot;''', вам не нужно будет искать приключений на свою задницу для лечения заболеваний. ''Наверное.'' Вас будет мучать скука, и вероятно так будет постоянно. Просто убедитесь что '''[[Chemist|химик]]''' или '''[[Chief Medical Officer|главврач]]''' есть поблизости, или же вы будете не в состоянии вылечить редкие заболевания и скорее всего получите очередную эпидемию.&lt;br /&gt;
&lt;br /&gt;
==Экипировка и оборудование==&lt;br /&gt;
Как и всякий высококлассный специалист, вы располагаете большим количеством снаряжения.&lt;br /&gt;
&lt;br /&gt;
===Средства индивидуальной защиты===&lt;br /&gt;
Начнем с необходимого для '''вашего''' выживания - с экипировки. Она позволит не испытывать на себе все &amp;quot;прелести&amp;quot; объектов ваших исследований.&lt;br /&gt;
*[[File:Sterilemask.png]] '''Марлевая повязка''', [[File:Brmask.png]] '''Дыхательная маска''' или [[File:Gas mask.png]] '''Противогаз''' и [[File:AirTank.png]] '''Дыхательный баллон'''&lt;br /&gt;
Все это защитит ваши дыхательные пути, а следовательно и вас от болезней, распространяющихся воздушно-капельным путем.&lt;br /&gt;
&lt;br /&gt;
*[[File:jumpsuit_virology.png]] '''Костюм''', [[File:labcoat_virology.png]] '''Лабораторный халат''', [[File:LGloves.png]] '''Латексные перчатки''', [[File:White_shoes.png]] '''Ботинки'''&lt;br /&gt;
Эти средства защищают от болезней, передающихся при контакте. Конечно, не только одежда медицинского персонала предоставляет подобную защиту, но и любая другая закрывающая кожу. Не просто так вирусологи древности закутывались в плащи и одевали маски!&lt;br /&gt;
&lt;br /&gt;
*[[File:Biosuit_virology.png]] '''Костюм биологической защиты''' с [[File:Biohood_virology.png]] '''капюшоном'''&lt;br /&gt;
В сочетании с остальными СИЗ дает абсолютную защиту от болезней, независимо от их способа передачи. Ни бактериальные, ни вирусные, ни протозойные, ни грибковые возбудители не проникнут через такой костюм (по крайней мере не должны, если это все же произошло - составляйте рекламацию).&lt;br /&gt;
&lt;br /&gt;
===Оборудование===&lt;br /&gt;
Комплектация вашей лаборатории зависит от [http://http://wiki.ss13.ru/index.php?title=Категория:Builds поставщика] оборудования вашей станции, так что этот вопрос будет подробно рассмотрен в соответствующих руководствах: [[Guide to Virology]], [[Guide to Virology/tgstation13]], [[Guide to Virology/vg]].&lt;br /&gt;
&lt;br /&gt;
===Прочее снаряжение===&lt;br /&gt;
*[[File:Health Analyzer.png]] '''[[Medical_Doctor#Как пользоваться анализатором здоровья|Анализатор здоровья]]''',  [[File:MED HUD.png]] '''Очки с медицинским интерфейсом'''&lt;br /&gt;
Для своевременного обнаружения инфицированных. &lt;br /&gt;
&lt;br /&gt;
*[[File:Virus_dish.png]] '''Чашечка с вирусом'''&lt;br /&gt;
Ёмкость для хранения и перемещения культур вирусов.&lt;br /&gt;
&lt;br /&gt;
*[[File:Vial.png]] '''Пробирка'''&lt;br /&gt;
Используется для выделения вирусов или антител из образцов крови в центрифуге.&lt;br /&gt;
&lt;br /&gt;
*[[File:Beaker.png]] '''Мензурка''', [[File:Syringe.png]] '''Шприц''', [[File:dropper.png]] '''Пипетка'''&lt;br /&gt;
Используются для перемещения жидкостей из одной емкости в другую.&lt;br /&gt;
&lt;br /&gt;
*[[Файл:Space Cleaner.png]] '''Распылитель с космоочистителем'''&lt;br /&gt;
Для очистки лаборатории от различных загрязнений, когда нахождение в ней всякого [[Janitor|неавторизованного персонала]] нежелательно.&lt;br /&gt;
&lt;br /&gt;
*[[File:Hand Labeler.png]] '''Ручной этикетировщик'''&lt;br /&gt;
Поможет не запутаться во всех этих колбах и пробирках.&lt;br /&gt;
&lt;br /&gt;
===Заражение обезьян===&lt;br /&gt;
Это ваша работа. Возьмите образец вируса, вколите в макаку и наблюдайте. Вылечите ее, когда вам потребуется.&lt;br /&gt;
&lt;br /&gt;
Если вы беспокоитесь об обезьянках, и не хотите иметь кучу заражённых приматов в загоне, возьмите одну и переведите её в свой &amp;quot;карцер&amp;quot;. Работайте над ней здесь. Это можно использовать как хранение всех вакцин в одном существе. &lt;br /&gt;
&lt;br /&gt;
Возьмите образец крови уже выздоровевшей от вируса обезьяны, перелейте ее в пробирку и поместите в PANDEMIC. Сделайте вакцину. Ура. Поздравляем! Вы нашли вакцину! &lt;br /&gt;
&lt;br /&gt;
Можно узнать метод лечения используя PANDEMIC, или воссоздать культуру вируса, если оная еще есть в крови, для [[Traitor|предателя]] или ваших нужд.&lt;br /&gt;
&lt;br /&gt;
===ЭКИПАЖ ЗАБОЛЕЛ!===&lt;br /&gt;
Если вы СЛУЧАЙНО заразили кого-то вирусом, то вам ничего не остаётся, кроме как объявить карантин и начать работу над вакциной. Обязательно вакцинируйте себя после создания лекарства. &amp;lt;s&amp;gt;Может быть, вы успеете, прежде чем орды больных ворвутся к вам по вашу душу.&amp;lt;/s&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===СОЗДАЙТЕ ПАНДЕМИЮ!===&lt;br /&gt;
Вы можете создать свою собственную болезнь. Прочтите [[Guide_to_Virology|руководство]].&lt;br /&gt;
==== Симбиоз ====&lt;br /&gt;
Вирусы не всегда плохие. Поработав, вы сможете создать вирус, убирающий нужду в еде, регенерацию здоровья. Согласуйте с [[Chief_Medical_Officer|CMO]] выпуск вируса и убедитесь что он не вредный, иначе к вам всё-таки ворвутся.&lt;br /&gt;
&lt;br /&gt;
==Советы==&lt;br /&gt;
* Вирусология, как и генетика может превратить вас в суперчеловека.&lt;br /&gt;
* Из-за кашля люди роняют вещи из рук, что мешает [[Changeling|генокрадам]] поглощать жертву.&lt;br /&gt;
* Полезный вирус может вас лечить, медленно, но в критическом состоянии вы не умрете. Человек может болеть тремя вирусами одновременно. Вирус, содержащий следующие симптомы, спасет вас из критического состояния(если нет побочных источников повреждений), защитит вас от удушья и позволит быстро бегать даже если на вас скафандр и включенные магнитные ботинки: &amp;quot;Toxic Compensation&amp;quot;, &amp;quot;Self-Respiration&amp;quot;, и &amp;quot;Stimulant&amp;quot;. Добавьте &amp;quot;Weight Even&amp;quot; для того, чтобы убрать голод.&lt;br /&gt;
** Вирусы с разными, индивидуальными симптомами могут быть смешаны, и они будут сочетаться.&lt;br /&gt;
** Если вы создали вирус с нежелательным синдромом, возьмите пипетку с [[Guide_to_Chemistry#Synaptizine|синаптизином]], чтобы убрать один из симптомов.&lt;br /&gt;
* Если вы вирусолог, желающий создать полезный вирус, но не можете поместить все симптомы в одну культуру, то уберите &amp;quot;Weight Even&amp;quot;. Голод только уменьшает скорость, а &amp;quot;Stimulant&amp;quot; аннулирует все замедления.&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Scientist&amp;diff=19715</id>
		<title>Scientist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Scientist&amp;diff=19715"/>
		<updated>2015-11-28T16:53:15Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:jobsci.png]]&amp;lt;br&amp;gt;[[Scientist|Ученый]]&lt;br /&gt;
|'''Доступ:''' Toxins; Xenobiology Lab; Artifact Lab; RnD Research Lab&lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Research Director]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' [http://www.youtube.com/watch?v=Jm-upHSP9KU Заниматься исследованиями]&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Research and Development]], [[Guide to Xenobiology]], [[Guide to Xenobotany]], [[Guide to Xenoarchaeology]], [[Guide to Toxins]], [[Guide to Telescience]]&lt;br /&gt;
!Сложно &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''“Я совершенно вымотан, но не могу прекратить работу. Мои эксперименты так важны, так прекрасны, так удивительны, что я с трудом могу оторваться от них, чтобы поесть. А когда пытаюсь уснуть, то всё время думаю о них. Полагаю, что буду продолжать пока не упаду замертво.''&amp;lt;br/&amp;gt;'''''&amp;quot;Никола Тесла, из писем&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:RnD.PNG|300px|right|thumb|Научный отдел]]&lt;br /&gt;
&lt;br /&gt;
Бравая команда учёных делится на 6 обширных областей в науке.&lt;br /&gt;
*Первый и самый банальный — это '''учёный-исследователь (Scientist)'''.&lt;br /&gt;
*Второй, всеми любимый — это '''исследователь плазмы (Plasma Researcher)'''&lt;br /&gt;
*Третья, опасная должность, вида «Зачем вы открыли этот , РД?!», — это '''ксенобиолог (Xenobiologist)'''.&lt;br /&gt;
*Четвертый вид учёных — это '''ксеноархеолог (Xenoarchaeologist)'''.&lt;br /&gt;
*Пятая, не менее важная область - '''специалист по управлению теленаукой (Telescientist)'''.&lt;br /&gt;
*Шестая, лучший друг ботаников, ксеноботаник (Xenobotanist).&lt;br /&gt;
&lt;br /&gt;
Стоит запомнить что все ваши коллеги - законченные социопаты, и вы будете в порядке. Главное не позволяйте этим идиотам околачиваться рядом во время ваших экспериментов. Серьёзно.&lt;br /&gt;
&lt;br /&gt;
= Лаборатории =&lt;br /&gt;
&lt;br /&gt;
Поскольку команда учёных имеет обширные знания в области создания и контролировании самых опасных веществ на станции, то конечно можно заметить, что на станции периодически что-то может взорваться, или персонал будет убит аурой артефакта, а может всех убьёт армия метройдов, которая хорошенько покушала медбей, сбежав по вентиляции из ксенобиологической лаборатории.&amp;lt;br&amp;gt;А так как ученых достаточно много и каждый делится на отдельную ветвь, то можно догадаться, что у всех свои задачи:&lt;br /&gt;
&lt;br /&gt;
== Исследования и Развитие == &lt;br /&gt;
Эта лаборатория призвана развивать «Хай-тек» устройства, в том числе оружие, энергоносители и печатные платы.&amp;lt;br&amp;gt;В определённый момент, вашим исследованиям потребуются разнообразные ресурсы с астероида. Поэтому вам заранее нужно согласовывать свой заказ с квартирмейстером.&amp;lt;br&amp;gt;Более подробное руководство, [[Guide_to_Research_and_Development |см. руководство по исследованиям и развитию.]]&lt;br /&gt;
&lt;br /&gt;
== Исследование токсинов ==  &lt;br /&gt;
В лаборатории по изучению токсинов ваша работа состоит в исследовании генерации энергии с помощью плазмы (обычно сводящейся к созданию бомб).&amp;lt;br&amp;gt;Более подробное руководство, [[Guide to Toxins|см. руководство по смешиванию газов.]]&lt;br /&gt;
&lt;br /&gt;
== Ксенобиология ==  &lt;br /&gt;
Учёные этой лаборатории, специализируются на изучении чужеродных форм жизни, таких как метроиды, слаймы и иногда чужих.&lt;br /&gt;
Бережное обращение и безопасность, вот залог успеха, так как эта лаборатория совсем не предназначена для неподготовленного персонала, который так и стремится выпустить ваших инопланетных &amp;quot;друзей&amp;quot;.&lt;br /&gt;
На разных станциях используется разные типы форм жизни.&amp;lt;br&amp;gt;Вы можете прочитать больше в гайде про [[Xenobiology/Metroids|метроидов]] и [[Xenobiology/Slimes|слаймов]].&lt;br /&gt;
&lt;br /&gt;
== Ксеноархеология ==  &lt;br /&gt;
Ваш отдел расположен вне станции. Можете быть спокойны, никто не будет мешать вашей очень важной задаче. Сосредоточьтесь на раскопках аномалий, а если вам всё же повезёт, вы сможете что-то найти и даже поэкспериментировать над своими находками.&amp;lt;br&amp;gt;Более подробное руководство, [[Guide_to_Xenoarchaeology |см. руководство по ксеноархеологии.]]&lt;br /&gt;
&lt;br /&gt;
== Теленаука ==&lt;br /&gt;
Отдел теленауки находится рядом с ИиР. В ней содержится 4 GPS, телепад, консоль для управления телепадом, био-костюм,  с баллонами (О2) и защитное стекло. Теленаука может переместить вас в любое место на станции, но для этого вам нужно 4 телекристалла и усовершенствовать телепад.&amp;lt;br&amp;gt;Более подробное руководство, [[Guide_to_Telescience |см. руководство по теленауке.]]&lt;br /&gt;
&lt;br /&gt;
== Ксеноботаника ==&lt;br /&gt;
Относительно, самая спокойная должность. Но на всякий случай держите огнемёт наготове, если ваш космический помидор решит захватить станцию.&amp;lt;br&amp;gt;Более подробное руководство, [[Guide_to_Xenobotany/Bay12 |см. руководство по ксеноботанике.]]&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Roboticist&amp;diff=19714</id>
		<title>Roboticist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Roboticist&amp;diff=19714"/>
		<updated>2015-11-28T16:51:43Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobrob.png]]&amp;lt;br&amp;gt;[[Roboticist|Роботехник]]&lt;br /&gt;
|'''Доступ:''' Robotics; Technical Storage; Maintenance &lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Engineer|Главный Инженер]], [[Research Director|Директор по Исследованиям]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Захватывать власть своей армией киборгов, [http://www.youtube.com/watch?v=C4cfo0f88Ug не забывая показывать им, кто в доме хозяин.]&lt;br /&gt;
&lt;br /&gt;
'''Гайды:''' [[Guide to Robotic|Гайд по Роботехнике]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Возиться с машинами намного проще, чем управлять людьми, достаточно действовать логично, чтобы добиться успеха. С людьми так не получается.''&amp;lt;br/&amp;gt;'''''Колин Пауэлл'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Работа Роботехника заключается в создании и обслуживании кибернетических систем, а также создании различных ботов и мехов.&lt;br /&gt;
== Отдел роботехники ==&lt;br /&gt;
&lt;br /&gt;
[[File:Roboticist.jpg|250px|thumb|Отдел робототехники, царство технологий.]]&lt;br /&gt;
&lt;br /&gt;
'''Ваш рабочий отсек из технической составляющей будет оборудован:'''&lt;br /&gt;
*Мусорным баком [[File:Disposal_Bin.png]]; &lt;br /&gt;
*Несколькими зарядными станциями для киборгов [[File:CyborgRecharger.png]] и мехов [[File:Recharge_Port.gif]];&lt;br /&gt;
*Фабрикаторами [[File:Exofab.png]]; &lt;br /&gt;
*Связующей R&amp;amp;D консолью, к которой будет подключен принтер плат [[File:Circuit_imprinter.png]];&lt;br /&gt;
*Небольшой хирургической комнатой. &lt;br /&gt;
'''Для работы вам выдадут:'''&lt;br /&gt;
*Несколько стаков металла (каждый стак по 50 листов)[[File:Metal.png]] и одним неполным стаком пласталя (10-20 листов)[[File:Metal_r.png]]; &lt;br /&gt;
*Немного улучшенных батареек питания [[File:Power_cell.png]] и зарядным устройством для них;&lt;br /&gt;
*Флеш-устройства [[Файл:Flash.png]] и сенсоры [[File:Prox_Sensor.png]]; &lt;br /&gt;
*Несколько мотков проводов [[File:CableCoils.png]], &lt;br /&gt;
*Топливный танкер [[File:Fueltank.png]];&lt;br /&gt;
*Парочку интерфейсов MMI [[File:MMI_empty.png]];&lt;br /&gt;
*А так же пустые аптечки и ящики из-под инструментов.&lt;br /&gt;
'''Разумеется, в хирургической части будет полный набор медицинских инструментов.'''&lt;br /&gt;
&lt;br /&gt;
==Эффективный механизм работы==&lt;br /&gt;
У вас есть два основных направления: кибернизация и постройка мехов. В первое время у вас не будет &amp;quot;клиентов&amp;quot; на кибернизацию, но всё же стоит построить парочку кибер-каркасов и заняться сборкой меха [[Guide_to_Robotics#A.P.L.U._Ripley|Рипли]] [[File:Ripley_new.png?]]. &lt;br /&gt;
&lt;br /&gt;
Наличие у шахтёров [[File:Ripley_new.png?]] с полным комплектов инструментов ([[File:Exosuit_drill.png]] бур простой\улучшенный, [[File:Hydraulic_clamp.png]] гидравлическая рука и [[File:Mech_scaner.png]] шахтёрский сканер) принесёт хорошую выгоду, подарив вам взамен алмазы, золото, серебро и так далее. &lt;br /&gt;
&lt;br /&gt;
'''Помните:''' Рипли ускорит работу шахтёров, а значит и эффективность работы Исследовательского Отдела.&lt;br /&gt;
&lt;br /&gt;
[[Guide_to_Robotics#Medibot|Медботы]] [[File:Medibot.png]], [[Guide_to_Robotics#Cleanbot|Клинботы]] [[File:Cleanbot.png]], [[Guide_to_Robotics#Floorbot|Флурботы]] [[File:Floorbot.png?]] - ваши верные помощники. Ещё одно маленькое направление в вашей работе, которое не требует особых затрат, зато значительно окупает потерю времени.&lt;br /&gt;
Не стоит забывать, что есть ещё два бота, а именно [[Guide_to_Robotics#Securitron|Секьюритоны]] [[File:Securitron.png]] и [[Guide_to_Robotics#ED-209|ED-209]] [[File:ED-209.png]], но эта парочка требует снаряжение, недоступное вам изначально. Свяжитесь с [[Warden|Варденом]] или [[Head of Security|Начальником Службы Безопасности]] и договоритесь о нескольких тазерах, бронежилетах и касках. Поверьте, они не должны вам отказать.&lt;br /&gt;
&lt;br /&gt;
==Что можно, а что нельзя==&lt;br /&gt;
'''Можно и нужно:'''&lt;br /&gt;
*[[Файл:Standard_cyborg.png]] Создавать каркасы для будущих киборгов.&lt;br /&gt;
*Стараться кибернизировать опасных личностей, вместо их казни.&lt;br /&gt;
*Обрезать LawSync (синхронизацию законов) и сбрасывать законы киборгу при сбое ИИ.&lt;br /&gt;
*[[Файл:Floorbot.png]] Собирать полезных ботов и отпускать их гулять по станции.&lt;br /&gt;
*[[Файл:Drone_animated.gif]] Создавать дронов, чтобы безнадёжно умершие игроки смогли вернуться в игру и чинить станцию.&lt;br /&gt;
*[[Файл:RoboticsControlConsole.png]] Собрать собственноручно контроль-консоли для мехов и киборгов.&lt;br /&gt;
*[[Файл:R%26D_console.png]] Не забывать периодически синхронизировать свою R&amp;amp;D консоль.&lt;br /&gt;
'''Нельзя:'''&lt;br /&gt;
*[[Файл:%2BMMI.png]] Вставлять MMI в каркас киборга не убедившись, что мозг проявляет активность. Будет неприятно, если вы создадите киборга-апатика.&lt;br /&gt;
*Взрывать всех киборгов лишь потому, что одного из них обработали е-магом [[File:Emag.png]].&lt;br /&gt;
*Немедля взрывать всех киборгов при малейшем [[AI_Malfunction|сбое ИИ]]. Вместо этого, разберите вашу консоль &amp;quot;Robotics Control&amp;quot; [[Файл:RoboticsControlConsole.png]] и переместите её куда-нибудь, где нет камер, так, чтобы вы могли блокировать киборгов и превращать их в верных союзников в борьбе против [[AI_Malfunction|сбойного ИИ]].&lt;br /&gt;
*Пытаться собрать мех, не оценив количество материалов, которое у вас есть.&lt;br /&gt;
*Использовать военные экзоскелеты с полным вооружением. Никто не говорит, что вам запрещено это делать, но с логической точки зрения это неправильно.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
'''Для ботов:'''&lt;br /&gt;
*Любому боту можно дать собственное имя, подписав его ручкой перед завершением его сборки. Это полезно для их отслеживания, иначе все они будут иметь базовое название &amp;quot;Medibot&amp;quot;.&lt;br /&gt;
*Цвет медбота зависит от цвета аптечки, которую вы возьмёте за основу.&lt;br /&gt;
*Фактически, можно взять любого бота вместе с собой, но только в виде несобранного корпуса и руки\сенсора (зависит от последней стадии сборки бота)&lt;br /&gt;
*У любого бота есть свой интерфейс и настраиваемые параметры, среди которых есть примитивная функция включения\выключения, смена режима патрулирования, система безопасности, а так же настройка специальных функций у определённых видов ботов. &lt;br /&gt;
*Выключение системы безопасности повлияет на работу и поведение бота: &lt;br /&gt;
**[[File:Securitron.png]] начнёт арестовывать всех подряд;&lt;br /&gt;
**[[File:Cleanbot.png]] начнёт использовать для очистки пола безвредную, но крайне неприятную пену, на которой можно подскользнуться;&lt;br /&gt;
**[[File:Medibot.png]] начнёт колоть людям то, что задаст сам пользователь (необходимо вставить пробирку с нужным веществом).&lt;br /&gt;
'''Для мехов:'''&lt;br /&gt;
*Во всех мехах присутствует система проверки по ДНК. Это своеобразный замок и, поверьте, эта функция защитит ваши мехи от нехороших людей.&lt;br /&gt;
*Шприцепушку [[File:Sgun.png]] можно зарядить целиком и за один раз, если воспользоваться коробкой со шприцами. Успешный тык по коробке гарантирует полный &amp;quot;магазин&amp;quot;.&lt;br /&gt;
'''Общее:'''&lt;br /&gt;
*Модификация фабрикатора [[File:Exofab.png]] существенно уменьшает потребление ресурсов и время на постройку, повышая общую эффективность. &lt;br /&gt;
Производство [[Guide_to_Robotics#A.P.L.U._Ripley|Рипли]] [[File:Ripley_new.png]] и [[Guide_to_Robotics#Odysseus|Одиссея]] [[File:Odysseus.png]] не будет затратным без апгрейда, но более продвинутые боевые мехи, вроде [[Guide_to_Robotics#Gygax|Гигакса]] [[File:Gygax.png]], [[Guide_to_Robotics#Durand|Дюранда]] [[File:Durand.png]],  [[Guide_to_Robotics#Phazon|Фазона]] [[File:Phazon.png]] и [[Guide_to_Robotics#H.O.N.K.|H.O.N.K.]] [[File:Honk.png]] потребуют много серебра, золота, плазмы, алмазов и даже бананиума, поэтому в таком случае апгрейд отлично сэкономит ваши материалы и нервы шахтёров.&lt;br /&gt;
*Модификация последней стадии для зарядных кибер-станций [[File:CyborgRecharger.png]] упростит вам задачу, ведь теперь зарядники будут чинить ваших киборгов.&lt;br /&gt;
*Вы не должны забивать фабрикаторы [[File:Exofab.png]] всем металлом, который у вас есть. Оставьте как минимум один стак для сборки мехов.&lt;br /&gt;
*Флеши[[Файл:Flash.png]] в вашем случае - не оружие самозащиты, а деталь для сборки киборгов. Не раздавайте их кому попало.&lt;br /&gt;
*Постарайтесь собрать корпус  Рипли [[File:Ripley_new.png?]] в самом начале смены, ведь если вам попадутся здравые учёные, то платы вы заполучите невероятно быстро.&lt;br /&gt;
*Если вы увидели киборга в вашем отсеке, то внимательно осмотрите его, ведь они приходят лишь в том случае, если им нужно заменить батарею, сменить модуль или просто починить.&lt;br /&gt;
*Если [[AI Malfunction|ИИ сбойный]], то необходимо воспользоваться необходимой консолью в офисе Исследовательского Директора, чтобы уничтожить напрямую связанных с ИИ киборгов. Консоль [[Файл:RoboticsControlConsole.png]] &amp;quot;Robotics Сontrol&amp;quot; - ваш верный друг и товарищ в битве с ошалевшими машинами.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Geneticist&amp;diff=19713</id>
		<title>Geneticist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Geneticist&amp;diff=19713"/>
		<updated>2015-11-28T16:50:45Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobgen.png]]&amp;lt;br&amp;gt;[[Geneticist|Генетик]]&lt;br /&gt;
|'''Доступ:''' Medbay; Morgue; Genetics&lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Medical Officer]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Изучать гены, клонировать умерших, усовершенствовать живых&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Genetics]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right&amp;quot;&amp;gt;''Бог – это эхо наших собственных дел.''&amp;lt;br/&amp;gt;'''''Выписка из учебника по генетике'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Gen.PNG|frame|right|Генетика. Трудно быть Богом.]]&lt;br /&gt;
&lt;br /&gt;
= Приятно познакомиться, Бог =&lt;br /&gt;
&lt;br /&gt;
'''Кто такой Бог? Какова его роль? Что он может?'''&lt;br /&gt;
&lt;br /&gt;
Человечество задавалось этими вопросами с самой колыбели своего существования, и... если вы считаете, что Бог - это создатель всей жизни в галактике, то у нас для вас радостные новости: работая в нашей корпорации НаноТразен, вы сможете почувствовать себя самим Богом! Сначала богом мелких паразитов, потом и более крупных животных, а после и представителей &amp;quot;расовых меньшинств&amp;quot;, и то когда пройдете восьмилетнее обучение у наших лучших специалистов, но зато какие возможности перед вами откроются в будущем!&lt;br /&gt;
&lt;br /&gt;
== Генетика как она есть ==&lt;br /&gt;
&lt;br /&gt;
По сути же, генетик - один из самых полезных людей в случае чрезвычайной ситуации на станции, ну или при обнаружении [http://lurkmore.to/Неведомая_ёбаная_хуйня НЕХ]. В первом случае генетик сможет быстро восстановить человеческие ресурсы, потерянные в битве с возникшей внештатной ситуацией, при помощи своего суперсовременного оборудования для клонирования: оно позволяет поставить клонирование людей чуть ли не на конвейерную ленту, а продукцию на выходе вы не сможете отличить от оригинала!&lt;br /&gt;
&lt;br /&gt;
Также, генетик имеет возможность &amp;quot;улучшать&amp;quot; экипаж с помощью открытых им суперсил, но здесь стоит заметить что исследование новых сил не подходит под юрисдикцию медицинского отсека, а потому на этом фронте вашим командующим будет уже [[Research_Director|Директор по исследованиям]]. Поскольку в целях безопасности настоятельно не рекомендуется испытывать новые гены на себе, корпорация предоставляет вам целый вольер, набитый специально отобранными мартышками: их гены абсолютно чисты от каких-либо дефектов, а потому вы можете использовать их для своих экспериментов и быть полностью уверенным, что любой косяк это исключительно ваша вина.&lt;br /&gt;
&lt;br /&gt;
'''Запомните, согласно уставу корпорации, вы не имеете права колоть кому-либо модифицированные гены''' без разрешения [[Research_Director|Директора по исследованиям]], [[Captain|Капитана]], или [[Head of Personnel|Главы персонала]], а также согласия на проведение генной терапии от человека, с которым она будет происходить, и его непосредственного начальника. &lt;br /&gt;
Данное нарушение расценивается как превышение должностных полномочий и карается [[Space Law|законом]].&lt;br /&gt;
&lt;br /&gt;
===А что это?===&lt;br /&gt;
&lt;br /&gt;
Генетик в своем роде уникальная профессия, у вас будет сразу два начальника - [[Chief_Medical_Officer|Старший медицинский офицер]] и [[Research_Director|Директор исследований]], и вдвое больше ответственности - ведь вам придется работать на два отдела, но в этом есть и свои плюсы: вдвое больше премиальных (если вы конечно будете работать вдвое усерднее), а еще возможность поиграть в Бога. Это явно того стоит.&lt;br /&gt;
&lt;br /&gt;
'''Но с чем же мне придётся работать?''' Естественно, что только с лучшим оборудованием которое у нас есть, ну почти. У вас будет: два новеньких модификатора генов; целый вольер с подопытными обезьянами, оборудованный по последнему слову техники; свои шкафчики для: белья, медикаментов, пациентов и много других; а также ультрасовременный под для клонирования, который сделает вашу работу незабываемо легкой - НаноТразен заботится обо всех своих сотрудниках. &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Советы==&lt;br /&gt;
* Если клонирование изменило ваш внешний вид, положите своё старое тело в сканер ДНК, запишите UI/UE в инжектор и вколите его себе. После этого к вам вернётся ваша старая внешность.&lt;br /&gt;
* Если у кого-то имплант в теле, его можно уничтожить, превратив тело в мартышку и обратно.&lt;br /&gt;
* Клонер изначально создаёт клонов со 190 ед. генетического урона и 99% повреждением мозга. До 40% генетического урона могут быть вылечены введением уникальных генов. Клонер тратит 2,5 минуты на изготовление клона. Извлечение клона на 40%, и последующее лечение его в криотрубе ускоряет процесс на несколько секунд, но это не значит, что вы можете клонировать двух человек одновременно.. Извлечение клона на 40%, отключение АПЦ или взлом клонера Е-Магом, а затем лечение клона в криокамере даёт ускорение процесса в 2 раза, и позволяет клонировать до 3-х человек одновременно.&lt;br /&gt;
* Отключение питания клонера выбрасывает клона, вне зависимости от состояния. Это можно использовать для быстрого клонирования: клонируйте человека на 25%, положите в крио, повторите с другим телом, и клонируйте третьего, пока одна из криокамер не освободится, повторите всё сначала.&lt;br /&gt;
* Превращение клона в мартышку вылечит его.&lt;br /&gt;
* The Genetics DNA altering console can spit out injectors for UEs and UIs as well as SEs. This means that, if you get a willing volunteer or even just human a monkey, you can run around the station changing everyone into the same person (if you do this without being antag or having people’s con-sent, you will get banned).&lt;br /&gt;
* You can put disks into the cloning computer to save the UI, UE and SE of people scanned.&lt;br /&gt;
* Водка хорошо выводит радиацию из крови.&lt;br /&gt;
* Генетические силы могут проявить изменения SE. Большинство людей вводят себе инжектор раз за разом, для получения сил. Но есть другой способ: положите человека в сканер, измените длительность и мощность излучения на 1/1, и облучайте случайные блоки. Таким образом, вы измените много блоков, и почти не получите радиации. Тем не менее, такой способ может вызвать случайные болезни, так что убедитесь что у вас есть чистый SE. Так же обратите внимание на значения блоков.&lt;br /&gt;
** Используйте &amp;quot;безопасный&amp;quot; блок и излучение 1/1. Безопасный блок - блок со значением 333-4bb. Тогда вам не слишком часто придётся сбрасывать SE.&lt;br /&gt;
* Радиация, а также радиационные штормы и мутаген имеют очень, ОЧЕНЬ небольшой шанс на положительные последствия. Скорее вы получите болезнь, чем суперсилу.&lt;br /&gt;
* Для улучшенного сканера самым оптимальным режимом является длительность излучения 4.&lt;br /&gt;
&lt;br /&gt;
'''Трудитесь на благо вашей Корпорации и она позаботится о вас. © НаноТразен'''&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chemist&amp;diff=19712</id>
		<title>Chemist</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chemist&amp;diff=19712"/>
		<updated>2015-11-28T16:50:00Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#DDA0DD;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchem.png]]&amp;lt;br&amp;gt;[[Chemist|Химик]]&lt;br /&gt;
|'''Доступ:''' Medbay, Chemistry&lt;br /&gt;
&lt;br /&gt;
'''Подчинение:''' [[Chief Medical Officer]]&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Смешивать химикаты и делать препараты&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Medicine]], [[Guide to Сhemistry]]&lt;br /&gt;
!Средне&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Чтобы восстановить здоровье необходимо смешать любые два из следующих ингредиентов: болотный тростник, виквит и канифоль. При правильном приготовлении побочных эффектов не наблюдается. Простое снадобье для снятия усталости - смешать скрибовое-желе и скаттл. Чтобы снадобье было сильнее, вместо желе используйте мясо гончей. Однако, мясо придает смеси отвратительный вкус. Покупатели обычно предпочитают вкусные снадобья более эффективным.''&amp;lt;br/&amp;gt;'''''Алхимический рецепт с одной из отдалённых планет'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Chemistry.png|280px|right|thumb|Место где происходят самые правдоподобные химические реакции]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Долг зовёт ===&lt;br /&gt;
&lt;br /&gt;
У вас, как у химика, есть несколько обязанностей. Давайте разберём их.&lt;br /&gt;
* Снабжать врачей и генетиков лекарствами по их первому требованию. Лучше, конечно, заранее приготовить несколько баночек, чтобы вы не метались по лаборатории в случае ЧП. Что вам понадобится? Если врачей мало - сварите криоксадон, крио будет работать без передыха. Если есть генетики - то варите алкизин и риталин, иначе напора падающих и ругающихся клонированных на ваш кабинет не избежать.&lt;br /&gt;
* Наливать ученым, и иногда роботехникам в колбы серную кислоту, она им требуется для травления плат. Ни в коем случае не отдавайте им свои большие колбы - никогда не вернут, пусть приходят со свей тарой.&lt;br /&gt;
* Выдавать ботаникам мутаген и аммиак, вы же хотите есть вкусную морковку у повара?&lt;br /&gt;
* Заполнять разбрызгиватель уборщика Спейс Клинером, во имя чистоты станции.&lt;br /&gt;
* Наливать клоуну Спейс Луб. Ну, это ваш долг.&lt;br /&gt;
* Всё остальное. Ассистент, просящий бикардинчику после драки, ХоС, требующий синаптизин, варден, выпрашивающий трик для химимплантов - каждая смена уникальна!&lt;br /&gt;
&lt;br /&gt;
=== Наука! ===&lt;br /&gt;
&lt;br /&gt;
Помните, химия - тоже наука, и пусть вам не выдали доступ в научный отдел, и ваша зарплата на порядок ниже этих тунеядцев в фиолетовом, вы можете экспериментировать! Обычно эксперименты начинаются со смесей для быстрого выведения из критического состояния. Идеал данной смеси - когда вам не нужен даже анализатор, вы просто колите одно и тоже замороженным, расстрелянным и избитым.&lt;br /&gt;
Извечная тема спора химиков - боевой коктейль. Смесь, которая превращает вас в универсального солдата, даёт вам скорость и силу. Не забывайте добавлять в неё лечащие компоненты.&lt;br /&gt;
А дальше химик открывает для себя гранаты с дымом, и тут он пропадает для мира. Ведь граната с дымом - это быстрое введение любых веществ всем в зоне поражения - а это приличных размеров отсек.&lt;br /&gt;
Помните, что для увеличения поражающей способности гранат вы можете выпросить у ученых корпус большой гранаты, в которую влезает намного больше веществ.&lt;br /&gt;
И ещё, когда вам все это наскучит: до нас дошли слухи об отдаленных станциях, где гениальные химики создают смеси, которые позволяют находиться в космосе без специальных приспособлений. Все эти смеси связаны общим именем, они названы в честь ученого, который первый массово их использовал, и, может быть, даже открыл. Запомните это название: &amp;lt;i&amp;gt;Хаусин&amp;lt;/i&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
== Делайте всё правильно ==&lt;br /&gt;
Химики очень подозрительные личности. У них есть все средства в мире чтобы уничтожить его в перерыве между ужасными и бесчеловечными убийствами. И самый лёгкий способ избежать подозрений (если вы конечно делаете что либо подозрительное)- это представить себя в лучшем свете и быть полезным станции в начале игры. И любой инцидент спишут на вашего коллегу, если он у вас конечно же есть.&lt;br /&gt;
&lt;br /&gt;
=== Инструменты торговли ===&lt;br /&gt;
* Chem Dispenser - переводит электроэнергию в различные химические элементы , благодаря &amp;lt;s&amp;gt;магии&amp;lt;/s&amp;gt; науке. Это один из самых незаменимых приборов на станции, сохраните его даже ценой ценой своей жизни.&lt;br /&gt;
* ChemMaster 3000 - может магическим образом отделять одни вещества от других, и имеет неограниченный запас пилюль/повязок (по 50 единиц вместимости) и бутылочек ( по 30 ед.).&lt;br /&gt;
* Reagent Grinder - такой же блендер как и у Повара. Может извлекать реагенты из вещей принесённых Шахтёрами, Поварами, и Ботаниками.&lt;br /&gt;
* Chemical Heater - нужен для создания многих рецептов требующих высокие температуры.&lt;br /&gt;
* Внутри шкафчика севернее вас вы найдёте коробку с банками для пилюль. На столе южнее лежит маркировщик. Используйте их для более удобного и эффективного хранения и распространения пилюль.&lt;br /&gt;
&lt;br /&gt;
=== Будь полезным ===&lt;br /&gt;
==== Начало раунда ====&lt;br /&gt;
'''Если кто-то приходит и просит у вас что-либо обслужите его первым. Никто не любит стоять в очереди. Если вы почти изготовили что-то необходимое вашему клиенту проинформируйте его о готовности.'''&lt;br /&gt;
&lt;br /&gt;
* Для [[Roboticist|Роботехник]]ов и [[Scientist|РнД]]:&lt;br /&gt;
** Наполните большую банку 100 ед. серной кислоты, отдайте им и повторите снова.&lt;br /&gt;
&lt;br /&gt;
* Для всей команды и особенно для [[Medical Doctor|Доктор]]ов:&lt;br /&gt;
** Сделайте [[Guide to Сhemistry/tg|кровоостанавливающий порошок, сульфадиазин серебра, синтезированную плоть, и активированный уголь]]. Наркотики как salbutmol и адреналин полезны, но ненужны .&lt;br /&gt;
** Положите на передний стол или в хим. хранилище под вашей лабораторией.&lt;br /&gt;
&lt;br /&gt;
* Пилюли/повязки для раненых:&lt;br /&gt;
*** Кровоостанавливающий порошок (Aluminum, Hydrogen, Oxygen, Sulfuric Acid - лечит физ. повреждения)&lt;br /&gt;
*** Сульфадиазин серебра (Ammonia, Silver, Sulfur, Oxygen, Chlorine - лечит ожоги)&lt;br /&gt;
*** Синтезированная плоть (Styptic Powder, Carbon, Blood - лечит физ. повреждения и ожоги)&lt;br /&gt;
*** Активированный уголь (Ash and Table Salt - от интоксикации)&lt;br /&gt;
*** Сальбутамол (Salicylic Acid, Lithium, Bromine, Ammonia, Aluminum - лечит удушье)&lt;br /&gt;
&lt;br /&gt;
* Для [[Atmospheric Technician|Атмосферников]] и [[Station Engineer|Инженеров]] припасено то, что поможет быстро заделать обшивку станции:&lt;br /&gt;
** Сделайте 30 ед. вспенивателя и фторсульфоновой кислоты, разлейте по 10 ед. в 3 банки.&lt;br /&gt;
** Сделайте 90 ед. железа, разлейте по 30 ед. в 3 другие банки.&lt;br /&gt;
** Поместите одну банку вспенивателя с кислотой и ещё одну банку железа в гранату - это граната с железной пеной, если вы сделали всё правильно у вас должно получиться 3 таких гранаты.&lt;br /&gt;
&lt;br /&gt;
==== Если вы хотите быть на высоте ====&lt;br /&gt;
* [[Botanist|Ботаники]] будут восхищаться вами если достанете им мутагена для мутаций растений. Так же они могут использовать диэтиламин как удобрение, [[Guide_to_Сhemistry/tg#Fluorosulfuric Acid|фтороносерную кислоту]] как эффективный способ уничтожения растений, пипетку для точных мутаций и [[Guide_to_Сhemistry/tg#Space_Cleaner|чистящее средство]] для очистки места от растворённых растений.&lt;br /&gt;
*  [[Virologist|Вирусологи]] будут ждать от вас [[Guide_to_Сhemistry/tg#Unstable_Mutagen|мутагена]] и [[Guide_to_Сhemistry/tg#Synaptizine|синаптизина]] для создания новых вирусов.&lt;br /&gt;
* [[Geneticist|Генетики]] могут извлечь выгоду от запаса [[Guide_to_Сhemistry/tg#Potassium_Iodide|иодида калия]] или таблеток [[Guide_to_Сhemistry/tg#Charcoal|активированного угля]] для лечения высокой радиации у себя и своих подопытных.&lt;br /&gt;
*  [[Janitor|Уборщики]] могут попросить вас заправить их пульверизатор с [[Guide_to_Сhemistry/tg#Space_Cleaner|чистящим средством]], особенно если вирусолог заразил весь экипаж и вокруг много блевотины.&lt;br /&gt;
* Можете помочь [[Chef|Повару]] таким способом: серная кислота для соевого соуса.&lt;br /&gt;
* [[Bartender|Бармен]] может попросить химикатов для коктейлей. Но учтите, что бармен может попросить ядохимикат, и лучше ему его не давать. &lt;br /&gt;
* [[Warden|Смотритель]] захочет препаратов для имплантирования арестантам, чтобы те не сопротивлялись.&lt;br /&gt;
* Измельчите еду, для того, чтобы сделать таблетки с питательными веществами, затем усмехнитесь над [[Chef|Поваром]]. &lt;br /&gt;
* В момент побега [[Terminology#Hulk|Халка]] из генетики возьмите шприц с [[Guide_to_Сhemistry/tg#Mutadone|мутадоном]] и [[Guide_to_Сhemistry/tg#Chloral_Hydrate|хлоралгидратом]], зарядите в шприцемет и попадите в него. Ему станет грустно.&lt;br /&gt;
* Если [[AI|ИИ]] свихнулся, или на станции улей [[Alien|ксеноморфов]], вас могут попросить [[Guide_to_Сhemistry/tg#Thermite|термит]], с помощью которого можно прожечь укрепленные или органические стены.&lt;br /&gt;
* Включите сканер содержимого на вашем [[PDA|КПК]] и проверьте еду с напитками в баре и кухне на яд. Так же, это можно использовать на людях, чтобы проверить чем они отравились.&lt;br /&gt;
* Вы, всё-таки, относитесь к [[Medical Doctor|врачам]]. Когда они отсутствуют - берите анализатор здоровья и начните помогать пациентам.&lt;br /&gt;
* Если вам СОВСЕМ нечего делать, создайте лекарственные таблетки и пластыри, поместите их на прилавок медбея.&lt;br /&gt;
* [[Clown|Клоун]] обязательно попросит [[Guide_to_Сhemistry/tg#Space_Lube|смазку]]. Смейтесь ему в лицо и не давайте ему её.&lt;br /&gt;
&lt;br /&gt;
=== Вооружение себя===&lt;br /&gt;
* Возьмите шприцемёт на столе западнее входа в медбей прежде чем доктора сделают это. Они ничего не смогут сделать с ним, но в ваших руках он станет ценным оружием, можете наполнить его [[Guide to Сhemistry/tg|хлоралгидратом или хуже]]. Если вы не успели - можете попытаться проскользнуть на мед. склад и взять там второй.&lt;br /&gt;
* Позже ближе к концу раунда, если вы сдружились с РнД, они могут дать вам улучшенную версию которая может держать в себе шесть шприцов если вы вежливо попросите об этом.&lt;br /&gt;
* Спрей из под отчистителя сойдёт за самодельный огнемёт если наполните его [[Guide to Сhemistry/tg|трехфтористым хлором]].&lt;br /&gt;
* У вас есть все инструменты чтобы изготавливать гранаты. См. ниже.&lt;br /&gt;
&lt;br /&gt;
===Химия 101===&lt;br /&gt;
В [[Guide to chemistry|гайде по химии]] есть список всех возможных веществ.&lt;br /&gt;
&lt;br /&gt;
{{anchor|Grenades}}&lt;br /&gt;
&lt;br /&gt;
===Гранаты===&lt;br /&gt;
Будучи химиком - вы единственный человек, имеющий доступ к гранатам. Можете поместить 2 пробирки с ЧЕМ-УГОДНО, в любую заготовку для гранаты. Выньте их, если необходимо, кликнув по гранате в руке. Очевидно, что пробирки взорвутся при взрыве гранаты. Вы можете сделать лечащую, вредную, любую гранату. Экспериментируйте! В конце концов, что за наука без опыта?&lt;br /&gt;
'''ОБЯЗАТЕЛЬНО ПОМНИТЕ'''. За вредные гранаты вас могут избить или убить, еще вы можете получить джоббан, не имея [[Traitor|спецроли]].&lt;br /&gt;
&lt;br /&gt;
====Создание гранат 101====&lt;br /&gt;
#Возьмите провода со стола.&lt;br /&gt;
#Вставьте провода в каркас гранаты.&lt;br /&gt;
#Вставьте в гранату пробирки с химикатами. Две - максимум.&lt;br /&gt;
#Можете завершать гранату, закрутив ее отверткой, или вставив таймер, открутив его, затем вставив в гранату и только потом ее закрутить.&lt;br /&gt;
#Активируйте гранату, кидайте.&lt;br /&gt;
&lt;br /&gt;
Для реакций, которые идут только будучи смешанными, разделите их на 2 пробирки и вставьте в гранату. Для ознакомления, прочтите [[Guide to chemistry]].&lt;br /&gt;
&lt;br /&gt;
===Таблетки и пластыри===&lt;br /&gt;
Таблетки - отличный способ дать ощутимое количество лекарств за раз. Таблетка может содержать 50 единиц химикатов, а в коробочке для таблеток их может быть 7! А сами коробочки можно хранить в карманах. Пластыри схожи с таблетками, но работают &amp;quot;наружно&amp;quot;. Препараты, как [[Guide_to_Сhemistry/tg#Synthflesh|синтифлеш]] и [[Guide_to_Сhemistry/tg#Styptic_Powder|кровоостанавливающий порошок]] будут лечить только в пластырях, и вызывать отравление при приёме таблетками. &lt;br /&gt;
&lt;br /&gt;
==== Химикаты в таблетки или пластыри ====&lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Epinephrine|Адреналин]] для стабилизации критически раненых. &lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Charcoal|Активированный уголь]] для вывода ядов. &lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Styptic_Powder|Кровоостанавливающий порошок]] лечить физические повреждения.&lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Silver_Sulfadiazine|Cульфадиазин Cеребра]] - лечить ожоги. &lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Mannitol|Маннитол]] лечит повреждения мозга. &lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Oculine|Окулин]] лечит ''физические'' повреждения глаз.&lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Inacusiate|Инакусит]] убирает глухоту.&lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Synaptizine|Синаптизин]] снижает длительность оглушения, но наносит урон ядом. &lt;br /&gt;
* Смесь [[Guide_to_Сhemistry/tg#Leporazine|лепоразина]] и [[Guide_to_Сhemistry/tg#Salbutamol|салбутамола]] позволит дольше прожить в космосе без скафандра. &lt;br /&gt;
* Не создавайте только [[Guide_to_Сhemistry/tg#Synthflesh|синтифлеш]], иначе вас будут ненавидеть. Пусть он и лечит ожоги и синяки, он не так полезен в одиночку. Смешивайте их с чем-то.&lt;br /&gt;
* Таблетка с  [[Guide_to_Сhemistry/tg#Mutadone|мутадоном]] убирает все генетические дефекты и суперсилы. Полезно для свежих клонов. &lt;br /&gt;
* Если [[Virologist|вирусолог]] придет с вакциной, хватит и 1 единицы препарата для лечения в таблетках.&lt;br /&gt;
&lt;br /&gt;
===Bottles(Бутыльки)===&lt;br /&gt;
Бутылочки нужны для содержания веществ не являющихся лекарствами, такими как кислоты, или лекарств которые вы планируете использовать позже, такие как криоксадон. Каждая бутылка может содержать 30 ед., и её можно выплеснуть на что-либо. Они могут быть произведены в любых количествах в вашем ''ChemMaster''&amp;quot;е, так что можете сходить с ума.&lt;br /&gt;
* Термит&lt;br /&gt;
* Кислоты&lt;br /&gt;
* Cryoxadone&lt;br /&gt;
* Space cleaner&lt;br /&gt;
* Лекарства, основанные на прикосновении&lt;br /&gt;
&lt;br /&gt;
==Советы==&lt;br /&gt;
* Эффект [[Guide_to_Сhemistry/tg#Chloral_Hydrate|хлоралгидрата]] не сработает, если вы были под кофе. Но вы всё ещё будете получать урон от передозировки. [[Guide_to_Сhemistry/tg#Charcoal|Антитоксин]] абсолютно аннулирует эффект хлоралгидрата.&lt;br /&gt;
* Эффекты разных химикатов сочетаются, это значит, что вы можете сделать пластырь из [[Guide_to_Сhemistry/tg#Silver_Sulfadiazine|сульфидиазина]] и [[Guide_to_Сhemistry/tg#Synthflesh|синтифлеша]]. Добавьте немного [[Guide_to_Сhemistry/tg#Omnizine|омнизина]] во время готовки лекарственных препаратов.&lt;br /&gt;
* [[Guide_to_Сhemistry/tg#Foaming_Agent|Пена]] и [[Guide_to_Сhemistry/tg#Smoke|дым]] берут свойства реагентов. Пена произведет эффект реагента при наружном применении, а дым - при применении вовнутрь. Пена из [[Guide_to_Сhemistry/tg#Synthflesh|синтифлеша]] вылечит из критического состояния моментально, а из [[Guide_to_Сhemistry/tg#Fluorosulfuric Acid|фторосерной кислоты]]  - убьет жертв ''незамедлительно''.&lt;br /&gt;
* Гранаты шикарны со всем. Экспериментируйте! &lt;br /&gt;
* Вы можете заправить пульверизатор синтифлешем для переносного лечения!&lt;br /&gt;
* Если вы размельчите '''разогретый''' donk pocket, попросите у капеллана святой воды, то сможете создать [[Guide_to_Сhemistry/tg#Strange_Reagent|странный реагент]], который может буквально привести к жизни труп. Смейтесь над генетиками, клонирование стало не нужным. Кстати, его можно разбавить, потому что нужно всего 0.4 единицы для воскрешения. &lt;br /&gt;
* Учтите, что странный реагент может оживить кого-то у кого меньше 100 физического урона и меньше 100 от ожогов. Это не сочетается. Труп с 99 того и 99 другого можно оживить.&lt;br /&gt;
* Препараты, нацеленные на наружное применение, '''РАБОТАЮТ''' для мертвых. Сделайте гранату из странного реагента и синтифлеша, киньте в кучу трупов, и наблюдайте как они восстают из мертвых. [[Traitor|Предатели]] разозлятся. &lt;br /&gt;
* Вам не обязательно делать гранату для пены. [[Guide_to_Сhemistry/tg#Foam_Surfactant|Пенообразователь]] в одной пробирке и вода в другой с сочетанием 1:1, смешайте - будет вам пена.&lt;br /&gt;
* Приемная выглядит как после резни? Приготовьте пену из [[Guide_to_Сhemistry/tg#Space_Cleaner|чистящего средства]], узрите, насколько стало чисто.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19622</id>
		<title>Обсуждение:Guide to Posters</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19622"/>
		<updated>2015-11-19T21:36:16Z</updated>

		<summary type="html">&lt;p&gt;IXVI: FY&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Что? Гайд к постерам, который переводит их текст? МОжет, еще запилим гайд к, ну я не знаю, НАДПИСИ У МОСТИКА? Который описывает, что на ней можно писать про ХоСа, как писать, как снимать там плитку и как она переводится? А еще переводим &amp;quot;репер&amp;quot; как &amp;quot;насильник&amp;quot;, еще несколько фактических ошибок. Короче - абсолютно бессмысленная статья, созданная ради ОЧКОВ ВИКИ))))), заремувьте ее, пожалуйста. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 17:17, 18 ноября 2015 (MSK)&lt;br /&gt;
**Увидел ангельский текст в статье - перевёл. На счёт насильника ошибся, бывает (для такого и создана волшебная кнопка &amp;quot;править&amp;quot;). А в общем да, статья достаточно бесполезна, я тоже вот смысла в ней не вижу. - [[Участник: Feomatar|Feomatar]] 16:36, 18 ноября 2015 (MSK)&lt;br /&gt;
**Я о том, что единственная нагрузка в этой статье - перевод ТЕКСТА ИЗ ИГРЫ. То есть это прям ну совсем полный идиотизьм. А править статью, которая не нужна - глупо. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 21:20, 18 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Ублюдки блядь, вы что делаете нахуй? Что это за параша? Гайд по ПЛАКАТАМ? Вы что, ебанутые, блядь? Пиздеееец. Просто пиздец. При прошлом конкурсе такой хуиты было мало. Я ебал просто. Идите нахуй. [[Участник:Alexix|Alexix]] ([[Обсуждение участника:Alexix|обсуждение]]) 01:43, 19 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Всем нравится, идите нахуй. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 00:34, 20 ноября 2015 (MSK) Идите нахуй дважды, блять.&lt;br /&gt;
&lt;br /&gt;
*Всем это кому? Поясните пожалуйста.--[[Участник:Recei|Recei]] ([[Обсуждение участника:Recei|обсуждение]]) 00:42, 20 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Запустите голосование в группе ss13 на сайте vk.com, и посмотрите результаты, прошу вас. Всем - это подавляющему большинству, да здравствует демократия. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 01:28, 20 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Мы не настолько еще отрупели, что бы слушать раков из ВК. И уж тем более ориентироваться на &amp;quot;большинство&amp;quot;. С уважением. --[[Участник:Recei|Recei]] ([[Обсуждение участника:Recei|обсуждение]]) 01:30, 20 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Я считаю вашу позицию &amp;quot;википедия для избранных&amp;quot; тупиковой в отношении развития сообщества игры. Согласитесь, что википедия более нужна для популяризации игры и введения новых игроков, а не для ностальгических воздыханий малочисленных элитирующих элементов. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 01:36, 20 ноября 2015 (MSK)&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19620</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19620"/>
		<updated>2015-11-19T21:30:00Z</updated>

		<summary type="html">&lt;p&gt;IXVI: remarks&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных рецептов и блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара.&lt;br /&gt;
&lt;br /&gt;
== Стандартные кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Универсальная машина, способная выжимать, крошить и молоть.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перемалывать туши в мясо.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
С помощью вашей скалки можно раскатать хлебное или сдобное тесто в лепёшку, которую затем можно разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
=== Нестандартные кухонные принадлежности ===&lt;br /&gt;
&lt;br /&gt;
В ходе своей работе вы можете столкнуться как со знакомым так и с малознакомым оборудованием. Как правило пользоваться им довольно просто и оно сможет весьма разнообразить ваше меню.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Blender e.png]] '''Старый блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, а посуду и соусы вы можете брать в раздатчике [[Файл:Dinnerware.png]] &amp;lt;br&amp;gt;&lt;br /&gt;
Но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках продовольствия.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Как правило рядом с кухней располагается отдел ботаники (или иначе гидропоники). В нём работают ваши коллеги, и основные поставщики свежих растений и новых культур на станции. У них есть множество гидропонических ванн под рассаду различнейших растений и как правило они сами будут спрашивать вас, какие овощи или фрукты нужны на кухню, или в бар. Не стесняйтесь просить у них что-либо повторно и проверять поставки в ваш универсальный холодильник.&lt;br /&gt;
&lt;br /&gt;
Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Из пшеницы можно сделать муку, а из некоторых грибов извлечь радий для коктейлей в бар. Лишние овощи можно превратить в молоко или мясо. Наконец, всё можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей. &lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
В вашей подсобке, где стоит мясорубка и крюк для подвешивания обезъян обитает ваш питомец - козёл Пити [[Файл:Goat.png]], больше похожий на буйвола и обладающий таким же буйным характером. Он привык к вам, но не любит чужаков и старается их запугать или боднуть. Пити лично ваше животное, но он не даёт ни молока, ни шерсти, так что решайте сами в каком виде он вам нравится больше.&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам коробку с обезьянками, ящик с цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку. Только не забудьте как следует накормить их перед тем, как использовать по назначению.&lt;br /&gt;
&lt;br /&gt;
Ходят слухи, что Корги - это отменное лакомство, но убийство данного вида животных категорически запрещено и не одобряется руководством, даже в экстренных случаях.&lt;br /&gt;
&lt;br /&gt;
=== Прочее ===&lt;br /&gt;
&lt;br /&gt;
Если у вас кончится перец, или запас универсальных энзимов, необходимых для приготовления сыров и шоколада, вы можете запросить ящик со снабжением в карго. За солью идите в отдел химии, а лишних обезъянок всегда можно попросить в генетике, или вирусологии - предварительно проверив их пригодность к употреблению.&lt;br /&gt;
&lt;br /&gt;
В тяжёлые времена на станции приходится питаться чем попало, и не дай бог попасть вам в очередной финансовый кризис компании Нанотрасен. На всякий случай знайте, что в технических тоннелях в обилии водятся мыши. Мясо пауков и космических карпов съедобно, но вредно для здоровья. А мясо космического медведя, если вам повезёт его найти - отменный деликатес. Говорят, что на некоторых потерпевших бедствие суднах экипаж решался на последнюю меру - каннибализм, так что желаем вам удачи.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19619</id>
		<title>Обсуждение:Guide to Posters</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19619"/>
		<updated>2015-11-19T21:28:43Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Что? Гайд к постерам, который переводит их текст? МОжет, еще запилим гайд к, ну я не знаю, НАДПИСИ У МОСТИКА? Который описывает, что на ней можно писать про ХоСа, как писать, как снимать там плитку и как она переводится? А еще переводим &amp;quot;репер&amp;quot; как &amp;quot;насильник&amp;quot;, еще несколько фактических ошибок. Короче - абсолютно бессмысленная статья, созданная ради ОЧКОВ ВИКИ))))), заремувьте ее, пожалуйста. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 17:17, 18 ноября 2015 (MSK)&lt;br /&gt;
**Увидел ангельский текст в статье - перевёл. На счёт насильника ошибся, бывает (для такого и создана волшебная кнопка &amp;quot;править&amp;quot;). А в общем да, статья достаточно бесполезна, я тоже вот смысла в ней не вижу. - [[Участник: Feomatar|Feomatar]] 16:36, 18 ноября 2015 (MSK)&lt;br /&gt;
**Я о том, что единственная нагрузка в этой статье - перевод ТЕКСТА ИЗ ИГРЫ. То есть это прям ну совсем полный идиотизьм. А править статью, которая не нужна - глупо. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 21:20, 18 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Ублюдки блядь, вы что делаете нахуй? Что это за параша? Гайд по ПЛАКАТАМ? Вы что, ебанутые, блядь? Пиздеееец. Просто пиздец. При прошлом конкурсе такой хуиты было мало. Я ебал просто. Идите нахуй. [[Участник:Alexix|Alexix]] ([[Обсуждение участника:Alexix|обсуждение]]) 01:43, 19 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Всем нравится, идите нахуй. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 00:34, 20 ноября 2015 (MSK) Идите нахуй дважды, блять.&lt;br /&gt;
&lt;br /&gt;
*Всем это кому? Поясните пожалуйста.--[[Участник:Recei|Recei]] ([[Обсуждение участника:Recei|обсуждение]]) 00:42, 20 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Запустите голосование в группе ss13 на сайте vk.com, и посмотрите результаты, прошу вас. Всем - это подавляющему большинству, да здравствует демократия. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 01:28, 20 ноября 2015 (MSK)&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19618</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19618"/>
		<updated>2015-11-19T21:22:57Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Kinda not making sense in sentences, got to resee it afterwards for a bit.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных рецептов и блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара.&lt;br /&gt;
&lt;br /&gt;
== Стандартные кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Универсальная машина, способная выжимать, крошить и молоть.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перемалывать туши в мясо.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
С помощью вашей скалки можно раскатать хлебное или сдобное тесто в лепёшку, которую затем можно разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
=== Нестандартные кухонные принадлежности ===&lt;br /&gt;
&lt;br /&gt;
В ходе своей работе вы можете столкнуться как со знакомым так и с малознакомым оборудованием. Как правило пользоваться ими довольно просто и они весьма разнообразят ваше меню.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Blender e.png]] '''Старый блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, а посуду и соусы вы можете брать в раздатчике [[Файл:Dinnerware.png]] &amp;lt;br&amp;gt;&lt;br /&gt;
Но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках продовольствия.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Как правило рядом с кухней располагается отдел ботаники (или иначе гидропоники). В нём работают ваши коллеги, и основные поставщики свежих растений и новых культур на станции. У них есть множество гидропонических ванн под рассаду различнейших растений и как правило они сами будут спрашивать вас, какие овощи или фрукты нужны на кухню, или в бар. Не стесняйтесь просить у них что-либо повторно и проверять поставки в ваш универсальный холодильник.&lt;br /&gt;
&lt;br /&gt;
Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Из пшеницы можно сделать муку, а из некоторых грибов извлечь радий для коктейлей в бар. Лишние овощи можно превратить в молоко или мясо. Наконец, всё можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей. &lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
В вашей подсобке, где стоит мясорубка и крюк для подвешивания обезъян обитает ваш питомец - козёл Пити [[Файл:Goat.png]], больше похожий на буйвола и обладающий таким же буйным характером. Он привык к вам, но не любит чужаков и старается их запугать или боднуть. Пити лично ваше животное, но он не даёт ни молока, ни шерсти, так что решайте сами в каком виде он вам нравится больше.&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам коробку с обезьянками, ящик с цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку. Только не забудьте как следует накормить их перед тем, как использовать по назначению.&lt;br /&gt;
&lt;br /&gt;
Ходят слухи, что Корги - это отменное лакомство, но убийство данного вида животных категорически запрещено и не одобряется руководством, даже в экстренных случаях.&lt;br /&gt;
&lt;br /&gt;
=== Прочее ===&lt;br /&gt;
&lt;br /&gt;
Если у вас кончится перец, или запас универсальных энзимов, необходимых для приготовления сыров и шоколада, вы можете запросить ящик со снабжением в карго. За солью идите в отдел химии, а лишних обезъянок всегда можно попросить в генетике, или вирусологии - предварительно проверив их пригодность к употреблению.&lt;br /&gt;
&lt;br /&gt;
В тяжёлые времена на станции приходится питаться чем попало, и не дай бог попасть вам в очередной финансовый кризис компании Нанотрасен. На всякий случай знайте, что в технических тоннелях в обилии водятся мыши. Мясо пауков и космических карпов съедобно, но вредно для здоровья. А мясо космического медведя, если вам повезёт его найти - отменный деликатес. Говорят, что на некоторых потерпевших бедствие суднах экипаж решался на последнюю меру - каннибализм, так что желаем вам удачи.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19617</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19617"/>
		<updated>2015-11-19T21:18:38Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Expanding description, adding more misc.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара. &lt;br /&gt;
&lt;br /&gt;
== Стандартные кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Универсальная машина, способная выжимать, крошить и молоть.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перемалывать туши в мясо.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
С помощью вашей скалки можно раскатать хлебное или сдобное тесто в лепёшку, которую затем можно разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
=== Нестандартные кухонные принадлежности ===&lt;br /&gt;
&lt;br /&gt;
В ходе своей работе вы можете столкнуться как со знакомым так и с малознакомым оборудованием. Как правило пользоваться ими довольно просто и они весьма разнообразят ваше меню.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Blender e.png]] '''Старый блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, а посуду и соусы вы можете брать в раздатчике [[Файл:Dinnerware.png]] &amp;lt;br&amp;gt;&lt;br /&gt;
Но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках продовольствия.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Как правило рядом с кухней располагается отдел ботаники (или иначе гидропоники). В нём работают ваши коллеги, и основные поставщики свежих растений и новых культур на станции. У них есть множество гидропонических ванн под рассаду различнейших растений и как правило они сами будут спрашивать вас, какие овощи или фрукты нужны на кухню, или в бар. Не стесняйтесь просить у них что-либо повторно и проверять поставки в ваш универсальный холодильник.&lt;br /&gt;
&lt;br /&gt;
Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Из пшеницы можно сделать муку, а из некоторых грибов извлечь радий для коктейлей в бар. Лишние овощи можно превратить в молоко или мясо. Наконец, всё можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей. &lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
В вашей подсобке, где стоит мясорубка и крюк для подвешивания обезъян обитает ваш питомец - козёл Пити [[Файл:Goat.png]], больше похожий на буйвола и обладающий таким же буйным характером. Он привык к вам, но не любит чужаков и старается их запугать или боднуть. Пити лично ваше животное, но он не даёт ни молока, ни шерсти, так что решайте сами в каком виде он вам нравится больше.&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам коробку с обезьянками, ящик с цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку. Только не забудьте как следует накормить их перед тем, как использовать по назначению.&lt;br /&gt;
&lt;br /&gt;
Ходят слухи, что Корги - это отменное лакомство, но убийство данного вида животных категорически запрещено и не одобряется руководством, даже в экстренных случаях.&lt;br /&gt;
&lt;br /&gt;
=== Прочее ===&lt;br /&gt;
&lt;br /&gt;
Если у вас кончится перец, или запас универсальных энзимов, необходимых для приготовления сыров и шоколада, вы можете запросить ящик со снабжением в карго. За солью идите в отдел химии, а лишних обезъянок всегда можно попросить в генетике, или вирусологии - предварительно проверив их пригодность к употреблению.&lt;br /&gt;
&lt;br /&gt;
В тяжёлые времена на станции приходится питаться чем попало, и не дай бог попасть вам в очередной финансовый кризис компании Нанотрасен. На всякий случай знайте, что в технических тоннелях в обилии водятся мыши. Мясо пауков и космических карпов съедобно, но вредно для здоровья. А мясо космического медведя, если вам повезёт его найти - отменный деликатес. Говорят, что на некоторых потерпевших бедствие суднах экипаж решался на последнюю меру - каннибализм, так что желаем вам удачи.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=%D0%A4%D0%B0%D0%B9%D0%BB:Dinnerware.png&amp;diff=19615</id>
		<title>Файл:Dinnerware.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%A4%D0%B0%D0%B9%D0%BB:Dinnerware.png&amp;diff=19615"/>
		<updated>2015-11-19T20:54:16Z</updated>

		<summary type="html">&lt;p&gt;IXVI: IXVI загрузил новую версию Файл:Dinnerware.png&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19614</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19614"/>
		<updated>2015-11-19T20:51:10Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Ты за 5 дней посмотрел, привлёк кого-то, исправил хоть что-то, или просто подставы кидаешь? Иди на хуй, не тебя звали.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков. Если вы работаете в Dream Maker - внимательно прочтите её и сообщите о найденных ошибках.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
При разработке большого проекта, хотя бы один из участников(а желательно все) должен быть ознакомлен с тем, что делает каждый из написанных модулей и какое у него применение. Хорошим тоном считается делать простое и понятное описание и название для каждого модуля. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
Например, при добавлении дополнительных функций к процедуре client.Topic() в разных местах в коде случается эффект сочетания зачений в родительском элементе:&lt;br /&gt;
&amp;lt;!--One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;вступление&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;И вот как-то раз...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;подсказка&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Буквально позавчера.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
В таком написании, эти два определения процедуры client/Topic(T) могут быть размещены в коде в любом месте. Если один из них будет выполнен и приведёт к значению ..() ,то другой уже не наступит. Вот в таких случаях и бывает полезно обращаться к процедуре-родителю&lt;br /&gt;
&amp;lt;!--As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Отладка кода===&lt;br /&gt;
&lt;br /&gt;
Или иначе дебаггинг(debugging).&lt;br /&gt;
&lt;br /&gt;
====Манеры хорошего кодера====&lt;br /&gt;
&lt;br /&gt;
Ошибка начинающих программистов в том, что они слишком полагаются на компилятор. Опытные баголовы и багоюзеры знают, что если код скомпилирован, то не факт что он работает как написано. Уязвимости бывают везде.&lt;br /&gt;
&amp;lt;!--The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Первый вызов для отладчика кода - суметь прочитать код и попробовать скомпилировать его в уме, так как его увидит машина. Возможно где-то не хватает переменных, возможно некоторые процессы ведут к нулевому значению, возможно некоторые условия невозможно выполнить в принципе. Думайте логически.&lt;br /&gt;
&amp;lt;!--The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Второй шаг - запустить код, так чтобы он заработал. Подставить необходимые переменные и запустить его в приложении. Сервер может выявить простые ошибки и баги, но только вы можете понять что работает не так, как оно должно работать, и почему это не так. А что работает именно так как описано в коде. Поиграйте с переменными и кодом, чтобы лучше понять механизмы компиляции и работы вашего кода.&lt;br /&gt;
&amp;lt;!--The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Затем проведите нагрузочное тестирование, попробуйте выйти за пределы допустимых параметров, указанных вами при создании объектов и фич для проекта. Как правило на этом этапе всплывают все баги и уязвимости в написанном и вы можете отловить их и пофиксить\оставить для рабочей версии проекта.&lt;br /&gt;
&amp;lt;!--After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;quot;Неуловимые&amp;quot; баги====&lt;br /&gt;
&lt;br /&gt;
Существует два типа багов: Краш-баги которые останавливают процесс целиком (proc crashers) и мелкие баги(silent errors), которые ломают отдельные фичи. : Пример Краш-бага - обращение к переменной объекта, отсутствие ответа от объекта, придание переменной по умолчанию равной нулю, что приводит к завершению оператора.&lt;br /&gt;
Когда крашится процедура, как правило сохраняются логи ошибки в world.log . При запуске созданного вами проекта в клиенте Dream Seeker, эта информация будет показана в отдельном окошке. При запуске проекта на сервере Dream Daemon - логи сохраняются в выводе серверной информации, либо в отдельном файле.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Самое главное - найти в логах название процедуры, которая вызвала падение выполнения кода, а также значение переменных src и usr на момент выполнения процедуры. Процедуры могут быть показаны цепочкой вызовов - будут показаны обращающиеся к этой и вызванной этой процедурой процедуры.  &lt;br /&gt;
&amp;lt;!--The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
Также вы можете воспользоваться макросом DEBUG, описанным выше для отлова багов и точным вычислением их месторасположения в коде исполняемого файла.&lt;br /&gt;
&amp;lt;!--If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
Существует команда, способная показать вам какое именно значение переменной привело к падению кода. Вот она:&lt;br /&gt;
&amp;lt;!--One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Отладка кода проводится как при отдельных случаях падения кода(и тогда удобнее пользоваться примерами приведёнными выше), так и по всем исполняемым строкам и файлам при финальной диагностике. В последнем случае вы можете пользоваться следующими макросами:&lt;br /&gt;
&amp;lt;!--Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
Вывод информации на отладку будет осуществляться, но он будет игнорироваться до тех пор, пока вы не используете макрос #DEBUG.&lt;br /&gt;
&amp;lt;!--You can then send output to debug and it will be ignored when not in DEBUG mode.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть полезный приём при поиске багов - вынести код в комментарии. Код, вынесенный в комментарий перестаёт восприниматься компилятором как исполняемые команды, зато виден разработчику. Это полезно для выделения кусков кода, ответственных за совершение ошибок при исполнении, и временном устранении их, вплоть до отладки проблемного места.&lt;br /&gt;
&amp;lt;!--Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.--&amp;gt;&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19612</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19612"/>
		<updated>2015-11-19T20:42:23Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Ну-ка покажи мне на картинке Barr.PNG блендер и соковыжималку, или иди нахуй. По-пизди ещё про билды, которые нигде не стоят, да.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара. &lt;br /&gt;
&lt;br /&gt;
== Стандартные кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Универсальная машина, способная выжимать, крошить и молоть.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перемалывать туши в мясо.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
С помощью вашей скалки можно раскатать хлебное или сдобное тесто в лепёшку, которую затем можно разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
=== Нестандартные кухонные принадлежности ===&lt;br /&gt;
&lt;br /&gt;
В ходе своей работе вы можете столкнуться как со знакомым так и с малознакомым оборудованием. Как правило пользоваться ими довольно просто и они весьма разнообразят ваше меню.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Blender e.png]] '''Старый блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Время от времени вы можете обратиться к ботаникам за снабжениями в виде ящиков с пшеницей, томатами и другими выращенными культурами. Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Наконец, все можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей.&lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам клетку с обезьянками, цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19611</id>
		<title>Обсуждение:Guide to Posters</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5:Guide_to_Posters&amp;diff=19611"/>
		<updated>2015-11-19T20:34:58Z</updated>

		<summary type="html">&lt;p&gt;IXVI: имхо&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*Что? Гайд к постерам, который переводит их текст? МОжет, еще запилим гайд к, ну я не знаю, НАДПИСИ У МОСТИКА? Который описывает, что на ней можно писать про ХоСа, как писать, как снимать там плитку и как она переводится? А еще переводим &amp;quot;репер&amp;quot; как &amp;quot;насильник&amp;quot;, еще несколько фактических ошибок. Короче - абсолютно бессмысленная статья, созданная ради ОЧКОВ ВИКИ))))), заремувьте ее, пожалуйста. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 17:17, 18 ноября 2015 (MSK)&lt;br /&gt;
**Увидел ангельский текст в статье - перевёл. На счёт насильника ошибся, бывает (для такого и создана волшебная кнопка &amp;quot;править&amp;quot;). А в общем да, статья достаточно бесполезна, я тоже вот смысла в ней не вижу. - [[Участник: Feomatar|Feomatar]] 16:36, 18 ноября 2015 (MSK)&lt;br /&gt;
**Я о том, что единственная нагрузка в этой статье - перевод ТЕКСТА ИЗ ИГРЫ. То есть это прям ну совсем полный идиотизьм. А править статью, которая не нужна - глупо. [[Участник:UcnaHez|UcnaHez]] ([[Обсуждение участника:UcnaHez|обсуждение]]) 21:20, 18 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Ублюдки блядь, вы что делаете нахуй? Что это за параша? Гайд по ПЛАКАТАМ? Вы что, ебанутые, блядь? Пиздеееец. Просто пиздец. При прошлом конкурсе такой хуиты было мало. Я ебал просто. Идите нахуй. [[Участник:Alexix|Alexix]] ([[Обсуждение участника:Alexix|обсуждение]]) 01:43, 19 ноября 2015 (MSK)&lt;br /&gt;
&lt;br /&gt;
*Всем нравится, идите нахуй. [[Участник:IXVI|IXVI]] ([[Обсуждение участника:IXVI|обсуждение]]) 00:34, 20 ноября 2015 (MSK) Идите нахуй дважды, блять.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19606</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19606"/>
		<updated>2015-11-19T16:55:13Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Кухонные принадлежности */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара. &lt;br /&gt;
&lt;br /&gt;
== Кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Машина для нарезки. В ней можно провернуть мясо, приготовить картофельные и морковные палочки, прокрутить соевые бобы. Используется только опытными кулинарами.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [[Файл:Blender e.png]] '''Блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перекручивать туши на мясо. Делает это просто и со вкусом.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
Скалкой можно раскатать хлебное или сдобное тесто в лепёшку, которую затем разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Время от времени вы можете обратиться к ботаникам за снабжениями в виде ящиков с пшеницей, томатами и другими выращенными культурами. Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Наконец, все можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей.&lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам клетку с обезьянками, цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19605</id>
		<title>Chef</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Chef&amp;diff=19605"/>
		<updated>2015-11-19T16:50:17Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Переделываю статейку под общий стиль&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;100%&amp;quot; style=&amp;quot;background-color:#DCDCDC;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#A9A9A9;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobchef.png]]&amp;lt;br&amp;gt;[[Chef|Шеф-повар]]&lt;br /&gt;
|'''Доступ:''' Kitchen, Morgue.&lt;br /&gt;
'''Подчинение:''' [[Head of Personnel|Глава персонала]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Готовить еду для экипажа и держать всех сытыми.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to food and drinks]]&lt;br /&gt;
&lt;br /&gt;
!Легко&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''Не существует ни единого факта, ни единого аргумента в оправдание мясоедения, которые нельзя было бы употребить и в оправдание каннибализма.''&amp;lt;br/&amp;gt;'''''Герберт Шелдон, &amp;quot;Книга здоровой пищи&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Barr.PNG|300px|right|thumb|Кухня, столовая и подсобка. Здесь находится все, что вам только нужно.]]&lt;br /&gt;
{{toc right}}&lt;br /&gt;
&lt;br /&gt;
'''Ваша работа — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=S5qUMK-TzOg готовить еду]''', кормить проголодавшихся и, что самое главное — ''творить'', ведь вы — [http://www.youtube.com/watch?feature=player_embedded&amp;amp;v=XUJydOCyReA кулинарный мастер], единственный и неповторимый в своем деле!&lt;br /&gt;
&lt;br /&gt;
== Вступление ==&lt;br /&gt;
&lt;br /&gt;
Профессия повара возможно считается не самой сложной и почётной среди остальных должностей экипажа космического корабля, он она по-своему привлекательна. Вас могут звать по-разному: повар, шеф-повар, кок, кухарка - в зависимости от настроения ваших клиентов - голодных работников всех отделов станции. У вас есть своё рабочее место - хорошо укомплектованная кухня горячего и холодного цеха, подсобное помещение для хранения припасов, а также стойка для раздачи готовых блюд. Скорее всего вас будут оценивать по вашим умениям, так что хорошо бы для начала узнать хотя бы рецепт яичницы, а с течением времени у вас будет всё больше разнообразных ингредиентов - и всё больше разнообразных блюд. &amp;lt;br&amp;gt;&lt;br /&gt;
И помните - все любят повара. &lt;br /&gt;
&lt;br /&gt;
== Кухонные принадлежности ==&lt;br /&gt;
&lt;br /&gt;
У повара есть несколько инструментов, которые встречаются практически на любой корабельной кухне. Это:&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Mw.png‎]] '''Микроволновая печь''' (Microwave)&lt;br /&gt;
&lt;br /&gt;
Микроволновая печь весьма капризная штука. Если вы не знаете рецепта, не экспериментируйте! Вы можете вместо еды получить несъедобную массу, также вы можете испачкать (а в худшем случае даже сломать) вашу микроволновку, и она будет непригодна для использования. Исправить ситуацию помогут флакон спейсклинера или инженер с набором инструментов.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Processor.png ‎]] '''Кухонный комбайн''' (Food Processor)&lt;br /&gt;
&lt;br /&gt;
Универсальная машина, способная выжимать, крошить и молоть.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [[Файл:Blender e.png]] '''Блендер''' (Blender)&lt;br /&gt;
&lt;br /&gt;
Блендер смешивает любую еду. Если не будете придерживаться строгого рецепта, то получите порцию ''питательных веществ'' (Nutriment). Это универсальный ингредиент, который содержится в любой пище. Это именно то, что насыщает вас, когда вы едите. Смешать кучу пончиков, бургеров и прочего для получения концентрированных питательных веществ может оказаться весьма полезным.&lt;br /&gt;
Вы можете смешать всё, что выращено в гидропонике, химические вещества, и большинство медикаментов, еды и жидкостей.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Juicer2.png]] '''Блендер''' (All-In-One Grinder)&lt;br /&gt;
&lt;br /&gt;
[http://www.youtube.com/embed/l0sbiSlyKtw Универсальный блендер] способен измельчать готовые блюда и растения, и выжимать сок из ягод и овощей. Это полезное и легкое во всех отношениях изобретение светлых умов из NanoTrasen ваш главный помощник в изучении кулинарного искусства. Количество получаемых веществ, или сока напрямую зависит он потенциала растений, так что, если хотите больше - добивайтесь от ботаника высококачественной продукции.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grinder.png]] '''Мясорубка''' (Gibber)&lt;br /&gt;
&lt;br /&gt;
Мясорубка позволяет перемалывать туши в мясо.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [[Файл:Mixer.gif]] '''Миксер''' (Candy Machine)&lt;br /&gt;
&lt;br /&gt;
Cделает из ваших продуктов конфетку. В прямом смысле.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Fryer.gif]] '''Фритюр''' (Deep Fryer)&lt;br /&gt;
&lt;br /&gt;
Прожаривает картошку и конечности Пун-пуна до румяной корочки.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Oven.gif]] '''Печь''' (Oven)&lt;br /&gt;
&lt;br /&gt;
Печенье из мяса? Пожалуйста! Пирог из спагетти? Да не вопрос!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Cereal.gif]] '''Машина для создания хлопьев''' (Сereal maker)&lt;br /&gt;
&lt;br /&gt;
Когда-нибудь мечтали отведать хлопья из мяса пришельцев? Смелей на кухню!&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Grill.gif]] '''Авто-гриль''' (Grille)&lt;br /&gt;
&lt;br /&gt;
Прожаренная курочка или зад ассистента за считанные секунды.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Icecream.png]] '''Раздатчик мороженого''' (Icecream)&lt;br /&gt;
&lt;br /&gt;
Окунитесь в детство вместе с алкогольным мороженным. &lt;br /&gt;
&lt;br /&gt;
* [[Файл:mixer0.png]] '''CondiMaster Neo'''&lt;br /&gt;
&lt;br /&gt;
Позволяет исследовать и фильтровать то, что вы получили с помощью блендера. Также, позволяет упаковывать приправы в специальные баночки.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* [[Файл:SmartFridge.png]] '''SmartFridge'''&lt;br /&gt;
&lt;br /&gt;
С помощью этого отличного холодильника вы сможете хранить урожай, выращенный ботаниками. Ваши овощи и фрукты всегда будут свежими, а блюда вкусными. Очень удобен в использовании, есть возможность загрузки всего содержимого сумки для растений и выдачи по х1, х5, х10 единиц одного наименования.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Kitchen knife.png]] '''Кухонный нож''' (Kitchen Knife)&lt;br /&gt;
&lt;br /&gt;
Кухонным ножом можно нарезать продукты, например, сыр, мясо, хлеб, торты или пиццу. Чтобы резать продукты обязательно нужен стол или поднос. Резать их на полу, или в руках — неудобно.&lt;br /&gt;
&lt;br /&gt;
* [[Файл:Rolling_pin.png]] '''Скалка''' (Rolling Pin)&lt;br /&gt;
&lt;br /&gt;
С помощью вашей скалки можно раскатать хлебное или сдобное тесто в лепёшку, которую затем можно разрезать ножом.&lt;br /&gt;
&lt;br /&gt;
== Снабжение ==&lt;br /&gt;
&lt;br /&gt;
У вас есть начальный запас ингредиентов на кухне, но он не неиссякаемый и когда-то закончится. Так что вам стоит заранее подумать об этом и начать договариваться о поставках.&lt;br /&gt;
&lt;br /&gt;
=== Гидропоника ===&lt;br /&gt;
&lt;br /&gt;
Время от времени вы можете обратиться к ботаникам за снабжениями в виде ящиков с пшеницей, томатами и другими выращенными культурами. Некоторые растения могут быть использованы как особые ингредиенты в некоторых рецептах или из них можно сделать соус. Наконец, все можно переработать в питательные вещества при помощи блендера. Не забудьте поблагодарить ботаников, если вы не хотите остаться без муки и овощей.&lt;br /&gt;
&lt;br /&gt;
=== Животные ===&lt;br /&gt;
&lt;br /&gt;
Вы можете попросить [[Quartermaster|завхоза]] прислать вам клетку с обезьянками, цыплятами или коровой. Обезьянок можно разделывать на мясо, предварительно подвесив их на мясной крюк. Цыплята могут отложить яйцо. Корову можно подоить, если у вас есть ведро. Кроме того и цыплят и коров можно пустить на мясо в мясорубку.&lt;br /&gt;
&lt;br /&gt;
==Подсказки==&lt;br /&gt;
* Кровь и Synthflesh вступают в реакцию и создают мясо. Химия- наука вкусная.&lt;br /&gt;
* Кухонные ножи и тесаки можно взять в раздатчики на кухне, они с легкостью помещаются в карман.&lt;br /&gt;
* Не распарывайте пун-пуна на мясо при помощи пик! С помощью нужных [[Guide_to_Surgery/Bay12|инструментов]] вырежьте мозг и сделайте из него блюдо! И только потом пустите его на мясо.&lt;br /&gt;
* Яйца можно раскрасить цветными мелками&lt;br /&gt;
* Ты можешь сделать бургер цветным, добавив нужный мелок в ингредиенты.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;br /&gt;
[[Category:/vg/station13]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19523</id>
		<title>Captain</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19523"/>
		<updated>2015-11-15T12:54:09Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Глава службы безопасности */ станцию, чтобы убедиться, что&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; |Описание&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobcap.png]]&amp;lt;br&amp;gt;[[Captain|Капитан]]&lt;br /&gt;
|'''Доступ:''' Полный доступ&lt;br /&gt;
'''Подчинение:''' ЦентКомм&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Организация и управление экипажем Космической Станции 13.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Space Law]], [[Standard Operating Procedure]], [[Chain of Command]], [[Guide to Trials]]&lt;br /&gt;
!Очень сложно&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right; margin-right:20%&amp;quot;&amp;gt;''Корабль держится в том числе на преданности одному человеку. Её ничем не заменишь... и его тоже.''&amp;lt;br/&amp;gt;'''''&amp;quot;Звездный Путь&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Captain's Quarters.png|280px|right|thumb|Капитанская каюта.]]&lt;br /&gt;
'''Капитан''', назначенный корпорацией NanoTrasen, является администратором и координатором №1, связующим звеном между главами, и именно от его своевременных решений и приказов будут зависеть десятки жизней членов экипажа. &lt;br /&gt;
&lt;br /&gt;
Очевидным является то, что в данном случае капитан — не владелец станции и не военный, не пьяный пират и не супергерой. '''Он''' — всего лишь один из служащих Корпорации, с чуть большим окладом, чем у его подчинённых, но с куда большей ответственностью.&lt;br /&gt;
&lt;br /&gt;
== Galactic Commander ==&lt;br /&gt;
[[Файл:CapitanByNorgot.png|right]]&lt;br /&gt;
Итак, сынок, тебе надоело нытье вечно недовольной жены по поводу зарплаты, и вот ты докарабкался, обламывая ногти, до звания капитана. Взгляни на то, что написано выше. Это официальное руководство к действию. Оно в своем роде идеально — если ты, конечно, нанялся работать на идеальную станцию, хе. Можешь рвануть с места в карьер, вооруженный им и верой в светлое будущее. Однако, если у тебя есть еще время и терпение, позволь мне дать тебе несколько советов насчет управления.&lt;br /&gt;
:'''1.''' Экипаж — это свора детей, которых кто-то пустил играть во взрослые игрушки. Детишки будут выкалывать друг другу глаза, бить по голове баллонами, сжигать в плазме, обкалывать токсинами, выливать кислоту на лица. Космос странно действует на психику, что тут можно сказать. Это непросто, но ты не должен делать с ними все вышеперечисленное в ответ. &lt;br /&gt;
*''Тебе нужно их чем-нибудь занять, это резко снизит градус бессмысленного насилия.''&lt;br /&gt;
:'''2.''' Если тебе повезет, то хотя бы несколько глав будут знать, что делать. Однако обычно люди на руководящих постах занимаются раскрытием своего внутреннего [[Clown|я]], бессмысленно носятся по станции либо с головой окунаются в общий водоворот насилия. Будет непросто, но и их ты тоже не можешь просто убить. Разжалуй и назначь на должность кого-нибудь более достойного. &lt;br /&gt;
*''Всегда следи за тем, как главы справляются со своими обязанностями. Не бойся выгонять их к чертовой матери. Не забывай назначать новых.''&lt;br /&gt;
:'''3.''' Многие люди не будут слушать твои приказы, какими бы разумными они не были. Так вот, убивать их тоже нельзя. Еще не разочаровался в работе, а, приятель? Тогда слушай дальше. Санкции за невыполнение приказа, не приведшее к катастрофическим последствиям, не заключаются в избиении и помещении в камеру на 10 минут. Влепи словесный выговор. Поговори с главой отдела. Разжалуй в ассистенты. &lt;br /&gt;
*''Еще раз, никаких тюремных сроков за неподчинение приказам, никаких пыток с привязыванием к стулу, никаких а-давайте-засунем-его-в-гиббер.''&lt;br /&gt;
:'''4.''' Итак, ты делал все правильно, а станция все равно погрузилась в хаос. Половина ее взорвана веселым химиком, другая объявила себя независимым рабовладельческим государством, ловит в технических тоннелях ассистентов и продает их с аукциона. С чем-то ты не сможешь совладать — это нормально. Делай что можешь. Отдавай приказы и полномочия верным людям, договаривайся, умоляй, подкупай — все, что нужно, лишь бы прекратить хаос и навести порядок. &lt;br /&gt;
*''Разбирайся с проблемами по очереди, не пытайся справиться со всем и сразу. Будь умнее, хитрее, дипломатичнее и безжалостнее, чем все твои враги вместе взятые.''&lt;br /&gt;
:'''5.''' '''Запомни раз и навсегда! Ты отвечаешь за жизнь каждого из этих тупых ублюдков, которых сослали служить под твоим командованием. Никогда не забывай об этом.'''&lt;br /&gt;
&lt;br /&gt;
== Основные советы ==&lt;br /&gt;
* Не потеряйте доверие экипажа: не отдавайте нелепых приказов и не нарушайте [[Space Law|закон]], иначе последствия не заставят себя ждать — от неподчинения до полномасштабной революции.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав, даже если он вам не нужен.&lt;br /&gt;
* Помните о цепи командования: отдавайте приказы главам, а не их подчинённым.&lt;br /&gt;
* Если главы нет - назначьте. Если глава некомпетентен - замените его.&lt;br /&gt;
* Если экипаж считает, что вы некомпетентны, и у него есть все основания так считать, сдайте полномочия и найдите себе замену.&lt;br /&gt;
* '''Бездействие в чрезвычайной ситуации — главный признак некомпетентности капитана.''' Помните, что чаще всего лишь с помощью правильных приказов можно спасти станцию от гибели.&lt;br /&gt;
&lt;br /&gt;
=== Весь экипаж ===&lt;br /&gt;
* Отдать приказ включить датчики жизнедеятельности и местоположения. Ну или просто прикажите перевести костюмы в третий режим - они поймут. Данные с датчиков отправляются на Crew Monitoring Computer (есть на мостике, в кабинете главного врача и в приемной медицинского отсека).&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Personnel|Глава персонала]] ===&lt;br /&gt;
* Если '''Глава персонала''' где-то шляется и его нет на рабочем месте, напомните ему о главной обязанности — сидеть в офисе и заниматься перераспределением кадров.&lt;br /&gt;
* Прикажите '''главе персонала''' брать отпечатки у новоприбывших членов экипажа и заводить досье в терминале Security Records.&lt;br /&gt;
* Порекомендуйте назначить всех свободных ассистентов на полезную должность.&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Security|Глава службы безопасности]] ===&lt;br /&gt;
* Не помешает лично проинспектировать бриг и тюремную станцию, чтобы убедиться что '''Глава службы безопасности''' не превратил их в лагерь смерти, а у заключённых есть еда и нет опасных предметов.&lt;br /&gt;
* Прикажите распределить охранников по станции, если глава службы безопасности ещё не сделал этого. Попросите главу персонала расширить допуск согласно району патрулирования.&lt;br /&gt;
&lt;br /&gt;
=== [[Research_Director|Директор исследований]], [[Chief_Medical_Officer|главный врач]], [[Chief_Engineer|главный инженер]] ===&lt;br /&gt;
* Как правило, особых указаний для этих глав не требуется. Просто напомните, что они отвечают за все действия своих подчинённых.&lt;br /&gt;
* Но вы можете проинспектировать их отделы спустя некоторое время, дабы проверить функциональность отделов и выполнение отданных вами поручений&lt;br /&gt;
&lt;br /&gt;
=== [[AI|ИИ]] ===&lt;br /&gt;
'''Прикажите ИИ:'''&lt;br /&gt;
* Докладывать обо всех нарушениях закона на станции, сообщать имена жертв и подозреваемых при наличии таковых.&lt;br /&gt;
* Докладывать обо всех несчастных случаях на станции.&lt;br /&gt;
* Запереть все неиспользуемые шлюзы, сжигатель (Igniter), аплоад, хранилище плат и крематорий до востребования.&lt;br /&gt;
&lt;br /&gt;
== I should go ==&lt;br /&gt;
 Непредвиденные обстоятельства? Чрезвычайная ситуация? Не знаете, что делать?&lt;br /&gt;
#'''Не паникуйте'''.&lt;br /&gt;
# Соберите как можно больше данных о происходящем.&lt;br /&gt;
# Узнайте о мнении каждого из глав. В конце концов, они — специалисты в своих областях.&lt;br /&gt;
# Если ситуация того требует, объявите общий сбор и устройте совет.&lt;br /&gt;
# Примите решение, отдайте соответствующие приказы.&lt;br /&gt;
# Если станции нанесён непоправимый ущерб:&lt;br /&gt;
#*  Объявите эвакуацию.&lt;br /&gt;
# Если станции нанесён поправимый ущерб:&lt;br /&gt;
#*  Скоординируйте действия экипажа с целью его исправлении.&lt;br /&gt;
#*  Устройте суд над виновными, если таковые есть.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19522</id>
		<title>Captain</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19522"/>
		<updated>2015-11-15T12:53:05Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Весь экипаж */ Ну или просто 'прикажте'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; |Описание&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobcap.png]]&amp;lt;br&amp;gt;[[Captain|Капитан]]&lt;br /&gt;
|'''Доступ:''' Полный доступ&lt;br /&gt;
'''Подчинение:''' ЦентКомм&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Организация и управление экипажем Космической Станции 13.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Space Law]], [[Standard Operating Procedure]], [[Chain of Command]], [[Guide to Trials]]&lt;br /&gt;
!Очень сложно&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right; margin-right:20%&amp;quot;&amp;gt;''Корабль держится в том числе на преданности одному человеку. Её ничем не заменишь... и его тоже.''&amp;lt;br/&amp;gt;'''''&amp;quot;Звездный Путь&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Captain's Quarters.png|280px|right|thumb|Капитанская каюта.]]&lt;br /&gt;
'''Капитан''', назначенный корпорацией NanoTrasen, является администратором и координатором №1, связующим звеном между главами, и именно от его своевременных решений и приказов будут зависеть десятки жизней членов экипажа. &lt;br /&gt;
&lt;br /&gt;
Очевидным является то, что в данном случае капитан — не владелец станции и не военный, не пьяный пират и не супергерой. '''Он''' — всего лишь один из служащих Корпорации, с чуть большим окладом, чем у его подчинённых, но с куда большей ответственностью.&lt;br /&gt;
&lt;br /&gt;
== Galactic Commander ==&lt;br /&gt;
[[Файл:CapitanByNorgot.png|right]]&lt;br /&gt;
Итак, сынок, тебе надоело нытье вечно недовольной жены по поводу зарплаты, и вот ты докарабкался, обламывая ногти, до звания капитана. Взгляни на то, что написано выше. Это официальное руководство к действию. Оно в своем роде идеально — если ты, конечно, нанялся работать на идеальную станцию, хе. Можешь рвануть с места в карьер, вооруженный им и верой в светлое будущее. Однако, если у тебя есть еще время и терпение, позволь мне дать тебе несколько советов насчет управления.&lt;br /&gt;
:'''1.''' Экипаж — это свора детей, которых кто-то пустил играть во взрослые игрушки. Детишки будут выкалывать друг другу глаза, бить по голове баллонами, сжигать в плазме, обкалывать токсинами, выливать кислоту на лица. Космос странно действует на психику, что тут можно сказать. Это непросто, но ты не должен делать с ними все вышеперечисленное в ответ. &lt;br /&gt;
*''Тебе нужно их чем-нибудь занять, это резко снизит градус бессмысленного насилия.''&lt;br /&gt;
:'''2.''' Если тебе повезет, то хотя бы несколько глав будут знать, что делать. Однако обычно люди на руководящих постах занимаются раскрытием своего внутреннего [[Clown|я]], бессмысленно носятся по станции либо с головой окунаются в общий водоворот насилия. Будет непросто, но и их ты тоже не можешь просто убить. Разжалуй и назначь на должность кого-нибудь более достойного. &lt;br /&gt;
*''Всегда следи за тем, как главы справляются со своими обязанностями. Не бойся выгонять их к чертовой матери. Не забывай назначать новых.''&lt;br /&gt;
:'''3.''' Многие люди не будут слушать твои приказы, какими бы разумными они не были. Так вот, убивать их тоже нельзя. Еще не разочаровался в работе, а, приятель? Тогда слушай дальше. Санкции за невыполнение приказа, не приведшее к катастрофическим последствиям, не заключаются в избиении и помещении в камеру на 10 минут. Влепи словесный выговор. Поговори с главой отдела. Разжалуй в ассистенты. &lt;br /&gt;
*''Еще раз, никаких тюремных сроков за неподчинение приказам, никаких пыток с привязыванием к стулу, никаких а-давайте-засунем-его-в-гиббер.''&lt;br /&gt;
:'''4.''' Итак, ты делал все правильно, а станция все равно погрузилась в хаос. Половина ее взорвана веселым химиком, другая объявила себя независимым рабовладельческим государством, ловит в технических тоннелях ассистентов и продает их с аукциона. С чем-то ты не сможешь совладать — это нормально. Делай что можешь. Отдавай приказы и полномочия верным людям, договаривайся, умоляй, подкупай — все, что нужно, лишь бы прекратить хаос и навести порядок. &lt;br /&gt;
*''Разбирайся с проблемами по очереди, не пытайся справиться со всем и сразу. Будь умнее, хитрее, дипломатичнее и безжалостнее, чем все твои враги вместе взятые.''&lt;br /&gt;
:'''5.''' '''Запомни раз и навсегда! Ты отвечаешь за жизнь каждого из этих тупых ублюдков, которых сослали служить под твоим командованием. Никогда не забывай об этом.'''&lt;br /&gt;
&lt;br /&gt;
== Основные советы ==&lt;br /&gt;
* Не потеряйте доверие экипажа: не отдавайте нелепых приказов и не нарушайте [[Space Law|закон]], иначе последствия не заставят себя ждать — от неподчинения до полномасштабной революции.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав, даже если он вам не нужен.&lt;br /&gt;
* Помните о цепи командования: отдавайте приказы главам, а не их подчинённым.&lt;br /&gt;
* Если главы нет - назначьте. Если глава некомпетентен - замените его.&lt;br /&gt;
* Если экипаж считает, что вы некомпетентны, и у него есть все основания так считать, сдайте полномочия и найдите себе замену.&lt;br /&gt;
* '''Бездействие в чрезвычайной ситуации — главный признак некомпетентности капитана.''' Помните, что чаще всего лишь с помощью правильных приказов можно спасти станцию от гибели.&lt;br /&gt;
&lt;br /&gt;
=== Весь экипаж ===&lt;br /&gt;
* Отдать приказ включить датчики жизнедеятельности и местоположения. Ну или просто прикажите перевести костюмы в третий режим - они поймут. Данные с датчиков отправляются на Crew Monitoring Computer (есть на мостике, в кабинете главного врача и в приемной медицинского отсека).&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Personnel|Глава персонала]] ===&lt;br /&gt;
* Если '''Глава персонала''' где-то шляется и его нет на рабочем месте, напомните ему о главной обязанности — сидеть в офисе и заниматься перераспределением кадров.&lt;br /&gt;
* Прикажите '''главе персонала''' брать отпечатки у новоприбывших членов экипажа и заводить досье в терминале Security Records.&lt;br /&gt;
* Порекомендуйте назначить всех свободных ассистентов на полезную должность.&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Security|Глава службы безопасности]] ===&lt;br /&gt;
* Не помешает лично проинспектировать бриг и тюремную станцию, чтобы убедиться, что '''Глава службы безопасности''' не превратил их в лагерь смерти, а у заключённых есть еда и нет опасных предметов.&lt;br /&gt;
* Прикажите распределить охранников по станции, если глава службы безопасности ещё не сделал этого. Попросите главу персонала расширить допуск согласно району патрулирования.&lt;br /&gt;
&lt;br /&gt;
=== [[Research_Director|Директор исследований]], [[Chief_Medical_Officer|главный врач]], [[Chief_Engineer|главный инженер]] ===&lt;br /&gt;
* Как правило, особых указаний для этих глав не требуется. Просто напомните, что они отвечают за все действия своих подчинённых.&lt;br /&gt;
* Но вы можете проинспектировать их отделы спустя некоторое время, дабы проверить функциональность отделов и выполнение отданных вами поручений&lt;br /&gt;
&lt;br /&gt;
=== [[AI|ИИ]] ===&lt;br /&gt;
'''Прикажите ИИ:'''&lt;br /&gt;
* Докладывать обо всех нарушениях закона на станции, сообщать имена жертв и подозреваемых при наличии таковых.&lt;br /&gt;
* Докладывать обо всех несчастных случаях на станции.&lt;br /&gt;
* Запереть все неиспользуемые шлюзы, сжигатель (Igniter), аплоад, хранилище плат и крематорий до востребования.&lt;br /&gt;
&lt;br /&gt;
== I should go ==&lt;br /&gt;
 Непредвиденные обстоятельства? Чрезвычайная ситуация? Не знаете, что делать?&lt;br /&gt;
#'''Не паникуйте'''.&lt;br /&gt;
# Соберите как можно больше данных о происходящем.&lt;br /&gt;
# Узнайте о мнении каждого из глав. В конце концов, они — специалисты в своих областях.&lt;br /&gt;
# Если ситуация того требует, объявите общий сбор и устройте совет.&lt;br /&gt;
# Примите решение, отдайте соответствующие приказы.&lt;br /&gt;
# Если станции нанесён непоправимый ущерб:&lt;br /&gt;
#*  Объявите эвакуацию.&lt;br /&gt;
# Если станции нанесён поправимый ущерб:&lt;br /&gt;
#*  Скоординируйте действия экипажа с целью его исправлении.&lt;br /&gt;
#*  Устройте суд над виновными, если таковые есть.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19521</id>
		<title>Captain</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Captain&amp;diff=19521"/>
		<updated>2015-11-15T12:52:10Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Капитан, 'принадлежащей корпорации'; какими бы разумными они 'ни' были; ловит в 'тех.' тоннелях; Если главы нет',' назначьте;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#EEEEFF;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; |Описание&lt;br /&gt;
!style=&amp;quot;background-color:lightblue;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Jobcap.png]]&amp;lt;br&amp;gt;[[Captain|Капитан]]&lt;br /&gt;
|'''Доступ:''' Полный доступ&lt;br /&gt;
'''Подчинение:''' ЦентКомм&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Организация и управление экипажем Космической Станции 13.&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Space Law]], [[Standard Operating Procedure]], [[Chain of Command]], [[Guide to Trials]]&lt;br /&gt;
!Очень сложно&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right; margin-right:20%&amp;quot;&amp;gt;''Корабль держится в том числе на преданности одному человеку. Её ничем не заменишь... и его тоже.''&amp;lt;br/&amp;gt;'''''&amp;quot;Звездный Путь&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Captain's Quarters.png|280px|right|thumb|Капитанская каюта.]]&lt;br /&gt;
'''Капитан''', назначенный корпорацией NanoTrasen, является администратором и координатором №1, связующим звеном между главами, и именно от его своевременных решений и приказов будут зависеть десятки жизней членов экипажа. &lt;br /&gt;
&lt;br /&gt;
Очевидным является то, что в данном случае капитан — не владелец станции и не военный, не пьяный пират и не супергерой. '''Он''' — всего лишь один из служащих Корпорации, с чуть большим окладом, чем у его подчинённых, но с куда большей ответственностью.&lt;br /&gt;
&lt;br /&gt;
== Galactic Commander ==&lt;br /&gt;
[[Файл:CapitanByNorgot.png|right]]&lt;br /&gt;
Итак, сынок, тебе надоело нытье вечно недовольной жены по поводу зарплаты, и вот ты докарабкался, обламывая ногти, до звания капитана. Взгляни на то, что написано выше. Это официальное руководство к действию. Оно в своем роде идеально — если ты, конечно, нанялся работать на идеальную станцию, хе. Можешь рвануть с места в карьер, вооруженный им и верой в светлое будущее. Однако, если у тебя есть еще время и терпение, позволь мне дать тебе несколько советов насчет управления.&lt;br /&gt;
:'''1.''' Экипаж — это свора детей, которых кто-то пустил играть во взрослые игрушки. Детишки будут выкалывать друг другу глаза, бить по голове баллонами, сжигать в плазме, обкалывать токсинами, выливать кислоту на лица. Космос странно действует на психику, что тут можно сказать. Это непросто, но ты не должен делать с ними все вышеперечисленное в ответ. &lt;br /&gt;
*''Тебе нужно их чем-нибудь занять, это резко снизит градус бессмысленного насилия.''&lt;br /&gt;
:'''2.''' Если тебе повезет, то хотя бы несколько глав будут знать, что делать. Однако обычно люди на руководящих постах занимаются раскрытием своего внутреннего [[Clown|я]], бессмысленно носятся по станции либо с головой окунаются в общий водоворот насилия. Будет непросто, но и их ты тоже не можешь просто убить. Разжалуй и назначь на должность кого-нибудь более достойного. &lt;br /&gt;
*''Всегда следи за тем, как главы справляются со своими обязанностями. Не бойся выгонять их к чертовой матери. Не забывай назначать новых.''&lt;br /&gt;
:'''3.''' Многие люди не будут слушать твои приказы, какими бы разумными они не были. Так вот, убивать их тоже нельзя. Еще не разочаровался в работе, а, приятель? Тогда слушай дальше. Санкции за невыполнение приказа, не приведшее к катастрофическим последствиям, не заключаются в избиении и помещении в камеру на 10 минут. Влепи словесный выговор. Поговори с главой отдела. Разжалуй в ассистенты. &lt;br /&gt;
*''Еще раз, никаких тюремных сроков за неподчинение приказам, никаких пыток с привязыванием к стулу, никаких а-давайте-засунем-его-в-гиббер.''&lt;br /&gt;
:'''4.''' Итак, ты делал все правильно, а станция все равно погрузилась в хаос. Половина ее взорвана веселым химиком, другая объявила себя независимым рабовладельческим государством, ловит в технических тоннелях ассистентов и продает их с аукциона. С чем-то ты не сможешь совладать — это нормально. Делай что можешь. Отдавай приказы и полномочия верным людям, договаривайся, умоляй, подкупай — все, что нужно, лишь бы прекратить хаос и навести порядок. &lt;br /&gt;
*''Разбирайся с проблемами по очереди, не пытайся справиться со всем и сразу. Будь умнее, хитрее, дипломатичнее и безжалостнее, чем все твои враги вместе взятые.''&lt;br /&gt;
:'''5.''' '''Запомни раз и навсегда! Ты отвечаешь за жизнь каждого из этих тупых ублюдков, которых сослали служить под твоим командованием. Никогда не забывай об этом.'''&lt;br /&gt;
&lt;br /&gt;
== Основные советы ==&lt;br /&gt;
* Не потеряйте доверие экипажа: не отдавайте нелепых приказов и не нарушайте [[Space Law|закон]], иначе последствия не заставят себя ждать — от неподчинения до полномасштабной революции.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав.&lt;br /&gt;
* Не стесняйтесь спросить совета у глав, даже если он вам не нужен.&lt;br /&gt;
* Помните о цепи командования: отдавайте приказы главам, а не их подчинённым.&lt;br /&gt;
* Если главы нет - назначьте. Если глава некомпетентен - замените его.&lt;br /&gt;
* Если экипаж считает, что вы некомпетентны, и у него есть все основания так считать, сдайте полномочия и найдите себе замену.&lt;br /&gt;
* '''Бездействие в чрезвычайной ситуации — главный признак некомпетентности капитана.''' Помните, что чаще всего лишь с помощью правильных приказов можно спасти станцию от гибели.&lt;br /&gt;
&lt;br /&gt;
=== Весь экипаж ===&lt;br /&gt;
* Отдать приказ включить датчики жизнедеятельности и местоположения. Ну или просто прикажте перевести костюмы в третий режим, они поймут. Данные с датчиков отправляются на Crew Monitoring Computer (есть на мостике, кабинете главного врача и в приемной медицинского отсека).&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Personnel|Глава персонала]] ===&lt;br /&gt;
* Если '''Глава персонала''' где-то шляется и его нет на рабочем месте, напомните ему о главной обязанности — сидеть в офисе и заниматься перераспределением кадров.&lt;br /&gt;
* Прикажите '''главе персонала''' брать отпечатки у новоприбывших членов экипажа и заводить досье в терминале Security Records.&lt;br /&gt;
* Порекомендуйте назначить всех свободных ассистентов на полезную должность.&lt;br /&gt;
&lt;br /&gt;
=== [[Head_of_Security|Глава службы безопасности]] ===&lt;br /&gt;
* Не помешает лично проинспектировать бриг и тюремную станцию, чтобы убедиться, что '''Глава службы безопасности''' не превратил их в лагерь смерти, а у заключённых есть еда и нет опасных предметов.&lt;br /&gt;
* Прикажите распределить охранников по станции, если глава службы безопасности ещё не сделал этого. Попросите главу персонала расширить допуск согласно району патрулирования.&lt;br /&gt;
&lt;br /&gt;
=== [[Research_Director|Директор исследований]], [[Chief_Medical_Officer|главный врач]], [[Chief_Engineer|главный инженер]] ===&lt;br /&gt;
* Как правило, особых указаний для этих глав не требуется. Просто напомните, что они отвечают за все действия своих подчинённых.&lt;br /&gt;
* Но вы можете проинспектировать их отделы спустя некоторое время, дабы проверить функциональность отделов и выполнение отданных вами поручений&lt;br /&gt;
&lt;br /&gt;
=== [[AI|ИИ]] ===&lt;br /&gt;
'''Прикажите ИИ:'''&lt;br /&gt;
* Докладывать обо всех нарушениях закона на станции, сообщать имена жертв и подозреваемых при наличии таковых.&lt;br /&gt;
* Докладывать обо всех несчастных случаях на станции.&lt;br /&gt;
* Запереть все неиспользуемые шлюзы, сжигатель (Igniter), аплоад, хранилище плат и крематорий до востребования.&lt;br /&gt;
&lt;br /&gt;
== I should go ==&lt;br /&gt;
 Непредвиденные обстоятельства? Чрезвычайная ситуация? Не знаете, что делать?&lt;br /&gt;
#'''Не паникуйте'''.&lt;br /&gt;
# Соберите как можно больше данных о происходящем.&lt;br /&gt;
# Узнайте о мнении каждого из глав. В конце концов, они — специалисты в своих областях.&lt;br /&gt;
# Если ситуация того требует, объявите общий сбор и устройте совет.&lt;br /&gt;
# Примите решение, отдайте соответствующие приказы.&lt;br /&gt;
# Если станции нанесён непоправимый ущерб:&lt;br /&gt;
#*  Объявите эвакуацию.&lt;br /&gt;
# Если станции нанесён поправимый ущерб:&lt;br /&gt;
#*  Скоординируйте действия экипажа с целью его исправлении.&lt;br /&gt;
#*  Устройте суд над виновными, если таковые есть.&lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Baystation12]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Guide_to_Posters&amp;diff=19518</id>
		<title>Guide to Posters</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Guide_to_Posters&amp;diff=19518"/>
		<updated>2015-11-15T11:12:23Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &amp;lt;u&amp;gt; и &amp;lt;s&amp;gt; поменял местами&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;В мире Станции-13 есть отличная вещь для пропаганды тех или иных вещей - постеры [[Файл:Poster.png]] - скатанные в рулон плакаты отличного фотографического качества, с превосходным дизайном и ёмким содержанием. Для их использования возьмите их в руку и щёлкните на стену, куда вы хотите повесить плакат. После этого постер начнёт автоматически разворачиваться на стене, издавая при этом приятный звук печати двухтонного типографского принтера. После размещения вы сможете снять постер со стены для повторного использования, использовав на нём кусачки([[Файл:Wirecutters.png]]), или просто сорвать его, щёлкнув по плакату пустой рукой.&lt;br /&gt;
----&lt;br /&gt;
Постеры бывают двух видов: Разрешённые &amp;lt;u&amp;gt;корпоративные&amp;lt;/u&amp;gt; ([[Файл:Poster_Legit.png]]) и Запрещённые &amp;lt;s&amp;gt;контрабандные&amp;lt;/s&amp;gt; ([[Файл:Poster.png]]). Корпоративные постеры разрешены к размещению по всей территории станции, они имеют синий оттенок в скатанном виде и как правило содержат полезную и предупредительную информацию, или могут быть чудесными картинами для украшения помещений. Контрабандные же постеры агитируют к насилию, революционным настроениям среди станции и свидетельствуют о определённом уровне недовольства [[Assistant|рабочих масс]] станции. Они имеют красный оттенок, и Сотрудники Безопасности будут стараться срывать их со стен, а также искать распространителя чтобы упечь его за решётку.&lt;br /&gt;
----&lt;br /&gt;
==Корпоративные постеры [[Файл:Poster_Legit.png]]==&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; width=&amp;quot;100%&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! style=&amp;quot;width: 5%&amp;quot;| №&lt;br /&gt;
! style=&amp;quot;width: 10%&amp;quot;| Изображение&lt;br /&gt;
! style=&amp;quot;width: 85%&amp;quot;| Слоган&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;1&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit1.png|Here For Your Safety]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster glorifying the station's security force.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;2&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit2.png|Nanotrasen Logo]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster depicting the Nanotrasen logo.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;3&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit3.png|Cleanliness]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster warning of the dangers of poor hygiene.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;4&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit4.png|Help Others]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster encouraging you to help fellow crewmembers.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;5&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit5.png|Build]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster glorifying the engineering team.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;6&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit6.png|Bless This Spess]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster blessing this area.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;7&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit7.png|Science]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster depicting an atom.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;8&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit8.png|Ian]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Arf arf. Yap.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;9&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit9.png|Obey]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| A poster instructing the viewer to obey authority.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;10&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit10.png|Walk]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing the viewer to walk instead of running.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;11&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit11.png|State Laws]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing cyborgs to state their laws.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;12&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit12.png|Love Ian]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Ian is love, Ian is life.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;13&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit13.png|Space Cops]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising the television show Space Cops.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;14&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit14.png|Ue No]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This thing is all in Japanese.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;15&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit15.png|Get Your LEGS]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;LEGS: Leadership, Experience, Genius, Subordination.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;16&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit16.png|Do Not Question]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing the viewer not to ask about things they aren't meant to know.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;17&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit17.png|Work For A Future]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster encouraging you to work for your future.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;18&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit18.png|Soft Cap Pop Art]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster reprint of some cheap pop art.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;19&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit19.png|Internals]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing the viewer to wear internals in the rare environments where there is no oxygen or the air has been rendered toxic.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;20&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit20.png|Eye Protection]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing the viewer to wear eye protection when dealing with chemicals, smoke, or bright lights.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;21&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit21.png|Report]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster instructing the viewer to report suspicious activity to the security force.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;22&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit22.png|Report Crimes]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster encouraging the swift reporting of crime or seditious behavior to station security.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;23&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit23.png|Ion Rifle]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster displaying an Ion Rifle.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;24&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit24.png|Foam Force Ad]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Foam Force, it's Foam or be Foamed!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;25&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit25.png|Cohiba Robusto Ad]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Cohiba Robusto, the classy cigar.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;26&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit26.png|50th Anniversary Vintage Reprint]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A reprint of a poster from 2505, commemorating the 50th Aniversery of Nanoposters Manufacturing, a subsidary of Nanotrasen.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;27&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit27.png|Fruit Bowl]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Simple, yet awe-inspiring.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;28&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit28.png|PDA Ad]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising the latest PDA from Nanotrasen suppliers.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;29&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit29.png|Enlist]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Enlist in the Nanotrasen Deathsquadron reserves today!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;30&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit30.png|Nanomichi Ad]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising Nanomichi brand audio cassettes.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;31&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit31.png|12 Gauge]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster boasting about the superiority of 12 gauge shotgun shells.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;32&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit32.png|High-Class Martini]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;I told you to shake it, no stirring.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;33&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit33.png|The Owl]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;The Owl would do his best to protect the station. Will you?&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;34&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit34.png|No ERP]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster reminds the crew that Eroticism, Rape and Pornography are banned on Nanotrasen stations.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;35&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster_Legit35.png|Carbon Dioxide]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This informational poster teaches the viewer what carbon dioxide is.&amp;quot;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Контрабандные постеры [[Файл:Poster.png]]==&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; width=&amp;quot;100%&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! style=&amp;quot;width: 5%&amp;quot;| №&lt;br /&gt;
! style=&amp;quot;width: 10%&amp;quot;| Изображение&lt;br /&gt;
! style=&amp;quot;width: 85%&amp;quot;| Слоган&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;1&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster1.png|Free Tonto!]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A salvaged shred of a much larger flag, colors bled together and faded from age.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;2&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster2.png|Atmosia Declaration of Independence]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A relic of a failed rebellion.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;3&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster3.png|Fun Police]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster condemning the station's security forces.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;4&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster4.png|Lusty Xenomorph]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A heretical poster depicting the titular star of an equally heretical book.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;5&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster5.png|Syndicate Recruitment]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;See the galaxy! Shatter corrupt megacorporations! Join today!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;6&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster6.png|Clown]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Honk.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;7&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster7.png|Smoke]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising a rival corporate brand of cigarettes.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;8&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster8.png|Grey Tide]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A rebellious poster symbolizing assistant solidarity.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;9&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster9.png|Missing Gloves]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster references the uproar that followed Nanotrasen's financial cuts toward insulated-glove purchases.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;10&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster10.png|Hacking Guide]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster details the internal workings of the common Nanotrasen airlock. Sadly, it appears out of date.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;11&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster11.png|RIP Badger]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This seditious poster references Nanotrasen's genocide of a space station full of badgers.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;12&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster12.png|Ambrosia Vulgaris]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster is lookin' pretty trippy man.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;13&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster13.png|Donut Corp]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster is an unauthorized advertisement for Donut Corp.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;14&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster14.png|EAT]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster promotes rank gluttony.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;15&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster15.png|Tools]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster looks like an advertisement for tools, but is in fact a subliminal jab at the tools at CentComm.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;16&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster16.png|Power]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster that positions the seat of power outside Nanotrasen.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;17&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster17.png|Space Cube]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Ignorant of Nature's Harmonic 6 Side Space Cube Creation, the Spacemen are Dumb, Educated Singularity Stupid and Evil.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;18&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster18.png|Communist State]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;All hail the Communist party!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;19&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster19.png|Lamarr]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster depicts Lamarr. Probably made by a traitorous Research Director.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;20&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster20.png|Borg Fancy]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Being fancy can be for any borg, just need a suit.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;21&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster21.png|Borg Fancy v2]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Borg Fancy, Now only taking the most fancy.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;22&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster22.png|Kosmicheskaya Stantsiya 13 Does Not Exist]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster mocking CentComm's denial of the existence of the derelict station near Space Station 13.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;23&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster23.png|Rebels Unite]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster urging the viewer to rebel against Nanotrasen.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;24&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster24.png|C-20r]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising the Scarborough Arms C-20r.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;25&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster25.png|Have a Puff]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Who cares about lung cancer when you're high as a kite?&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;26&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster26.png|Revolver]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Because seven shots are all you need.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;27&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster27.png|D-Day Promo]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A promotional poster for some rapper.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;28&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster28.png|Syndicate Pistol]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;A poster advertising syndicate pistols as being 'classy as fuck'. It is covered in faded gang tags.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;29&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster29.png|Energy Swords]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;All the colors of the bloody murder rainbow.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;30&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster30.png|Red Rum]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Looking at this poster makes you want to kill.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;31&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster31.png|CC 64K Ad]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;The latest portable computer from Comrade Computing, with a whole 64kB of ram!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;32&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster32.png|Punch Shit]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Fight things for no reason, like a man!&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;33&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster33.png|The Griffin]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;The Griffin commands you to be the worst you can be. Will you?&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;34&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster34.png|Lizard]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This lewd poster depicts a lizard preparing to mate.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;35&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster35.png|Free Drone]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;This poster commemorates the bravery of the rogue drone banned by CentComm.&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;center&amp;gt;36&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;lt;center&amp;gt;[[Файл:Poster36.png|Busty Backdoor Xeno Babes 6]]&amp;lt;/center&amp;gt;&lt;br /&gt;
| &amp;quot;Get a load, or give, of these all natural Xenos!&amp;quot;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
Обратите внимания, что спрайт постера перекрывает спрайты настенного оборудования - экранов, консолей, апц, интеркомов, кнопок включения света и аварийных рычагов - делая эти устройства невидимыми за листом плаката.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Lawyer&amp;diff=19514</id>
		<title>Lawyer</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Lawyer&amp;diff=19514"/>
		<updated>2015-11-15T10:41:54Z</updated>

		<summary type="html">&lt;p&gt;IXVI: Наркоман, почитай как надо редактировать вики, чтобы у тебя хотя бы картинки отображались. :)&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#ffeaea;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Joblaw.png‎]]&amp;lt;br&amp;gt;[[Lawyer|Адвокат]]&lt;br /&gt;
|'''Доступ:''' Кабинет адвоката, Зал суда, Бриг.&lt;br /&gt;
'''Подчинение:''' [[Head of Security|Глава СБ]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Предоставлять подсудимым и подозреваемым юридическую защиту.&lt;br /&gt;
&lt;br /&gt;
'''Другие названия:''' Юрист&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Security]], [[Guide to Trials]], [[Space Law]], [[Guide to Paperworks]]&lt;br /&gt;
!Средне - Очень сложно&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''“Когда обнаруживаешь, что ты чуть ли не единственный, кто эти моральные преграды имеет, возникает порой искушение послать их к черту — не по убеждению и не ради удовольствия, а просто потому, что обидно быть ангелом в аду, в то время как дьявол везде себя чувствует дома.”&lt;br /&gt;
''&amp;lt;br/&amp;gt;'''''Мартен Паж, &amp;quot;Как я стал идиотом&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Lawyer.PNG|right|thumb|Офис адвоката. Кофе, пончики, бездельники.]]&lt;br /&gt;
[[File:Law_MetaOffice.png|right|thumb|Офис адвоката на Metastation.]]&lt;br /&gt;
&lt;br /&gt;
== Юриспруденция-13 ==&lt;br /&gt;
&lt;br /&gt;
Вот перечень дел, с которыми приходится сталкиваться штатному законнику:&lt;br /&gt;
&lt;br /&gt;
*'''Проводить консультации по [[Space Law|Космо-Закону]]''' Теоретически, адвокат должен присутствовать при процедуре заключения в камеру. Для этого вам понадобится отличное знание свода законов, либо экземпляр книги по Космо-закону. Вашими усилиями срок может быть сокращён, заменён на альтернативное наказание, либо на более тяжкое наказание. В зависимости от [[Clown|клиента]].&lt;br /&gt;
&lt;br /&gt;
*'''Быть адвокатом''' Теоретически, адвокат ведёт дело каждого злоумышленника и способен более тонко разобраться в составе преступления, участниках и доказательствах каждого дела. Важнейшие вещи здесь - это записи службы безопасности, улики и свидетельства участников.&lt;br /&gt;
&lt;br /&gt;
*'''Заботиться о своих клиентах''' Поскольку обычно СБ проводит задержания в агрессивной манере, и относится к преступникам как к швали - то, теоретически, адвокат берёт на себя заботу о здоровье и благополучии своих клиентов. Зачастую, именно он добивается сокращения срока задержания, в связи с кошмарными условиями.&lt;br /&gt;
&lt;br /&gt;
*'''Следить за порядком на бриге''' Теоретически, в 90% случаев процедура дознания и обыска ведётся на территории брига. Поэтому адвокат должен чётко знать, где лежат вещи его клиента, где хранятся улики и чья кровь осталась на вот этом станбатоне. Также адвокат должен уметь предсказать в какой именно момент этот порядок перестанет существовать.&lt;br /&gt;
&lt;br /&gt;
*'''Пропускать желающих на бриг''' Теоретически, адвокат имеет доступ на бриг, в отличие от гражданского персонала, и в его обязанности входит сопровождать людей для дачи показаний, либо выпровождать заключённых отсидевших свой срок. И возвращать им их &amp;lt;s&amp;gt;улики&amp;lt;/s&amp;gt; вещи.&lt;br /&gt;
&lt;br /&gt;
*'''Вести судебный процесс''' Теоретически, каждый член экипажа имеет право отстаивать свои права в судебном порядке. Поэтому время от времени на борту корабля проводятся суды с участием Верховного судьи, Обвиняемого и Защиты. Вы можете оказаться на любой из этих сторон.&lt;br /&gt;
&lt;br /&gt;
*'''Оказывать нотариальные услуги''' Ничто так высоко не ценится, как грамотно составленный, подтверждённый печатью документ, сопровождающий любые виды деятельности: От заказа ящика бананов, до лицензии на убийство. К сожалению, большинство персонала не может грамотно изложить свои доводы, составить документ и получить заветную печать - и совершают свои поступки полу-легальным путём. Так вот, теоретически - хороший адвокат, как человек связанный с законом и лояльный к службе безопасности, способен быстро и без проволочек получить любое разрешение на станции.&lt;br /&gt;
&lt;br /&gt;
*'''Участие в делах''' о покушениях, нарушениях, кражах, обмане, нарушении техники безопасности, подозрительных объектах и субъектах, денежных спорах, наследственных делах, приватизации отделов и инвентаря, скупки акций Нанотрасен, теоретически - даже в праве на собственность атомной бомбы НТ в личное пользование на неопределённый срок. Хороший адвокат всегда в бизнесе.&lt;br /&gt;
&lt;br /&gt;
== Закон в моих руках ==&lt;br /&gt;
Законы юрисдикции присутствуют и на нашей станции, куда уж без них! Надеждой и опорой невиновных или преступников, совершивших малые преступления - будете именно вы, адвокат. Вам будут предоставлены все привилегии проведения честных судов. Ваша главная опора - это закон. Закон на станции действует всегда, но иногда требуется вмешательство человека с стороны. Это вы и есть. Добро пожаловать. &lt;br /&gt;
&lt;br /&gt;
===Все для дела===&lt;br /&gt;
Вы имеете в своей комнате запасную одежду, сканер для проверки подлинности улик, бумагу, карандаши, диктофон и свод космического закона. Также ваша комната оснащена специальными шторами, для конфиденциальных бесед с клиентами.&lt;br /&gt;
&lt;br /&gt;
==Слово и честь - вот мое оружие==&lt;br /&gt;
В ваших обязанностях уличать Службу Безопасности в необоснованных сроках задержания. Здесь свою роль играет то, как они задержали преступника, какой урон ему был нанесен. Рекомендуется обзавестись поддержкой мед-персонала, который мог бы выделить вам бесценный анализатор здоровья. Также, без поддержки авторитета в лице капитана, вам будет трудно говорить с СБ &amp;quot;на ты&amp;quot;. Но не беспокойтесь, юрисдикция предписана законом, потому вам предоставят всю возможную помощь в ведении собственного следствия.&lt;br /&gt;
&lt;br /&gt;
Иметь обаяние предписано самой романтике профессии юриста! Не пытайтесь провоцировать охрану, помогать очевидным преступникам и до последнего стоять на стороне обвиняемого. У нас интеллигентная и нравственная охрана, потому все будет соответствующе. &lt;br /&gt;
&lt;br /&gt;
===Проверьте всё дважды===&lt;br /&gt;
Клиент - всегда прав. Но в этот раз правы вы, и только вы. Не верьте ни единому слову истца или детектива. Они не имеют права фальсифицировать или укрывать улики, но дружба в рядах нашей Службы Безопасности доходит до того, что они способны друг друга прикрывать от позора безосновательных тюремных сроков.&lt;br /&gt;
&lt;br /&gt;
===Этика справедливости===&lt;br /&gt;
Мы уверены в верности ваших слов, не разочаруйте наших надежд. Ложь и обман наказуем в виде разжалования, а если ваш клиент - явный преступник, то не стоит прибегать к методам воров и дебоширов, которых вы только и встретите. На уважение ответят уважением. Силовые структуры могут вам и не верить, но поддержки у иных глав станции вы должны добиться. Только из-за того, что вы адвокат. Ведь на станции только грамотные и психически уравновешенные люди, понимающие всю важность вашей должности. &lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19471</id>
		<title>DM Guide 11</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19471"/>
		<updated>2015-11-14T20:36:25Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Инструкция ввода */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Это 11 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap11.html Оригинальная 11 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
{{Заготовка|url=http://www.byond.com/docs/guide/chap11.html}}&lt;br /&gt;
&lt;br /&gt;
=Глава 11=&lt;br /&gt;
&lt;br /&gt;
Ввод\вывод Пользователя &amp;lt;!--User Input/Output--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Взаимодействие с пользователем - это главная цель любых программ в Dream Maker и эта глава описывает основы языка, отвечающего за ввод и вывод информации. &lt;br /&gt;
&amp;lt;!--Interacting with the user is the ultimate purpose of any DM program. This chapter describes the elements of the language which make it possible. To come this far would have been impossible without a casual introduction to some of the input/output instructions, but even those have more power to offer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Ввод==&lt;br /&gt;
&lt;br /&gt;
Есть два основных пути получения информации от игрока. Первый - ввод по запросу клиента(игрока), второй - ввод по запросу сервера(игры). Разница в том, посылает ли игрок информацию на обработку, или игра запрашивает необходимую информацию.&lt;br /&gt;
&amp;lt;!--There are two basic ways of getting information from the player. One is client initiated and the other is server initiated input. The difference is in whether the player sends unsolicited input or whether the game asks for it. These will be discussed in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Операторы (verbs)===&lt;br /&gt;
&lt;br /&gt;
До сих пор весь ввод был со стороны пользователя. Игрок может написать команду, нажать кнопку управления, щёлкнуть на объект и т.д. Эти виды ввода информации однородны, так как ими управляют одинаковые операторы(verbs). То есть нажатие на кнопку влево вызывает определённый процесс и задаёт ему значение &amp;quot;кнопка влево&amp;quot;.&lt;br /&gt;
&amp;lt;!--All user input seen so far has come at the initiative of the user. The player may type a command, press a direction key, click an object, etc. These forms of input are all similar because they are ultimately handled by verbs. In the case of the direction keys and mouse clicks, players don't need to actually type any command--the client does it all. However, from the programmer's point of view, these are all the same: The player calls a procedure and possibly passes some arguments to it.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть несколько заранее определённых операторов(verbs), принимающих ввод информации от игрока. Это кнопки направления\стрелки (напр. client.North()), щелчок мыши ((client.Click() и client.DblClick()) и ссылки топиков (client.Topic()). Все остальные операторы(verbs) задаются программистом.&lt;br /&gt;
&amp;lt;!--The only pre-defined verbs are associated with the client data object. They are the direction keys (e.g. client.North()), mouse clicks (client.Click() and client.DblClick()), and topic links (client.Topic()). All other verbs are defined by the programmer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Общий вид для определения оператора(verb) следующий:&lt;br /&gt;
: verb/Name(Arg1 = default input-type in List,...)&lt;br /&gt;
&lt;br /&gt;
Количество аргументов может быть любым. Каждый из них может иметь значение по умолчанию, тип ввода и список допустимых значений.&lt;br /&gt;
&amp;lt;!--The general format for defining a verb includes any number of arguments. Each one may have a default value, an input type, and a list of possible values.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Инструкция ввода===&lt;br /&gt;
&lt;br /&gt;
Инструкция ввода - это то, что позволяет вам(со стороны игры) запросить у игрока информацию ввода. На ней построены все взаимоотношения сервера с клиентом. Она похожа на простой одиночный оператор(verb).&lt;br /&gt;
&amp;lt;!--The input instruction allows you to ask the player for information. This is how DM provides server-initiated input. It is similar to a single verb argument.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;gt;input(User=usr,Message,Title,Default) input	(User,Query,Title,Default) as input-type in List&lt;br /&gt;
&lt;br /&gt;
User - это имя игрока(моба).&lt;br /&gt;
Query - текст запроса ввода.&lt;br /&gt;
Title - текст отображения запроса ввода.&lt;br /&gt;
Default - значение по умолчанию для данного запроса.&lt;br /&gt;
input-type - тип ввода информации.&lt;br /&gt;
List - список возможных значений для данного запроса.&lt;br /&gt;
Исполнение данного оператора задаёт значение введённое игроком. &amp;lt;!--Returns value entered by player.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Всё, кроме текста ввода - необязательные опциональные параметры. User ассоциируется с usr, и обращается к нему.&lt;br /&gt;
Если input type не задано, то тип ввода информации будет текстовым по умолчанию.&lt;br /&gt;
&amp;lt;!--All but the input text itself are optional parameters. User defaults to the current usr, which is usually the desired target. If no input type or possible value list is specified, the default input type is text. Otherwise, the input type defaults to accept anything in the supplied list, which contains the only values the user is allowed to enter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Обратите внимание, что инструкция ввода не будет запрошена, пока пользователь не введёт значение. При поддержки многопользовательской системы ожидать ответа от одного пользователя невозможно, поэтому при запросе ввода информации в режим ожидания входит только текущая исполняемая процедура.&lt;br /&gt;
&amp;lt;!--Note that the input instruction does not return until the user has entered a value. Since the entire multi-user system cannot halt while waiting for this to happen, only the current procedure waits. More will be said on the subject of multi-tasking in chapter 13.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Инструкция ввода для игрока выглядит как запрос ответа на сложившуюся ситуацию. В таком случае простое применение оператора(verb) было бы слишком неточным для определения дальнейших действий игры.&lt;br /&gt;
&amp;lt;!--One case in which the input instruction proves useful is when something happens in the game that the player needs to respond to. A verb would be too open-ended for the task, making it difficult for the player to guess what to do next.&lt;br /&gt;
&lt;br /&gt;
The following code, for example, handles a rather sad event in the life of a player.--&amp;gt;&lt;br /&gt;
Следующий код показывается пример подобного случая:&lt;br /&gt;
&lt;br /&gt;
: mob/proc/Die()&lt;br /&gt;
:   if(!key) //NPC&lt;br /&gt;
:      del src&lt;br /&gt;
:   else     //PC&lt;br /&gt;
:      loc = null  //покидает игру&lt;br /&gt;
:      var/again = input(&amp;quot;Играть снова?&amp;quot;) in list(&amp;quot;Да&amp;quot;,&amp;quot;Нет&amp;quot;)&lt;br /&gt;
:      if(again == &amp;quot;Да&amp;quot;)&lt;br /&gt;
:         Login() //возвращается в игру&lt;br /&gt;
:      else&lt;br /&gt;
:         del src&lt;br /&gt;
Когда вызвана процедура Die(), игрокам будет выдано сообщение - желают ли они продолжить игру. Если они отвечают &amp;quot;Да&amp;quot;, то они возвращаются обратно в игру, в противном случае - нет. (Пример, конечно, довольно грубый, но вполне наглядный.)&lt;br /&gt;
&lt;br /&gt;
==Output==&lt;br /&gt;
&lt;br /&gt;
All output is generated by the &amp;lt;&amp;lt; operator. This sends the specified output to one or more players.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Output&lt;br /&gt;
The target may be a single object or a list of objects. Any non-mob target will be replaced by its contents. This allows you to send output to a region on the map or to a room, and all the players inside will receive it.&lt;br /&gt;
&lt;br /&gt;
There are several different types of output. In many cases, the way the output should be handled is automatically detected from the type of data provided. Several instructions for producing various types of output are listed in the following table. In addition to these instructions are some which further clarify how the output should be treated when the type of data alone is not enough to determine this.&lt;br /&gt;
&lt;br /&gt;
Figure 11.16: Output Methods&lt;br /&gt;
&lt;br /&gt;
text()&lt;br /&gt;
&lt;br /&gt;
file()&lt;br /&gt;
image()&lt;br /&gt;
browse()&lt;br /&gt;
sound()&lt;br /&gt;
ftp()&lt;br /&gt;
run()&lt;br /&gt;
link()&lt;br /&gt;
The first group of instructions produce various types of data for output or other purposes. The second group are only meaningful for directly producing output. All of these instructions are described individually in the following sections. The general format for using them is the same.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Method(Output)&lt;br /&gt;
&lt;br /&gt;
===text output===&lt;br /&gt;
&lt;br /&gt;
A text output value is displayed in the client's scrolling terminal window. The text value may be the result of any expression. Frequently, it is a text string with embedded expressions inside it. Although it is not necessary to use the text instruction for this purpose, one reason for doing so is to use trailing rather than directly embedded expressions.&lt;br /&gt;
&lt;br /&gt;
text	(Text,Arg1,Arg2,...)&lt;br /&gt;
Text is the text string with expression markers.&lt;br /&gt;
Args are the expressions to insert.&lt;br /&gt;
Returns text with arguments substituted in.&lt;br /&gt;
The position in the text where a trailing argument will be inserted is marked with empty brackets [ ]. The substitution arguments are then listed in the same order as the expression markers.&lt;br /&gt;
&lt;br /&gt;
For substituting short expressions into the text, it is convenient to simply embed them directly. However, many lengthy expressions embedded into a text string can make it difficult to read. In that case, trailing expressions may be the better choice. The two methods can be mixed as desired.&lt;br /&gt;
&lt;br /&gt;
The following two versions of a look verb are equivalent.&lt;br /&gt;
&lt;br /&gt;
mob&lt;br /&gt;
   var/money = 2&lt;br /&gt;
&lt;br /&gt;
   verb/look1()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;[src] has [contents.len] items and [money] buffalo chips.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   verb/look2()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; text(&amp;quot;[src] has [] items and [] buffalo chips.&amp;quot;,&lt;br /&gt;
                   contents.len,&lt;br /&gt;
                   money)&lt;br /&gt;
Note that the text instruction is not limited to being used as an output method. It may be used anywhere you wish to use trailing expressions with a text string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===browse output===&lt;br /&gt;
&lt;br /&gt;
The browse output method displays text output in a pop-up window. This is intended for viewing longer text documents. If treated as normal terminal output instead, the user might have to scroll back up to find the top of the message.&lt;br /&gt;
&lt;br /&gt;
browse	(Doc, Options)&lt;br /&gt;
Doc is the message to display.	Options are various window-specific options. Consult the reference for specifics.&lt;br /&gt;
By default, each message replaces any previous message being displayed but the user can move back to previous messages stored in the client's memory. In many ways, the client terminal behaves like a telnet session and the browse window behaves like a web browser. One displays output sequentially in a continuous stream. The other displays it in discrete chunks--one document after another. The two are each useful in different situations.&lt;br /&gt;
&lt;br /&gt;
The document is often a text string. However, it may be a file instead. The type of file will determine how it is handled. Files may reside in the resource cache or in the file system. As always, cached items may be specified by putting the file name in single quotes. An external file, on the other hand, is indicated using the file instruction described in section 11.2.7.&lt;br /&gt;
&lt;br /&gt;
The browse output method is often used in conjunction with the message input type. One allows the composition of messages and the other displays them.&lt;br /&gt;
&lt;br /&gt;
The following example defines a message scroll. Players can write poetry on it in moments of inspiration.&lt;br /&gt;
&lt;br /&gt;
obj/scroll/verb&lt;br /&gt;
   write(msg as message)&lt;br /&gt;
      desc = msg&lt;br /&gt;
   read()&lt;br /&gt;
      usr &amp;lt;&amp;lt; browse(desc)&lt;br /&gt;
&lt;br /&gt;
===sound output===&lt;br /&gt;
&lt;br /&gt;
The sound output method plays a sound to the player. Either wav or midi sound files may be used, usually for short noises and music respectively. Such files are treated this way by default, but the sound instruction can be used to control how the sound is played.&lt;br /&gt;
&lt;br /&gt;
sound	(File,Repeat)&lt;br /&gt;
File is the sound file to play.&lt;br /&gt;
Repeat is 1 to play sound repeatedly.&lt;br /&gt;
A repeated sound is played in the background while other sounds are played in the foreground. Only one background sound and one foreground sound may be played at a time, so subsequent output replaces any previous sound with the same repeat setting. To stop a sound, specify null as the file.&lt;br /&gt;
&lt;br /&gt;
Background music is often repeated while occasional noises play in the foreground. The following example defines a background sound for each area.&lt;br /&gt;
&lt;br /&gt;
area&lt;br /&gt;
   var/music = 'default.midi'&lt;br /&gt;
   Enter()&lt;br /&gt;
      . = ..()&lt;br /&gt;
      if(.) usr &amp;lt;&amp;lt; sound(music,1)&lt;br /&gt;
The line . = ..() is commonly used when you want to return the same value as the parent proc but you need to do something after finding out what that value is. That way, if the user is refused access to the area for some reason, the music will not be played.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===image output===&lt;br /&gt;
&lt;br /&gt;
The image instruction is used to create a purely virtual object. It may appear at the specified location to selected players, but it corresponds to no real data object.&lt;br /&gt;
&lt;br /&gt;
image	(Icon,Loc)&lt;br /&gt;
Icon is the icon or object type to use.&lt;br /&gt;
Loc is the location of the image.&lt;br /&gt;
Returns a reference to the image.&lt;br /&gt;
If the location of the image is something movable like a mob, it will follow the object around. The image icon is displayed in a layer above everything else, so it is best suited for special effects like a selection box, burst of fire, etc.&lt;br /&gt;
&lt;br /&gt;
The image instruction may be used outside the context of the output instruction. In this case it returns a reference to the image but does not actually display the image to any players. This reference can be sent as output and may be deleted later to destroy the image.&lt;br /&gt;
&lt;br /&gt;
The following example allows the player to select an enemy by clicking on it. The currently selected enemy is outlined with an image.&lt;br /&gt;
&lt;br /&gt;
mob/var&lt;br /&gt;
   mob/enemy&lt;br /&gt;
   enemy_marker&lt;br /&gt;
&lt;br /&gt;
client/Click(mob/M)&lt;br /&gt;
   if(istype(M))&lt;br /&gt;
      del usr.enemy_marker&lt;br /&gt;
      usr.enemy = M&lt;br /&gt;
      usr.enemy_marker = image('outline.dmi',M)&lt;br /&gt;
      usr &amp;lt;&amp;lt; usr.enemy_marker&lt;br /&gt;
The code works by first deleting any old enemy marker. A new one is then made and displayed to the user. No one else will see the image--only the player who clicked on the enemy.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===ftp output===&lt;br /&gt;
&lt;br /&gt;
The ftp output method sends a file to the player. This complements the file input type which allows the player to send a file to the server. The terminology normally used is that a file is uploaded when it is input and downloaded when it is output.&lt;br /&gt;
&lt;br /&gt;
ftp	(File,Name)&lt;br /&gt;
File is the file to send.&lt;br /&gt;
Name is the optional suggested file name.&lt;br /&gt;
The file to send may be either a resource file (in the cache) or a file in the file system. The difference is whether the file is specified in single or double quotes. A file in single quotes will be loaded into the resource cache at compile-time. A file in double quotes will be accessed from the file system (i.e. hard-disk) at run-time. The latter might be useful if you need to update the file periodically without recompiling.&lt;br /&gt;
&lt;br /&gt;
The suggested file name defaults to the name of the file being sent. This is used as the default name when the player chooses where to store the file. If the player decides not to download the file, it is always possible to cancel at that point or during the transfer.&lt;br /&gt;
&lt;br /&gt;
The following example sends a help file to players when they click on the appropriate topic.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; ftp(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
mob/Login()&lt;br /&gt;
   ..()&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;Download the  help file  if you are new here.&amp;quot;&lt;br /&gt;
For this to work, the file &amp;quot;help.txt&amp;quot; must exist in the current directory of the server. This can be assured by putting it in the same place as the dmb file. Since the file was specified in double quotes, it will be accessed at run-time rather than compile-time. That means you are free to edit it at a later date.&lt;br /&gt;
&lt;br /&gt;
The HTML tag &amp;lt;A HREF...&amp;gt; is used to embed a hyperlink in some output text. It will be described in section 11.4.3.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===run file output===&lt;br /&gt;
&lt;br /&gt;
The run output method is like ftp except it displays or executes the specified file rather than saving it to disk. The action taken depends on the type of file. For example, HTML and jpeg files might be shown in the player's web browser.&lt;br /&gt;
&lt;br /&gt;
run(File)&lt;br /&gt;
Obviously it would be a severe security risk to players if executable files could be run without their authorization. Viruses and other malicious programs could be released onto their computer just by connecting to a game. For this reason, players are asked before executing any potentially dangerous file. That is the default behavior. The player can configure the client to always or never run files if they choose. A similar choice can be made about downloading files.&lt;br /&gt;
&lt;br /&gt;
The previous example which gave the player a help file could easily be changed to instead display the file. If the player wishes, it would still be possible to save the file to disk.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; run(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===file output===&lt;br /&gt;
&lt;br /&gt;
The file instruction returns a reference to a file object. It takes the file's path (in a text string) as an argument. The output methods browse, ftp, and run can all take a file reference as an argument. In the case of browse it is necessary to use file to distinguish between a text message and a file name. In the case of ftp and run it is not necessary to use file because the name of the file may simply be used directly. If no output method is specified for a file, it is implicitly handled by run.&lt;br /&gt;
&lt;br /&gt;
file	(Path)&lt;br /&gt;
Path is the name of the file.&lt;br /&gt;
Returns a reference to the file.&lt;br /&gt;
The path may be absolute or relative to the server's working directory, which is the same directory that contains the world .dmb file. Since this is evaluated at run-time, the file need not exist until the statement is actually executed. This is different from cache file references (in single quotes) which are evaluated at compile-time. For more uses of the file object, see section 17.6.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===link output===&lt;br /&gt;
&lt;br /&gt;
The link output method is like run except it executes a URL rather than a file. The URL could be a web address, a BYOND address, or a topic link.&lt;br /&gt;
&lt;br /&gt;
link	(url)&lt;br /&gt;
url is the URL to execute.&lt;br /&gt;
The beginning of the URL specifies the communication protocol. If the URL begins with &amp;quot;byond://&amp;quot; then it is treated as a BYOND address. This is the default protocol if none is specified. A URL beginning with &amp;quot;#&amp;quot; is a topic link. Other protocols (like &amp;quot;http://&amp;quot; are handled by the player's web browser.&lt;br /&gt;
&lt;br /&gt;
A BYOND link causes the player's client to reconnect to the specified address. Topic links merely cause the specified topic to be accessed in the current world (by calling client.Topic()). A web link causes the web browser to switch to the specified URL.&lt;br /&gt;
&lt;br /&gt;
The general format for a BYOND address includes a server address and topic.&lt;br /&gt;
&lt;br /&gt;
byond://server#topic&lt;br /&gt;
The topic is optional and is only used in rare cases like servers with multiple entry points. The server address may be either the name of a registered server or the network address in the form ip:port. The IP address would either be raw network numbers (e.g. 123.456.789.123) or the corresponding machine name (e.g. dantom.com). The port number is the network port on which the server is running. This is reported when the server starts up.&lt;br /&gt;
&lt;br /&gt;
By default, players are asked whether they accept links activated in this manner. They can, however, configure the client to always or never accept them.&lt;br /&gt;
&lt;br /&gt;
The link output method is very similar to the hyperlink text tag which has already been introduced. They both can take the same types of URLs and act upon them in the same manner. Hyperlinks embedded in text are normally used to provide access to optional information. The link output method, on the other hand, is useful when the player's action has already indicated desire to follow the link.&lt;br /&gt;
&lt;br /&gt;
For example, a link from one world to another could be activated by entrance into a special turf.&lt;br /&gt;
&lt;br /&gt;
turf/wormhole/Enter()&lt;br /&gt;
   usr &amp;lt;&amp;lt; link(&amp;quot;byond://WormWorld&amp;quot;)&lt;br /&gt;
   return 1&lt;br /&gt;
This example assumes the existence of a world registered under the name &amp;quot;WormWorld&amp;quot;. Running and registering a networked world will be discussed in chapter 12.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Macros==&lt;br /&gt;
&lt;br /&gt;
Both input and output text may contain special codes that are not displayed literally but which are replaced by some other text. These are called text macros and begin with a backslash \ and may end with a space (which is ignored). They are summarized in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Expression Modifiers===&lt;br /&gt;
&lt;br /&gt;
Figure 11.17: Text Macros for use with Expressions&lt;br /&gt;
&lt;br /&gt;
\the, \The&lt;br /&gt;
&lt;br /&gt;
definite article if needed&lt;br /&gt;
\a, \an, \A, \An	indefinite article if needed&lt;br /&gt;
\he, \He, \she, \She	he, she, they, it&lt;br /&gt;
\his, \His	his, her, their, its&lt;br /&gt;
\hers	his, hers, theirs, its&lt;br /&gt;
\him	him, her, them, it&lt;br /&gt;
\himself, \herself	himself, herself, themself, itself&lt;br /&gt;
\th	1st, 2nd, 3rd, ...&lt;br /&gt;
\s	1 dog, 2 dogs, ...&lt;br /&gt;
The first group of text macros work in conjunction with an embedded expression. The article macros precede the expression and the others follow it. Any amount of text and even inapplicable expressions may exist between the macro and its associated expression.&lt;br /&gt;
&lt;br /&gt;
The articles and various pronouns work with object or text expressions. The plural and ordinal macros \s and \th are used with numerical expressions. If no expression of the appropriate type is found, these macros do nothing.&lt;br /&gt;
&lt;br /&gt;
An embedded object is replaced by a definite article and its name. In other words, the following two are equivalent:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] smiles.&amp;quot;&lt;br /&gt;
&amp;quot;\The [usr] smiles.&amp;quot;&lt;br /&gt;
These could produce &amp;quot;Andrew smiles.&amp;quot; or &amp;quot;The cat smiles.&amp;quot; depending on the name of the user.&lt;br /&gt;
&lt;br /&gt;
Note that the articles may be supplied in either capitalized or lowercase form. The implicit definite article is automatically chosen in capital form if preceded by a period. If that is incorrect, you can specify the desired form explicitly.&lt;br /&gt;
&lt;br /&gt;
If an indefinite article is desired instead of the default definite one, it must be explicitly specified. If no article at all is desired, the name can be embedded directly in place of the object.&lt;br /&gt;
&lt;br /&gt;
The following example uses an indefinite article instead of a definite one when a mob picks up an object.&lt;br /&gt;
&lt;br /&gt;
obj/verb/get()&lt;br /&gt;
   set src in view(0)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] picks up \a [src].&amp;quot;&lt;br /&gt;
   Move(usr)&lt;br /&gt;
It doesn't matter whether you use &amp;quot;a&amp;quot; or &amp;quot;an&amp;quot; in the macro. The appropriate one will be chosen for the word that follows. It is common to use whichever one makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Proper Nouns====&lt;br /&gt;
&lt;br /&gt;
There are two special text macros for controlling whether the name of an object is considered to be a proper noun or not. These are \proper and \improper. By default, if the object name is capitalized, it is assumed to be proper, and otherwise it is assumed to be improper. To override this, you can put \proper or \improper at the beginning of the object's name.&lt;br /&gt;
&lt;br /&gt;
As you have seen in the preceding section, the difference between proper and improper nouns is that articles are suppressed in front of proper nouns. For example, if you had something called a &amp;quot;BYOND dime,&amp;quot; you would need to use the \improper macro as follows:&lt;br /&gt;
&lt;br /&gt;
obj/BD&lt;br /&gt;
   name = &amp;quot;\improper BYOND dime&amp;quot;&lt;br /&gt;
mob/verb/get(obj/O in view(0))&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;You pick up \an [O].&amp;quot;&lt;br /&gt;
   O.Move(usr)&lt;br /&gt;
Since we used \improper in this example, somebody picking up a BYOND dime would see, &amp;quot;You pick up a BYOND dime.&amp;quot; rather than &amp;quot;You pick up BYOND dime.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Numerical Expressions====&lt;br /&gt;
&lt;br /&gt;
There are macros which depend upon the preceding numerical expression. The \th macro produces the ordinal ending for the supplied number. For the number 1, it produces &amp;quot;st&amp;quot; to make &amp;quot;1st&amp;quot;, for the number 2, &amp;quot;nd&amp;quot; and so on. From 4 and on it produces &amp;quot;th&amp;quot;, which is where it gets its name.&lt;br /&gt;
&lt;br /&gt;
The \s macro produces &amp;quot;s&amp;quot; if the preceding numerical expression is not equal to 1 and nothing otherwise. This is useful for making plurals like &amp;quot;You have [count] coin\s.&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Special Characters===&lt;br /&gt;
&lt;br /&gt;
Figure 11.18: Special Character Macros&lt;br /&gt;
&lt;br /&gt;
\&amp;quot;&lt;br /&gt;
&lt;br /&gt;
double quote&lt;br /&gt;
\\	backslash&lt;br /&gt;
\&amp;lt;	less than&lt;br /&gt;
\&amp;gt;	greater than&lt;br /&gt;
\&amp;amp;	ampersand&lt;br /&gt;
\n	newline&lt;br /&gt;
\...	suppress newline at end&lt;br /&gt;
\(space)	skip a space&lt;br /&gt;
There are a few special characters that may not be directly entered into a text string. These must be escaped by preceding them with a backslash. This forces the special meaning to be ignored and the literal character to be inserted instead.&lt;br /&gt;
&lt;br /&gt;
The double quote, for example, must be escaped or it would prematurely end the text string.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] says, \&amp;quot;[msg]\&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Newlines====&lt;br /&gt;
&lt;br /&gt;
A newline may be inserted with the \n macro. The compiler does not allow direct insertion of newlines in a text string because this is often a mistake resulting from a missing end quote. You can continue a lengthy text string onto the next line by escaping the newline, but then the newline is entirely ignored.&lt;br /&gt;
&lt;br /&gt;
There is an implicit newline inserted at the end of all output text. This means that instead of using the \n macro directly, the text can simply be broken up into individual lines which are output one at a time.&lt;br /&gt;
&lt;br /&gt;
In some cases, you may want to suppress the implicit newline at the end of the text. This can be done with the \... macro. By putting it at the end of the text, subsequent output will start on the same line where the previous one left off.&lt;br /&gt;
&lt;br /&gt;
A newline is actually an end-of-paragraph marker. It should not be used inside the paragraph to make lines fit the screen because not everyone's terminal will be the same width. It is best to let the terminal automatically handle word-wrap within paragraphs and reserve the newline for marking the end of it.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Formatting Tags==&lt;br /&gt;
&lt;br /&gt;
Text may be formatted by inserting HTML elements, more commonly known as tags, that control its appearance. DM understands a subset of HTML tags, consisting of the most commonly used elements.&lt;br /&gt;
&lt;br /&gt;
A tag is surrounded by &amp;lt; &amp;gt; angle brackets. The first thing inside the brackets is the name of the tag. Many tags come in pairs--one to start an effect and another to end it. The end tag has the same name as the start tag except it starts with `/'. Tag names are not case sensitive.&lt;br /&gt;
&lt;br /&gt;
The following example displays some text in bold.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;I am very mad!&amp;quot;&lt;br /&gt;
The start tag &amp;lt;B&amp;gt; turns on bold lettering and &amp;lt;/B&amp;gt; turns it off. For a complete list of tags understood by DM, see page 3 in the appendix. The most commonly used ones are listed in figure 11.19 for easy reference.&lt;br /&gt;
&lt;br /&gt;
Figure 11.19: Common text tags&lt;br /&gt;
&lt;br /&gt;
&amp;lt;A&amp;gt;&amp;lt;/A&amp;gt;&lt;br /&gt;
&lt;br /&gt;
anchor (for hyperlinks)&lt;br /&gt;
&amp;lt;B&amp;gt;&amp;lt;/B&amp;gt;	bold&lt;br /&gt;
&amp;lt;BIG&amp;gt;&amp;lt;/BIG&amp;gt;	bigger text&lt;br /&gt;
&amp;lt;BR&amp;gt;	line break&lt;br /&gt;
&amp;lt;FONT&amp;gt;&amp;lt;/FONT&amp;gt;	font face, size, and color&lt;br /&gt;
&amp;lt;I&amp;gt;&amp;lt;/I&amp;gt;	italic&lt;br /&gt;
&amp;lt;P&amp;gt;&amp;lt;/P&amp;gt;	paragraph&lt;br /&gt;
&amp;lt;S&amp;gt;&amp;lt;/S&amp;gt;	overstrike&lt;br /&gt;
&amp;lt;SMALL&amp;gt;&amp;lt;/SMALL&amp;gt;	smaller text&lt;br /&gt;
&amp;lt;TT&amp;gt;&amp;lt;/TT&amp;gt;	typewriter style&lt;br /&gt;
&amp;lt;U&amp;gt;&amp;lt;/U&amp;gt;	underline&lt;br /&gt;
&amp;lt;PRE&amp;gt;&amp;lt;/PRE&amp;gt;	preformatted whitespace&lt;br /&gt;
&amp;lt;XMP&amp;gt;&amp;lt;/XMP&amp;gt;	literally preformatted text&lt;br /&gt;
&amp;lt;BEEP&amp;gt;&lt;br /&gt;
&lt;br /&gt;
make a beeping sound&lt;br /&gt;
&lt;br /&gt;
===Whitespace===&lt;br /&gt;
&lt;br /&gt;
Whitespace refers to any spaces, tabs, or newlines. In standard HTML, whitespace serves merely to delimit words. The amount of space and whether it is a tab, space, or newline is irrelevant.&lt;br /&gt;
&lt;br /&gt;
DM processes whitespace like standard HTML when it is inside of a pair of start and end tags. So, for example, inside of &amp;lt;P&amp;gt; and &amp;lt;/P&amp;gt;, the paragraph markers, standard HTML rules are in effect; newlines, spaces, and tabs serve merely to delimit words. Note that an entire document could be surrounded by &amp;lt;HTML&amp;gt; and &amp;lt;/HTML&amp;gt; to mark the whole thing as standard HTML.&lt;br /&gt;
&lt;br /&gt;
Outside of all HTML tags, DM handles whitespace a little differently. Spaces still delimit words, but newlines (embedded with \n) mark the end of lines. In other words, the newline is automatically converted to &amp;lt;BR&amp;gt;, the linebreak tag. That is convenient for use in messages composed by players when it would be annoying to write formal HTML with paragraph tags and so forth.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;FONT&amp;gt; tag is used to control various characteristics of the font being used. It takes additional arguments in the form of attributes.&lt;br /&gt;
&lt;br /&gt;
For example, to make the font much bigger, you could use the start tag &amp;lt;FONT SIZE=+3&amp;gt;. The name of the attribute in this case is SIZE, and its value is +3, which makes the font three sizes bigger. You can put quotes around the attribute value if it contains any spaces. In this case there was no need.&lt;br /&gt;
&lt;br /&gt;
The attributes of &amp;lt;FONT&amp;gt; are FACE, SIZE, and COLOR. You can use as many of these attributes in one tag as you like. Just separate each attribute assignment by some space like this: &amp;lt;nowiki&amp;gt;&amp;lt;FONT SIZE=+3 COLOR=red&amp;gt;&amp;lt;/nowiki&amp;gt;. The nuances of these three tags are discussed in the following individual sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FACE attribute====&lt;br /&gt;
&lt;br /&gt;
The FACE attribute selects the name of the font you wish to use. It may be a single font (such as InnoDBl) or a comma-separated list (such as InnoDBl,Helvetica). If the user doesn't have a font with the same name on their system, the next font will be tried. Remember to put quotes around the attribute value if it contains any spaces.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====SIZE attribute====&lt;br /&gt;
&lt;br /&gt;
The SIZE attribute changes the size of the text. It can be a relative change, like +3, or an absolute size, such as 5. Font sizes are numbered from 1 to 7, with 1 being the smallest and 7 being the largest. Each increment is roughly 1.5 times the apparent size of the previous one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====COLOR attribute====&lt;br /&gt;
&lt;br /&gt;
The COLOR attribute selects the foreground color of the text. It may be either a color name or a hexadecimal RGB value.&lt;br /&gt;
&lt;br /&gt;
RGB stands for red, green, and blue, the three primary colors from which all the others can be produced. Hexadecimal is a base-16 number system commonly used by programmers for specifying binary values. The hexadecimal digits are 0 to 9 and A to F, a full four bits of information. Lowercase letters may be used as well.&lt;br /&gt;
&lt;br /&gt;
Each primary color is given a range of eight bits. Therefore it takes exactly two hexadecimal digits to specify a single component and six digits to specify a complete color value. The first two digits are for red; the next two are for green; and the last two are for blue (hence RGB). The color black is 000000, which has all three colors turned off. The color white is FFFFFF with all three colors at their maximum intensity.&lt;br /&gt;
&lt;br /&gt;
The following two lines are identical:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
Notice that a # symbol is placed in front of the numeric color value to indicate that it is a hexadecimal value. Otherwise, a color name is expected. If you can't find the color you want in the list of named colors, find the closest one and tweak the intensities to your satisfaction.&lt;br /&gt;
&lt;br /&gt;
Figure 11.20: Named Colors&lt;br /&gt;
&lt;br /&gt;
black&lt;br /&gt;
&lt;br /&gt;
#000000&lt;br /&gt;
silver	#C0C0C0&lt;br /&gt;
grey	#808080&lt;br /&gt;
white	#FFFFFF&lt;br /&gt;
maroon&lt;br /&gt;
&lt;br /&gt;
#800000&lt;br /&gt;
red	#FF0000&lt;br /&gt;
purple	#800080&lt;br /&gt;
fuchsia	#FF00FF&lt;br /&gt;
green&lt;br /&gt;
&lt;br /&gt;
#00C000&lt;br /&gt;
lime	#00FF00&lt;br /&gt;
olive	#808000&lt;br /&gt;
yellow	#FFFF00&lt;br /&gt;
navy&lt;br /&gt;
&lt;br /&gt;
#000080&lt;br /&gt;
blue	#0000FF&lt;br /&gt;
teal	#008080&lt;br /&gt;
aqua	#00FFFF&lt;br /&gt;
It is also possible to enter color components as 4 rather than 8 bit numbers. In that case, only three hexadecimal digits are required rather than six. Internally, the color is converted to full 8 bit notation by repeating each digit. For example, black #000 becomes #000000, white #FFF becomes #FFFFFF, and red #F00 becomes FF0000.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlinks===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;A&amp;gt; tag is used to mark a particular spot (or anchor) in the text. In DM, you use it to insert a clickable hyperlink. To specify the destination URL of a link, use the HREF attribute.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;lt;A HREF='#topic'&amp;gt; click here &amp;lt;/A&amp;gt; ...&amp;quot;&lt;br /&gt;
The form of the URL is the same as the link output method described in section 11.2.8. It may be either a BYOND address, a topic link, or a web address.&lt;br /&gt;
&lt;br /&gt;
The TITLE attribute may be assigned to a description of the link. It is made visible when the user holds the mouse over the link.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Style Sheets==&lt;br /&gt;
&lt;br /&gt;
HTML tags, such as &amp;lt;FONT&amp;gt; may be used to directly format output text. Another approach, however, is to use HTML tags to specify purely structural information and use a style sheet to define how various elements within that structure should be treated. DM uses a subset of the Cascading Style Sheet (CSS) language, which was introduced for this purpose in HTML documents.&lt;br /&gt;
&lt;br /&gt;
As an example of a style sheet, suppose one wanted combat and conversational messages to appear differently--perhaps using different colors. Instead of using the &amp;lt;FONT&amp;gt; tag to color the text, you could use &amp;lt;SPAN&amp;gt; to mark the beginning and ending of the text and to specify what kind of message it is. The result might be text such as the following:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] spanks [targ]!&amp;quot;&lt;br /&gt;
&amp;quot;[usr] says, '[msg]'&amp;quot;&lt;br /&gt;
The CLASS attribute may be used with any tag, but the generic containers SPAN and DIV are often convenient because they have no other side-effect. &amp;lt;SPAN&amp;gt; is for text within a single paragraph and &amp;lt;DIV&amp;gt; is for whole paragraphs. The way text belonging to a particular class is formatted may be controlled in a style sheet such as the following:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This says that text in the `combat' class should be colored red and text in the `chat' class should be colored green. These classes are not pre-defined; they were just made up to suit the situation. You can invent as many new classes as you like.&lt;br /&gt;
&lt;br /&gt;
In order to make this style sheet take effect you have several options. One is to put it in a text string (double quotes) and assign it to client.script. This will load the style sheet when the player connects. You could accomplish the same thing by putting the style sheet in a file and assigning the file (in single quotes) to client.script. It is also possible for a player to put the style sheet in a client-side script file and load it that way. More will be said about DM Script, which encompasses more than just style sheets, in the appendix (page [4]).&lt;br /&gt;
&lt;br /&gt;
The advantage of using style sheets instead of direct formatting tags is that you can cleanly separate structural information (such as combat and conversational messages) from formatting information (such as red and green text). By separating the two, you or the player can easily plug in different formatting schemes without changing any of the actual content.&lt;br /&gt;
&lt;br /&gt;
A style sheet is composed of a list of rules, such as the two rules in the preceding example. Each rule contains one or more selectors followed by a body of attribute assignments (in braces). The selector specifies the context of the rule and the body specifies the format.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Context Selectors===&lt;br /&gt;
&lt;br /&gt;
A selector may specify a container tag (such as SPAN, BODY, or P) and a class. The above example could have been written with a selector of SPAN.chat. However, by leaving out the tag, it applies to any tag with CLASS=chat. It is also possible to only specify the tag and not the class. In that case, the selector applies to any matching tag, regardless of its class.&lt;br /&gt;
&lt;br /&gt;
To specify a nested context, several simple selectors may be listed one after the other. For example, emphasized text within a combat message could be enlarged with the following rule:&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
It is also possible to list several selectors separated by commas in order to make them all apply to the same body. For example, this next rule is equivalent to the two following ones:&lt;br /&gt;
&lt;br /&gt;
.combat EM, .chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
.chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
===Style Attributes===&lt;br /&gt;
&lt;br /&gt;
The body of a style rule contains a list of attribute assignments, delimited by semicolons. Each assignment takes the form of an attribute name, followed by a colon, followed by the value of the attribute. Figure 11.21 summarizes the recognized attributes and sample values.&lt;br /&gt;
&lt;br /&gt;
Figure 11.21: Style Attributes&lt;br /&gt;
&lt;br /&gt;
color&lt;br /&gt;
&lt;br /&gt;
#F00, #FF000, red&lt;br /&gt;
background	same as color&lt;br /&gt;
font-size	10pt, 1.5em, 150%&lt;br /&gt;
font-style	normal or italic&lt;br /&gt;
font-weight	normal, bold, lighter, darker, or 100 to 900&lt;br /&gt;
font-family	monospace, sans-serif, serif, cursive, ...&lt;br /&gt;
font	style weight size family&lt;br /&gt;
text-decoration	none or underline&lt;br /&gt;
text-align	left, right, or center&lt;br /&gt;
width	16px, 32px, auto&lt;br /&gt;
height	16px, 32px, auto&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The font family may be a specific font name or a more general category such as monospace or sans-serif. Since not all users necessarily have the same fonts installed, it is a good idea to list alternate fonts. The desired font is placed first, followed by other possible fall-backs, each separated by a comma. Usually a general family such as monospace is listed last of all. Any font names containing a space should be enclosed in quotes.&lt;br /&gt;
&lt;br /&gt;
The font attribute is a special short-hand for assigning font-size, font-style, font-weight, and font-family in one statement. Any properties that are not specified in the font statement are assigned to their default values.&lt;br /&gt;
&lt;br /&gt;
The following example sets the font for the &amp;lt;BODY&amp;gt; tag. Even if you don't explicitly use &amp;lt;BODY&amp;gt; in output text, it is applied implicitly.&lt;br /&gt;
&lt;br /&gt;
BODY {font: 12pt 'Times New Roman', sans-serif}&lt;br /&gt;
This sets the font to 12 point and selects Times New Roman if it is available and otherwise falls back on a system-determined sans-serif font. This command also implicitly specifies not to use italics and normal font weight (not bold).&lt;br /&gt;
&lt;br /&gt;
Font sizes may be specified in points (1pt = 1/72 of an inch), picas (1pc = 12pt), pixels (px), inches (in), centimeters (cm), and millimeters (mm). There are also various levels corresponding to the traditional 1 to 7 HTML scale. These are xx-small, x-small, small, medium, large, x-large, and xx-large. In addition to these absolute font sizes, it is possible to use a relative size, such as 150% or equivalently 1.5em. This scales the font relative to the currently active font setting.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlink Pseudo-Classes===&lt;br /&gt;
&lt;br /&gt;
In addition to regular stylistic classes, there are special pseudo-classes for handling embedded hyperlinks. These are specified in the selector with the class starting with a colon rather than a dot. They are :link, :visited, and :active. These only apply to the &amp;lt;A&amp;gt; tag. The :link class applies to hyperlinks in their normal state. Once a link has been clicked, it belongs instead to the :visited class. When the user holds the mouse over a link, it temporarily belongs to the :active class. The only attribute that may change in an active or visited link is the text color.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Canvas Background Color===&lt;br /&gt;
&lt;br /&gt;
The background attribute is only relevant to the &amp;lt;BODY&amp;gt; context. It causes the entire terminal background to change color. When doing this, it is usually necessary to change the foreground colors of text or it may become unreadable. The various standard classes of output generated by Dream Seeker are presented in figure 11.22.&lt;br /&gt;
&lt;br /&gt;
Figure 11.22: System Colors&lt;br /&gt;
&lt;br /&gt;
system notice&lt;br /&gt;
&lt;br /&gt;
general notices from the client&lt;br /&gt;
system command echo	command echoing&lt;br /&gt;
system command expansion	command-line expansion list&lt;br /&gt;
system pager	pager messages&lt;br /&gt;
system irc	IRC command prefix&lt;br /&gt;
The value of the CLASS attribute may contain a list of classes separated by spaces. This permits client output to be in the `system' class as well as more specific ones. That allows you to change all of these colors in one shot if you are too lazy to change them each individually. For example, if you define a style sheet that changes the background color, you might need to redefine the various foreground colors like this:&lt;br /&gt;
&lt;br /&gt;
BODY {background: aqua; color: black}&lt;br /&gt;
.system {color: red; font-weight: bold}&lt;br /&gt;
.command {color: green}&lt;br /&gt;
In this example, the background color of the terminal will be aqua, normal text from the server will be black, and all output from the client will be bold and red, except echoed commands and expansion lists, which will be bold and green. The more specific .command rule is placed after the general .system rule so that its color takes precedence. This is how style sheets are composed--you write general rules first followed by any exceptions.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Style Rule Precedence===&lt;br /&gt;
&lt;br /&gt;
The order in which rules are specified is one of the factors that determines precedence of style sheet commands. The language is known as Cascading Style Sheets because of its ability to handle several layers of stylistic rules, intermingling the configurations of the user and the designer in an ordered fashion.&lt;br /&gt;
&lt;br /&gt;
Rules are selected by first finding all matching candidates for a given attribute in the current HTML tag being processed. If there is more than one, rules from a higher level style sheet take precedence over lower level ones. That means the basic user configurable settings in Dream Seeker are the lowest priority, followed by a style sheet in the user's .dms script file, followed by a style sheet from the designer's client.script setting, because that is the order in which these are read by the style sheet manager.&lt;br /&gt;
&lt;br /&gt;
Rules from the same style sheet are ordered by specificity. The selector SPAN.chat is more specific than .chat and .chat EM is more specific than EM. In general, the more classes referenced by a selector, the more specific it is. When that results in a tie, the selector with the greater number of tags takes precedence.&lt;br /&gt;
&lt;br /&gt;
Finally, if two rules about the same attribute come from the same sheet and have the same specificity, the final one to be defined takes precedence.&lt;br /&gt;
&lt;br /&gt;
In the rare event that a rule needs to break out of the normal order of precedence, it can be flagged as important. In this case it will take precedence over all other &amp;quot;unimportant&amp;quot; rules. However, if more than one rule is important, the normal rules of precedence will be used to resolve the conflict.&lt;br /&gt;
&lt;br /&gt;
The important flag is applied after the attribute assignment like this:&lt;br /&gt;
&lt;br /&gt;
BODY.background {&lt;br /&gt;
   background: white ! important;&lt;br /&gt;
   font: serif&lt;br /&gt;
}&lt;br /&gt;
In the above example, only the background color is important, not the font specification.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===The STYLE attribute===&lt;br /&gt;
&lt;br /&gt;
Style commands may also be inserted directly in an HTML tag to control its appearance. This does not have the advantages of independent style sheets, which separate content from presentation, but it does allow you to use the style sheet syntax when formatting text.&lt;br /&gt;
&lt;br /&gt;
The following example uses the style attribute to color some text:&lt;br /&gt;
&lt;br /&gt;
usr &amp;lt;&amp;lt; &amp;quot;That HURT!&amp;quot;&lt;br /&gt;
As you can see, the STYLE attribute of any tag can be assigned to a text string containing a list of attribute assignments. Just the body of the style rule is given, since no selector is needed to match the current context.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Inline Icons==&lt;br /&gt;
&lt;br /&gt;
The \icon text macro causes the following embedded expression to be interpreted as an icon rather than as text. For example, an object would be replaced by its icon rather than by its name.&lt;br /&gt;
&lt;br /&gt;
The following example prefixes conversational text with the speaker's icon, making it easier to associate the message with the appropriate object on the map.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
The \icon text macro expands internally to an &amp;lt;IMG&amp;gt; tag. The previous example, could be rewritten as follows:&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot; \&lt;br /&gt;
              [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
From this, you can see that the object's current icon state is used. A reference to the icon itself is inserted using the \ref text macro, which generates a unique identifier corresponding to an object.&lt;br /&gt;
&lt;br /&gt;
A final noteworthy point is that the image belongs to a style class called `icon'. This can be used to configure global properties of icons in the text terminal. For example, a full 32x32 pixel icon doesn't always fit in with surrounding text very well. A single style sheet rule takes care of that:&lt;br /&gt;
&lt;br /&gt;
IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
This is, in fact, a built-in default rule, so you don't have to define it yourself. You could override it to get full 32x32 icons. You could even define special rules to allow icons in certain contexts to be different sizes. The &amp;lt;BIG&amp;gt; and &amp;lt;SMALL&amp;gt; tags are ideal:&lt;br /&gt;
&lt;br /&gt;
BIG IMG.icon {height: 32px; width: 32px}&lt;br /&gt;
SMALL IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
Using the &amp;lt;BIG&amp;gt; tag, you could then output a full-sized icon, even though the default is small. The following example does that when the DM speaks in order to satisfy an inflated ego.&lt;br /&gt;
&lt;br /&gt;
mob/DM/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Special Effects==&lt;br /&gt;
&lt;br /&gt;
There are a couple miscellaneous commands which create special output effects. Like the image instruction, they produce a purely visual result.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===missile instruction===&lt;br /&gt;
&lt;br /&gt;
The missile instruction creates an image which moves from one location to another. It is often used as a symbolic indicator of the source and target of a projectile.&lt;br /&gt;
&lt;br /&gt;
missile	(Icon,Start,End)&lt;br /&gt;
Icon is the image icon or object type.&lt;br /&gt;
Start is the missile source.&lt;br /&gt;
End is the missile destination.&lt;br /&gt;
This could be used in a game of darts:&lt;br /&gt;
&lt;br /&gt;
obj/dart&lt;br /&gt;
   verb/throw(mob/M)&lt;br /&gt;
      missile(src,usr,M)&lt;br /&gt;
      del src&lt;br /&gt;
If more realism is desired, a check could be made first to determine if there is a straight unobstructed path between the attacker and target. (However, realism (in my opinion) is much overrated. Don't let it spoil a good piece of code unless you really have to. I am sure there are many cases in which our own universe too is unrealistic because God couldn't resist a simpler way of implementing things here and there. The sky is a perfect example. I mean, it looks a bit fake sometimes, doesn't it?)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===flick instruction===&lt;br /&gt;
&lt;br /&gt;
The flick instruction causes a temporary transition in the icon state of an object. It lasts until all the frames in that particular state have been played and then reverts to the true icon state.&lt;br /&gt;
&lt;br /&gt;
flick	(State,Obj)&lt;br /&gt;
State is the icon or icon state to display.&lt;br /&gt;
Obj is the target object.&lt;br /&gt;
Note that it is possible to specify an entirely different icon file. Normally, however, just the state of the existing icon file is specified.&lt;br /&gt;
&lt;br /&gt;
The flick instruction is often used for temporary animation sequences (like smiling, writhing in pain, etc.). These are different from changes of state which have a longer duration (like sleeping, flying, etc.). In those cases, one would simply assign the icon_state variable directly.&lt;br /&gt;
&lt;br /&gt;
Sometimes, however, a flick is used in the transition between two permanent states. The following example defines a door turf which does exactly that.&lt;br /&gt;
&lt;br /&gt;
turf/door&lt;br /&gt;
   icon = 'door.dmi'&lt;br /&gt;
   icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
   density = 1&lt;br /&gt;
   opacity = 1&lt;br /&gt;
   verb/open()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(!density) return //already open&lt;br /&gt;
      density = 0&lt;br /&gt;
      opacity = 0&lt;br /&gt;
      flick(&amp;quot;opening&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;open&amp;quot;&lt;br /&gt;
   verb/close()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(density) return //already closed&lt;br /&gt;
      density = 1&lt;br /&gt;
      opacity = 1&lt;br /&gt;
      flick(&amp;quot;closing&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
The advantage of using icon states in this way is that the code remains very general. All the map designer has to do is plug in different icons with the same states and a variety of doors can be made from the one basic definition.&lt;br /&gt;
&lt;br /&gt;
If the icon state specified by the flick instruction does not exist, it has no effect. In the above code, for example, a door icon could be used that did not have &amp;quot;opening&amp;quot; and &amp;quot;closing&amp;quot; states defined. Everything would work--only the transition would not be animated.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19469</id>
		<title>DM Guide 11</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19469"/>
		<updated>2015-11-14T20:31:19Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Verbs */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Это 11 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap11.html Оригинальная 11 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
{{Заготовка|url=http://www.byond.com/docs/guide/chap11.html}}&lt;br /&gt;
&lt;br /&gt;
=Глава 11=&lt;br /&gt;
&lt;br /&gt;
Ввод\вывод Пользователя &amp;lt;!--User Input/Output--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Взаимодействие с пользователем - это главная цель любых программ в Dream Maker и эта глава описывает основы языка, отвечающего за ввод и вывод информации. &lt;br /&gt;
&amp;lt;!--Interacting with the user is the ultimate purpose of any DM program. This chapter describes the elements of the language which make it possible. To come this far would have been impossible without a casual introduction to some of the input/output instructions, but even those have more power to offer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Ввод==&lt;br /&gt;
&lt;br /&gt;
Есть два основных пути получения информации от игрока. Первый - ввод по запросу клиента(игрока), второй - ввод по запросу сервера(игры). Разница в том, посылает ли игрок информацию на обработку, или игра запрашивает необходимую информацию.&lt;br /&gt;
&amp;lt;!--There are two basic ways of getting information from the player. One is client initiated and the other is server initiated input. The difference is in whether the player sends unsolicited input or whether the game asks for it. These will be discussed in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Операторы (verbs)===&lt;br /&gt;
&lt;br /&gt;
До сих пор весь ввод был со стороны пользователя. Игрок может написать команду, нажать кнопку управления, щёлкнуть на объект и т.д. Эти виды ввода информации однородны, так как ими управляют одинаковые операторы(verbs). То есть нажатие на кнопку влево вызывает определённый процесс и задаёт ему значение &amp;quot;кнопка влево&amp;quot;.&lt;br /&gt;
&amp;lt;!--All user input seen so far has come at the initiative of the user. The player may type a command, press a direction key, click an object, etc. These forms of input are all similar because they are ultimately handled by verbs. In the case of the direction keys and mouse clicks, players don't need to actually type any command--the client does it all. However, from the programmer's point of view, these are all the same: The player calls a procedure and possibly passes some arguments to it.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть несколько заранее определённых операторов(verbs), принимающих ввод информации от игрока. Это кнопки направления\стрелки (напр. client.North()), щелчок мыши ((client.Click() и client.DblClick()) и ссылки топиков (client.Topic()). Все остальные операторы(verbs) задаются программистом.&lt;br /&gt;
&amp;lt;!--The only pre-defined verbs are associated with the client data object. They are the direction keys (e.g. client.North()), mouse clicks (client.Click() and client.DblClick()), and topic links (client.Topic()). All other verbs are defined by the programmer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Общий вид для определения оператора(verb) следующий:&lt;br /&gt;
: verb/Name(Arg1 = default input-type in List,...)&lt;br /&gt;
&lt;br /&gt;
Количество аргументов может быть любым. Каждый из них может иметь значение по умолчанию, тип ввода и список допустимых значений.&lt;br /&gt;
&amp;lt;!--The general format for defining a verb includes any number of arguments. Each one may have a default value, an input type, and a list of possible values.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Инструкция ввода===&lt;br /&gt;
&lt;br /&gt;
Инструкция ввода - это то, что позволяет вам(со стороны игры) запросить у игрока информацию ввода. На ней построены все взаимоотношения сервера с клиентом. Она похожа на простой одиночный оператор(verb).&lt;br /&gt;
&amp;lt;!--The input instruction allows you to ask the player for information. This is how DM provides server-initiated input. It is similar to a single verb argument.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;gt;input(User=usr,Message,Title,Default) input	(User,Query,Title,Default) as input-type in List&lt;br /&gt;
&lt;br /&gt;
User - это имя игрока(моба).&lt;br /&gt;
Query - текст запроса ввода.&lt;br /&gt;
Title - текст отображения запроса ввода.&lt;br /&gt;
Default - значение по умолчанию для данного запроса.&lt;br /&gt;
input-type - тип ввода информации.&lt;br /&gt;
List - список возможных значений для данного запроса.&lt;br /&gt;
Исполнение данного оператора задаёт значение введённое игроком. &amp;lt;!--Returns value entered by player.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Всё, кроме текста ввода - необязательные опциональные параметры. User ассоциируется с usr, и обращается к нему.&lt;br /&gt;
Если input type не задано, то тип ввода информации будет текстовым по умолчанию.&lt;br /&gt;
&amp;lt;!--All but the input text itself are optional parameters. User defaults to the current usr, which is usually the desired target. If no input type or possible value list is specified, the default input type is text. Otherwise, the input type defaults to accept anything in the supplied list, which contains the only values the user is allowed to enter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Обратите внимание, что инструкция ввода не будет запрошена, пока пользователь не введёт значение. При поддержки многопользовательской системы ожидать ответа от одного пользователя невозможно, поэтому при запросе ввода информации в режим ожидания входит только текущая исполняемая процедура.&lt;br /&gt;
&amp;lt;!--Note that the input instruction does not return until the user has entered a value. Since the entire multi-user system cannot halt while waiting for this to happen, only the current procedure waits. More will be said on the subject of multi-tasking in chapter 13.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One case in which the input instruction proves useful is when something happens in the game that the player needs to respond to. A verb would be too open-ended for the task, making it difficult for the player to guess what to do next.&lt;br /&gt;
&lt;br /&gt;
The following code, for example, handles a rather sad event in the life of a player.&lt;br /&gt;
&lt;br /&gt;
mob/proc/Die()&lt;br /&gt;
   if(!key) //NPC&lt;br /&gt;
      del src&lt;br /&gt;
   else     //PC&lt;br /&gt;
      loc = null  //vacate the scene&lt;br /&gt;
      var/again = input(&amp;quot;Play Again?&amp;quot;) in list(&amp;quot;yes&amp;quot;,&amp;quot;no&amp;quot;)&lt;br /&gt;
      if(again == &amp;quot;yes&amp;quot;)&lt;br /&gt;
         Login() //back to square one!&lt;br /&gt;
      else&lt;br /&gt;
         del src&lt;br /&gt;
When the Die() proc is called, players are asked if they would like to play again. If they do, they are logged in again, presumably to start over. Otherwise, they are deleted (and logged out).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Output==&lt;br /&gt;
&lt;br /&gt;
All output is generated by the &amp;lt;&amp;lt; operator. This sends the specified output to one or more players.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Output&lt;br /&gt;
The target may be a single object or a list of objects. Any non-mob target will be replaced by its contents. This allows you to send output to a region on the map or to a room, and all the players inside will receive it.&lt;br /&gt;
&lt;br /&gt;
There are several different types of output. In many cases, the way the output should be handled is automatically detected from the type of data provided. Several instructions for producing various types of output are listed in the following table. In addition to these instructions are some which further clarify how the output should be treated when the type of data alone is not enough to determine this.&lt;br /&gt;
&lt;br /&gt;
Figure 11.16: Output Methods&lt;br /&gt;
&lt;br /&gt;
text()&lt;br /&gt;
&lt;br /&gt;
file()&lt;br /&gt;
image()&lt;br /&gt;
browse()&lt;br /&gt;
sound()&lt;br /&gt;
ftp()&lt;br /&gt;
run()&lt;br /&gt;
link()&lt;br /&gt;
The first group of instructions produce various types of data for output or other purposes. The second group are only meaningful for directly producing output. All of these instructions are described individually in the following sections. The general format for using them is the same.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Method(Output)&lt;br /&gt;
&lt;br /&gt;
===text output===&lt;br /&gt;
&lt;br /&gt;
A text output value is displayed in the client's scrolling terminal window. The text value may be the result of any expression. Frequently, it is a text string with embedded expressions inside it. Although it is not necessary to use the text instruction for this purpose, one reason for doing so is to use trailing rather than directly embedded expressions.&lt;br /&gt;
&lt;br /&gt;
text	(Text,Arg1,Arg2,...)&lt;br /&gt;
Text is the text string with expression markers.&lt;br /&gt;
Args are the expressions to insert.&lt;br /&gt;
Returns text with arguments substituted in.&lt;br /&gt;
The position in the text where a trailing argument will be inserted is marked with empty brackets [ ]. The substitution arguments are then listed in the same order as the expression markers.&lt;br /&gt;
&lt;br /&gt;
For substituting short expressions into the text, it is convenient to simply embed them directly. However, many lengthy expressions embedded into a text string can make it difficult to read. In that case, trailing expressions may be the better choice. The two methods can be mixed as desired.&lt;br /&gt;
&lt;br /&gt;
The following two versions of a look verb are equivalent.&lt;br /&gt;
&lt;br /&gt;
mob&lt;br /&gt;
   var/money = 2&lt;br /&gt;
&lt;br /&gt;
   verb/look1()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;[src] has [contents.len] items and [money] buffalo chips.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   verb/look2()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; text(&amp;quot;[src] has [] items and [] buffalo chips.&amp;quot;,&lt;br /&gt;
                   contents.len,&lt;br /&gt;
                   money)&lt;br /&gt;
Note that the text instruction is not limited to being used as an output method. It may be used anywhere you wish to use trailing expressions with a text string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===browse output===&lt;br /&gt;
&lt;br /&gt;
The browse output method displays text output in a pop-up window. This is intended for viewing longer text documents. If treated as normal terminal output instead, the user might have to scroll back up to find the top of the message.&lt;br /&gt;
&lt;br /&gt;
browse	(Doc, Options)&lt;br /&gt;
Doc is the message to display.	Options are various window-specific options. Consult the reference for specifics.&lt;br /&gt;
By default, each message replaces any previous message being displayed but the user can move back to previous messages stored in the client's memory. In many ways, the client terminal behaves like a telnet session and the browse window behaves like a web browser. One displays output sequentially in a continuous stream. The other displays it in discrete chunks--one document after another. The two are each useful in different situations.&lt;br /&gt;
&lt;br /&gt;
The document is often a text string. However, it may be a file instead. The type of file will determine how it is handled. Files may reside in the resource cache or in the file system. As always, cached items may be specified by putting the file name in single quotes. An external file, on the other hand, is indicated using the file instruction described in section 11.2.7.&lt;br /&gt;
&lt;br /&gt;
The browse output method is often used in conjunction with the message input type. One allows the composition of messages and the other displays them.&lt;br /&gt;
&lt;br /&gt;
The following example defines a message scroll. Players can write poetry on it in moments of inspiration.&lt;br /&gt;
&lt;br /&gt;
obj/scroll/verb&lt;br /&gt;
   write(msg as message)&lt;br /&gt;
      desc = msg&lt;br /&gt;
   read()&lt;br /&gt;
      usr &amp;lt;&amp;lt; browse(desc)&lt;br /&gt;
&lt;br /&gt;
===sound output===&lt;br /&gt;
&lt;br /&gt;
The sound output method plays a sound to the player. Either wav or midi sound files may be used, usually for short noises and music respectively. Such files are treated this way by default, but the sound instruction can be used to control how the sound is played.&lt;br /&gt;
&lt;br /&gt;
sound	(File,Repeat)&lt;br /&gt;
File is the sound file to play.&lt;br /&gt;
Repeat is 1 to play sound repeatedly.&lt;br /&gt;
A repeated sound is played in the background while other sounds are played in the foreground. Only one background sound and one foreground sound may be played at a time, so subsequent output replaces any previous sound with the same repeat setting. To stop a sound, specify null as the file.&lt;br /&gt;
&lt;br /&gt;
Background music is often repeated while occasional noises play in the foreground. The following example defines a background sound for each area.&lt;br /&gt;
&lt;br /&gt;
area&lt;br /&gt;
   var/music = 'default.midi'&lt;br /&gt;
   Enter()&lt;br /&gt;
      . = ..()&lt;br /&gt;
      if(.) usr &amp;lt;&amp;lt; sound(music,1)&lt;br /&gt;
The line . = ..() is commonly used when you want to return the same value as the parent proc but you need to do something after finding out what that value is. That way, if the user is refused access to the area for some reason, the music will not be played.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===image output===&lt;br /&gt;
&lt;br /&gt;
The image instruction is used to create a purely virtual object. It may appear at the specified location to selected players, but it corresponds to no real data object.&lt;br /&gt;
&lt;br /&gt;
image	(Icon,Loc)&lt;br /&gt;
Icon is the icon or object type to use.&lt;br /&gt;
Loc is the location of the image.&lt;br /&gt;
Returns a reference to the image.&lt;br /&gt;
If the location of the image is something movable like a mob, it will follow the object around. The image icon is displayed in a layer above everything else, so it is best suited for special effects like a selection box, burst of fire, etc.&lt;br /&gt;
&lt;br /&gt;
The image instruction may be used outside the context of the output instruction. In this case it returns a reference to the image but does not actually display the image to any players. This reference can be sent as output and may be deleted later to destroy the image.&lt;br /&gt;
&lt;br /&gt;
The following example allows the player to select an enemy by clicking on it. The currently selected enemy is outlined with an image.&lt;br /&gt;
&lt;br /&gt;
mob/var&lt;br /&gt;
   mob/enemy&lt;br /&gt;
   enemy_marker&lt;br /&gt;
&lt;br /&gt;
client/Click(mob/M)&lt;br /&gt;
   if(istype(M))&lt;br /&gt;
      del usr.enemy_marker&lt;br /&gt;
      usr.enemy = M&lt;br /&gt;
      usr.enemy_marker = image('outline.dmi',M)&lt;br /&gt;
      usr &amp;lt;&amp;lt; usr.enemy_marker&lt;br /&gt;
The code works by first deleting any old enemy marker. A new one is then made and displayed to the user. No one else will see the image--only the player who clicked on the enemy.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===ftp output===&lt;br /&gt;
&lt;br /&gt;
The ftp output method sends a file to the player. This complements the file input type which allows the player to send a file to the server. The terminology normally used is that a file is uploaded when it is input and downloaded when it is output.&lt;br /&gt;
&lt;br /&gt;
ftp	(File,Name)&lt;br /&gt;
File is the file to send.&lt;br /&gt;
Name is the optional suggested file name.&lt;br /&gt;
The file to send may be either a resource file (in the cache) or a file in the file system. The difference is whether the file is specified in single or double quotes. A file in single quotes will be loaded into the resource cache at compile-time. A file in double quotes will be accessed from the file system (i.e. hard-disk) at run-time. The latter might be useful if you need to update the file periodically without recompiling.&lt;br /&gt;
&lt;br /&gt;
The suggested file name defaults to the name of the file being sent. This is used as the default name when the player chooses where to store the file. If the player decides not to download the file, it is always possible to cancel at that point or during the transfer.&lt;br /&gt;
&lt;br /&gt;
The following example sends a help file to players when they click on the appropriate topic.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; ftp(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
mob/Login()&lt;br /&gt;
   ..()&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;Download the  help file  if you are new here.&amp;quot;&lt;br /&gt;
For this to work, the file &amp;quot;help.txt&amp;quot; must exist in the current directory of the server. This can be assured by putting it in the same place as the dmb file. Since the file was specified in double quotes, it will be accessed at run-time rather than compile-time. That means you are free to edit it at a later date.&lt;br /&gt;
&lt;br /&gt;
The HTML tag &amp;lt;A HREF...&amp;gt; is used to embed a hyperlink in some output text. It will be described in section 11.4.3.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===run file output===&lt;br /&gt;
&lt;br /&gt;
The run output method is like ftp except it displays or executes the specified file rather than saving it to disk. The action taken depends on the type of file. For example, HTML and jpeg files might be shown in the player's web browser.&lt;br /&gt;
&lt;br /&gt;
run(File)&lt;br /&gt;
Obviously it would be a severe security risk to players if executable files could be run without their authorization. Viruses and other malicious programs could be released onto their computer just by connecting to a game. For this reason, players are asked before executing any potentially dangerous file. That is the default behavior. The player can configure the client to always or never run files if they choose. A similar choice can be made about downloading files.&lt;br /&gt;
&lt;br /&gt;
The previous example which gave the player a help file could easily be changed to instead display the file. If the player wishes, it would still be possible to save the file to disk.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; run(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===file output===&lt;br /&gt;
&lt;br /&gt;
The file instruction returns a reference to a file object. It takes the file's path (in a text string) as an argument. The output methods browse, ftp, and run can all take a file reference as an argument. In the case of browse it is necessary to use file to distinguish between a text message and a file name. In the case of ftp and run it is not necessary to use file because the name of the file may simply be used directly. If no output method is specified for a file, it is implicitly handled by run.&lt;br /&gt;
&lt;br /&gt;
file	(Path)&lt;br /&gt;
Path is the name of the file.&lt;br /&gt;
Returns a reference to the file.&lt;br /&gt;
The path may be absolute or relative to the server's working directory, which is the same directory that contains the world .dmb file. Since this is evaluated at run-time, the file need not exist until the statement is actually executed. This is different from cache file references (in single quotes) which are evaluated at compile-time. For more uses of the file object, see section 17.6.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===link output===&lt;br /&gt;
&lt;br /&gt;
The link output method is like run except it executes a URL rather than a file. The URL could be a web address, a BYOND address, or a topic link.&lt;br /&gt;
&lt;br /&gt;
link	(url)&lt;br /&gt;
url is the URL to execute.&lt;br /&gt;
The beginning of the URL specifies the communication protocol. If the URL begins with &amp;quot;byond://&amp;quot; then it is treated as a BYOND address. This is the default protocol if none is specified. A URL beginning with &amp;quot;#&amp;quot; is a topic link. Other protocols (like &amp;quot;http://&amp;quot; are handled by the player's web browser.&lt;br /&gt;
&lt;br /&gt;
A BYOND link causes the player's client to reconnect to the specified address. Topic links merely cause the specified topic to be accessed in the current world (by calling client.Topic()). A web link causes the web browser to switch to the specified URL.&lt;br /&gt;
&lt;br /&gt;
The general format for a BYOND address includes a server address and topic.&lt;br /&gt;
&lt;br /&gt;
byond://server#topic&lt;br /&gt;
The topic is optional and is only used in rare cases like servers with multiple entry points. The server address may be either the name of a registered server or the network address in the form ip:port. The IP address would either be raw network numbers (e.g. 123.456.789.123) or the corresponding machine name (e.g. dantom.com). The port number is the network port on which the server is running. This is reported when the server starts up.&lt;br /&gt;
&lt;br /&gt;
By default, players are asked whether they accept links activated in this manner. They can, however, configure the client to always or never accept them.&lt;br /&gt;
&lt;br /&gt;
The link output method is very similar to the hyperlink text tag which has already been introduced. They both can take the same types of URLs and act upon them in the same manner. Hyperlinks embedded in text are normally used to provide access to optional information. The link output method, on the other hand, is useful when the player's action has already indicated desire to follow the link.&lt;br /&gt;
&lt;br /&gt;
For example, a link from one world to another could be activated by entrance into a special turf.&lt;br /&gt;
&lt;br /&gt;
turf/wormhole/Enter()&lt;br /&gt;
   usr &amp;lt;&amp;lt; link(&amp;quot;byond://WormWorld&amp;quot;)&lt;br /&gt;
   return 1&lt;br /&gt;
This example assumes the existence of a world registered under the name &amp;quot;WormWorld&amp;quot;. Running and registering a networked world will be discussed in chapter 12.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Macros==&lt;br /&gt;
&lt;br /&gt;
Both input and output text may contain special codes that are not displayed literally but which are replaced by some other text. These are called text macros and begin with a backslash \ and may end with a space (which is ignored). They are summarized in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Expression Modifiers===&lt;br /&gt;
&lt;br /&gt;
Figure 11.17: Text Macros for use with Expressions&lt;br /&gt;
&lt;br /&gt;
\the, \The&lt;br /&gt;
&lt;br /&gt;
definite article if needed&lt;br /&gt;
\a, \an, \A, \An	indefinite article if needed&lt;br /&gt;
\he, \He, \she, \She	he, she, they, it&lt;br /&gt;
\his, \His	his, her, their, its&lt;br /&gt;
\hers	his, hers, theirs, its&lt;br /&gt;
\him	him, her, them, it&lt;br /&gt;
\himself, \herself	himself, herself, themself, itself&lt;br /&gt;
\th	1st, 2nd, 3rd, ...&lt;br /&gt;
\s	1 dog, 2 dogs, ...&lt;br /&gt;
The first group of text macros work in conjunction with an embedded expression. The article macros precede the expression and the others follow it. Any amount of text and even inapplicable expressions may exist between the macro and its associated expression.&lt;br /&gt;
&lt;br /&gt;
The articles and various pronouns work with object or text expressions. The plural and ordinal macros \s and \th are used with numerical expressions. If no expression of the appropriate type is found, these macros do nothing.&lt;br /&gt;
&lt;br /&gt;
An embedded object is replaced by a definite article and its name. In other words, the following two are equivalent:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] smiles.&amp;quot;&lt;br /&gt;
&amp;quot;\The [usr] smiles.&amp;quot;&lt;br /&gt;
These could produce &amp;quot;Andrew smiles.&amp;quot; or &amp;quot;The cat smiles.&amp;quot; depending on the name of the user.&lt;br /&gt;
&lt;br /&gt;
Note that the articles may be supplied in either capitalized or lowercase form. The implicit definite article is automatically chosen in capital form if preceded by a period. If that is incorrect, you can specify the desired form explicitly.&lt;br /&gt;
&lt;br /&gt;
If an indefinite article is desired instead of the default definite one, it must be explicitly specified. If no article at all is desired, the name can be embedded directly in place of the object.&lt;br /&gt;
&lt;br /&gt;
The following example uses an indefinite article instead of a definite one when a mob picks up an object.&lt;br /&gt;
&lt;br /&gt;
obj/verb/get()&lt;br /&gt;
   set src in view(0)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] picks up \a [src].&amp;quot;&lt;br /&gt;
   Move(usr)&lt;br /&gt;
It doesn't matter whether you use &amp;quot;a&amp;quot; or &amp;quot;an&amp;quot; in the macro. The appropriate one will be chosen for the word that follows. It is common to use whichever one makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Proper Nouns====&lt;br /&gt;
&lt;br /&gt;
There are two special text macros for controlling whether the name of an object is considered to be a proper noun or not. These are \proper and \improper. By default, if the object name is capitalized, it is assumed to be proper, and otherwise it is assumed to be improper. To override this, you can put \proper or \improper at the beginning of the object's name.&lt;br /&gt;
&lt;br /&gt;
As you have seen in the preceding section, the difference between proper and improper nouns is that articles are suppressed in front of proper nouns. For example, if you had something called a &amp;quot;BYOND dime,&amp;quot; you would need to use the \improper macro as follows:&lt;br /&gt;
&lt;br /&gt;
obj/BD&lt;br /&gt;
   name = &amp;quot;\improper BYOND dime&amp;quot;&lt;br /&gt;
mob/verb/get(obj/O in view(0))&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;You pick up \an [O].&amp;quot;&lt;br /&gt;
   O.Move(usr)&lt;br /&gt;
Since we used \improper in this example, somebody picking up a BYOND dime would see, &amp;quot;You pick up a BYOND dime.&amp;quot; rather than &amp;quot;You pick up BYOND dime.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Numerical Expressions====&lt;br /&gt;
&lt;br /&gt;
There are macros which depend upon the preceding numerical expression. The \th macro produces the ordinal ending for the supplied number. For the number 1, it produces &amp;quot;st&amp;quot; to make &amp;quot;1st&amp;quot;, for the number 2, &amp;quot;nd&amp;quot; and so on. From 4 and on it produces &amp;quot;th&amp;quot;, which is where it gets its name.&lt;br /&gt;
&lt;br /&gt;
The \s macro produces &amp;quot;s&amp;quot; if the preceding numerical expression is not equal to 1 and nothing otherwise. This is useful for making plurals like &amp;quot;You have [count] coin\s.&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Special Characters===&lt;br /&gt;
&lt;br /&gt;
Figure 11.18: Special Character Macros&lt;br /&gt;
&lt;br /&gt;
\&amp;quot;&lt;br /&gt;
&lt;br /&gt;
double quote&lt;br /&gt;
\\	backslash&lt;br /&gt;
\&amp;lt;	less than&lt;br /&gt;
\&amp;gt;	greater than&lt;br /&gt;
\&amp;amp;	ampersand&lt;br /&gt;
\n	newline&lt;br /&gt;
\...	suppress newline at end&lt;br /&gt;
\(space)	skip a space&lt;br /&gt;
There are a few special characters that may not be directly entered into a text string. These must be escaped by preceding them with a backslash. This forces the special meaning to be ignored and the literal character to be inserted instead.&lt;br /&gt;
&lt;br /&gt;
The double quote, for example, must be escaped or it would prematurely end the text string.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] says, \&amp;quot;[msg]\&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Newlines====&lt;br /&gt;
&lt;br /&gt;
A newline may be inserted with the \n macro. The compiler does not allow direct insertion of newlines in a text string because this is often a mistake resulting from a missing end quote. You can continue a lengthy text string onto the next line by escaping the newline, but then the newline is entirely ignored.&lt;br /&gt;
&lt;br /&gt;
There is an implicit newline inserted at the end of all output text. This means that instead of using the \n macro directly, the text can simply be broken up into individual lines which are output one at a time.&lt;br /&gt;
&lt;br /&gt;
In some cases, you may want to suppress the implicit newline at the end of the text. This can be done with the \... macro. By putting it at the end of the text, subsequent output will start on the same line where the previous one left off.&lt;br /&gt;
&lt;br /&gt;
A newline is actually an end-of-paragraph marker. It should not be used inside the paragraph to make lines fit the screen because not everyone's terminal will be the same width. It is best to let the terminal automatically handle word-wrap within paragraphs and reserve the newline for marking the end of it.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Formatting Tags==&lt;br /&gt;
&lt;br /&gt;
Text may be formatted by inserting HTML elements, more commonly known as tags, that control its appearance. DM understands a subset of HTML tags, consisting of the most commonly used elements.&lt;br /&gt;
&lt;br /&gt;
A tag is surrounded by &amp;lt; &amp;gt; angle brackets. The first thing inside the brackets is the name of the tag. Many tags come in pairs--one to start an effect and another to end it. The end tag has the same name as the start tag except it starts with `/'. Tag names are not case sensitive.&lt;br /&gt;
&lt;br /&gt;
The following example displays some text in bold.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;I am very mad!&amp;quot;&lt;br /&gt;
The start tag &amp;lt;B&amp;gt; turns on bold lettering and &amp;lt;/B&amp;gt; turns it off. For a complete list of tags understood by DM, see page 3 in the appendix. The most commonly used ones are listed in figure 11.19 for easy reference.&lt;br /&gt;
&lt;br /&gt;
Figure 11.19: Common text tags&lt;br /&gt;
&lt;br /&gt;
&amp;lt;A&amp;gt;&amp;lt;/A&amp;gt;&lt;br /&gt;
&lt;br /&gt;
anchor (for hyperlinks)&lt;br /&gt;
&amp;lt;B&amp;gt;&amp;lt;/B&amp;gt;	bold&lt;br /&gt;
&amp;lt;BIG&amp;gt;&amp;lt;/BIG&amp;gt;	bigger text&lt;br /&gt;
&amp;lt;BR&amp;gt;	line break&lt;br /&gt;
&amp;lt;FONT&amp;gt;&amp;lt;/FONT&amp;gt;	font face, size, and color&lt;br /&gt;
&amp;lt;I&amp;gt;&amp;lt;/I&amp;gt;	italic&lt;br /&gt;
&amp;lt;P&amp;gt;&amp;lt;/P&amp;gt;	paragraph&lt;br /&gt;
&amp;lt;S&amp;gt;&amp;lt;/S&amp;gt;	overstrike&lt;br /&gt;
&amp;lt;SMALL&amp;gt;&amp;lt;/SMALL&amp;gt;	smaller text&lt;br /&gt;
&amp;lt;TT&amp;gt;&amp;lt;/TT&amp;gt;	typewriter style&lt;br /&gt;
&amp;lt;U&amp;gt;&amp;lt;/U&amp;gt;	underline&lt;br /&gt;
&amp;lt;PRE&amp;gt;&amp;lt;/PRE&amp;gt;	preformatted whitespace&lt;br /&gt;
&amp;lt;XMP&amp;gt;&amp;lt;/XMP&amp;gt;	literally preformatted text&lt;br /&gt;
&amp;lt;BEEP&amp;gt;&lt;br /&gt;
&lt;br /&gt;
make a beeping sound&lt;br /&gt;
&lt;br /&gt;
===Whitespace===&lt;br /&gt;
&lt;br /&gt;
Whitespace refers to any spaces, tabs, or newlines. In standard HTML, whitespace serves merely to delimit words. The amount of space and whether it is a tab, space, or newline is irrelevant.&lt;br /&gt;
&lt;br /&gt;
DM processes whitespace like standard HTML when it is inside of a pair of start and end tags. So, for example, inside of &amp;lt;P&amp;gt; and &amp;lt;/P&amp;gt;, the paragraph markers, standard HTML rules are in effect; newlines, spaces, and tabs serve merely to delimit words. Note that an entire document could be surrounded by &amp;lt;HTML&amp;gt; and &amp;lt;/HTML&amp;gt; to mark the whole thing as standard HTML.&lt;br /&gt;
&lt;br /&gt;
Outside of all HTML tags, DM handles whitespace a little differently. Spaces still delimit words, but newlines (embedded with \n) mark the end of lines. In other words, the newline is automatically converted to &amp;lt;BR&amp;gt;, the linebreak tag. That is convenient for use in messages composed by players when it would be annoying to write formal HTML with paragraph tags and so forth.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;FONT&amp;gt; tag is used to control various characteristics of the font being used. It takes additional arguments in the form of attributes.&lt;br /&gt;
&lt;br /&gt;
For example, to make the font much bigger, you could use the start tag &amp;lt;FONT SIZE=+3&amp;gt;. The name of the attribute in this case is SIZE, and its value is +3, which makes the font three sizes bigger. You can put quotes around the attribute value if it contains any spaces. In this case there was no need.&lt;br /&gt;
&lt;br /&gt;
The attributes of &amp;lt;FONT&amp;gt; are FACE, SIZE, and COLOR. You can use as many of these attributes in one tag as you like. Just separate each attribute assignment by some space like this: &amp;lt;nowiki&amp;gt;&amp;lt;FONT SIZE=+3 COLOR=red&amp;gt;&amp;lt;/nowiki&amp;gt;. The nuances of these three tags are discussed in the following individual sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FACE attribute====&lt;br /&gt;
&lt;br /&gt;
The FACE attribute selects the name of the font you wish to use. It may be a single font (such as InnoDBl) or a comma-separated list (such as InnoDBl,Helvetica). If the user doesn't have a font with the same name on their system, the next font will be tried. Remember to put quotes around the attribute value if it contains any spaces.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====SIZE attribute====&lt;br /&gt;
&lt;br /&gt;
The SIZE attribute changes the size of the text. It can be a relative change, like +3, or an absolute size, such as 5. Font sizes are numbered from 1 to 7, with 1 being the smallest and 7 being the largest. Each increment is roughly 1.5 times the apparent size of the previous one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====COLOR attribute====&lt;br /&gt;
&lt;br /&gt;
The COLOR attribute selects the foreground color of the text. It may be either a color name or a hexadecimal RGB value.&lt;br /&gt;
&lt;br /&gt;
RGB stands for red, green, and blue, the three primary colors from which all the others can be produced. Hexadecimal is a base-16 number system commonly used by programmers for specifying binary values. The hexadecimal digits are 0 to 9 and A to F, a full four bits of information. Lowercase letters may be used as well.&lt;br /&gt;
&lt;br /&gt;
Each primary color is given a range of eight bits. Therefore it takes exactly two hexadecimal digits to specify a single component and six digits to specify a complete color value. The first two digits are for red; the next two are for green; and the last two are for blue (hence RGB). The color black is 000000, which has all three colors turned off. The color white is FFFFFF with all three colors at their maximum intensity.&lt;br /&gt;
&lt;br /&gt;
The following two lines are identical:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
Notice that a # symbol is placed in front of the numeric color value to indicate that it is a hexadecimal value. Otherwise, a color name is expected. If you can't find the color you want in the list of named colors, find the closest one and tweak the intensities to your satisfaction.&lt;br /&gt;
&lt;br /&gt;
Figure 11.20: Named Colors&lt;br /&gt;
&lt;br /&gt;
black&lt;br /&gt;
&lt;br /&gt;
#000000&lt;br /&gt;
silver	#C0C0C0&lt;br /&gt;
grey	#808080&lt;br /&gt;
white	#FFFFFF&lt;br /&gt;
maroon&lt;br /&gt;
&lt;br /&gt;
#800000&lt;br /&gt;
red	#FF0000&lt;br /&gt;
purple	#800080&lt;br /&gt;
fuchsia	#FF00FF&lt;br /&gt;
green&lt;br /&gt;
&lt;br /&gt;
#00C000&lt;br /&gt;
lime	#00FF00&lt;br /&gt;
olive	#808000&lt;br /&gt;
yellow	#FFFF00&lt;br /&gt;
navy&lt;br /&gt;
&lt;br /&gt;
#000080&lt;br /&gt;
blue	#0000FF&lt;br /&gt;
teal	#008080&lt;br /&gt;
aqua	#00FFFF&lt;br /&gt;
It is also possible to enter color components as 4 rather than 8 bit numbers. In that case, only three hexadecimal digits are required rather than six. Internally, the color is converted to full 8 bit notation by repeating each digit. For example, black #000 becomes #000000, white #FFF becomes #FFFFFF, and red #F00 becomes FF0000.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlinks===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;A&amp;gt; tag is used to mark a particular spot (or anchor) in the text. In DM, you use it to insert a clickable hyperlink. To specify the destination URL of a link, use the HREF attribute.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;lt;A HREF='#topic'&amp;gt; click here &amp;lt;/A&amp;gt; ...&amp;quot;&lt;br /&gt;
The form of the URL is the same as the link output method described in section 11.2.8. It may be either a BYOND address, a topic link, or a web address.&lt;br /&gt;
&lt;br /&gt;
The TITLE attribute may be assigned to a description of the link. It is made visible when the user holds the mouse over the link.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Style Sheets==&lt;br /&gt;
&lt;br /&gt;
HTML tags, such as &amp;lt;FONT&amp;gt; may be used to directly format output text. Another approach, however, is to use HTML tags to specify purely structural information and use a style sheet to define how various elements within that structure should be treated. DM uses a subset of the Cascading Style Sheet (CSS) language, which was introduced for this purpose in HTML documents.&lt;br /&gt;
&lt;br /&gt;
As an example of a style sheet, suppose one wanted combat and conversational messages to appear differently--perhaps using different colors. Instead of using the &amp;lt;FONT&amp;gt; tag to color the text, you could use &amp;lt;SPAN&amp;gt; to mark the beginning and ending of the text and to specify what kind of message it is. The result might be text such as the following:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] spanks [targ]!&amp;quot;&lt;br /&gt;
&amp;quot;[usr] says, '[msg]'&amp;quot;&lt;br /&gt;
The CLASS attribute may be used with any tag, but the generic containers SPAN and DIV are often convenient because they have no other side-effect. &amp;lt;SPAN&amp;gt; is for text within a single paragraph and &amp;lt;DIV&amp;gt; is for whole paragraphs. The way text belonging to a particular class is formatted may be controlled in a style sheet such as the following:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This says that text in the `combat' class should be colored red and text in the `chat' class should be colored green. These classes are not pre-defined; they were just made up to suit the situation. You can invent as many new classes as you like.&lt;br /&gt;
&lt;br /&gt;
In order to make this style sheet take effect you have several options. One is to put it in a text string (double quotes) and assign it to client.script. This will load the style sheet when the player connects. You could accomplish the same thing by putting the style sheet in a file and assigning the file (in single quotes) to client.script. It is also possible for a player to put the style sheet in a client-side script file and load it that way. More will be said about DM Script, which encompasses more than just style sheets, in the appendix (page [4]).&lt;br /&gt;
&lt;br /&gt;
The advantage of using style sheets instead of direct formatting tags is that you can cleanly separate structural information (such as combat and conversational messages) from formatting information (such as red and green text). By separating the two, you or the player can easily plug in different formatting schemes without changing any of the actual content.&lt;br /&gt;
&lt;br /&gt;
A style sheet is composed of a list of rules, such as the two rules in the preceding example. Each rule contains one or more selectors followed by a body of attribute assignments (in braces). The selector specifies the context of the rule and the body specifies the format.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Context Selectors===&lt;br /&gt;
&lt;br /&gt;
A selector may specify a container tag (such as SPAN, BODY, or P) and a class. The above example could have been written with a selector of SPAN.chat. However, by leaving out the tag, it applies to any tag with CLASS=chat. It is also possible to only specify the tag and not the class. In that case, the selector applies to any matching tag, regardless of its class.&lt;br /&gt;
&lt;br /&gt;
To specify a nested context, several simple selectors may be listed one after the other. For example, emphasized text within a combat message could be enlarged with the following rule:&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
It is also possible to list several selectors separated by commas in order to make them all apply to the same body. For example, this next rule is equivalent to the two following ones:&lt;br /&gt;
&lt;br /&gt;
.combat EM, .chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
.chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
===Style Attributes===&lt;br /&gt;
&lt;br /&gt;
The body of a style rule contains a list of attribute assignments, delimited by semicolons. Each assignment takes the form of an attribute name, followed by a colon, followed by the value of the attribute. Figure 11.21 summarizes the recognized attributes and sample values.&lt;br /&gt;
&lt;br /&gt;
Figure 11.21: Style Attributes&lt;br /&gt;
&lt;br /&gt;
color&lt;br /&gt;
&lt;br /&gt;
#F00, #FF000, red&lt;br /&gt;
background	same as color&lt;br /&gt;
font-size	10pt, 1.5em, 150%&lt;br /&gt;
font-style	normal or italic&lt;br /&gt;
font-weight	normal, bold, lighter, darker, or 100 to 900&lt;br /&gt;
font-family	monospace, sans-serif, serif, cursive, ...&lt;br /&gt;
font	style weight size family&lt;br /&gt;
text-decoration	none or underline&lt;br /&gt;
text-align	left, right, or center&lt;br /&gt;
width	16px, 32px, auto&lt;br /&gt;
height	16px, 32px, auto&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The font family may be a specific font name or a more general category such as monospace or sans-serif. Since not all users necessarily have the same fonts installed, it is a good idea to list alternate fonts. The desired font is placed first, followed by other possible fall-backs, each separated by a comma. Usually a general family such as monospace is listed last of all. Any font names containing a space should be enclosed in quotes.&lt;br /&gt;
&lt;br /&gt;
The font attribute is a special short-hand for assigning font-size, font-style, font-weight, and font-family in one statement. Any properties that are not specified in the font statement are assigned to their default values.&lt;br /&gt;
&lt;br /&gt;
The following example sets the font for the &amp;lt;BODY&amp;gt; tag. Even if you don't explicitly use &amp;lt;BODY&amp;gt; in output text, it is applied implicitly.&lt;br /&gt;
&lt;br /&gt;
BODY {font: 12pt 'Times New Roman', sans-serif}&lt;br /&gt;
This sets the font to 12 point and selects Times New Roman if it is available and otherwise falls back on a system-determined sans-serif font. This command also implicitly specifies not to use italics and normal font weight (not bold).&lt;br /&gt;
&lt;br /&gt;
Font sizes may be specified in points (1pt = 1/72 of an inch), picas (1pc = 12pt), pixels (px), inches (in), centimeters (cm), and millimeters (mm). There are also various levels corresponding to the traditional 1 to 7 HTML scale. These are xx-small, x-small, small, medium, large, x-large, and xx-large. In addition to these absolute font sizes, it is possible to use a relative size, such as 150% or equivalently 1.5em. This scales the font relative to the currently active font setting.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlink Pseudo-Classes===&lt;br /&gt;
&lt;br /&gt;
In addition to regular stylistic classes, there are special pseudo-classes for handling embedded hyperlinks. These are specified in the selector with the class starting with a colon rather than a dot. They are :link, :visited, and :active. These only apply to the &amp;lt;A&amp;gt; tag. The :link class applies to hyperlinks in their normal state. Once a link has been clicked, it belongs instead to the :visited class. When the user holds the mouse over a link, it temporarily belongs to the :active class. The only attribute that may change in an active or visited link is the text color.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Canvas Background Color===&lt;br /&gt;
&lt;br /&gt;
The background attribute is only relevant to the &amp;lt;BODY&amp;gt; context. It causes the entire terminal background to change color. When doing this, it is usually necessary to change the foreground colors of text or it may become unreadable. The various standard classes of output generated by Dream Seeker are presented in figure 11.22.&lt;br /&gt;
&lt;br /&gt;
Figure 11.22: System Colors&lt;br /&gt;
&lt;br /&gt;
system notice&lt;br /&gt;
&lt;br /&gt;
general notices from the client&lt;br /&gt;
system command echo	command echoing&lt;br /&gt;
system command expansion	command-line expansion list&lt;br /&gt;
system pager	pager messages&lt;br /&gt;
system irc	IRC command prefix&lt;br /&gt;
The value of the CLASS attribute may contain a list of classes separated by spaces. This permits client output to be in the `system' class as well as more specific ones. That allows you to change all of these colors in one shot if you are too lazy to change them each individually. For example, if you define a style sheet that changes the background color, you might need to redefine the various foreground colors like this:&lt;br /&gt;
&lt;br /&gt;
BODY {background: aqua; color: black}&lt;br /&gt;
.system {color: red; font-weight: bold}&lt;br /&gt;
.command {color: green}&lt;br /&gt;
In this example, the background color of the terminal will be aqua, normal text from the server will be black, and all output from the client will be bold and red, except echoed commands and expansion lists, which will be bold and green. The more specific .command rule is placed after the general .system rule so that its color takes precedence. This is how style sheets are composed--you write general rules first followed by any exceptions.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Style Rule Precedence===&lt;br /&gt;
&lt;br /&gt;
The order in which rules are specified is one of the factors that determines precedence of style sheet commands. The language is known as Cascading Style Sheets because of its ability to handle several layers of stylistic rules, intermingling the configurations of the user and the designer in an ordered fashion.&lt;br /&gt;
&lt;br /&gt;
Rules are selected by first finding all matching candidates for a given attribute in the current HTML tag being processed. If there is more than one, rules from a higher level style sheet take precedence over lower level ones. That means the basic user configurable settings in Dream Seeker are the lowest priority, followed by a style sheet in the user's .dms script file, followed by a style sheet from the designer's client.script setting, because that is the order in which these are read by the style sheet manager.&lt;br /&gt;
&lt;br /&gt;
Rules from the same style sheet are ordered by specificity. The selector SPAN.chat is more specific than .chat and .chat EM is more specific than EM. In general, the more classes referenced by a selector, the more specific it is. When that results in a tie, the selector with the greater number of tags takes precedence.&lt;br /&gt;
&lt;br /&gt;
Finally, if two rules about the same attribute come from the same sheet and have the same specificity, the final one to be defined takes precedence.&lt;br /&gt;
&lt;br /&gt;
In the rare event that a rule needs to break out of the normal order of precedence, it can be flagged as important. In this case it will take precedence over all other &amp;quot;unimportant&amp;quot; rules. However, if more than one rule is important, the normal rules of precedence will be used to resolve the conflict.&lt;br /&gt;
&lt;br /&gt;
The important flag is applied after the attribute assignment like this:&lt;br /&gt;
&lt;br /&gt;
BODY.background {&lt;br /&gt;
   background: white ! important;&lt;br /&gt;
   font: serif&lt;br /&gt;
}&lt;br /&gt;
In the above example, only the background color is important, not the font specification.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===The STYLE attribute===&lt;br /&gt;
&lt;br /&gt;
Style commands may also be inserted directly in an HTML tag to control its appearance. This does not have the advantages of independent style sheets, which separate content from presentation, but it does allow you to use the style sheet syntax when formatting text.&lt;br /&gt;
&lt;br /&gt;
The following example uses the style attribute to color some text:&lt;br /&gt;
&lt;br /&gt;
usr &amp;lt;&amp;lt; &amp;quot;That HURT!&amp;quot;&lt;br /&gt;
As you can see, the STYLE attribute of any tag can be assigned to a text string containing a list of attribute assignments. Just the body of the style rule is given, since no selector is needed to match the current context.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Inline Icons==&lt;br /&gt;
&lt;br /&gt;
The \icon text macro causes the following embedded expression to be interpreted as an icon rather than as text. For example, an object would be replaced by its icon rather than by its name.&lt;br /&gt;
&lt;br /&gt;
The following example prefixes conversational text with the speaker's icon, making it easier to associate the message with the appropriate object on the map.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
The \icon text macro expands internally to an &amp;lt;IMG&amp;gt; tag. The previous example, could be rewritten as follows:&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot; \&lt;br /&gt;
              [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
From this, you can see that the object's current icon state is used. A reference to the icon itself is inserted using the \ref text macro, which generates a unique identifier corresponding to an object.&lt;br /&gt;
&lt;br /&gt;
A final noteworthy point is that the image belongs to a style class called `icon'. This can be used to configure global properties of icons in the text terminal. For example, a full 32x32 pixel icon doesn't always fit in with surrounding text very well. A single style sheet rule takes care of that:&lt;br /&gt;
&lt;br /&gt;
IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
This is, in fact, a built-in default rule, so you don't have to define it yourself. You could override it to get full 32x32 icons. You could even define special rules to allow icons in certain contexts to be different sizes. The &amp;lt;BIG&amp;gt; and &amp;lt;SMALL&amp;gt; tags are ideal:&lt;br /&gt;
&lt;br /&gt;
BIG IMG.icon {height: 32px; width: 32px}&lt;br /&gt;
SMALL IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
Using the &amp;lt;BIG&amp;gt; tag, you could then output a full-sized icon, even though the default is small. The following example does that when the DM speaks in order to satisfy an inflated ego.&lt;br /&gt;
&lt;br /&gt;
mob/DM/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Special Effects==&lt;br /&gt;
&lt;br /&gt;
There are a couple miscellaneous commands which create special output effects. Like the image instruction, they produce a purely visual result.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===missile instruction===&lt;br /&gt;
&lt;br /&gt;
The missile instruction creates an image which moves from one location to another. It is often used as a symbolic indicator of the source and target of a projectile.&lt;br /&gt;
&lt;br /&gt;
missile	(Icon,Start,End)&lt;br /&gt;
Icon is the image icon or object type.&lt;br /&gt;
Start is the missile source.&lt;br /&gt;
End is the missile destination.&lt;br /&gt;
This could be used in a game of darts:&lt;br /&gt;
&lt;br /&gt;
obj/dart&lt;br /&gt;
   verb/throw(mob/M)&lt;br /&gt;
      missile(src,usr,M)&lt;br /&gt;
      del src&lt;br /&gt;
If more realism is desired, a check could be made first to determine if there is a straight unobstructed path between the attacker and target. (However, realism (in my opinion) is much overrated. Don't let it spoil a good piece of code unless you really have to. I am sure there are many cases in which our own universe too is unrealistic because God couldn't resist a simpler way of implementing things here and there. The sky is a perfect example. I mean, it looks a bit fake sometimes, doesn't it?)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===flick instruction===&lt;br /&gt;
&lt;br /&gt;
The flick instruction causes a temporary transition in the icon state of an object. It lasts until all the frames in that particular state have been played and then reverts to the true icon state.&lt;br /&gt;
&lt;br /&gt;
flick	(State,Obj)&lt;br /&gt;
State is the icon or icon state to display.&lt;br /&gt;
Obj is the target object.&lt;br /&gt;
Note that it is possible to specify an entirely different icon file. Normally, however, just the state of the existing icon file is specified.&lt;br /&gt;
&lt;br /&gt;
The flick instruction is often used for temporary animation sequences (like smiling, writhing in pain, etc.). These are different from changes of state which have a longer duration (like sleeping, flying, etc.). In those cases, one would simply assign the icon_state variable directly.&lt;br /&gt;
&lt;br /&gt;
Sometimes, however, a flick is used in the transition between two permanent states. The following example defines a door turf which does exactly that.&lt;br /&gt;
&lt;br /&gt;
turf/door&lt;br /&gt;
   icon = 'door.dmi'&lt;br /&gt;
   icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
   density = 1&lt;br /&gt;
   opacity = 1&lt;br /&gt;
   verb/open()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(!density) return //already open&lt;br /&gt;
      density = 0&lt;br /&gt;
      opacity = 0&lt;br /&gt;
      flick(&amp;quot;opening&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;open&amp;quot;&lt;br /&gt;
   verb/close()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(density) return //already closed&lt;br /&gt;
      density = 1&lt;br /&gt;
      opacity = 1&lt;br /&gt;
      flick(&amp;quot;closing&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
The advantage of using icon states in this way is that the code remains very general. All the map designer has to do is plug in different icons with the same states and a variety of doors can be made from the one basic definition.&lt;br /&gt;
&lt;br /&gt;
If the icon state specified by the flick instruction does not exist, it has no effect. In the above code, for example, a door icon could be used that did not have &amp;quot;opening&amp;quot; and &amp;quot;closing&amp;quot; states defined. Everything would work--only the transition would not be animated.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19468</id>
		<title>DM Guide 11</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_11&amp;diff=19468"/>
		<updated>2015-11-14T20:30:10Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Глава 11 */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Это 11 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap11.html Оригинальная 11 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
{{Заготовка|url=http://www.byond.com/docs/guide/chap11.html}}&lt;br /&gt;
&lt;br /&gt;
=Глава 11=&lt;br /&gt;
&lt;br /&gt;
Ввод\вывод Пользователя &amp;lt;!--User Input/Output--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Взаимодействие с пользователем - это главная цель любых программ в Dream Maker и эта глава описывает основы языка, отвечающего за ввод и вывод информации. &lt;br /&gt;
&amp;lt;!--Interacting with the user is the ultimate purpose of any DM program. This chapter describes the elements of the language which make it possible. To come this far would have been impossible without a casual introduction to some of the input/output instructions, but even those have more power to offer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Ввод==&lt;br /&gt;
&lt;br /&gt;
Есть два основных пути получения информации от игрока. Первый - ввод по запросу клиента(игрока), второй - ввод по запросу сервера(игры). Разница в том, посылает ли игрок информацию на обработку, или игра запрашивает необходимую информацию.&lt;br /&gt;
&amp;lt;!--There are two basic ways of getting information from the player. One is client initiated and the other is server initiated input. The difference is in whether the player sends unsolicited input or whether the game asks for it. These will be discussed in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Verbs===&lt;br /&gt;
&lt;br /&gt;
До сих пор весь ввод был со стороны пользователя. Игрок может написать команду, нажать кнопку управления, щёлкнуть на объект и т.д. Эти виды ввода информации однородны, так как ими управляют одинаковые операторы(verbs). То есть нажатие на кнопку влево вызывает определённый процесс и задаёт ему значение &amp;quot;кнопка влево&amp;quot;.&lt;br /&gt;
&amp;lt;!--All user input seen so far has come at the initiative of the user. The player may type a command, press a direction key, click an object, etc. These forms of input are all similar because they are ultimately handled by verbs. In the case of the direction keys and mouse clicks, players don't need to actually type any command--the client does it all. However, from the programmer's point of view, these are all the same: The player calls a procedure and possibly passes some arguments to it.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть несколько заранее определённых операторов(verbs), принимающих ввод информации от игрока. Это кнопки направления\стрелки (напр. client.North()), щелчок мыши ((client.Click() и client.DblClick()) и ссылки топиков (client.Topic()). Все остальные операторы(verbs) задаются программистом.&lt;br /&gt;
&amp;lt;!--The only pre-defined verbs are associated with the client data object. They are the direction keys (e.g. client.North()), mouse clicks (client.Click() and client.DblClick()), and topic links (client.Topic()). All other verbs are defined by the programmer.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Общий вид для определения оператора(verb) следующий:&lt;br /&gt;
: verb/Name(Arg1 = default input-type in List,...)&lt;br /&gt;
&lt;br /&gt;
Количество аргументов может быть любым. Каждый из них может иметь значение по умолчанию, тип ввода и список допустимых значений.&lt;br /&gt;
&amp;lt;!--The general format for defining a verb includes any number of arguments. Each one may have a default value, an input type, and a list of possible values.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Инструкция ввода===&lt;br /&gt;
&lt;br /&gt;
Инструкция ввода - это то, что позволяет вам(со стороны игры) запросить у игрока информацию ввода. На ней построены все взаимоотношения сервера с клиентом. Она похожа на простой одиночный оператор(verb).&lt;br /&gt;
&amp;lt;!--The input instruction allows you to ask the player for information. This is how DM provides server-initiated input. It is similar to a single verb argument.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;gt;input(User=usr,Message,Title,Default) input	(User,Query,Title,Default) as input-type in List&lt;br /&gt;
&lt;br /&gt;
User - это имя игрока(моба).&lt;br /&gt;
Query - текст запроса ввода.&lt;br /&gt;
Title - текст отображения запроса ввода.&lt;br /&gt;
Default - значение по умолчанию для данного запроса.&lt;br /&gt;
input-type - тип ввода информации.&lt;br /&gt;
List - список возможных значений для данного запроса.&lt;br /&gt;
Исполнение данного оператора задаёт значение введённое игроком. &amp;lt;!--Returns value entered by player.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Всё, кроме текста ввода - необязательные опциональные параметры. User ассоциируется с usr, и обращается к нему.&lt;br /&gt;
Если input type не задано, то тип ввода информации будет текстовым по умолчанию.&lt;br /&gt;
&amp;lt;!--All but the input text itself are optional parameters. User defaults to the current usr, which is usually the desired target. If no input type or possible value list is specified, the default input type is text. Otherwise, the input type defaults to accept anything in the supplied list, which contains the only values the user is allowed to enter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Обратите внимание, что инструкция ввода не будет запрошена, пока пользователь не введёт значение. При поддержки многопользовательской системы ожидать ответа от одного пользователя невозможно, поэтому при запросе ввода информации в режим ожидания входит только текущая исполняемая процедура.&lt;br /&gt;
&amp;lt;!--Note that the input instruction does not return until the user has entered a value. Since the entire multi-user system cannot halt while waiting for this to happen, only the current procedure waits. More will be said on the subject of multi-tasking in chapter 13.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One case in which the input instruction proves useful is when something happens in the game that the player needs to respond to. A verb would be too open-ended for the task, making it difficult for the player to guess what to do next.&lt;br /&gt;
&lt;br /&gt;
The following code, for example, handles a rather sad event in the life of a player.&lt;br /&gt;
&lt;br /&gt;
mob/proc/Die()&lt;br /&gt;
   if(!key) //NPC&lt;br /&gt;
      del src&lt;br /&gt;
   else     //PC&lt;br /&gt;
      loc = null  //vacate the scene&lt;br /&gt;
      var/again = input(&amp;quot;Play Again?&amp;quot;) in list(&amp;quot;yes&amp;quot;,&amp;quot;no&amp;quot;)&lt;br /&gt;
      if(again == &amp;quot;yes&amp;quot;)&lt;br /&gt;
         Login() //back to square one!&lt;br /&gt;
      else&lt;br /&gt;
         del src&lt;br /&gt;
When the Die() proc is called, players are asked if they would like to play again. If they do, they are logged in again, presumably to start over. Otherwise, they are deleted (and logged out).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Output==&lt;br /&gt;
&lt;br /&gt;
All output is generated by the &amp;lt;&amp;lt; operator. This sends the specified output to one or more players.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Output&lt;br /&gt;
The target may be a single object or a list of objects. Any non-mob target will be replaced by its contents. This allows you to send output to a region on the map or to a room, and all the players inside will receive it.&lt;br /&gt;
&lt;br /&gt;
There are several different types of output. In many cases, the way the output should be handled is automatically detected from the type of data provided. Several instructions for producing various types of output are listed in the following table. In addition to these instructions are some which further clarify how the output should be treated when the type of data alone is not enough to determine this.&lt;br /&gt;
&lt;br /&gt;
Figure 11.16: Output Methods&lt;br /&gt;
&lt;br /&gt;
text()&lt;br /&gt;
&lt;br /&gt;
file()&lt;br /&gt;
image()&lt;br /&gt;
browse()&lt;br /&gt;
sound()&lt;br /&gt;
ftp()&lt;br /&gt;
run()&lt;br /&gt;
link()&lt;br /&gt;
The first group of instructions produce various types of data for output or other purposes. The second group are only meaningful for directly producing output. All of these instructions are described individually in the following sections. The general format for using them is the same.&lt;br /&gt;
&lt;br /&gt;
Target &amp;lt;&amp;lt; Method(Output)&lt;br /&gt;
&lt;br /&gt;
===text output===&lt;br /&gt;
&lt;br /&gt;
A text output value is displayed in the client's scrolling terminal window. The text value may be the result of any expression. Frequently, it is a text string with embedded expressions inside it. Although it is not necessary to use the text instruction for this purpose, one reason for doing so is to use trailing rather than directly embedded expressions.&lt;br /&gt;
&lt;br /&gt;
text	(Text,Arg1,Arg2,...)&lt;br /&gt;
Text is the text string with expression markers.&lt;br /&gt;
Args are the expressions to insert.&lt;br /&gt;
Returns text with arguments substituted in.&lt;br /&gt;
The position in the text where a trailing argument will be inserted is marked with empty brackets [ ]. The substitution arguments are then listed in the same order as the expression markers.&lt;br /&gt;
&lt;br /&gt;
For substituting short expressions into the text, it is convenient to simply embed them directly. However, many lengthy expressions embedded into a text string can make it difficult to read. In that case, trailing expressions may be the better choice. The two methods can be mixed as desired.&lt;br /&gt;
&lt;br /&gt;
The following two versions of a look verb are equivalent.&lt;br /&gt;
&lt;br /&gt;
mob&lt;br /&gt;
   var/money = 2&lt;br /&gt;
&lt;br /&gt;
   verb/look1()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;[src] has [contents.len] items and [money] buffalo chips.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   verb/look2()&lt;br /&gt;
      set src in view()&lt;br /&gt;
      usr &amp;lt;&amp;lt; text(&amp;quot;[src] has [] items and [] buffalo chips.&amp;quot;,&lt;br /&gt;
                   contents.len,&lt;br /&gt;
                   money)&lt;br /&gt;
Note that the text instruction is not limited to being used as an output method. It may be used anywhere you wish to use trailing expressions with a text string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===browse output===&lt;br /&gt;
&lt;br /&gt;
The browse output method displays text output in a pop-up window. This is intended for viewing longer text documents. If treated as normal terminal output instead, the user might have to scroll back up to find the top of the message.&lt;br /&gt;
&lt;br /&gt;
browse	(Doc, Options)&lt;br /&gt;
Doc is the message to display.	Options are various window-specific options. Consult the reference for specifics.&lt;br /&gt;
By default, each message replaces any previous message being displayed but the user can move back to previous messages stored in the client's memory. In many ways, the client terminal behaves like a telnet session and the browse window behaves like a web browser. One displays output sequentially in a continuous stream. The other displays it in discrete chunks--one document after another. The two are each useful in different situations.&lt;br /&gt;
&lt;br /&gt;
The document is often a text string. However, it may be a file instead. The type of file will determine how it is handled. Files may reside in the resource cache or in the file system. As always, cached items may be specified by putting the file name in single quotes. An external file, on the other hand, is indicated using the file instruction described in section 11.2.7.&lt;br /&gt;
&lt;br /&gt;
The browse output method is often used in conjunction with the message input type. One allows the composition of messages and the other displays them.&lt;br /&gt;
&lt;br /&gt;
The following example defines a message scroll. Players can write poetry on it in moments of inspiration.&lt;br /&gt;
&lt;br /&gt;
obj/scroll/verb&lt;br /&gt;
   write(msg as message)&lt;br /&gt;
      desc = msg&lt;br /&gt;
   read()&lt;br /&gt;
      usr &amp;lt;&amp;lt; browse(desc)&lt;br /&gt;
&lt;br /&gt;
===sound output===&lt;br /&gt;
&lt;br /&gt;
The sound output method plays a sound to the player. Either wav or midi sound files may be used, usually for short noises and music respectively. Such files are treated this way by default, but the sound instruction can be used to control how the sound is played.&lt;br /&gt;
&lt;br /&gt;
sound	(File,Repeat)&lt;br /&gt;
File is the sound file to play.&lt;br /&gt;
Repeat is 1 to play sound repeatedly.&lt;br /&gt;
A repeated sound is played in the background while other sounds are played in the foreground. Only one background sound and one foreground sound may be played at a time, so subsequent output replaces any previous sound with the same repeat setting. To stop a sound, specify null as the file.&lt;br /&gt;
&lt;br /&gt;
Background music is often repeated while occasional noises play in the foreground. The following example defines a background sound for each area.&lt;br /&gt;
&lt;br /&gt;
area&lt;br /&gt;
   var/music = 'default.midi'&lt;br /&gt;
   Enter()&lt;br /&gt;
      . = ..()&lt;br /&gt;
      if(.) usr &amp;lt;&amp;lt; sound(music,1)&lt;br /&gt;
The line . = ..() is commonly used when you want to return the same value as the parent proc but you need to do something after finding out what that value is. That way, if the user is refused access to the area for some reason, the music will not be played.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===image output===&lt;br /&gt;
&lt;br /&gt;
The image instruction is used to create a purely virtual object. It may appear at the specified location to selected players, but it corresponds to no real data object.&lt;br /&gt;
&lt;br /&gt;
image	(Icon,Loc)&lt;br /&gt;
Icon is the icon or object type to use.&lt;br /&gt;
Loc is the location of the image.&lt;br /&gt;
Returns a reference to the image.&lt;br /&gt;
If the location of the image is something movable like a mob, it will follow the object around. The image icon is displayed in a layer above everything else, so it is best suited for special effects like a selection box, burst of fire, etc.&lt;br /&gt;
&lt;br /&gt;
The image instruction may be used outside the context of the output instruction. In this case it returns a reference to the image but does not actually display the image to any players. This reference can be sent as output and may be deleted later to destroy the image.&lt;br /&gt;
&lt;br /&gt;
The following example allows the player to select an enemy by clicking on it. The currently selected enemy is outlined with an image.&lt;br /&gt;
&lt;br /&gt;
mob/var&lt;br /&gt;
   mob/enemy&lt;br /&gt;
   enemy_marker&lt;br /&gt;
&lt;br /&gt;
client/Click(mob/M)&lt;br /&gt;
   if(istype(M))&lt;br /&gt;
      del usr.enemy_marker&lt;br /&gt;
      usr.enemy = M&lt;br /&gt;
      usr.enemy_marker = image('outline.dmi',M)&lt;br /&gt;
      usr &amp;lt;&amp;lt; usr.enemy_marker&lt;br /&gt;
The code works by first deleting any old enemy marker. A new one is then made and displayed to the user. No one else will see the image--only the player who clicked on the enemy.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===ftp output===&lt;br /&gt;
&lt;br /&gt;
The ftp output method sends a file to the player. This complements the file input type which allows the player to send a file to the server. The terminology normally used is that a file is uploaded when it is input and downloaded when it is output.&lt;br /&gt;
&lt;br /&gt;
ftp	(File,Name)&lt;br /&gt;
File is the file to send.&lt;br /&gt;
Name is the optional suggested file name.&lt;br /&gt;
The file to send may be either a resource file (in the cache) or a file in the file system. The difference is whether the file is specified in single or double quotes. A file in single quotes will be loaded into the resource cache at compile-time. A file in double quotes will be accessed from the file system (i.e. hard-disk) at run-time. The latter might be useful if you need to update the file periodically without recompiling.&lt;br /&gt;
&lt;br /&gt;
The suggested file name defaults to the name of the file being sent. This is used as the default name when the player chooses where to store the file. If the player decides not to download the file, it is always possible to cancel at that point or during the transfer.&lt;br /&gt;
&lt;br /&gt;
The following example sends a help file to players when they click on the appropriate topic.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; ftp(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
mob/Login()&lt;br /&gt;
   ..()&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;Download the  help file  if you are new here.&amp;quot;&lt;br /&gt;
For this to work, the file &amp;quot;help.txt&amp;quot; must exist in the current directory of the server. This can be assured by putting it in the same place as the dmb file. Since the file was specified in double quotes, it will be accessed at run-time rather than compile-time. That means you are free to edit it at a later date.&lt;br /&gt;
&lt;br /&gt;
The HTML tag &amp;lt;A HREF...&amp;gt; is used to embed a hyperlink in some output text. It will be described in section 11.4.3.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===run file output===&lt;br /&gt;
&lt;br /&gt;
The run output method is like ftp except it displays or executes the specified file rather than saving it to disk. The action taken depends on the type of file. For example, HTML and jpeg files might be shown in the player's web browser.&lt;br /&gt;
&lt;br /&gt;
run(File)&lt;br /&gt;
Obviously it would be a severe security risk to players if executable files could be run without their authorization. Viruses and other malicious programs could be released onto their computer just by connecting to a game. For this reason, players are asked before executing any potentially dangerous file. That is the default behavior. The player can configure the client to always or never run files if they choose. A similar choice can be made about downloading files.&lt;br /&gt;
&lt;br /&gt;
The previous example which gave the player a help file could easily be changed to instead display the file. If the player wishes, it would still be possible to save the file to disk.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; run(&amp;quot;help.txt&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===file output===&lt;br /&gt;
&lt;br /&gt;
The file instruction returns a reference to a file object. It takes the file's path (in a text string) as an argument. The output methods browse, ftp, and run can all take a file reference as an argument. In the case of browse it is necessary to use file to distinguish between a text message and a file name. In the case of ftp and run it is not necessary to use file because the name of the file may simply be used directly. If no output method is specified for a file, it is implicitly handled by run.&lt;br /&gt;
&lt;br /&gt;
file	(Path)&lt;br /&gt;
Path is the name of the file.&lt;br /&gt;
Returns a reference to the file.&lt;br /&gt;
The path may be absolute or relative to the server's working directory, which is the same directory that contains the world .dmb file. Since this is evaluated at run-time, the file need not exist until the statement is actually executed. This is different from cache file references (in single quotes) which are evaluated at compile-time. For more uses of the file object, see section 17.6.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===link output===&lt;br /&gt;
&lt;br /&gt;
The link output method is like run except it executes a URL rather than a file. The URL could be a web address, a BYOND address, or a topic link.&lt;br /&gt;
&lt;br /&gt;
link	(url)&lt;br /&gt;
url is the URL to execute.&lt;br /&gt;
The beginning of the URL specifies the communication protocol. If the URL begins with &amp;quot;byond://&amp;quot; then it is treated as a BYOND address. This is the default protocol if none is specified. A URL beginning with &amp;quot;#&amp;quot; is a topic link. Other protocols (like &amp;quot;http://&amp;quot; are handled by the player's web browser.&lt;br /&gt;
&lt;br /&gt;
A BYOND link causes the player's client to reconnect to the specified address. Topic links merely cause the specified topic to be accessed in the current world (by calling client.Topic()). A web link causes the web browser to switch to the specified URL.&lt;br /&gt;
&lt;br /&gt;
The general format for a BYOND address includes a server address and topic.&lt;br /&gt;
&lt;br /&gt;
byond://server#topic&lt;br /&gt;
The topic is optional and is only used in rare cases like servers with multiple entry points. The server address may be either the name of a registered server or the network address in the form ip:port. The IP address would either be raw network numbers (e.g. 123.456.789.123) or the corresponding machine name (e.g. dantom.com). The port number is the network port on which the server is running. This is reported when the server starts up.&lt;br /&gt;
&lt;br /&gt;
By default, players are asked whether they accept links activated in this manner. They can, however, configure the client to always or never accept them.&lt;br /&gt;
&lt;br /&gt;
The link output method is very similar to the hyperlink text tag which has already been introduced. They both can take the same types of URLs and act upon them in the same manner. Hyperlinks embedded in text are normally used to provide access to optional information. The link output method, on the other hand, is useful when the player's action has already indicated desire to follow the link.&lt;br /&gt;
&lt;br /&gt;
For example, a link from one world to another could be activated by entrance into a special turf.&lt;br /&gt;
&lt;br /&gt;
turf/wormhole/Enter()&lt;br /&gt;
   usr &amp;lt;&amp;lt; link(&amp;quot;byond://WormWorld&amp;quot;)&lt;br /&gt;
   return 1&lt;br /&gt;
This example assumes the existence of a world registered under the name &amp;quot;WormWorld&amp;quot;. Running and registering a networked world will be discussed in chapter 12.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Macros==&lt;br /&gt;
&lt;br /&gt;
Both input and output text may contain special codes that are not displayed literally but which are replaced by some other text. These are called text macros and begin with a backslash \ and may end with a space (which is ignored). They are summarized in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Expression Modifiers===&lt;br /&gt;
&lt;br /&gt;
Figure 11.17: Text Macros for use with Expressions&lt;br /&gt;
&lt;br /&gt;
\the, \The&lt;br /&gt;
&lt;br /&gt;
definite article if needed&lt;br /&gt;
\a, \an, \A, \An	indefinite article if needed&lt;br /&gt;
\he, \He, \she, \She	he, she, they, it&lt;br /&gt;
\his, \His	his, her, their, its&lt;br /&gt;
\hers	his, hers, theirs, its&lt;br /&gt;
\him	him, her, them, it&lt;br /&gt;
\himself, \herself	himself, herself, themself, itself&lt;br /&gt;
\th	1st, 2nd, 3rd, ...&lt;br /&gt;
\s	1 dog, 2 dogs, ...&lt;br /&gt;
The first group of text macros work in conjunction with an embedded expression. The article macros precede the expression and the others follow it. Any amount of text and even inapplicable expressions may exist between the macro and its associated expression.&lt;br /&gt;
&lt;br /&gt;
The articles and various pronouns work with object or text expressions. The plural and ordinal macros \s and \th are used with numerical expressions. If no expression of the appropriate type is found, these macros do nothing.&lt;br /&gt;
&lt;br /&gt;
An embedded object is replaced by a definite article and its name. In other words, the following two are equivalent:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] smiles.&amp;quot;&lt;br /&gt;
&amp;quot;\The [usr] smiles.&amp;quot;&lt;br /&gt;
These could produce &amp;quot;Andrew smiles.&amp;quot; or &amp;quot;The cat smiles.&amp;quot; depending on the name of the user.&lt;br /&gt;
&lt;br /&gt;
Note that the articles may be supplied in either capitalized or lowercase form. The implicit definite article is automatically chosen in capital form if preceded by a period. If that is incorrect, you can specify the desired form explicitly.&lt;br /&gt;
&lt;br /&gt;
If an indefinite article is desired instead of the default definite one, it must be explicitly specified. If no article at all is desired, the name can be embedded directly in place of the object.&lt;br /&gt;
&lt;br /&gt;
The following example uses an indefinite article instead of a definite one when a mob picks up an object.&lt;br /&gt;
&lt;br /&gt;
obj/verb/get()&lt;br /&gt;
   set src in view(0)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] picks up \a [src].&amp;quot;&lt;br /&gt;
   Move(usr)&lt;br /&gt;
It doesn't matter whether you use &amp;quot;a&amp;quot; or &amp;quot;an&amp;quot; in the macro. The appropriate one will be chosen for the word that follows. It is common to use whichever one makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Proper Nouns====&lt;br /&gt;
&lt;br /&gt;
There are two special text macros for controlling whether the name of an object is considered to be a proper noun or not. These are \proper and \improper. By default, if the object name is capitalized, it is assumed to be proper, and otherwise it is assumed to be improper. To override this, you can put \proper or \improper at the beginning of the object's name.&lt;br /&gt;
&lt;br /&gt;
As you have seen in the preceding section, the difference between proper and improper nouns is that articles are suppressed in front of proper nouns. For example, if you had something called a &amp;quot;BYOND dime,&amp;quot; you would need to use the \improper macro as follows:&lt;br /&gt;
&lt;br /&gt;
obj/BD&lt;br /&gt;
   name = &amp;quot;\improper BYOND dime&amp;quot;&lt;br /&gt;
mob/verb/get(obj/O in view(0))&lt;br /&gt;
   usr &amp;lt;&amp;lt; &amp;quot;You pick up \an [O].&amp;quot;&lt;br /&gt;
   O.Move(usr)&lt;br /&gt;
Since we used \improper in this example, somebody picking up a BYOND dime would see, &amp;quot;You pick up a BYOND dime.&amp;quot; rather than &amp;quot;You pick up BYOND dime.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Numerical Expressions====&lt;br /&gt;
&lt;br /&gt;
There are macros which depend upon the preceding numerical expression. The \th macro produces the ordinal ending for the supplied number. For the number 1, it produces &amp;quot;st&amp;quot; to make &amp;quot;1st&amp;quot;, for the number 2, &amp;quot;nd&amp;quot; and so on. From 4 and on it produces &amp;quot;th&amp;quot;, which is where it gets its name.&lt;br /&gt;
&lt;br /&gt;
The \s macro produces &amp;quot;s&amp;quot; if the preceding numerical expression is not equal to 1 and nothing otherwise. This is useful for making plurals like &amp;quot;You have [count] coin\s.&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Special Characters===&lt;br /&gt;
&lt;br /&gt;
Figure 11.18: Special Character Macros&lt;br /&gt;
&lt;br /&gt;
\&amp;quot;&lt;br /&gt;
&lt;br /&gt;
double quote&lt;br /&gt;
\\	backslash&lt;br /&gt;
\&amp;lt;	less than&lt;br /&gt;
\&amp;gt;	greater than&lt;br /&gt;
\&amp;amp;	ampersand&lt;br /&gt;
\n	newline&lt;br /&gt;
\...	suppress newline at end&lt;br /&gt;
\(space)	skip a space&lt;br /&gt;
There are a few special characters that may not be directly entered into a text string. These must be escaped by preceding them with a backslash. This forces the special meaning to be ignored and the literal character to be inserted instead.&lt;br /&gt;
&lt;br /&gt;
The double quote, for example, must be escaped or it would prematurely end the text string.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;[usr] says, \&amp;quot;[msg]\&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Newlines====&lt;br /&gt;
&lt;br /&gt;
A newline may be inserted with the \n macro. The compiler does not allow direct insertion of newlines in a text string because this is often a mistake resulting from a missing end quote. You can continue a lengthy text string onto the next line by escaping the newline, but then the newline is entirely ignored.&lt;br /&gt;
&lt;br /&gt;
There is an implicit newline inserted at the end of all output text. This means that instead of using the \n macro directly, the text can simply be broken up into individual lines which are output one at a time.&lt;br /&gt;
&lt;br /&gt;
In some cases, you may want to suppress the implicit newline at the end of the text. This can be done with the \... macro. By putting it at the end of the text, subsequent output will start on the same line where the previous one left off.&lt;br /&gt;
&lt;br /&gt;
A newline is actually an end-of-paragraph marker. It should not be used inside the paragraph to make lines fit the screen because not everyone's terminal will be the same width. It is best to let the terminal automatically handle word-wrap within paragraphs and reserve the newline for marking the end of it.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Text Formatting Tags==&lt;br /&gt;
&lt;br /&gt;
Text may be formatted by inserting HTML elements, more commonly known as tags, that control its appearance. DM understands a subset of HTML tags, consisting of the most commonly used elements.&lt;br /&gt;
&lt;br /&gt;
A tag is surrounded by &amp;lt; &amp;gt; angle brackets. The first thing inside the brackets is the name of the tag. Many tags come in pairs--one to start an effect and another to end it. The end tag has the same name as the start tag except it starts with `/'. Tag names are not case sensitive.&lt;br /&gt;
&lt;br /&gt;
The following example displays some text in bold.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;I am very mad!&amp;quot;&lt;br /&gt;
The start tag &amp;lt;B&amp;gt; turns on bold lettering and &amp;lt;/B&amp;gt; turns it off. For a complete list of tags understood by DM, see page 3 in the appendix. The most commonly used ones are listed in figure 11.19 for easy reference.&lt;br /&gt;
&lt;br /&gt;
Figure 11.19: Common text tags&lt;br /&gt;
&lt;br /&gt;
&amp;lt;A&amp;gt;&amp;lt;/A&amp;gt;&lt;br /&gt;
&lt;br /&gt;
anchor (for hyperlinks)&lt;br /&gt;
&amp;lt;B&amp;gt;&amp;lt;/B&amp;gt;	bold&lt;br /&gt;
&amp;lt;BIG&amp;gt;&amp;lt;/BIG&amp;gt;	bigger text&lt;br /&gt;
&amp;lt;BR&amp;gt;	line break&lt;br /&gt;
&amp;lt;FONT&amp;gt;&amp;lt;/FONT&amp;gt;	font face, size, and color&lt;br /&gt;
&amp;lt;I&amp;gt;&amp;lt;/I&amp;gt;	italic&lt;br /&gt;
&amp;lt;P&amp;gt;&amp;lt;/P&amp;gt;	paragraph&lt;br /&gt;
&amp;lt;S&amp;gt;&amp;lt;/S&amp;gt;	overstrike&lt;br /&gt;
&amp;lt;SMALL&amp;gt;&amp;lt;/SMALL&amp;gt;	smaller text&lt;br /&gt;
&amp;lt;TT&amp;gt;&amp;lt;/TT&amp;gt;	typewriter style&lt;br /&gt;
&amp;lt;U&amp;gt;&amp;lt;/U&amp;gt;	underline&lt;br /&gt;
&amp;lt;PRE&amp;gt;&amp;lt;/PRE&amp;gt;	preformatted whitespace&lt;br /&gt;
&amp;lt;XMP&amp;gt;&amp;lt;/XMP&amp;gt;	literally preformatted text&lt;br /&gt;
&amp;lt;BEEP&amp;gt;&lt;br /&gt;
&lt;br /&gt;
make a beeping sound&lt;br /&gt;
&lt;br /&gt;
===Whitespace===&lt;br /&gt;
&lt;br /&gt;
Whitespace refers to any spaces, tabs, or newlines. In standard HTML, whitespace serves merely to delimit words. The amount of space and whether it is a tab, space, or newline is irrelevant.&lt;br /&gt;
&lt;br /&gt;
DM processes whitespace like standard HTML when it is inside of a pair of start and end tags. So, for example, inside of &amp;lt;P&amp;gt; and &amp;lt;/P&amp;gt;, the paragraph markers, standard HTML rules are in effect; newlines, spaces, and tabs serve merely to delimit words. Note that an entire document could be surrounded by &amp;lt;HTML&amp;gt; and &amp;lt;/HTML&amp;gt; to mark the whole thing as standard HTML.&lt;br /&gt;
&lt;br /&gt;
Outside of all HTML tags, DM handles whitespace a little differently. Spaces still delimit words, but newlines (embedded with \n) mark the end of lines. In other words, the newline is automatically converted to &amp;lt;BR&amp;gt;, the linebreak tag. That is convenient for use in messages composed by players when it would be annoying to write formal HTML with paragraph tags and so forth.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;FONT&amp;gt; tag is used to control various characteristics of the font being used. It takes additional arguments in the form of attributes.&lt;br /&gt;
&lt;br /&gt;
For example, to make the font much bigger, you could use the start tag &amp;lt;FONT SIZE=+3&amp;gt;. The name of the attribute in this case is SIZE, and its value is +3, which makes the font three sizes bigger. You can put quotes around the attribute value if it contains any spaces. In this case there was no need.&lt;br /&gt;
&lt;br /&gt;
The attributes of &amp;lt;FONT&amp;gt; are FACE, SIZE, and COLOR. You can use as many of these attributes in one tag as you like. Just separate each attribute assignment by some space like this: &amp;lt;nowiki&amp;gt;&amp;lt;FONT SIZE=+3 COLOR=red&amp;gt;&amp;lt;/nowiki&amp;gt;. The nuances of these three tags are discussed in the following individual sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FACE attribute====&lt;br /&gt;
&lt;br /&gt;
The FACE attribute selects the name of the font you wish to use. It may be a single font (such as InnoDBl) or a comma-separated list (such as InnoDBl,Helvetica). If the user doesn't have a font with the same name on their system, the next font will be tried. Remember to put quotes around the attribute value if it contains any spaces.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====SIZE attribute====&lt;br /&gt;
&lt;br /&gt;
The SIZE attribute changes the size of the text. It can be a relative change, like +3, or an absolute size, such as 5. Font sizes are numbered from 1 to 7, with 1 being the smallest and 7 being the largest. Each increment is roughly 1.5 times the apparent size of the previous one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====COLOR attribute====&lt;br /&gt;
&lt;br /&gt;
The COLOR attribute selects the foreground color of the text. It may be either a color name or a hexadecimal RGB value.&lt;br /&gt;
&lt;br /&gt;
RGB stands for red, green, and blue, the three primary colors from which all the others can be produced. Hexadecimal is a base-16 number system commonly used by programmers for specifying binary values. The hexadecimal digits are 0 to 9 and A to F, a full four bits of information. Lowercase letters may be used as well.&lt;br /&gt;
&lt;br /&gt;
Each primary color is given a range of eight bits. Therefore it takes exactly two hexadecimal digits to specify a single component and six digits to specify a complete color value. The first two digits are for red; the next two are for green; and the last two are for blue (hence RGB). The color black is 000000, which has all three colors turned off. The color white is FFFFFF with all three colors at their maximum intensity.&lt;br /&gt;
&lt;br /&gt;
The following two lines are identical:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
&amp;quot;This is red.&amp;quot;&lt;br /&gt;
Notice that a # symbol is placed in front of the numeric color value to indicate that it is a hexadecimal value. Otherwise, a color name is expected. If you can't find the color you want in the list of named colors, find the closest one and tweak the intensities to your satisfaction.&lt;br /&gt;
&lt;br /&gt;
Figure 11.20: Named Colors&lt;br /&gt;
&lt;br /&gt;
black&lt;br /&gt;
&lt;br /&gt;
#000000&lt;br /&gt;
silver	#C0C0C0&lt;br /&gt;
grey	#808080&lt;br /&gt;
white	#FFFFFF&lt;br /&gt;
maroon&lt;br /&gt;
&lt;br /&gt;
#800000&lt;br /&gt;
red	#FF0000&lt;br /&gt;
purple	#800080&lt;br /&gt;
fuchsia	#FF00FF&lt;br /&gt;
green&lt;br /&gt;
&lt;br /&gt;
#00C000&lt;br /&gt;
lime	#00FF00&lt;br /&gt;
olive	#808000&lt;br /&gt;
yellow	#FFFF00&lt;br /&gt;
navy&lt;br /&gt;
&lt;br /&gt;
#000080&lt;br /&gt;
blue	#0000FF&lt;br /&gt;
teal	#008080&lt;br /&gt;
aqua	#00FFFF&lt;br /&gt;
It is also possible to enter color components as 4 rather than 8 bit numbers. In that case, only three hexadecimal digits are required rather than six. Internally, the color is converted to full 8 bit notation by repeating each digit. For example, black #000 becomes #000000, white #FFF becomes #FFFFFF, and red #F00 becomes FF0000.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlinks===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;A&amp;gt; tag is used to mark a particular spot (or anchor) in the text. In DM, you use it to insert a clickable hyperlink. To specify the destination URL of a link, use the HREF attribute.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;lt;A HREF='#topic'&amp;gt; click here &amp;lt;/A&amp;gt; ...&amp;quot;&lt;br /&gt;
The form of the URL is the same as the link output method described in section 11.2.8. It may be either a BYOND address, a topic link, or a web address.&lt;br /&gt;
&lt;br /&gt;
The TITLE attribute may be assigned to a description of the link. It is made visible when the user holds the mouse over the link.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Style Sheets==&lt;br /&gt;
&lt;br /&gt;
HTML tags, such as &amp;lt;FONT&amp;gt; may be used to directly format output text. Another approach, however, is to use HTML tags to specify purely structural information and use a style sheet to define how various elements within that structure should be treated. DM uses a subset of the Cascading Style Sheet (CSS) language, which was introduced for this purpose in HTML documents.&lt;br /&gt;
&lt;br /&gt;
As an example of a style sheet, suppose one wanted combat and conversational messages to appear differently--perhaps using different colors. Instead of using the &amp;lt;FONT&amp;gt; tag to color the text, you could use &amp;lt;SPAN&amp;gt; to mark the beginning and ending of the text and to specify what kind of message it is. The result might be text such as the following:&lt;br /&gt;
&lt;br /&gt;
&amp;quot;[usr] spanks [targ]!&amp;quot;&lt;br /&gt;
&amp;quot;[usr] says, '[msg]'&amp;quot;&lt;br /&gt;
The CLASS attribute may be used with any tag, but the generic containers SPAN and DIV are often convenient because they have no other side-effect. &amp;lt;SPAN&amp;gt; is for text within a single paragraph and &amp;lt;DIV&amp;gt; is for whole paragraphs. The way text belonging to a particular class is formatted may be controlled in a style sheet such as the following:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This says that text in the `combat' class should be colored red and text in the `chat' class should be colored green. These classes are not pre-defined; they were just made up to suit the situation. You can invent as many new classes as you like.&lt;br /&gt;
&lt;br /&gt;
In order to make this style sheet take effect you have several options. One is to put it in a text string (double quotes) and assign it to client.script. This will load the style sheet when the player connects. You could accomplish the same thing by putting the style sheet in a file and assigning the file (in single quotes) to client.script. It is also possible for a player to put the style sheet in a client-side script file and load it that way. More will be said about DM Script, which encompasses more than just style sheets, in the appendix (page [4]).&lt;br /&gt;
&lt;br /&gt;
The advantage of using style sheets instead of direct formatting tags is that you can cleanly separate structural information (such as combat and conversational messages) from formatting information (such as red and green text). By separating the two, you or the player can easily plug in different formatting schemes without changing any of the actual content.&lt;br /&gt;
&lt;br /&gt;
A style sheet is composed of a list of rules, such as the two rules in the preceding example. Each rule contains one or more selectors followed by a body of attribute assignments (in braces). The selector specifies the context of the rule and the body specifies the format.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Context Selectors===&lt;br /&gt;
&lt;br /&gt;
A selector may specify a container tag (such as SPAN, BODY, or P) and a class. The above example could have been written with a selector of SPAN.chat. However, by leaving out the tag, it applies to any tag with CLASS=chat. It is also possible to only specify the tag and not the class. In that case, the selector applies to any matching tag, regardless of its class.&lt;br /&gt;
&lt;br /&gt;
To specify a nested context, several simple selectors may be listed one after the other. For example, emphasized text within a combat message could be enlarged with the following rule:&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
It is also possible to list several selectors separated by commas in order to make them all apply to the same body. For example, this next rule is equivalent to the two following ones:&lt;br /&gt;
&lt;br /&gt;
.combat EM, .chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
.combat EM {font-size: larger}&lt;br /&gt;
.chat EM {font-size: larger}&lt;br /&gt;
&lt;br /&gt;
===Style Attributes===&lt;br /&gt;
&lt;br /&gt;
The body of a style rule contains a list of attribute assignments, delimited by semicolons. Each assignment takes the form of an attribute name, followed by a colon, followed by the value of the attribute. Figure 11.21 summarizes the recognized attributes and sample values.&lt;br /&gt;
&lt;br /&gt;
Figure 11.21: Style Attributes&lt;br /&gt;
&lt;br /&gt;
color&lt;br /&gt;
&lt;br /&gt;
#F00, #FF000, red&lt;br /&gt;
background	same as color&lt;br /&gt;
font-size	10pt, 1.5em, 150%&lt;br /&gt;
font-style	normal or italic&lt;br /&gt;
font-weight	normal, bold, lighter, darker, or 100 to 900&lt;br /&gt;
font-family	monospace, sans-serif, serif, cursive, ...&lt;br /&gt;
font	style weight size family&lt;br /&gt;
text-decoration	none or underline&lt;br /&gt;
text-align	left, right, or center&lt;br /&gt;
width	16px, 32px, auto&lt;br /&gt;
height	16px, 32px, auto&lt;br /&gt;
&lt;br /&gt;
===Fonts===&lt;br /&gt;
&lt;br /&gt;
The font family may be a specific font name or a more general category such as monospace or sans-serif. Since not all users necessarily have the same fonts installed, it is a good idea to list alternate fonts. The desired font is placed first, followed by other possible fall-backs, each separated by a comma. Usually a general family such as monospace is listed last of all. Any font names containing a space should be enclosed in quotes.&lt;br /&gt;
&lt;br /&gt;
The font attribute is a special short-hand for assigning font-size, font-style, font-weight, and font-family in one statement. Any properties that are not specified in the font statement are assigned to their default values.&lt;br /&gt;
&lt;br /&gt;
The following example sets the font for the &amp;lt;BODY&amp;gt; tag. Even if you don't explicitly use &amp;lt;BODY&amp;gt; in output text, it is applied implicitly.&lt;br /&gt;
&lt;br /&gt;
BODY {font: 12pt 'Times New Roman', sans-serif}&lt;br /&gt;
This sets the font to 12 point and selects Times New Roman if it is available and otherwise falls back on a system-determined sans-serif font. This command also implicitly specifies not to use italics and normal font weight (not bold).&lt;br /&gt;
&lt;br /&gt;
Font sizes may be specified in points (1pt = 1/72 of an inch), picas (1pc = 12pt), pixels (px), inches (in), centimeters (cm), and millimeters (mm). There are also various levels corresponding to the traditional 1 to 7 HTML scale. These are xx-small, x-small, small, medium, large, x-large, and xx-large. In addition to these absolute font sizes, it is possible to use a relative size, such as 150% or equivalently 1.5em. This scales the font relative to the currently active font setting.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Hyperlink Pseudo-Classes===&lt;br /&gt;
&lt;br /&gt;
In addition to regular stylistic classes, there are special pseudo-classes for handling embedded hyperlinks. These are specified in the selector with the class starting with a colon rather than a dot. They are :link, :visited, and :active. These only apply to the &amp;lt;A&amp;gt; tag. The :link class applies to hyperlinks in their normal state. Once a link has been clicked, it belongs instead to the :visited class. When the user holds the mouse over a link, it temporarily belongs to the :active class. The only attribute that may change in an active or visited link is the text color.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Canvas Background Color===&lt;br /&gt;
&lt;br /&gt;
The background attribute is only relevant to the &amp;lt;BODY&amp;gt; context. It causes the entire terminal background to change color. When doing this, it is usually necessary to change the foreground colors of text or it may become unreadable. The various standard classes of output generated by Dream Seeker are presented in figure 11.22.&lt;br /&gt;
&lt;br /&gt;
Figure 11.22: System Colors&lt;br /&gt;
&lt;br /&gt;
system notice&lt;br /&gt;
&lt;br /&gt;
general notices from the client&lt;br /&gt;
system command echo	command echoing&lt;br /&gt;
system command expansion	command-line expansion list&lt;br /&gt;
system pager	pager messages&lt;br /&gt;
system irc	IRC command prefix&lt;br /&gt;
The value of the CLASS attribute may contain a list of classes separated by spaces. This permits client output to be in the `system' class as well as more specific ones. That allows you to change all of these colors in one shot if you are too lazy to change them each individually. For example, if you define a style sheet that changes the background color, you might need to redefine the various foreground colors like this:&lt;br /&gt;
&lt;br /&gt;
BODY {background: aqua; color: black}&lt;br /&gt;
.system {color: red; font-weight: bold}&lt;br /&gt;
.command {color: green}&lt;br /&gt;
In this example, the background color of the terminal will be aqua, normal text from the server will be black, and all output from the client will be bold and red, except echoed commands and expansion lists, which will be bold and green. The more specific .command rule is placed after the general .system rule so that its color takes precedence. This is how style sheets are composed--you write general rules first followed by any exceptions.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Style Rule Precedence===&lt;br /&gt;
&lt;br /&gt;
The order in which rules are specified is one of the factors that determines precedence of style sheet commands. The language is known as Cascading Style Sheets because of its ability to handle several layers of stylistic rules, intermingling the configurations of the user and the designer in an ordered fashion.&lt;br /&gt;
&lt;br /&gt;
Rules are selected by first finding all matching candidates for a given attribute in the current HTML tag being processed. If there is more than one, rules from a higher level style sheet take precedence over lower level ones. That means the basic user configurable settings in Dream Seeker are the lowest priority, followed by a style sheet in the user's .dms script file, followed by a style sheet from the designer's client.script setting, because that is the order in which these are read by the style sheet manager.&lt;br /&gt;
&lt;br /&gt;
Rules from the same style sheet are ordered by specificity. The selector SPAN.chat is more specific than .chat and .chat EM is more specific than EM. In general, the more classes referenced by a selector, the more specific it is. When that results in a tie, the selector with the greater number of tags takes precedence.&lt;br /&gt;
&lt;br /&gt;
Finally, if two rules about the same attribute come from the same sheet and have the same specificity, the final one to be defined takes precedence.&lt;br /&gt;
&lt;br /&gt;
In the rare event that a rule needs to break out of the normal order of precedence, it can be flagged as important. In this case it will take precedence over all other &amp;quot;unimportant&amp;quot; rules. However, if more than one rule is important, the normal rules of precedence will be used to resolve the conflict.&lt;br /&gt;
&lt;br /&gt;
The important flag is applied after the attribute assignment like this:&lt;br /&gt;
&lt;br /&gt;
BODY.background {&lt;br /&gt;
   background: white ! important;&lt;br /&gt;
   font: serif&lt;br /&gt;
}&lt;br /&gt;
In the above example, only the background color is important, not the font specification.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===The STYLE attribute===&lt;br /&gt;
&lt;br /&gt;
Style commands may also be inserted directly in an HTML tag to control its appearance. This does not have the advantages of independent style sheets, which separate content from presentation, but it does allow you to use the style sheet syntax when formatting text.&lt;br /&gt;
&lt;br /&gt;
The following example uses the style attribute to color some text:&lt;br /&gt;
&lt;br /&gt;
usr &amp;lt;&amp;lt; &amp;quot;That HURT!&amp;quot;&lt;br /&gt;
As you can see, the STYLE attribute of any tag can be assigned to a text string containing a list of attribute assignments. Just the body of the style rule is given, since no selector is needed to match the current context.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Inline Icons==&lt;br /&gt;
&lt;br /&gt;
The \icon text macro causes the following embedded expression to be interpreted as an icon rather than as text. For example, an object would be replaced by its icon rather than by its name.&lt;br /&gt;
&lt;br /&gt;
The following example prefixes conversational text with the speaker's icon, making it easier to associate the message with the appropriate object on the map.&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
The \icon text macro expands internally to an &amp;lt;IMG&amp;gt; tag. The previous example, could be rewritten as follows:&lt;br /&gt;
&lt;br /&gt;
mob/verb/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot; \&lt;br /&gt;
              [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
From this, you can see that the object's current icon state is used. A reference to the icon itself is inserted using the \ref text macro, which generates a unique identifier corresponding to an object.&lt;br /&gt;
&lt;br /&gt;
A final noteworthy point is that the image belongs to a style class called `icon'. This can be used to configure global properties of icons in the text terminal. For example, a full 32x32 pixel icon doesn't always fit in with surrounding text very well. A single style sheet rule takes care of that:&lt;br /&gt;
&lt;br /&gt;
IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
This is, in fact, a built-in default rule, so you don't have to define it yourself. You could override it to get full 32x32 icons. You could even define special rules to allow icons in certain contexts to be different sizes. The &amp;lt;BIG&amp;gt; and &amp;lt;SMALL&amp;gt; tags are ideal:&lt;br /&gt;
&lt;br /&gt;
BIG IMG.icon {height: 32px; width: 32px}&lt;br /&gt;
SMALL IMG.icon {height: 16px; width: 16px}&lt;br /&gt;
Using the &amp;lt;BIG&amp;gt; tag, you could then output a full-sized icon, even though the default is small. The following example does that when the DM speaks in order to satisfy an inflated ego.&lt;br /&gt;
&lt;br /&gt;
mob/DM/say(Msg as text)&lt;br /&gt;
   view() &amp;lt;&amp;lt; &amp;quot;\icon[usr] [usr] says, '[Msg]'&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Special Effects==&lt;br /&gt;
&lt;br /&gt;
There are a couple miscellaneous commands which create special output effects. Like the image instruction, they produce a purely visual result.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===missile instruction===&lt;br /&gt;
&lt;br /&gt;
The missile instruction creates an image which moves from one location to another. It is often used as a symbolic indicator of the source and target of a projectile.&lt;br /&gt;
&lt;br /&gt;
missile	(Icon,Start,End)&lt;br /&gt;
Icon is the image icon or object type.&lt;br /&gt;
Start is the missile source.&lt;br /&gt;
End is the missile destination.&lt;br /&gt;
This could be used in a game of darts:&lt;br /&gt;
&lt;br /&gt;
obj/dart&lt;br /&gt;
   verb/throw(mob/M)&lt;br /&gt;
      missile(src,usr,M)&lt;br /&gt;
      del src&lt;br /&gt;
If more realism is desired, a check could be made first to determine if there is a straight unobstructed path between the attacker and target. (However, realism (in my opinion) is much overrated. Don't let it spoil a good piece of code unless you really have to. I am sure there are many cases in which our own universe too is unrealistic because God couldn't resist a simpler way of implementing things here and there. The sky is a perfect example. I mean, it looks a bit fake sometimes, doesn't it?)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===flick instruction===&lt;br /&gt;
&lt;br /&gt;
The flick instruction causes a temporary transition in the icon state of an object. It lasts until all the frames in that particular state have been played and then reverts to the true icon state.&lt;br /&gt;
&lt;br /&gt;
flick	(State,Obj)&lt;br /&gt;
State is the icon or icon state to display.&lt;br /&gt;
Obj is the target object.&lt;br /&gt;
Note that it is possible to specify an entirely different icon file. Normally, however, just the state of the existing icon file is specified.&lt;br /&gt;
&lt;br /&gt;
The flick instruction is often used for temporary animation sequences (like smiling, writhing in pain, etc.). These are different from changes of state which have a longer duration (like sleeping, flying, etc.). In those cases, one would simply assign the icon_state variable directly.&lt;br /&gt;
&lt;br /&gt;
Sometimes, however, a flick is used in the transition between two permanent states. The following example defines a door turf which does exactly that.&lt;br /&gt;
&lt;br /&gt;
turf/door&lt;br /&gt;
   icon = 'door.dmi'&lt;br /&gt;
   icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
   density = 1&lt;br /&gt;
   opacity = 1&lt;br /&gt;
   verb/open()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(!density) return //already open&lt;br /&gt;
      density = 0&lt;br /&gt;
      opacity = 0&lt;br /&gt;
      flick(&amp;quot;opening&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;open&amp;quot;&lt;br /&gt;
   verb/close()&lt;br /&gt;
      set src in view(1)&lt;br /&gt;
      if(density) return //already closed&lt;br /&gt;
      density = 1&lt;br /&gt;
      opacity = 1&lt;br /&gt;
      flick(&amp;quot;closing&amp;quot;,src)&lt;br /&gt;
      icon_state = &amp;quot;closed&amp;quot;&lt;br /&gt;
The advantage of using icon states in this way is that the code remains very general. All the map designer has to do is plug in different icons with the same states and a variety of doors can be made from the one basic definition.&lt;br /&gt;
&lt;br /&gt;
If the icon state specified by the flick instruction does not exist, it has no effect. In the above code, for example, a door icon could be used that did not have &amp;quot;opening&amp;quot; and &amp;quot;closing&amp;quot; states defined. Everything would work--only the transition would not be animated.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19457</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19457"/>
		<updated>2015-11-14T20:02:18Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* О порядке написания кода */ последняя правка. Хорошо бы какой-нибудь кодер проверил и упорядочил главы и содержание. Я не кодер.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
При разработке большого проекта, хотя бы один из участников(а желательно все) должен быть ознакомлен с тем, что делает каждый из написанных модулей и какое у него применение. Хорошим тоном считается делать простое и понятное описание и название для каждого модуля. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
Например, при добавлении дополнительных функций к процедуре client.Topic() в разных местах в коде случается эффект сочетания зачений в родительском элементе:&lt;br /&gt;
&amp;lt;!--One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
:  if(T == &amp;quot;вступление&amp;quot;)&lt;br /&gt;
:  usr &amp;lt;&amp;lt; &amp;quot;И вот как-то раз...&amp;quot;&lt;br /&gt;
:  else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
:  if(T == &amp;quot;подсказка&amp;quot;)&lt;br /&gt;
:  usr &amp;lt;&amp;lt; &amp;quot;Буквально позавчера.&amp;quot;&lt;br /&gt;
:  else ..()&lt;br /&gt;
В таком написании, эти два определения процедуры client/Topic(T) могут быть размещены в коде в любом месте. Если один из них будет выполнен и приведёт к значению ..() ,то другой уже не наступит. Вот в таких случаях и бывает полезно обращаться к процедуре-родителю&lt;br /&gt;
&amp;lt;!--As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Отладка кода===&lt;br /&gt;
&lt;br /&gt;
Или иначе дебаггинг(debugging).&lt;br /&gt;
&lt;br /&gt;
====Манеры хорошего кодера====&lt;br /&gt;
&lt;br /&gt;
Ошибка начинающих программистов в том, что они слишком полагаются на компилятор. Опытные баголовы и багоюзеры знают, что если код скомпилирован, то не факт что он работает как написано. Уязвимости бывают везде.&lt;br /&gt;
&amp;lt;!--The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Первый вызов для отладчика кода - суметь прочитать код и попробовать скомпилировать его в уме, так как его увидит машина. Возможно где-то не хватает переменных, возможно некоторые процессы ведут к нулевому значению, возможно некоторые условия невозможно выполнить в принципе. Думайте логически.&lt;br /&gt;
&amp;lt;!--The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Второй шаг - запустить код, так чтобы он заработал. Подставить необходимые переменные и запустить его в приложении. Сервер может выявить простые ошибки и баги, но только вы можете понять что работает не так, как оно должно работать, и почему это не так. А что работает именно так как описано в коде. Поиграйте с переменными и кодом, чтобы лучше понять механизмы компиляции и работы вашего кода.&lt;br /&gt;
&amp;lt;!--The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Затем проведите нагрузочное тестирование, попробуйте выйти за пределы допустимых параметров, указанных вами при создании объектов и фич для проекта. Как правило на этом этапе всплывают все баги и уязвимости в написанном и вы можете отловить их и пофиксить\оставить для рабочей версии проекта.&lt;br /&gt;
&amp;lt;!--After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;quot;Неуловимые&amp;quot; баги====&lt;br /&gt;
&lt;br /&gt;
Существует два типа багов: Краш-баги которые останавливают процесс целиком (proc crashers) и мелкие баги(silent errors), которые ломают отдельные фичи. : Пример Краш-бага - обращение к переменной объекта, отсутствие ответа от объекта, придание переменной по умолчанию равной нулю, что приводит к завершению оператора.&lt;br /&gt;
Когда крашится процедура, как правило сохраняются логи ошибки в world.log . При запуске созданного вами проекта в клиенте Dream Seeker, эта информация будет показана в отдельном окошке. При запуске проекта на сервере Dream Daemon - логи сохраняются в выводе серверной информации, либо в отдельном файле.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Самое главное - найти в логах название процедуры, которая вызвала падение выполнения кода, а также значение переменных src и usr на момент выполнения процедуры. Процедуры могут быть показаны цепочкой вызовов - будут показаны обращающиеся к этой и вызванной этой процедурой процедуры.  &lt;br /&gt;
&amp;lt;!--The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
Также вы можете воспользоваться макросом DEBUG, описанным выше для отлова багов и точным вычислением их месторасположения в коде исполняемого файла.&lt;br /&gt;
&amp;lt;!--If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
Существует команда, способная показать вам какое именно значение переменной привело к падению кода. Вот она:&lt;br /&gt;
&amp;lt;!--One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Отладка кода проводится как при отдельных случаях падения кода(и тогда удобнее пользоваться примерами приведёнными выше), так и по всем исполняемым строкам и файлам при финальной диагностике. В последнем случае вы можете пользоваться следующими макросами:&lt;br /&gt;
&amp;lt;!--Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
Вывод информации на отладку будет осуществляться, но он будет игнорироваться до тех пор, пока вы не используете макрос #DEBUG.&lt;br /&gt;
&amp;lt;!--You can then send output to debug and it will be ignored when not in DEBUG mode.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть полезный приём при поиске багов - вынести код в комментарии. Код, вынесенный в комментарий перестаёт восприниматься компилятором как исполняемые команды, зато виден разработчику. Это полезно для выделения кусков кода, ответственных за совершение ошибок при исполнении, и временном устранении их, вплоть до отладки проблемного места.&lt;br /&gt;
&amp;lt;!--Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.--&amp;gt;&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19456</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19456"/>
		<updated>2015-11-14T20:01:27Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Debugging Code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
При разработке большого проекта, хотя бы один из участников(а желательно все) должен быть ознакомлен с тем, что делает каждый из написанных модулей и какое у него применение. Хорошим тоном считается делать простое и понятное описание и название для каждого модуля. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
Например, при добавлении дополнительных функций к процедуре client.Topic() в разных местах в коде случается эффект сочетания зачений в родительском элементе:&lt;br /&gt;
&amp;lt;!--One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;вступление&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;И вот как-то раз...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;подсказка&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Буквально позавчера.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
В таком написании, эти два определения процедуры client/Topic(T) могут быть размещены в коде в любом месте. Если один из них будет выполнен и приведёт к значению ..() ,то другой уже не наступит. Вот в таких случаях и бывает полезно обращаться к процедуре-родителю&lt;br /&gt;
&amp;lt;!--As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Отладка кода===&lt;br /&gt;
&lt;br /&gt;
Или иначе дебаггинг(debugging).&lt;br /&gt;
&lt;br /&gt;
====Манеры хорошего кодера====&lt;br /&gt;
&lt;br /&gt;
Ошибка начинающих программистов в том, что они слишком полагаются на компилятор. Опытные баголовы и багоюзеры знают, что если код скомпилирован, то не факт что он работает как написано. Уязвимости бывают везде.&lt;br /&gt;
&amp;lt;!--The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Первый вызов для отладчика кода - суметь прочитать код и попробовать скомпилировать его в уме, так как его увидит машина. Возможно где-то не хватает переменных, возможно некоторые процессы ведут к нулевому значению, возможно некоторые условия невозможно выполнить в принципе. Думайте логически.&lt;br /&gt;
&amp;lt;!--The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Второй шаг - запустить код, так чтобы он заработал. Подставить необходимые переменные и запустить его в приложении. Сервер может выявить простые ошибки и баги, но только вы можете понять что работает не так, как оно должно работать, и почему это не так. А что работает именно так как описано в коде. Поиграйте с переменными и кодом, чтобы лучше понять механизмы компиляции и работы вашего кода.&lt;br /&gt;
&amp;lt;!--The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Затем проведите нагрузочное тестирование, попробуйте выйти за пределы допустимых параметров, указанных вами при создании объектов и фич для проекта. Как правило на этом этапе всплывают все баги и уязвимости в написанном и вы можете отловить их и пофиксить\оставить для рабочей версии проекта.&lt;br /&gt;
&amp;lt;!--After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;quot;Неуловимые&amp;quot; баги====&lt;br /&gt;
&lt;br /&gt;
Существует два типа багов: Краш-баги которые останавливают процесс целиком (proc crashers) и мелкие баги(silent errors), которые ломают отдельные фичи. : Пример Краш-бага - обращение к переменной объекта, отсутствие ответа от объекта, придание переменной по умолчанию равной нулю, что приводит к завершению оператора.&lt;br /&gt;
Когда крашится процедура, как правило сохраняются логи ошибки в world.log . При запуске созданного вами проекта в клиенте Dream Seeker, эта информация будет показана в отдельном окошке. При запуске проекта на сервере Dream Daemon - логи сохраняются в выводе серверной информации, либо в отдельном файле.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Самое главное - найти в логах название процедуры, которая вызвала падение выполнения кода, а также значение переменных src и usr на момент выполнения процедуры. Процедуры могут быть показаны цепочкой вызовов - будут показаны обращающиеся к этой и вызванной этой процедурой процедуры.  &lt;br /&gt;
&amp;lt;!--The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
Также вы можете воспользоваться макросом DEBUG, описанным выше для отлова багов и точным вычислением их месторасположения в коде исполняемого файла.&lt;br /&gt;
&amp;lt;!--If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
Существует команда, способная показать вам какое именно значение переменной привело к падению кода. Вот она:&lt;br /&gt;
&amp;lt;!--One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Отладка кода проводится как при отдельных случаях падения кода(и тогда удобнее пользоваться примерами приведёнными выше), так и по всем исполняемым строкам и файлам при финальной диагностике. В последнем случае вы можете пользоваться следующими макросами:&lt;br /&gt;
&amp;lt;!--Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
Вывод информации на отладку будет осуществляться, но он будет игнорироваться до тех пор, пока вы не используете макрос #DEBUG.&lt;br /&gt;
&amp;lt;!--You can then send output to debug and it will be ignored when not in DEBUG mode.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Есть полезный приём при поиске багов - вынести код в комментарии. Код, вынесенный в комментарий перестаёт восприниматься компилятором как исполняемые команды, зато виден разработчику. Это полезно для выделения кусков кода, ответственных за совершение ошибок при исполнении, и временном устранении их, вплоть до отладки проблемного места.&lt;br /&gt;
&amp;lt;!--Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.--&amp;gt;&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19426</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19426"/>
		<updated>2015-11-14T17:23:45Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Типичные проблемы в больших проектах */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
При разработке большого проекта, хотя бы один из участников(а желательно все) должен быть ознакомлен с тем, что делает каждый из написанных модулей и какое у него применение. Хорошим тоном считается делать простое и понятное описание и название для каждого модуля. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
Например, при добавлении дополнительных функций к процедуре client.Topic() в разных местах в коде случается эффект сочетания зачений в родительском элементе:&lt;br /&gt;
&amp;lt;!--One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;вступление&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;И вот как-то раз...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;подсказка&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Буквально позавчера.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
В таком написании, эти два определения процедуры client/Topic(T) могут быть размещены в коде в любом месте. Если один из них будет выполнен и приведёт к значению ..() ,то другой уже не наступит. Вот в таких случаях и бывает полезно обращаться к процедуре-родителю&lt;br /&gt;
&amp;lt;!--As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19425</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19425"/>
		<updated>2015-11-14T17:21:00Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Типичные проблемы в больших проектах */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
При разработке большого проекта, хотя бы один из участников(а желательно все) должен быть ознакомлен с тем, что делает каждый из написанных модулей и какое у него применение. Хорошим тоном считается делать простое и понятное описание и название для каждого модуля. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
Например, при добавлении дополнительных функций к процедуре client.Topic() в разных местах в коде случается эффект сочетания зачений в родительском элементе:&lt;br /&gt;
&amp;lt;!--One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;вступление&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;И вот как-то раз...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;подсказка&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Буквально позавчера.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
В таком написании, эти два определения процедуры client/Topic(T) могут быть &lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19424</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19424"/>
		<updated>2015-11-14T17:11:07Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Типичные проблемы в больших проектах */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Понятие модуля применимо не только к какой-либо части кода, а чаще подразумевает файл или группу файлов. Открытая часть модуля - процедуры, переменные и объекты, свободные для использования в других местах помимо самого модуля. Закрытая часть модуля - это собственно тело самого модуля, сам код, который однокомпонентен.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19411</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19411"/>
		<updated>2015-11-14T14:44:24Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Типичные проблемы в больших проектах */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* Последовательность кода важна при наследовании процедур или переменных объекта. Если какая-либо процедура повторяется несколько раз, то она наследует последовательность выполнения первого раза.&lt;br /&gt;
&amp;lt;!--Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=Lawyer&amp;diff=19410</id>
		<title>Lawyer</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=Lawyer&amp;diff=19410"/>
		<updated>2015-11-14T13:54:20Z</updated>

		<summary type="html">&lt;p&gt;IXVI: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; cellspacing=&amp;quot;0&amp;quot; cellpadding=&amp;quot;2&amp;quot; width=&amp;quot;80%&amp;quot; style=&amp;quot;background-color:#ffeaea;&amp;quot;&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; width=200|Профессия&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; |Роль&lt;br /&gt;
!style=&amp;quot;background-color:#dd3e40;&amp;quot; width=100|Сложность&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
![[File:Joblaw.png‎]]&amp;lt;br&amp;gt;[[Lawyer|Адвокат]]&lt;br /&gt;
|'''Доступ:''' Кабинет адвоката, Зал суда, Бриг.&lt;br /&gt;
'''Подчинение:''' [[Head of Security|Глава СБ]].&lt;br /&gt;
&lt;br /&gt;
'''Обязанности:''' Предоставлять подсудимым и подозреваемым юридическую защиту.&lt;br /&gt;
&lt;br /&gt;
'''Другие названия:''' Юрист&lt;br /&gt;
&lt;br /&gt;
'''Guides:''' [[Guide to Security]], [[Guide to Trials]], [[Space Law]], [[Guide to Paperworks]]&lt;br /&gt;
!Средне - Очень сложно&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;p style=&amp;quot;text-align:right;&amp;quot;&amp;gt;''“Когда обнаруживаешь, что ты чуть ли не единственный, кто эти моральные преграды имеет, возникает порой искушение послать их к черту — не по убеждению и не ради удовольствия, а просто потому, что обидно быть ангелом в аду, в то время как дьявол везде себя чувствует дома.”&lt;br /&gt;
''&amp;lt;br/&amp;gt;'''''Мартен Паж, &amp;quot;Как я стал идиотом&amp;quot;'''''&amp;lt;/p&amp;gt;&lt;br /&gt;
[[File:Lawyer.PNG|right|thumb|Офис адвоката. Кофе, пончики, бездельники.]]&lt;br /&gt;
[[File:Law_MetaOffice.png|right|thumb|Офис адвоката на Metastation.]]&lt;br /&gt;
&lt;br /&gt;
== Юриспруденция-13 ==&lt;br /&gt;
&lt;br /&gt;
Вот перечень дел, с которыми приходится сталкиваться штатному законнику:&lt;br /&gt;
&lt;br /&gt;
*'''Проводить консультации по [[Space Law|Космо-Закону]]''' Теоретически, адвокат должен присутствовать при процедуре заключения в камеру. Для этого вам понадобится отличное знание свода законов, либо экземпляр книги по Космо-закону. Вашими усилиями срок может быть сокращён, заменён на альтернативное наказание, либо на более тяжкое наказание. В зависимости от [[Clown|клиента]].&lt;br /&gt;
&lt;br /&gt;
*'''Быть адвокатом''' Теоретически, адвокат ведёт дело каждого злоумышленника и способен более тонко разобраться в составе преступления, участниках и доказательствах каждого дела. Важнейшие вещи здесь - это записи службы безопасности, улики и свидетельства участников.&lt;br /&gt;
&lt;br /&gt;
*'''Заботиться о своих клиентах''' Поскольку обычно СБ проводит задержания в агрессивной манере, и относится к преступникам как к швали - то, теоретически, адвокат берёт на себя заботу о здоровье и благополучии своих клиентов. Зачастую, именно он добивается сокращения срока задержания, в связи с кошмарными условиями.&lt;br /&gt;
&lt;br /&gt;
*'''Следить за порядком на бриге''' Теоретически, в 90% случаев процедура дознания и обыска ведётся на территории брига. Поэтому адвокат должен чётко знать, где лежат вещи его клиента, где хранятся улики и чья кровь осталась на вот этом станбатоне. Также адвокат должен уметь предсказать в какой именно момент этот порядок перестанет существовать.&lt;br /&gt;
&lt;br /&gt;
*'''Пропускать желающих на бриг''' Теоретически, адвокат имеет доступ на бриг, в отличие от гражданского персонала, и в его обязанности входит сопровождать людей для дачи показаний, либо выпровождать заключённых отсидевших свой срок. И возвращать им их &amp;lt;s&amp;gt;улики&amp;lt;/s&amp;gt; вещи.&lt;br /&gt;
&lt;br /&gt;
*'''Вести судебный процесс''' Теоретически, каждый член экипажа имеет право отстаивать свои права в судебном порядке. Поэтому время от времени на борту корабля проводятся суды с участием Верховного судьи, Обвиняемого и Защиты. Вы можете оказаться на любой из этих сторон.&lt;br /&gt;
&lt;br /&gt;
*'''Оказывать нотариальные услуги''' Ничто так высоко не ценится, как грамотно составленный, подтверждённый печатью документ, сопровождающий любые виды деятельности: От заказа ящика бананов, до лицензии на убийство. К сожалению, большинство персонала не может грамотно изложить свои доводы, составить документ и получить заветную печать - и совершают свои поступки полу-легальным путём. Так вот, теоретически - хороший адвокат, как человек связанный с законом и лояльный к службе безопасности, способен быстро и без проволочек получить любое разрешение на станции.&lt;br /&gt;
&lt;br /&gt;
*'''Участие в делах''' о покушениях, нарушениях, кражах, обмане, нарушении техники безопасности, подозрительных объектах и субъектах, денежных спорах, наследственных делах, приватизации отделов и инвентаря, скупки акций Нанотрасен, теоретически - даже в праве на собственность атомной бомбы НТ в личное пользование на неопределённый срок. Хороший адвокат всегда в бизнесе.&lt;br /&gt;
&lt;br /&gt;
== Закон в моих руках ==&lt;br /&gt;
Законы юрисдикции присутствуют и на нашей станции, куда уж без них! Надеждой и опорой невиновных или преступников, совершивших малые преступления - будете именно вы, адвокат. Вам будут предоставлены все привилегии проведения честных судов. Ваша главная опора - это закон. Закон на станции действует всегда, но иногда требуется вмешательство человека с стороны. Это вы и есть. Добро пожаловать. &lt;br /&gt;
&lt;br /&gt;
===Все для дела===&lt;br /&gt;
Вы имеете в своей комнате запасную одежду, сканер для проверки подлинности улик, бумагу, карандаши, диктофон и свод космического закона. Также ваша комната оснащена специальными шторами, для конфиденциальных бесед с клиентами.&lt;br /&gt;
&lt;br /&gt;
==Слово и честь - вот мое оружие==&lt;br /&gt;
В ваших обязанностях уличать Службу Безопасности в необоснованных сроках задержания. Здесь свою роль играет то, как они задержали преступника, какой урон ему был нанесен. Рекомендуется обзавестись поддержкой мед-персонала, который мог бы выделить вам бесценный анализатор здоровья. Также, без поддержки авторитета в лице капитана, вам будет трудно говорить с СБ &amp;quot;на ты&amp;quot;. Но не беспокойтесь, юрисдикция предписана законом, потому вам предоставят всю возможную помощь в ведении собственного следствия.&lt;br /&gt;
&lt;br /&gt;
Иметь обаяние предписано самой романтике профессии юриста! Не пытайтесь провоцировать охрану, помогать очевидным преступникам и до последнего стоять на стороне обвиняемого. У нас интеллигентная и нравственная охрана, потому все будет соответствующе. &lt;br /&gt;
&lt;br /&gt;
===Проверьте всё дважды===&lt;br /&gt;
Клиент - всегда прав. Но в этот раз правы вы, и только вы. Не верьте ни единому слову истца или детектива. Они не имеют права фальсифицировать или укрывать улики, но дружба в рядах нашей Службы Безопасности доходит до того, что они способны друг друга прикрывать от позора безосновательных тюремных сроков.&lt;br /&gt;
&lt;br /&gt;
===Этика справедливости===&lt;br /&gt;
Мы уверены в верности ваших слов, не разочаруйте наших надежд. Ложь и обман наказуем в виде разжалования, а если ваш клиент - явный преступник, то не стоит прибегать к методам воров и дебоширов, которых вы только и встретите. На уважение ответят уважением. Силовые структуры могут вам и не верить, но поддержки у иных глав станции вы должны добиться. Только из-за того, что вы адвокат. Ведь на станции только грамотные и психически уравновешенные люди, понимающие всю важность вашей должности. &lt;br /&gt;
&lt;br /&gt;
{{JobMenu}}&lt;br /&gt;
[[Category:/tg/station13]]&lt;br /&gt;
[[Category:Fernflower]]&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19408</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19408"/>
		<updated>2015-11-14T13:20:29Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Типичные проблемы в больших проектах */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===О порядке написания кода===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях:&lt;br /&gt;
* Препроцессор читает код исключительно последовательно - с первой строчки до последней. Поэтому макросы (значения макросов) , которые запрашивают препроцессорные команды, должны быть записаны в коде ранее препроцессорных команд. В данном случае более удобно использовать переменные(variables).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.--&amp;gt;&lt;br /&gt;
* &lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19407</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19407"/>
		<updated>2015-11-14T13:15:05Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Some Code Management Issues */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Типичные проблемы в больших проектах==&lt;br /&gt;
&lt;br /&gt;
Первая и наиболее важная - поддержка простого кода. Старайтесь не использовать весь ваш код в одном файле. Думайте о возможных будущих правках и старайтесь диверсифицировать строки кода для дальнейшего удобного чтения и поиска возможных ошибок, и задания переменных. Старайтесь придерживаться модульной системы - под каждую задумку отдельный файл кода, это позволит без проблем сохранить и переносить ваши фичи с одной сборки на другую.&lt;br /&gt;
&amp;lt;!--There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
По мере роста проекта, весь последующий код накладывается на предыдущий. Кроме того, код постоянно усложняется - от простых переменных - к сложным, от сложных переменных - к процедурным, от процедурных - к объектам, и так далее по нарастающей. Помните об этом и старайтесь не перекрывать и не повторять ранее использованные строки и описания. &lt;br /&gt;
&amp;lt;!--If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Как упорядочить код===&lt;br /&gt;
&lt;br /&gt;
Во многих случаях, последовательность или порядок кода в Dream Maker не имеет особого значения(sic!). Например процедура, переменная или тип объекта могут быть заданы до или после их прямой компиляции. Это непривычная особенность, отличающая код DM от других, где порядок написания имеет важное значение при исполнении программ.&lt;br /&gt;
&amp;lt;!--In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Последовательность кода важна в нескольких случаях. В препроцессоре,&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19406</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19406"/>
		<updated>2015-11-14T12:59:31Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #ifdef */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
: set category = &amp;quot;Debugging&amp;quot;      &lt;br /&gt;
: usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19405</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19405"/>
		<updated>2015-11-14T12:59:14Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #if */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world) &amp;lt;br&amp;gt;&lt;br /&gt;
set category = &amp;quot;Debugging&amp;quot;       &amp;lt;br&amp;gt;&lt;br /&gt;
usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
: //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19404</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19404"/>
		<updated>2015-11-14T12:58:46Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #if */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world) &amp;lt;br&amp;gt;&lt;br /&gt;
set category = &amp;quot;Debugging&amp;quot;       &amp;lt;br&amp;gt;&lt;br /&gt;
usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0  &amp;lt;br&amp;gt;&lt;br /&gt;
//Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19403</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19403"/>
		<updated>2015-11-14T12:58:33Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #ifdef */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world) &amp;lt;br&amp;gt;&lt;br /&gt;
set category = &amp;quot;Debugging&amp;quot;       &amp;lt;br&amp;gt;&lt;br /&gt;
usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
   //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19402</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19402"/>
		<updated>2015-11-14T12:57:38Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Условная компиляция */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Компиляция по условиям (Условная компиляция)===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
   //Неактивный код.&lt;br /&gt;
: #endif&lt;br /&gt;
Так как Dream Maker поддерживает вложенность команд одна в другую, также возможно взять ненужный\неиспользуемый на данный момент кусок кода в /* комментарий */ - используя разметку /* */&lt;br /&gt;
Оператор #if привычен для использования программистами С, так как в этом языке компилятор плохо поддерживает вложенность команд.&lt;br /&gt;
&amp;lt;!--Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19399</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19399"/>
		<updated>2015-11-14T10:50:55Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Условная компиляция */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Условная компиляция===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода при помощи #ifdef :&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
Команда #if - более общая версия #ifdef, так как включает определения не только макросов но и констант. То есть если выражение совпадает (true), то код внутри #if будет скомпилирован, если выражение не совпадает (false), то код не будет выполняться. В случае невыполнения условий применяется команда #elif, а в случае невыполнения никаких условий из заданных вами, используется команда #else.&lt;br /&gt;
&amp;lt;!--command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #elif Условие&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #else&lt;br /&gt;
//Код условия.&lt;br /&gt;
: #endif&lt;br /&gt;
Условия могут состоять из базовых (простых) операторов, или логических (boolean) операторов. После проверки данного макроса выдаётся результат = 1 , или = 0&lt;br /&gt;
&amp;lt;!--The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro - название макроса.&lt;br /&gt;
Выдаёт 1 (Returns 1) если макрос определён &amp;lt;!--if macro has been defined--&amp;gt; и 0, если не был.&lt;br /&gt;
Часто команда #if используется для блокировки выполнения куска кода - в случае если происходит краш, или нужно выключить какую-либо фичу без выпиливания куска кода. Вот пример выполнения кода:&lt;br /&gt;
&amp;lt;!--One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
: #endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19398</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19398"/>
		<updated>2015-11-14T10:36:56Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Chapter 19 */ Двоеточие перед решёткой.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
: #include &amp;lt;libfile&amp;gt;&lt;br /&gt;
: #include &amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
: #define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
: #define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
: #define FILE_DIR icons&lt;br /&gt;
: #define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Условная компиляция===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
: #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода:&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
: #if Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
: #elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
: #else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
: #endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
: #if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
: #endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
: #error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
: #ifndef DM&lt;br /&gt;
: #error You need to define DM as the name of your key!&lt;br /&gt;
: #endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
: #ifdef DEBUG&lt;br /&gt;
: #define debug world.log&lt;br /&gt;
: #else&lt;br /&gt;
: #define debug null&lt;br /&gt;
: #endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19397</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19397"/>
		<updated>2015-11-14T10:23:34Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #ifdef */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Условная компиляция===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# #ifdef	Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
# #endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода:&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19395</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19395"/>
		<updated>2015-11-14T09:20:24Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Conditional Compilation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Условная компиляция===&lt;br /&gt;
&lt;br /&gt;
Препроцессоры могут быть использованы для пропуска части кода по заданным усолвиям, которые определяются наличием или значением используемых макросов. Таким образом вы сможете управлять какими-либо добавочными настройками(фичами), размещая условия компиляции в начале кода.&lt;br /&gt;
&amp;lt;!--The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот данные макросы условий для компиляции.&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
Команда #ifdef разрешает компилировать последующий код, только если определённому макросу было задано определённое значение. Выполнение данной команды завершается оператором #endif&lt;br /&gt;
&amp;lt;!--command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#ifdef	Macro&lt;br /&gt;
//Условие для дальнейшего выполнения кода.&lt;br /&gt;
#endif&lt;br /&gt;
Также существует команда #ifndef - она срабатывает если значение определённого макроса не было задано.&lt;br /&gt;
&amp;lt;!--There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Например макрос DEBUG можно включать для определённого участка кода:&lt;br /&gt;
&amp;lt;!--The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19393</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19393"/>
		<updated>2015-11-14T08:46:08Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* Препроцессор */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Специальные макросы===&lt;br /&gt;
&lt;br /&gt;
Есть несколько макросов, имеющих определённые специальные значения.&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
Макрос FILE_DIR - определяет поисковый путь для ресурс-паков, включённых в ваш проект. Может быть использван(переопределён) многократно, каждый новый заданный путь просто будет добавлен в другим путям поискам.&lt;br /&gt;
&amp;lt;!--macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path - путь к ресурс-пакам.&lt;br /&gt;
Используя данный макрос, вы сможете сократить пути поиска ваших ресурсов компилятором. Просто заранее введите возможные пути расположения файлов, и в дальнейшем набирайте только имя искомого файла(ресурс-пака).&lt;br /&gt;
&amp;lt;!--By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как пример - задание макросов для поиска спрайтов(icons) и звуков(sounds):&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
Макрос DEBUG включает добавление дополнительной информации в файл .dmb ,что плохо сказывается на скорости исполнения процедур кода, но построчно записывает информацию о выполнении всего кодового файла - в том числе где возникают ошибки, баги и отчего крашится код.&lt;br /&gt;
&amp;lt;!--macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
Просто добавьте эту строчку в ваш код, и режим Debug будет включен.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __FILE__ показывает файл в котором распологается исполняемый в данный момент код. Полезный макрос для создания Debug-сообщений.&lt;br /&gt;
&amp;lt;!--macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
Макрос __LINE__ показывает строчку кода, которая исполняется в данный момент. Тоже полезен для выведения Debug-сообщений. Вот пример:&lt;br /&gt;
&amp;lt;!--macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //Сейчас крашнется.&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //Нет? Странно...&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
Макрос DM_VERSION показывает номер версии вашего компилятора. Используется для определения устаревшей версии кода, и замены некоторых операторов на новые.&lt;br /&gt;
&amp;lt;!--macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
Макрос #undef убирает заранее заданный макрос. Его можно расположить после исполненного макроса для переназначения значений, а также в конце кодового файла, чтобы данный макрос не перешёл на исполнение в другие файлы.&lt;br /&gt;
&amp;lt;!--command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Conditional Compilation===&lt;br /&gt;
&lt;br /&gt;
The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.&lt;br /&gt;
&lt;br /&gt;
The commands for conditionally compiling code are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
The #ifdef command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.&lt;br /&gt;
&lt;br /&gt;
#ifdef	Macro&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19392</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19392"/>
		<updated>2015-11-14T08:31:18Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* оператор #define */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Также можно придавать макросу значения аргументов, для более точного применения их в коде:&lt;br /&gt;
&amp;lt;!--It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 - название первого аргумента.&lt;br /&gt;
Arg2 - название второго аргумента, и т.д.&lt;br /&gt;
Перечисляемые аргументы будут найдены в коде, и им будет подставлено значение(value) данного макроса. Считается что это процедурный уровень, но так как он оперирует текстовыми значениями, его возможности более обширны и гибки.&lt;br /&gt;
&amp;lt;!--Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Использовать макросы в выражениях следует с осторожностью - компилятор может не успеть посчитать вставленный из макроса текст, особенно в сочетании с другими текстовыми значениями кода. Для безопасности вы можете взять значения макроса в круглые скобки #define Macro (Value) - чтобы значение не пересекалось с другим исполняемым кодом.&lt;br /&gt;
&amp;lt;!--Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Вот пример кода, применяемый для решения проблем с оператором сдвигом разряда &amp;lt;&amp;lt; ,без затрагивания остальной части кода после вставления макроса.&lt;br /&gt;
&amp;lt;!--The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Special Macros===&lt;br /&gt;
&lt;br /&gt;
There are a few macros with special meanings. These are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
The FILE_DIR macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path is the location of resource files.&lt;br /&gt;
By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.&lt;br /&gt;
&lt;br /&gt;
The following example is a typical case. It simply defines two directories--one for icons and one for sounds.&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
It doesn't matter if you give DEBUG a value or not. Just defining it turns on debugging mode.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
The __FILE__ macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
The __LINE__ macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
The DM_VERSION macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
The #undef command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Conditional Compilation===&lt;br /&gt;
&lt;br /&gt;
The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.&lt;br /&gt;
&lt;br /&gt;
The commands for conditionally compiling code are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
The #ifdef command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.&lt;br /&gt;
&lt;br /&gt;
#ifdef	Macro&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19391</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19391"/>
		<updated>2015-11-14T08:22:54Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* #define */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===''оператор'' #define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс), или иначе говоря переменную в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. Примеры:&lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name - название макроса(префикса).&lt;br /&gt;
Value - значение макроса(переменной).&lt;br /&gt;
&lt;br /&gt;
Команды препроцессора заканчивают исполнение по завершении строчки кода, в которой они описаны. Если вы хотите расписать свой код на несколько строк, используйте символ \ в конце строки.&lt;br /&gt;
&amp;lt;!--This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Название макроса может состоять из заглавных и строчных букв, цифр и символа подчёркивания, но не может начинаться с цифры. По умолчанию НАЗВАНИЕ МАКРОСОВ часто набирают исключительно заглавными буквами.&lt;br /&gt;
&amp;lt;!--The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 is the name of the first argument.&lt;br /&gt;
Arg2 is the name of the second argument, etc.&lt;br /&gt;
Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.&lt;br /&gt;
&lt;br /&gt;
Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.&lt;br /&gt;
&lt;br /&gt;
The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Special Macros===&lt;br /&gt;
&lt;br /&gt;
There are a few macros with special meanings. These are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
The FILE_DIR macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path is the location of resource files.&lt;br /&gt;
By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.&lt;br /&gt;
&lt;br /&gt;
The following example is a typical case. It simply defines two directories--one for icons and one for sounds.&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
It doesn't matter if you give DEBUG a value or not. Just defining it turns on debugging mode.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
The __FILE__ macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
The __LINE__ macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
The DM_VERSION macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
The #undef command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Conditional Compilation===&lt;br /&gt;
&lt;br /&gt;
The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.&lt;br /&gt;
&lt;br /&gt;
The commands for conditionally compiling code are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
The #ifdef command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.&lt;br /&gt;
&lt;br /&gt;
#ifdef	Macro&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
	<entry>
		<id>https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19385</id>
		<title>DM Guide 19</title>
		<link rel="alternate" type="text/html" href="https://wiki.ss13.ru/index.php?title=DM_Guide_19&amp;diff=19385"/>
		<updated>2015-11-13T20:30:49Z</updated>

		<summary type="html">&lt;p&gt;IXVI: /* The Preprocessor */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Заготовка}}&lt;br /&gt;
''Это 19 глава перевода оригинального руководства по Dream Maker от разработчиков.''&lt;br /&gt;
&lt;br /&gt;
[http://wiki.ss13.ru/index.php?title=All_about_the_code Остальные главы руководства и статьи о программировании на коде BYOND от любителей на русском.]&lt;br /&gt;
&lt;br /&gt;
[http://www.byond.com/docs/guide/chap19.html Оригинальная 19 глава руководства на английском языке]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Chapter 19=&lt;br /&gt;
&lt;br /&gt;
Управление кодом в Больших Проектах&lt;br /&gt;
&lt;br /&gt;
До сих пор примеры были небольшими и простыми, умещающимися в один файл .dm кодировки. Однако в дальнейшем может оказаться более удобным разделять и различать код для различных объектов в раздельные файлы. Например систему рукопашного боя в одном месте, описание мобов в другом, работу двигателей в третьем, и так далее. Также это хорошая практика для кодеров - возиться каждый со своим файлом, а не дёргать один общий.&lt;br /&gt;
&lt;br /&gt;
Также разделение кода по различным файлам делает ваши наработки более мобильными - их можно вставлять в другие проекты\сборки\заготовки. Такие файлы кода часто называют библиотеками (как dll) и вы можете найти множество других библиотек, а также делиться своими собственными.&lt;br /&gt;
&lt;br /&gt;
==Включение файлов (''оператор'' #include)==&lt;br /&gt;
&lt;br /&gt;
Содержимое одного файла может быть свободно включено в другой, благодарю использованию команды #include &amp;lt;br&amp;gt;&lt;br /&gt;
Есть две формы записи данного оператора, в зависимости от способа поиска включаемого содержимого. В первом случае компилятор будет искать файл в директории /library, а в другом случае он обратится к текущей директории и если не найдёт искомый файл, то к /library. Например&lt;br /&gt;
&amp;lt;!-- The contents of one source file may be inserted into another by using the #include command. There are two forms depending on where you want the compiler to look for the file. In one case it only looks in the library directory and in the other it looks in the current directory first and then in the library directory if necessary. Оригинал--&amp;gt;&lt;br /&gt;
#include	&amp;lt;libfile&amp;gt;&lt;br /&gt;
#include	&amp;quot;dmfile&amp;quot;&lt;br /&gt;
libfile - это включаемая библиотека. &amp;lt;!-- library file --&amp;gt;&lt;br /&gt;
&amp;quot;dmfile&amp;quot; - это файл исходного кода. &amp;lt;!-- source code file --&amp;gt;&lt;br /&gt;
Если один и тот же файл включается несколько раз, то проводится только первый запрос. Делается это для предотвращения повторов данной библиотеки кода, которую запрашивают несколько файлов в одном проекте.&amp;lt;!-- This prevents trouble in cases where several files in a project all include the same library file. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Все проекты по умолчанию включают файл &amp;lt;stddef.dm&amp;gt; в начало кода. Это библиотека, описывающая несколько постоянных переменных и определителей.&amp;lt;!-- This file defines a few standard constants and makes some basic definitions. --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Помимо включения файлов типа .dm , команда #include также используется для прикрепления карт уровней (например.dmm) к проекту. Синтакс(написание) оператора точно такое же. Карты уровней вставляются в главную карту мира и распределяются по z-уровню. Икс и Игрик координаты автоматически определяются по размеру наибольшей из вставляемых карт.&lt;br /&gt;
&amp;lt;!--Besides inserting source code files (ending in .dm), the #include command is also used to attach map files (ending in .dmm) to a project. The syntax is the same in either case. Map files are inserted into the main world map in successive z-levels and the x-y boundaries of the main map are automatically adjusted to fit the largest map which is included.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Рисунок 19.28: Перед Пре-процессингом&lt;br /&gt;
&lt;br /&gt;
Когда вы используете Dream Maker для управления своим проектом, вам крайне редко придётся использовать сами операторы #include и #define FILE_DIR macros. В Dream Maker эти функции реализуются через сам интерфейс. &amp;lt;!--If you are using the Dream Maker interface to manage your project, you will very rarely have to use the standard #include and #define FILE_DIR macros. The reason is that Dream Maker automates these functions through the interface.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Как упоминалось ранее, кодовые файлы и файлы карт добавляются через чек-бокс в диспетчере файлов. Привязка файлов происходит также. Все файлы в директории вашего проекта и внутри неё автоматически размещаются без добавления путей к ним. И путь к каждому файлу в Dream Maker упрощается до названия самого файла, например: world/icons/mobs/warrior.dmi = warrior.dmi&lt;br /&gt;
&amp;lt;!--As mentioned earlier, code and map files are included by selecting the corresponding check-boxes in the file tree. The file referencing is handled with similar ease. All files in the project directory and below are automatically recognized without the need to supply directories or manually create FILE_DIR entries. For instance, if your project is in the directory world, you may access the file world/icons/mobs/warrior.dmi by simply supplying the name, warrior.dmi.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
В некоторых случаях применение команды #include размещает файл на исполнение выше, чем это указанно в коде. Подробнее об этом в разделе 19.3.1.&lt;br /&gt;
&amp;lt;!--One time when you might need to use #include directly is to force a file to be processed before the code which follows. Section 19.3.1 describes the few situations in which the order of DM source code does matter.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Препроцессор==&lt;br /&gt;
&lt;br /&gt;
Команда #include - одна из нескольких &amp;quot;препроцессорных&amp;quot; команд. Опознать их можно по символу &amp;quot;#&amp;quot; и последовательному расположению в коде (Препроцессор Dream Maker в данном случае подобен компиляторам C и C++. Также эти люди называют команды &amp;quot;препроцессорными директивами). Препроцессор управляет данными командами, пока файл кода начинает исполняться и может изменять поведение файлов, в зависимости от распознавания их компилятором. Другие препроцессорные команды изложены ниже:&lt;br /&gt;
&amp;lt;!--The #include command is one of several preprocessor commands. They all begin with &amp;quot;#&amp;quot; and are placed on a line by themselves. (The DM preprocessor is identical to the one used in C and C++ compilers. The commands are often called preprocessor directives by C programmers.) The preprocessor handles such commands while the code file is initially being read and can be used to alter the appearance of the file as seen by the compiler. Additional preprocessor commands will be described in the following sections.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#define===&lt;br /&gt;
&lt;br /&gt;
Команда #define создаёт макрос(префикс) в препроцессоре. Любые участки с данным префиксом в коде будут замещены содержанием данного макроса. В местах, где макрос является частью другого слова или используется в текстовом описании, команда не сработает. &lt;br /&gt;
&amp;lt;!--command creates a preprocessor macro. Any subsequent(последующий) occurrences(случай) of the macro in the code will be replaced by the contents of the macro. Places where the macro occurs as part of another word or inside a text string do not count and will not be substituted.--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define	Name Value&lt;br /&gt;
Name is the macro name.&lt;br /&gt;
Value is the text to substitute in its place.&lt;br /&gt;
This and all other preprocessor commands are terminated by the end of the line. Therefore, if you wish to extend it onto multiple lines, you must use \ to escape the end of the line.&lt;br /&gt;
&lt;br /&gt;
The name of the macro may consist of upper and lowercase letters as well as digits and the underscore, as long as the first character is not a digit. By convention, macros are often named in all uppercase, but this is not a requirement.&lt;br /&gt;
&lt;br /&gt;
It is also possible to have the macro take arguments which may then be substituted into the replacement text as desired.&lt;br /&gt;
&lt;br /&gt;
#define	Name(Arg1,Arg2,...) Value&lt;br /&gt;
Arg1 is the name of the first argument.&lt;br /&gt;
Arg2 is the name of the second argument, etc.&lt;br /&gt;
Wherever the argument names appear in the replacement text, they will be replaced by the values passed to the macro when it is used. Such a macro can be used like a procedure, but since it operates at the textual level, it is possible to do things which would not be possible with a procedure.&lt;br /&gt;
&lt;br /&gt;
Care should be taken when using macros in expressions. Since the macro substitution simply inserts text from one place into another there is no guarantee that expressions within the macro will be evaluated before being combined with an outer expression. To be safe, you can put parenthesis around macro expressions to ensure they do not get combined in some unforeseen way with the external code.&lt;br /&gt;
&lt;br /&gt;
The following code, for example, uses this technique to prevent the bitshift operator &amp;lt;&amp;lt; from taking a lower order of operations when the macro is used in some larger expression.&lt;br /&gt;
&lt;br /&gt;
#define FLAG1 (1&amp;lt;&amp;lt;0)&lt;br /&gt;
#define FLAG2 (1&amp;lt;&amp;lt;1)&lt;br /&gt;
#define FLAG3 (1&amp;lt;&amp;lt;2)&lt;br /&gt;
&lt;br /&gt;
===Special Macros===&lt;br /&gt;
&lt;br /&gt;
There are a few macros with special meanings. These are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====FILE_DIR====&lt;br /&gt;
&lt;br /&gt;
The FILE_DIR macro defines the search path for resource files (i.e. files in single quotes). Unlike most macros, it may be defined multiple times in a cumulative fashion. Subsequent definitions simply add to the list of paths to search.&lt;br /&gt;
&lt;br /&gt;
#define	FILE_DIR Path&lt;br /&gt;
Path is the location of resource files.&lt;br /&gt;
By using this macro, you can avoid entering the full path to resource files but can instead just enter the name of the file and let the compiler find it for you. Of course this would lead to confusion if the files in all the specified locations do not have unique names. If that happens, the first one found will be used.&lt;br /&gt;
&lt;br /&gt;
The following example is a typical case. It simply defines two directories--one for icons and one for sounds.&lt;br /&gt;
&lt;br /&gt;
#define FILE_DIR icons&lt;br /&gt;
#define FILE_DIR sounds&lt;br /&gt;
&lt;br /&gt;
====DEBUG====&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro enables the inclusion of extra debugging information in the dmb file. This makes the file bigger and will result in very slightly slower execution of procedures. However, the advantage is that when a proc crashes, it will tell you the source file and line number where the problem occurred. Without the extra debugging information, only the name of the procedure is reported.&lt;br /&gt;
&lt;br /&gt;
#define DEBUG&lt;br /&gt;
It doesn't matter if you give DEBUG a value or not. Just defining it turns on debugging mode.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__FILE__====&lt;br /&gt;
&lt;br /&gt;
The __FILE__ macro is replaced by a text string containing the name of the current source file. This may be useful when generating debugging error messages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====__LINE__====&lt;br /&gt;
&lt;br /&gt;
The __LINE__ macro is replaced by the number of the current source line being read. This too may be useful when generating debugging error messages. The following example demonstrates this.&lt;br /&gt;
&lt;br /&gt;
proc/MyProc()&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
   world.log &amp;lt;&amp;lt; &amp;quot;[__FILE__]:[__LINE__]: We got this far!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   //blah blah&lt;br /&gt;
&lt;br /&gt;
====DM_VERSION====&lt;br /&gt;
&lt;br /&gt;
The DM_VERSION macro is the version number of the compiler (217 at the time I am writing). This could be used by library writers when the code requires new language features that were not available before a certain version or if the syntax changed in some way. By using conditional compilation or the #error command, one could make the library code adapt to earlier versions of the compiler just in case someone tries to use one.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#undef===&lt;br /&gt;
&lt;br /&gt;
The #undef command removes a macro. In the code that follows, the macro will no longer be substituted. This could be used at the end of library files to prevent any macros that are used internally from taking effect in the code that includes them.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Conditional Compilation===&lt;br /&gt;
&lt;br /&gt;
The preprocessor can be used to skip sections of code conditionally. The condition usually depends on the existence or value of other macros. In this way you can turn on or off features in the code by configuring a few macro definitions at the top of the project.&lt;br /&gt;
&lt;br /&gt;
The commands for conditionally compiling code are described in the following sections.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====#ifdef====&lt;br /&gt;
&lt;br /&gt;
The #ifdef command compiles the code which follows only if the specified macro has been defined. The section is terminated by the #endif command.&lt;br /&gt;
&lt;br /&gt;
#ifdef	Macro&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
There is also a #ifndef command which has the opposite effect. The code that follows is only compiled if the macro is not defined.&lt;br /&gt;
&lt;br /&gt;
The DEBUG macro is sometimes used to turn on certain debugging features in the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
mob/verb/GotoMob(mob/M in world)&lt;br /&gt;
   set category = &amp;quot;Debugging&amp;quot;&lt;br /&gt;
   usr.loc = M.loc&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
====#if====&lt;br /&gt;
&lt;br /&gt;
The #if command is a more general version of the #ifdef command because it can take any expression involving other macros and constants. If the expression is true, the code which follows is compiled. Otherwise it is skipped. Alternate conditions can be supplied with the #elif command and a final section to be compiled if all else fails may follow the #else command.&lt;br /&gt;
&lt;br /&gt;
#if	Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#elif Condition&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#else&lt;br /&gt;
//Conditional code.&lt;br /&gt;
#endif&lt;br /&gt;
The condition may involve any of the basic operators but usually only uses the boolean operators. One addition is the defined instruction which tests if the specified macro has been defined.&lt;br /&gt;
&lt;br /&gt;
defined	(Macro)&lt;br /&gt;
Macro is the name of a macro.&lt;br /&gt;
Returns 1 if macro has been defined and 0 if not.&lt;br /&gt;
One common use of the #if command is to block out a section of code. This is sometimes done in the course of debugging or possibly to turn off a feature without throwing away the code. The following example demonstrates this technique.&lt;br /&gt;
&lt;br /&gt;
#if 0&lt;br /&gt;
   //Disabled code.&lt;br /&gt;
#endif&lt;br /&gt;
Since DM allows comments to be nested (one inside another) it is also possible to accomplish the same thing by putting /* */ around the disabled code. It is a C programmer's habit to use the #if command because many C compilers get confused by nested comments.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===#error===&lt;br /&gt;
&lt;br /&gt;
The #error command stops compilation and displays the specified error message. Library writers can use this to tell the user of the library if something is wrong.&lt;br /&gt;
&lt;br /&gt;
#error Message&lt;br /&gt;
The following example will refuse to compile if the DM macro is not defined.&lt;br /&gt;
&lt;br /&gt;
#ifndef DM&lt;br /&gt;
#error You need to define DM as the name of your key!&lt;br /&gt;
#endif&lt;br /&gt;
&lt;br /&gt;
==Some Code Management Issues==&lt;br /&gt;
&lt;br /&gt;
There are a few things to keep in mind when working with large DM projects. First and foremost one must strive for simplicity. The art of programming is mostly a matter of realizing your own limitations and compensating for them.&lt;br /&gt;
&lt;br /&gt;
If, as the project grows, each new piece of code depends upon the details of every previous piece of code, the complexity of the project is growing exponentially. Before you know it, the code will rise up in revolt and stick you in a dark smelly dungeon. End of story.&lt;br /&gt;
&lt;br /&gt;
Fortunately, most programming tasks do not require exponential complexity. With a good design, you can split the project into pieces which interact with each other in a fairly simple way. These pieces are often called modules which is why this practice is termed modular programming. (It is interesting to note, however, that all such schemes to avoid exponentially complex code ultimately fail. They only move the exponential growth to a higher level--from individual statements to procedures to objects and on and on. It may be true that complexity will always win out in the end and that every project undergoing perpetual growth must periodically be redesigned from scratch in order to remain comprehensible. Or perhaps this tendency is merely the result of a periodic increase in wisdom to offset the inevitable decline in intelligence. In my own case, I know this to be a prominent factor.)&lt;br /&gt;
&lt;br /&gt;
Although the term module can refer to any unit of code, it most often is embodied by a file or group of files. The public parts of the module are those procedures, variables, and object types which are advertised for use by code outside the module. This is called the module interface and defines the syntax for putting information in and getting results out of the module. All other private material is considered internal to the module and is not for use by outside code.&lt;br /&gt;
&lt;br /&gt;
When devising a project, one should foresee the function of the different component modules and have a rough idea of the interface to each one. When work commences on a module, it is worth putting a description of the public interface in a comment at the top of the file. This helps focus development along lines consistent with a good clean interface. You will also find it a useful reference in the future when you or someone else needs to use the module. You won't need to page through expanses of code to figure out how to operate your wonderful gadget.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ordering Code===&lt;br /&gt;
&lt;br /&gt;
In many cases, the sequential order of DM code makes no difference. For example, a procedure, variable, or object type may be defined before or after being used in the code. This is different from some languages which require every symbol to be defined prior to being used.&lt;br /&gt;
&lt;br /&gt;
There are a few cases, however, when the order of code does matter. The preprocessor, for example, operates strictly sequentially from top to bottom of the code. The principle consequence of this is that macro definitions must precede their use. This is one good reason to instead use constant variables for the purpose when it is possible.&lt;br /&gt;
&lt;br /&gt;
Another time when code sequence matters is when overriding object procedures or variable initializations. If the same procedure is overridden several times in the same object type, subsequent versions take precedence and will treat previous ones as their parent procedure.&lt;br /&gt;
&lt;br /&gt;
One might, for example, add functionality to the client.Topic() procedure in several different locations in the code. As long as you remember to execute the parent procedure each time, the additions are cumulative.&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;introduction&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;Once upon a time...&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
&lt;br /&gt;
client/Topic(T)&lt;br /&gt;
   if(T == &amp;quot;help&amp;quot;)&lt;br /&gt;
      usr &amp;lt;&amp;lt; &amp;quot;The situation is helpless.&amp;quot;&lt;br /&gt;
   else ..()&lt;br /&gt;
As written, these two definitions of the Topic procedure can fall in any order with any amount of intervening code. If one of them neglected to call ..(), however, it would disable any previous versions of the procedure. It is therefore good practice to always call the parent procedure unless you specifically wish to disable it. Then you don't have to worry about maintaining any special order of the procedures.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Debugging Code===&lt;br /&gt;
&lt;br /&gt;
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Good Coding Habits====&lt;br /&gt;
&lt;br /&gt;
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.&lt;br /&gt;
&lt;br /&gt;
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.&lt;br /&gt;
&lt;br /&gt;
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.&lt;br /&gt;
&lt;br /&gt;
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.&lt;br /&gt;
&lt;br /&gt;
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Elusive Bugs====&lt;br /&gt;
&lt;br /&gt;
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.&lt;br /&gt;
&lt;br /&gt;
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.&lt;br /&gt;
&lt;br /&gt;
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.&lt;br /&gt;
&lt;br /&gt;
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.&lt;br /&gt;
&lt;br /&gt;
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.&lt;br /&gt;
&lt;br /&gt;
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:&lt;br /&gt;
&lt;br /&gt;
world.log &amp;lt;&amp;lt; &amp;quot;[__LINE__]: myvar = [myvar]&amp;quot;&lt;br /&gt;
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.&lt;br /&gt;
&lt;br /&gt;
#ifdef DEBUG&lt;br /&gt;
#define debug world.log&lt;br /&gt;
#else&lt;br /&gt;
#define debug null&lt;br /&gt;
#endif&lt;br /&gt;
You can then send output to debug and it will be ignored when not in DEBUG mode.&lt;br /&gt;
&lt;br /&gt;
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.&lt;br /&gt;
&lt;br /&gt;
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.&lt;/div&gt;</summary>
		<author><name>IXVI</name></author>
	</entry>
</feed>