Файлы с расширением .dm написаны на языке программирования DM (Dream Maker). Этот язык используется для разработки игр в платформе BYOND (Build Your Own Net Dream). BYOND — это онлайн-платформа, которая использует язык DM для создания многопользовательских игр.
User
Понял. Я смотрю репозиторий билда SS13, там есть код на DM. Мог бы ты, сугубо в теории, сделать полный аналог какой-то механики на C#, если я тебе скину код DM?
Assistant
Да, я могу помочь с переводом кода с Dream Maker (DM) на C#. Однако, следует учитывать, что некоторые аспекты автоматической конвертации могут потребовать дополнительных разъяснений или адаптаций, поскольку DM и C# — это разные языки программирования с разными парадигмами и библиотеками.
Пожалуйста, предоставьте код на DM, который вы хотите перевести на C#, и я постараюсь помочь вам с этой задачей.
User
Мы будем переделывать механику рыбалки. Знаешь ведь структуру написания для SS14?
Assistant
Да, у меня есть общее представление о структуре кода и механиках для Space Station 14 (SS14), которая переписывается преимущественно на C#. Если у вас есть конкретный код механики рыбалки на DM для SS13, я могу помочь с его адаптацией на C# для SS14.
Пожалуйста, предоставьте исходный код на DM, и я постараюсь его преобразовать.
User
Удочка для рыбалки:
#define FISHING_ROD_REEL_CAST_RANGE 2
/obj/item/fishing_rod
name = "fishing rod"
desc = "You can fish with this."
icon = 'icons/obj/fishing.dmi'
icon_state = "fishing_rod"
lefthand_file = 'icons/mob/inhands/equipment/fishing_rod_lefthand.dmi'
righthand_file = 'icons/mob/inhands/equipment/fishing_rod_righthand.dmi'
inhand_icon_state = "rod"
inhand_x_dimension = 64
inhand_y_dimension = 64
force = 8
w_class = WEIGHT_CLASS_HUGE
code
/// How far can you cast this
var/cast_range = 3
/// Fishing minigame difficulty modifier (additive)
var/difficulty_modifier = 0
/// Explaination of rod functionality shown in the ui
var/ui_description = "A classic fishing rod, with no special qualities."
var/obj/item/bait
var/obj/item/fishing_line/line = /obj/item/fishing_line
var/obj/item/fishing_hook/hook = /obj/item/fishing_hook
/// Currently hooked item for item reeling
var/atom/movable/currently_hooked
/// Fishing line visual for the hooked item
var/datum/beam/fishing_line/fishing_line
/// Are we currently casting
var/casting = FALSE
/// The default color for the reel overlay if no line is equipped.
var/default_line_color = "gray"
///should there be a fishing line?
var/display_fishing_line = TRUE
///The name of the icon state of the reel overlay
var/reel_overlay = "reel_overlay"
///Prevents spamming the line casting, without affecting the player's click cooldown.
COOLDOWN_DECLARE(casting_cd)
Преобразование вашего кода механики рыбалки с DM на C# для SS14 потребует значительного объема работы, так как оба языка различны как в структуре, так и в подходе. Вот основной скелет, включающий аналогичные функции и классы. Предполагаем, что у вас уже есть установленные базовые структуры проекта SS14.
Определим основу класса FishingRod в C#:
csharp
User
Тут довольно много разных файлов для рыбалки, мне скинуть все? Пока что звучит сложно
Assistant
Я понимаю, что задача может показаться сложной, особенно когда она включает множество различных файлов и взаимодействий. Чтобы помочь вам лучше организовать процесс конвертации и придания структуры кода на C#, предлагаем начать с самых важных файлов и функциональных блоков.
Основной класс FishingRod:
Перенос основной логики удочки, включая свойства и основные методы.
Взаимодействия с пользователем:
Настройка контекстных меню, основного взаимодействия и осмотра предмета.
Логика рыбалки и состояния:
Создание линии, зацепление и вытягивание предметов.
Обработка состояния и визуализации:
Обработка появления и исчезновения снастей, обновления внешнего вида.
Если у вас есть готовый набор файлов, полезным шагом будет начать с одного файла (например, основной файл с основной механикой удочки) и постепенно добавлять новые части по мере их необходимости.
Конвертируя поэтапно, будет легче отслеживать и тестировать работу каждого этапа, вместо того чтобы пытаться осилить весь объем сразу. Вот пример более подробной проработки одного файла:
Пример основного класса FishingRod на C#
csharp
User
Я так понимаю, удочка здесь тоже прописана. Но в SS14 предметы создаются через прототип на YML, а на C# только их механики
Assistant
Да, в SS14 предметы действительно создаются через прототипы на YAML (YML), а логика их работы прописывается на C#. Это позволяет отделить данные от логики и делает процесс моддинга и настройки более простым.
Вот как можно разбить вашу задачу на более управляемые части:
Создание YAML прототипа для удочки:
Реализация механики на C#:
Часть 1: Прототипы YAML для удочки и связанных объектов
Создайте YAML файл для предметов удочки, лески и крючка.
yaml
# prototypes/items/fishing.yml
- type: entity
id: FishingRod
name: "Fishing Rod"
components:
- type: Item
sprite: "fishing_rod"
inhand_sprite: "fishing_rod_inhand"
- type: FishingRod
cast_range: 3
difficulty_modifier: 0
ui_description: "A classic fishing rod, with no special qualities."
Создайте аналогичные прототипы для лески и крючка.
Создайте компоненты на C# для управления логикой работы удочки. Начнем с основного класса FishingRod и реализуем основные методы.
csharp
User
Описание добавляется в прототип строкой под названием. То есть:
name:
discription:
Assistant
Да, вы правы. Описание можно добавить непосредственно в YAML-прототип, используя строку description:. Давайте уточним и обновим наши примеры YAML-файлов соответствующим образом.
Обновленные прототипы YAML
Fishing Rod (Удочка)
yaml
# prototypes/items/fishing.yml
- type: entity
id: FishingRod
name: "Fishing Rod"
description: "A classic fishing rod, with no special qualities."
components:
- type: Item
sprite: "fishing_rod"
inhand_sprite: "fishing_rod_inhand"
- type: FishingRod
cast_range: 3
difficulty_modifier: 0
ui_description: "A classic fishing rod, with no special qualities."
Fishing Line (Леска)
yaml
- type: entity
id: FishingLine
name: "Fishing Line"
description: "A fishing line suitable for using with a fishing rod."
components:
- type: Item
sprite: "fishing_line"
inhand_sprite: "fishing_line_inhand"
Fishing Hook (Крючок)
yaml
- type: entity
id: FishingHook
name: "Fishing Hook"
description: "A fishing hook suitable for using with a fishing rod."
components:
- type: Item
sprite: "fishing_hook"
inhand_sprite: "fishing_hook_inhand"
Компонент FishingRod на C#
Теперь, когда у нас есть прототипы, вернемся к C# компоненту. Обновим его для поддержки взаимодействий и основных функций:
csharp
User
Давай займёмся чем-то попроще для начала. Что насчёт того, чтобы реализовать аквариум? DM код тоже есть
Assistant
Конечно, давайте начнем с аквариума. Это хорошая отправная точка, так как он, вероятно, менее сложен, и это даст вам некоторое понимание о взаимодействии между YAML-прототипами и C#-кодом в SS14.
Предоставьте, пожалуйста, пример DM кода для аквариума, и мы начнем процесс пересмотра и реализации его в C#.
User
#define AQUARIUM_LAYER_STEP 0.01
/// Aquarium content layer offsets
#define AQUARIUM_MIN_OFFSET 0.02
#define AQUARIUM_MAX_OFFSET 1
/// The layer of the glass overlay
#define AQUARIUM_GLASS_LAYER 0.01
/// The layer of the aquarium pane borders
#define AQUARIUM_BORDERS_LAYER AQUARIUM_MAX_OFFSET + AQUARIUM_LAYER_STEP
/// Layer for stuff rendered below the glass overlay
#define AQUARIUM_BELOW_GLASS_LAYER 0.01
/obj/structure/aquarium
name = "aquarium"
desc = "A vivarium in which aquatic fauna and flora are usually kept and displayed."
density = TRUE
anchored = FALSE
code
icon = 'icons/obj/structures/aquarium/tanks.dmi'
icon_state = "aquarium_map"
integrity_failure = 0.3
/// The icon state is used for mapping so mappers know what they're placing. This prefixes the real icon used in game.
/// For an example, "aquarium" gives the base sprite of "aquarium_base", the glass is "aquarium_glass_water", and so on.
var/icon_prefix = "aquarium"
var/fluid_type = AQUARIUM_FLUID_FRESHWATER
var/fluid_temp = DEFAULT_AQUARIUM_TEMP
var/min_fluid_temp = MIN_AQUARIUM_TEMP
var/max_fluid_temp = MAX_AQUARIUM_TEMP
///While the feed storage is not empty, this is the interval which the fish are fed.
var/feeding_interval = 3 MINUTES
///The last time fishes were fed by the acquarium itsef.
var/last_feeding
/// Can fish reproduce in this quarium.
var/allow_breeding = TRUE
//This is the area where fish can swim
var/aquarium_zone_min_px = 2
var/aquarium_zone_max_px = 31
var/aquarium_zone_min_py = 10
var/aquarium_zone_max_py = 28
var/list/fluid_types = list(AQUARIUM_FLUID_SALTWATER, AQUARIUM_FLUID_FRESHWATER, AQUARIUM_FLUID_SULPHWATEVER, AQUARIUM_FLUID_AIR)
var/panel_open = FALSE
///Current layers in use by aquarium contents
var/list/used_layers = list()
/// /obj/item/fish in the aquarium, sorted by type - does not include things with aquarium visuals that are not fish
var/list/tracked_fish_by_type
/// Var used to keep track of the current beauty of the aquarium, which can be throughfully changed by aquarium content.
var/current_beauty = 150
Assistant
Отлично! Мы начнем с разработки YAML-прототипа для аквариума и затем создадим компонент на C# для управления его логикой. Вот как мы можем организовать это:
YAML-прототип для аквариума
Создадим прототип YAML для аквариума:
yaml
# prototypes/entities/aquarium.yml
- type: entity
id: Aquarium
name: "Aquarium"
description: "A vivarium in which aquatic fauna and flora are usually kept and displayed."
components:
- type: Physics
bodyType: Static
- type: Appearance
sprite: "objects/structures/aquarium/aquarium_base"
- type: Transform
- type: Anchored
- type: Aquarium
fluid_type: "freshwater"
fluid_temp: 20.0
min_fluid_temp: 5.0
max_fluid_temp: 30.0
feeding_interval: 180.0
allow_breeding: true
C# Компонент для аквариума
Создадим AquariumComponent для управления логикой аквариума.
csharp
User
Знаешь, я ведь совсем не умею в кодинг, только с YAML работал и META файлы для текстур. Давай максимально просто, с чего мне начать, чтобы это реализовать? Что мне надо, буквально "куда жмать"?
Assistant
Конечно, давайте поэтапно разберем, как создать и настроить аквариум в SS14. Мы начнем с базовых вещей, с которыми вы уже знакомы, а затем перейдем к более сложным частям. Рассмотрим следующий порядок действий:
Создание прототипа объекта в YAML.
Создание компонента на C# для управления логикой.
Регистрация системы и компонента.
Тестирование и отладка.
Шаг 1. Создание YAML-прототипа
Откройте папку с проектом SS14.
Переходите в папку, где хранятся YAML файлы прототипов, например, Resources/Prototypes/Entities. Создайте там новый YAML файл, например, aquarium.yml.
В файле aquarium.yml добавьте следующий содержимое:
yaml
# Resources/Prototypes/Entities/aquarium.yml
- type: entity
id: Aquarium
name: "Aquarium"
description: "A vivarium in which aquatic fauna and flora are usually kept and displayed."
components:
- type: Physics
bodyType: Static
- type: Appearance
sprite: "Objects/Structures/Aquarium/aquarium_base.rsi"
- type: Transform
- type: Anchored
- type: Aquarium
fluid_type: "freshwater"
fluid_temp: 20.0
min_fluid_temp: 5.0
max_fluid_temp: 30.0
feeding_interval: 180.0
allow_breeding: true
Шаг 2. Создание компонента на C#
Откройте и настройте проект в вашей предпочитаемой IDE (например, Rider, Visual Studio, VSCode).
Перейдите в папку с серверным кодом проекта, например, Content.Server/Components/Aquarium.
Создайте новый файл и назовите его AquariumComponent.cs. В этом файле добавьте следующий код:
csharp
Assistant
Понял, давайте поэтапно и максимально просто разберем, как создать и настроить аквариум в SS14. Мы начнем с самых базовых шагов и будем двигаться вперед шаг за шагом.
Что вам нужно 1. Убедитесь, что ваш рабочий проект SS14 настроен
Убедитесь, что у вас установлен и настроен SS14. Вам потребуется среда разработки (например, Rider, Visual Studio, VSCode) и доступ к файлам проекта.
Шаг 1. Создание YAML-прототипа
Создайте новый YAML-файл для аквариума:
Перейдите в папку с YAML-прототипами вашего проекта. Обычно это будет что-то вроде Resources/Prototypes/Entities.
Создайте новый файл с именем aquarium.yml.
Добавьте следующий содержимое в aquarium.yml:
yaml
# Resources/Prototypes/Entities/aquarium.yml
- type: entity
id: Aquarium
name: "Aquarium"
description: "A vivarium in which aquatic fauna and flora are usually kept and displayed."
components:
- type: Physics
bodyType: Static
- type: Appearance
sprite: "Objects/Structures/Aquarium/aquarium_base.rsi" # Убедитесь, что этот путь корректен
- type: Transform
- type: Anchored
- type: Aquarium
fluid_type: "freshwater"
fluid_temp: 20.0
min_fluid_temp: 5.0
max_fluid_temp: 30.0
feeding_interval: 180.0
allow_breeding: true
Шаг 2. Создание компонента на C#
Создайте новый файл компонента:
В вашей IDE (например, Rider, Visual Studio, VSCode) перейдите в папку с серверным кодом проекта. Обычно это что-то вроде Content.Server/Components/Aquarium.
Создайте новый файл с именем AquariumComponent.cs.
Добавьте следующий код в AquariumComponent.cs:
csharp
User
Смотри, касаемо текстур - тут есть две вариации. Один красивый аквариум, собранный и второй будто бы без каркаса, видно микросхемки. Плюс есть несколько состояний - платформа, стеклянные станки и состояния треснувших. Это очень похоже на то, как реализован в игре glass box, то есть стеклянное демонстрационное хранилище. Я мог бы предоставить его код или прототип, если будет нужно
Assistant
Конечно, предоставьте код или прототип glass box (стеклянной демонстрационной коробки). Это даст нам лучшее представление о том, как реализовать аквариум с разными состояниями — нормальное, без каркаса, треснувшее и так далее. Используя этот пример, мы сможем более точно воссоздать аквариум с различными визуальными состояниями.
Ожидаемая структура для таких объектов
Прототип YAML для аквариума с разными состояниями.
Компонент на C# для управления состояниями и взаимодействием.
Визуальные состояния в ресурсе sprite.
Пока предоставьте код или YAML-прототип для glass box, после чего мы сможем продолжить.
type: entity
id: GlassBox
name: glass box
description: A sturdy showcase for an expensive exhibit.
parent: BaseGlassBox
abstract: true # TODO: Temporarily abstract. Remove it after item scaling in cabinets is implemented.
components:
Отлично, теперь у нас есть пример структурного прототипа для объекта с несколькими состояниями. Мы можем использовать этот пример для создания нашего аквариума с разными состояниями (целый, без каркаса, треснувший и т.д.)
Шаг 1. Создание YAML-прототипа для аквариума
Используя структуру прототипа для glass box, мы можем создать похожий прототип для аквариума. Мы начнем с базового YAML-файла.
Создайте новый YAML файл для аквариума:
Переходите в Resources/Prototypes/Entities.
Создайте новый файл с именем aquarium.yml.
В этот файл добавьте следующие данные:
yaml
User
Я так посмотрел, у нас вроде нет понятия чистой и грязной воды в игре. А у тебя в качестве реагента оно указано. Есть только Water
Assistant
Спасибо за замечание! Давайте упростим наш пример, чтобы он использовал существующие данные и реагенты в игре, такие как обычная Water, вместо любых специфических реактивов, которых нет.
Шаг 1. Обновленный YAML-прототип для аквариума
Откройте aquarium.yml и обновите его следующими данными:
/obj/item/fishing_rod/examine(mob/user)
. = ..()
var/list/equipped_stuff = list()
if(line)
equipped_stuff += "[icon2html(line, user)] [line.name]"
if(hook)
equipped_stuff += "[icon2html(hook, user)] [hook.name]"
if(bait)
equipped_stuff += "[icon2html(bait, user)] [bait] as bait."
if(length(equipped_stuff))
. += span_notice("It has \a [english_list(equipped_stuff)] equipped.")
if(!bait)
. += span_warning("It doesn't have a bait attached to it. Fishing will be more tedious!")
/**
Is there a reason why this fishing rod couldn't fish in target_fish_source?
If so, return the denial reason as a string, otherwise return null.
Arguments:
target_fish_source - The /datum/fish_source we're trying to fish in.
*/
/obj/item/fishing_rod/proc/reason_we_cant_fish(datum/fish_source/target_fish_source)
return hook?.reason_we_cant_fish(target_fish_source)
/obj/item/fishing_rod/proc/consume_bait(atom/movable/reward)
// catching things that aren't fish or alive mobs doesn't consume baits.
if(isnull(reward) || isnull(bait) || HAS_TRAIT(bait, TRAIT_BAIT_UNCONSUMABLE))
return
if(isliving(reward))
var/mob/living/caught_mob = reward
if(caught_mob.stat == DEAD)
return
else if(!isfish(reward))
return
QDEL_NULL(bait)
update_icon()
// Reel in if able
if(currently_hooked)
reel(user)
return ITEM_INTERACT_BLOCKING
SEND_SIGNAL(interacting_with, COMSIG_PRE_FISHING)
cast_line(interacting_with, user)
return ITEM_INTERACT_SUCCESS
/obj/item/fishing_rod/ranged_interact_with_atom_secondary(atom/interacting_with, mob/living/user, list/modifiers)
//Stop reeling, delete the fishing line
if(currently_hooked)
QDEL_NULL(fishing_line)
return ITEM_INTERACT_BLOCKING
return ..()
/// If the line to whatever that is is clear and we're not already busy, try fishing in it
/obj/item/fishing_rod/proc/cast_line(atom/target, mob/user)
if(casting || currently_hooked)
return
if(!hook)
balloon_alert(user, "install a hook first!")
return
if(!COOLDOWN_FINISHED(src, casting_cd))
return
casting = TRUE
var/obj/projectile/fishing_cast/cast_projectile = new(get_turf(src))
cast_projectile.range = cast_range
cast_projectile.owner = src
cast_projectile.original = target
cast_projectile.fired_from = src
cast_projectile.firer = user
cast_projectile.impacted = list(WEAKREF(user) = TRUE)
cast_projectile.preparePixelProjectile(target, user)
cast_projectile.fire()
COOLDOWN_START(src, casting_cd, 1 SECONDS)
/// Called by hook projectile when hitting things
/obj/item/fishing_rod/proc/hook_hit(atom/atom_hit_by_hook_projectile)
var/mob/user = loc
if(!hook || !istype(user))
return
if(SEND_SIGNAL(atom_hit_by_hook_projectile, COMSIG_FISHING_ROD_CAST, src, user) & FISHING_ROD_CAST_HANDLED)
return
/// If you can't fish in it, try hooking it
hook_item(user, atom_hit_by_hook_projectile)
/obj/item/fishing_rod/proc/get_fishing_overlays()
. = list()
var/line_color = line?.line_color || default_line_color
/// Line part by the rod, always visible
var/mutable_appearance/reel_appearance = mutable_appearance(icon, reel_overlay)
reel_appearance.color = line_color
. += reel_appearance
code
// Line & hook is also visible when only bait is equipped but it uses default appearances then
if(hook || bait)
var/mutable_appearance/line_overlay = mutable_appearance(icon, "line_overlay")
line_overlay.color = line_color
. += line_overlay
. += hook?.rod_overlay_icon_state || "hook_overlay"
if(bait)
var/bait_state = "worm_overlay" //default to worm overlay for anything without specific one
if(istype(bait, /obj/item/food/bait))
var/obj/item/food/bait/real_bait = bait
bait_state = real_bait.rod_overlay_icon_state
if(istype(bait, /obj/item/stock_parts/power_store/cell/lead))
bait_state = "battery_overlay"
. += bait_state
///assign an item to the given slot and its standard effects, while Exited() should handle unsetting the slot.
/obj/item/fishing_rod/proc/set_slot(obj/item/equipment, slot)
switch(slot)
if(ROD_SLOT_BAIT)
bait = equipment
if(ROD_SLOT_HOOK)
hook = equipment
if(ROD_SLOT_LINE)
line = equipment
cast_range += FISHING_ROD_REEL_CAST_RANGE
///Found in the fishing toolbox (the hook and line are separate items)
/obj/item/fishing_rod/unslotted
hook = null
line = null
/obj/item/fishing_rod/bone
name = "bone fishing rod"
desc = "A humble rod, made with whatever happened to be on hand."
icon_state = "fishing_rod_bone"
reel_overlay = "reel_bone"
default_line_color = "red"
line = null //sinew line (usable to fish in lava) not included
hook = /obj/item/fishing_hook/bone
/obj/item/fishing_rod/telescopic
name = "telescopic fishing rod"
icon_state = "fishing_rod_telescopic"
desc = "A lightweight, ergonomic, easy to store telescopic fishing rod. "
inhand_icon_state = null
force = 0
w_class = WEIGHT_CLASS_NORMAL
ui_description = "A collapsible fishing rod that can fit within a backpack."
reel_overlay = "reel_telescopic"
///The force of the item when extended.
var/active_force = 8
/obj/item/fishing_rod/telescopic/reason_we_cant_fish(datum/fish_source/target_fish_source)
if(!HAS_TRAIT(src, TRAIT_TRANSFORM_ACTIVE))
return "You need to extend your fishing rod before you can cast the line."
return ..()
/obj/item/fishing_rod/telescopic/cast_line(atom/target, mob/user, proximity_flag)
if(!HAS_TRAIT(src, TRAIT_TRANSFORM_ACTIVE))
if(!proximity_flag)
balloon_alert(user, "extend the rod first!")
return
return ..()
///Stops the fishing rod from being collapsed while fishing.
/obj/item/fishing_rod/telescopic/proc/pre_transform(obj/item/source, mob/user, active)
SIGNAL_HANDLER
if(HAS_TRAIT(src, TRAIT_TRANSFORM_ACTIVE))
return
//the fishing minigame uses the attack_self signal to let the user end it early without having to drop the rod.
if(HAS_TRAIT(user, TRAIT_GONE_FISHING))
return COMPONENT_BLOCK_TRANSFORM
///Gives feedback to the user, makes it show up inhand, toggles whether it can be used for fishing.
/obj/item/fishing_rod/telescopic/proc/on_transform(obj/item/source, mob/user, active)
SIGNAL_HANDLER
code
inhand_icon_state = active ? "rod" : null // When inactive, there is no inhand icon_state.
if(user)
balloon_alert(user, active ? "extended" : "collapsed")
playsound(src, 'sound/weapons/batonextend.ogg', 50, TRUE)
update_appearance(UPDATE_OVERLAYS)
QDEL_NULL(fishing_line)
return COMPONENT_NO_DEFAULT_MESSAGE
/obj/item/fishing_rod/telescopic/master
name = "master fishing rod"
desc = "The mythical rod of a lost fisher king. Said to be imbued with un-paralleled fishing power. There's writing on the back of the pole. "中国航天制造""
difficulty_modifier = -10
ui_description = "This rod makes fishing easy even for an absolute beginner."
icon_state = "fishing_rod_master"
reel_overlay = "reel_master"
active_force = 13 //It's that sturdy
cast_range = 5
line = /obj/item/fishing_line/bouncy
hook = /obj/item/fishing_hook/weighted
/obj/item/fishing_rod/tech
name = "advanced fishing rod"
desc = "An embedded universal constructor along with micro-fusion generator makes this marvel of technology never run out of bait. Interstellar treaties prevent using it outside of recreational fishing. And you can fish with this. "
ui_description = "This rod has an infinite supply of synth-bait. Also doubles as an Experi-Scanner for fish."
icon_state = "fishing_rod_science"
reel_overlay = "reel_science"
bait = /obj/item/food/bait/doughball/synthetic/unconsumable
/obj/projectile/fishing_cast/on_hit(atom/target, blocked = 0, pierce_hit)
. = ..()
if(blocked < 100)
QDEL_NULL(our_line) //we need to delete the old beam datum, otherwise it won't let you fish.
owner.hook_hit(target)
using Robust.Shared.GameObjects;
using Content.Shared.Actions;
using Content.Shared.Inventory;
using Content.Shared.MobState;
namespace Content.Server.Items
{
public class FishingRod : Component
{
public override string Name => "FishingRod";
private int castRange = 3;
private int difficultyModifier = 0;
private string uiDescription = "A classic fishing rod, with no special qualities.";
private IEntity bait;
private IEntity line;
private IEntity hook;
private IEntity currentlyHooked;
private bool casting = false;
private bool displayFishingLine = true;
private string reelOverlay = "reel_overlay";
private void Initialize()
{
// Register context actions and UI description
}
public void AddContext(EntityUid heldItem, EntityUid user)
{
// Implement context menu generation in C#
}
public void Examine(EntityUid user)
{
// Implement examination behavior
}
private void Interact(EntityUid user)
{
if (currentlyHooked != null)
{
Reel(user);
}
}
private void Reel(EntityUid user)
{
// Implement reeling logic similar to DM code
}
private void CreateFishingLine(EntityUid target)
{
if (!displayFishingLine || !EntityManager.EntityExists(target)) return;
// Implement fishing line creation similar to DM code
}
private void HookItem(EntityUid target, EntityUid user)
{
if (currentlyHooked != null) return;
if (hook != null && hook.Components.ContainsKey("CanBeHooked"))
{
currentlyHooked = target;
CreateFishingLine(target);
}
}
private void CastLine(EntityUid target, EntityUid user)
{
if (casting || currentlyHooked != null) return;
casting = true;
// Implement casting logic and projectile creation
Timer.Spawn(1000, () => { casting = false; });
}
private void UseSlot(string slot, EntityUid user, EntityUid newItem)
{
// Implement item slot management
}
public void OnProjectileHit(EntityUid target)
{
if (hook != null && target != Entity.Null)
{
HookItem(target, _playerManager.LocalPlayer?.ControlledEntity ?? Entity.Null);
}
}
public void UpdateAppearance()
{
// Implement appearance updating
}
}
}
Основные моменты, которые нужно учесть:
Взаимодействия с пользователем.
Реализация кода логики рыбалки, который управляет созданием и удалением снастей, завершением процесса, использованием UI и контекстных меню.
Управление состоянием предмета.
Пример использования сигналов и управления состоянием:
csharp
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<FishingRodComponent, ComponentInit>(OnItemInit);
SubscribeLocalEvent<FishingRodComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<FishingRodComponent, AltUseInHandEvent>(OnAltUseInHand);
}
private void OnItemInit(EntityUid uid, FishingRodComponent component, ComponentInit args)
{
// Инициализация предмета
}
private void OnUseInHand(EntityUid uid, FishingRodComponent component, UseInHandEvent args)
{
// Обработка использования предмета в руках
}
private void OnAltUseInHand(EntityUid uid, FishingRodComponent component, AltUseInHandEvent args)
{
// Обработка использования предмета с альтернативным кликом
}
Добавьте в ваш компонент FishingRod свойства и методы для управления багажом, такими как добавление/удаление приманки, лески и крючка.
Этот пример на C# дает базовую реализацию, повторяющую ключевые механики DM версии, но весь код нужно будет детально проработать и адаптировать для движка SS14, особенно в плане графики, сетевых взаимодействий и обработки событий.
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Server.Items
{
[RegisterComponent]
public class FishingRodComponent : Component
{
public override string Name => "FishingRod";
[DataField("cast_range")]
private int _castRange = 3;
[DataField("difficulty_modifier")]
private int _difficultyModifier = 0;
[DataField("ui_description")]
private string _uiDescription = "A classic fishing rod, with no special qualities.";
private IEntity _bait;
private IEntity _line;
private IEntity _hook;
private IEntity _currentlyHooked;
private bool _casting = false;
private bool _displayFishingLine = true;
private string _reelOverlay = "reel_overlay";
protected override void Initialize()
{
base.Initialize();
// Add initialization logic here
}
public void AddContext(EntityUid heldItem, EntityUid user)
{
// Implement context menu generation in C#
}
public void Examine(EntityUid user)
{
// Implement examination behavior
}
private void Interact(EntityUid user)
{
if (_currentlyHooked != null)
{
Reel(user);
}
}
private void Reel(EntityUid user)
{
// Implement reeling logic similar to DM code
}
private void CreateFishingLine(EntityUid target)
{
if (!_displayFishingLine || !EntityManager.EntityExists(target)) return;
// Implement fishing line creation similar to DM code
}
private void HookItem(EntityUid target, EntityUid user)
{
if (_currentlyHooked != null) return;
if (_hook != null && _hook.TryGetComponent<CanBeHookedComponent>(out var _))
{
_currentlyHooked = target;
CreateFishingLine(target);
}
}
private void CastLine(EntityUid target, EntityUid user)
{
if (_casting || _currentlyHooked != null) return;
_casting = true;
// Implement casting logic and projectile creation
Timer.Spawn(1000, () =>
{
_casting = false;
});
}
private void UseSlot(string slot, EntityUid user, EntityUid newItem)
{
// Implement item slot management logic
}
}
}
Дополнительные файлы и компоненты
Пожалуйста, укажите, какие файлы или аспекты вам особенно интересны или вызывают затруднения. Так будет проще дать конкретные рекомендации и примеры кода.
Если у вас есть несколько ключевых файлов, можно сосредоточиться на них по очереди, добавляя новые функциональные блоки по мере их необходимости:
Основная механика предмета (fishing_rod)
Объект-удочка и его свойства (fishing_line, fishing_hook и т.д.)
Основные функции взаимодействия и UI
Визуализация и обновление состояния предмета
Для организованного процесса начните с какого-то важного аспекта и постепенно добавляйте связанные компоненты и взаимодействия. По мере необходимости, мы можем помочь вам с конкретными вопросами и проблемами, возникающими на пути.
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Server.GameObjects;
using Robust.Shared.Players;
using Robust.Shared.Timing;
using Content.Server.Hands.Components;
using Content.Server.Inventory.Components;
using Content.Server.Administration;
namespace Content.Server.Items
{
[RegisterComponent]
public class FishingRodComponent : Component
{
public override string Name => "FishingRod";
[DataField("castRange")]
private int _castRange = 3;
[DataField("difficultyModifier")]
private int _difficultyModifier = 0;
[DataField("uiDescription")]
private string _uiDescription = "A classic fishing rod, with no special qualities.";
private IEntity _bait;
private IEntity _line;
private IEntity _hook;
private IEntity _currentlyHooked;
private bool _casting = false;
private bool _displayFishingLine = true;
private string _reelOverlay = "reel_overlay";
public override void Initialize()
{
base.Initialize();
// Дополнительная инициализация, если требуется.
}
public void AddContext(EntityUid heldItem, EntityUid user)
{
// Реализуйте контекстное меню
}
public void Examine(EntityUid user)
{
// Реализуйте осмотр (examine)
}
private void Interact(EntityUid user)
{
if (_currentlyHooked != null)
{
Reel(user);
}
}
private void Reel(EntityUid user)
{
// Реализуйте логику подматывания
}
private void CreateFishingLine(EntityUid target)
{
if (!_displayFishingLine || !EntityManager.EntityExists(target)) return;
// Реализуйте создание лески для удочки
}
private void HookItem(EntityUid target, EntityUid user)
{
if (_currentlyHooked != null) return;
if (_hook != null && _hook.TryGetComponent<CanBeHookedComponent>(out var _))
{
_currentlyHooked = target;
CreateFishingLine(target);
}
}
private void CastLine(EntityUid target, EntityUid user)
{
if (_casting || _currentlyHooked != null) return;
_casting = true;
// Реализуйте логику заброса лески
Timer.Spawn(1000, () =>
{
_casting = false;
});
}
private void UseSlot(string slot, EntityUid user, EntityUid newItem)
{
// Реализуйте управление слотами для предметов
}
}
}
Основная механика взаимодействия пользователя и удочки
Мы также можем создать систему для обработки взаимодействий. Например, когда игрок использует удочку, чтобы бросить леску.
csharp
using Robust.Shared.GameObjects;
using Robust.Shared.Timing;
using Content.Shared.ActionBlocker;
using Content.Shared.Interaction;
namespace Content.Server.Items
{
public class FishingRodSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<FishingRodComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<FishingRodComponent, AfterInteractEvent>(OnAfterInteract);
}
private void OnUseInHand(EntityUid uid, FishingRodComponent component, UseInHandEvent args)
{
if (!args.Handled)
{
component.Interact(args.User);
args.Handled = true;
}
}
private void OnAfterInteract(EntityUid uid, FishingRodComponent component, AfterInteractEvent args)
{
if (!args.Handled && args.Target != null)
{
component.CastLine(args.Target.Value, args.User);
args.Handled = true;
}
}
}
}
Этот подход помогает разделить логику предмета и сами предметы, делая ваш код более организованным и понятным для других разработчиков. Вы можете продолжить добавлять остальные функции и взаимодействия по аналогичному шаблону, комбинируя YML и C# для полного воспроизведения механики рыбалки из SS13 в SS14.
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Server.GameObjects;
using Robust.Shared.Players;
using Robust.Shared.Timing;
using Content.Server.Hands.Components;
using Content.Server.Administration;
namespace Content.Server.Items
{
[RegisterComponent]
public class FishingRodComponent : Component
{
public override string Name => "FishingRod";
[DataField("castRange")]
private int _castRange = 3;
[DataField("difficultyModifier")]
private int _difficultyModifier = 0;
[DataField("uiDescription")]
private string _uiDescription = "A classic fishing rod, with no special qualities.";
private IEntity _bait;
private IEntity _line;
private IEntity _hook;
private IEntity _currentlyHooked;
private bool _casting = false;
private bool _displayFishingLine = true;
private string _reelOverlay = "reel_overlay";
public override void Initialize()
{
base.Initialize();
// Дополнительная инициализация, если требуется.
}
public void AddContext(EntityUid heldItem, EntityUid user)
{
// Реализуйте контекстное меню
}
public void Examine(EntityUid user)
{
// Реализуйте осмотр (examine)
}
private void Interact(EntityUid user)
{
if (_currentlyHooked != null)
{
Reel(user);
}
}
private void Reel(EntityUid user)
{
// Реализуйте логику подматывания
}
private void CreateFishingLine(EntityUid target)
{
if (!_displayFishingLine || !EntityManager.EntityExists(target)) return;
// Реализуйте создание лески для удочки
}
private void HookItem(EntityUid target, EntityUid user)
{
if (_currentlyHooked != null) return;
if (_hook != null && _hook.TryGetComponent<CanBeHookedComponent>(out var _))
{
_currentlyHooked = target;
CreateFishingLine(target);
}
}
private void CastLine(EntityUid target, EntityUid user)
{
if (_casting || _currentlyHooked != null) return;
_casting = true;
// Реализуйте логику заброса лески
Timer.Spawn(1000, () =>
{
_casting = false;
});
}
private void UseSlot(string slot, EntityUid user, EntityUid newItem)
{
// Реализуйте управление слотами для предметов
}
}
}
Основная механика взаимодействия пользователя и удочки
Создадим также систему для обработки взаимодействий, как только игрок использует удочку для заброса лески.
csharp
using Robust.Shared.GameObjects;
using Robust.Shared.Timing;
using Content.Shared.ActionBlocker;
using Content.Shared.Interaction;
namespace Content.Server.Items
{
public class FishingRodSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<FishingRodComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<FishingRodComponent, AfterInteractEvent>(OnAfterInteract);
}
private void OnUseInHand(EntityUid uid, FishingRodComponent component, UseInHandEvent args)
{
if (!args.Handled)
{
component.Interact(args.User);
args.Handled = true;
}
}
private void OnAfterInteract(EntityUid uid, FishingRodComponent component, AfterInteractEvent args)
{
if (!args.Handled && args.Target != null)
{
component.CastLine(args.Target.Value, args.User);
args.Handled = true;
}
}
}
}
Инициализация и подключение системы
Не забудьте добавить систему FishingRodSystem в ваш игровой проект, чтобы система была активирована и слушала события.
csharp
using Robust.Shared.IoC;
using Robust.Shared.GameObjects;
using Content.Server.Items;
using Robust.Server.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Configuration;
namespace Content.Server
{
internal class ServerGameSystem : GameSystem
{
[Dependency] private readonly IEntityManager _entityManager = default!;
private FishingRodSystem _fishingRodSystem;
public override void Initialize()
{
base.Initialize();
_entityManager.SystemManager.LoadSystem<FishingRodSystem>();
_fishingRodSystem = _entityManager.SystemManager.GetEntitySystem<FishingRodSystem>();
}
}
}
Заключение
Запуск механики требует подгрузки прототипов YAML в игру и связывания их с компонентами на C#. Такой подход позволяет отделить данные от логики, делая систему более гибкой и легкой в сопровождении и моддинге. Начав с основ механизмов, вы сможете постепенно добавлять функциональные части и расширять возможности игры.
/// Returns tracked_fish_by_type but flattened and without the items in the blacklist, also shuffled if shuffle is TRUE.
/obj/structure/aquarium/proc/get_fishes(shuffle = FALSE, blacklist)
. = list()
for(var/fish_type in tracked_fish_by_type)
. += tracked_fish_by_type[fish_type]
. -= blacklist
if(shuffle)
. = shuffle(.)
return .
/obj/structure/aquarium/proc/request_layer(layer_type)
/**
* base aq layer
* min_offset = this value is returned on bottom layer mode
* min_offset + 0.1 fish1
* min_offset + 0.2 fish2
* ... these layers are returned for auto layer mode and tracked by used_layers
* min_offset + max_offset = this value is returned for top layer mode
* min_offset + max_offset + 1 = this is used for glass overlay
*/
//optional todo: hook up sending surface changed on aquarium changing layers
switch(layer_type)
if(AQUARIUM_LAYER_MODE_BEHIND_GLASS)
return layer + AQUARIUM_BELOW_GLASS_LAYER
if(AQUARIUM_LAYER_MODE_BOTTOM)
return layer + AQUARIUM_MIN_OFFSET
if(AQUARIUM_LAYER_MODE_TOP)
return layer + AQUARIUM_MAX_OFFSET
if(AQUARIUM_LAYER_MODE_AUTO)
var/chosen_layer = AQUARIUM_MIN_OFFSET + AQUARIUM_LAYER_STEP
while((chosen_layer in used_layers) && (chosen_layer <= AQUARIUM_MAX_OFFSET))
chosen_layer += AQUARIUM_LAYER_STEP
used_layers += chosen_layer
return layer + chosen_layer
/obj/structure/aquarium/proc/free_layer(value)
used_layers -= value
/obj/structure/aquarium/update_icon()
. = ..()
///"aquarium_map" is used for mapping, so mappers can tell what it's.
icon_state = icon_prefix + "_base"
/obj/structure/aquarium/examine(mob/user)
. = ..()
. += span_notice("Alt-click to [panel_open ? "close" : "open"] the control and feed panel.")
if(panel_open && reagents.total_volume)
. += span_notice("You can use a plunger to empty the feed storage.")
if(istype(item, /obj/item/fish_feed) && !panel_open)
if(!item.reagents.total_volume)
balloon_alert(user, "[item] is empty!")
return TRUE
var/list/fishes = get_fishes()
for(var/obj/item/fish/fish as anything in fishes)
fish.feed(item.reagents)
balloon_alert(user, "fed the fish")
return TRUE
if(istype(item, /obj/item/aquarium_upgrade))
var/obj/item/aquarium_upgrade/upgrade = item
if(upgrade.upgrade_from_type != type)
balloon_alert(user, "wrong kind of aquarium!")
return
balloon_alert(user, "upgrading...")
if(!do_after(user, 5 SECONDS, src))
return
var/obj/structure/aquarium/upgraded_aquarium = new upgrade.upgrade_to_type(loc)
for(var/atom/movable/moving in contents)
moving.forceMove(upgraded_aquarium)
balloon_alert(user, "upgraded")
qdel(upgrade)
qdel(src)
return
return ..()
/obj/structure/aquarium/proc/on_attacked(datum/source, mob/attacker, attack_flags)
var/list/fishes = get_fishes()
//I wish this were an aquarium signal, but the aquarium_content component got in the way.
for(var/obj/item/fish/fish as anything in fishes)
SEND_SIGNAL(fish, COMSIG_FISH_STIRRED)
/// Tries to put mob pulled by the user in the aquarium after a delay
/obj/structure/aquarium/proc/try_to_put_mob_in(mob/user)
if(user.pulling && isliving(user.pulling))
var/mob/living/living_pulled = user.pulling
if(living_pulled.buckled || living_pulled.has_buckled_mobs())
to_chat(user, span_warning("[living_pulled] is attached to something!"))
return
user.visible_message(span_danger("[user] starts to put [living_pulled] into [src]!"))
if(do_after(user, 10 SECONDS, target = src))
if(QDELETED(living_pulled) || user.pulling != living_pulled || living_pulled.buckled || living_pulled.has_buckled_mobs())
return
var/datum/component/aquarium_content/content_component = living_pulled.GetComponent(/datum/component/aquarium_content)
if(content_component || content_component.is_ready_to_insert(src))
return
user.visible_message(span_danger("[user] stuffs [living_pulled] into [src]!"))
living_pulled.forceMove(src)
update_appearance()
var/morb = HAS_TRAIT(user, TRAIT_MORBID)
//Check if there are live fish - good mood
//All fish dead - bad mood.
//No fish - nothing.
if(alive_fish > 0)
user.add_mood_event("aquarium", morb ? /datum/mood_event/morbid_aquarium_bad : /datum/mood_event/aquarium_positive)
else if(dead_fish > 0)
user.add_mood_event("aquarium", morb ? /datum/mood_event/morbid_aquarium_good : /datum/mood_event/aquarium_negative)
// Could maybe scale power of this mood with number/types of fish
/obj/structure/aquarium/ui_static_data(mob/user)
. = ..()
//I guess these should depend on the fluid so lava critters can get high or stuff below water freezing point but let's keep it simple for now.
.["minTemperature"] = min_fluid_temp
.["maxTemperature"] = max_fluid_temp
.["fluidTypes"] = fluid_types
new /obj/item/aquarium_prop/sand(src)
new /obj/item/aquarium_prop/seaweed(src)
new /obj/item/fish/goldfish/gill(src)
reagents.add_reagent(/datum/reagent/consumable/nutriment, 2)
new /obj/item/aquarium_prop/sand(src)
new /obj/item/aquarium_prop/seaweed(src)
new /obj/item/fish/goldfish(src)
new /obj/item/fish/angelfish(src)
new /obj/item/fish/guppy(src)
//They'll be alive for about 30 minutes with this amount.
reagents.add_reagent(/datum/reagent/consumable/nutriment, 3)
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Aquarium
{
[RegisterComponent]
public class AquariumComponent : Component
{
public override string Name => "Aquarium";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_type")]
private string _fluidType = "freshwater";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_temp")]
private float _fluidTemp = 20f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("min_fluid_temp")]
private float _minFluidTemp = 5f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("max_fluid_temp")]
private float _maxFluidTemp = 30f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("feeding_interval")]
private float _feedingInterval = 180f; // 3 minutes
private float _lastFeedingTime = 0f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("allow_breeding")]
private bool _allowBreeding = true;
// A list to keep track of fish in the aquarium
private readonly List<IEntity> _fish = new();
protected override void Initialize()
{
base.Initialize();
Owner.EnsureComponent<TransformComponent>().Anchored = true;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
float currentTime = IoCManager.Resolve<IGameTiming>().CurTime.TotalSeconds;
if (currentTime >= _lastFeedingTime + _feedingInterval)
{
FeedFish();
_lastFeedingTime = currentTime;
}
}
private void FeedFish()
{
foreach (var fish in _fish)
{
if (fish.TryGetComponent<FishComponent>(out var fishComponent))
{
fishComponent.Feed(); // Implement the feeding logic in the FishComponent
}
}
}
public void AddFish(IEntity fish)
{
_fish.Add(fish);
}
public void RemoveFish(IEntity fish)
{
_fish.Remove(fish);
}
protected override void Shutdown()
{
base.Shutdown();
_fish.Clear();
}
// Implement other methods as needed, such as handling interactions with the aquarium,
// changing the fluid type, adjusting temperature, etc.
}
}
Взаимодействие с аквариумом
Теперь добавим обработчики взаимодействий для аквариума.
csharp
using Robust.Shared.GameObjects;
using Content.Shared.Interaction;
namespace Content.Server.Aquarium
{
public class AquariumSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AquariumComponent, InteractHandEvent>(OnHandInteract);
SubscribeLocalEvent<AquariumComponent, InteractUsingEvent>(OnInteractUsing);
}
private void OnHandInteract(EntityUid uid, AquariumComponent component, InteractHandEvent args)
{
// Handle hand interaction with the aquarium (e.g., opening/closing the panel)
if (args.Handled) return;
// Example logic: Toggle panel open/close
// component.TogglePanel();
args.Handled = true;
}
private void OnInteractUsing(EntityUid uid, AquariumComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
// Handle interactions with items (e.g., adding fish feed, upgrading the aquarium)
if (args.Used.TryGetComponent<FishFeedComponent>(out var fishFeed))
{
component.AddFishFeed(fishFeed);
args.Handled = true;
}
}
}
}
Не забудьте зарегистрировать систему
Не забудьте зарегистрировать систему и загрузить её в главном классе вашего модуля:
csharp
public override void Initialize()
{
base.Initialize();
IoCManager.Resolve<IEntitySystemManager>().LoadSystems();
IoCManager.Resolve<IEntitySystemManager>().InitializeSystem<AquariumSystem>();
}
Дополнительные шаги
Создайте компоненты для рыбы: Создайте компонент FishComponent, который будет содержать логику кормления рыбы и другие поведения.
Добавьте логику для панели управления аквариумом: Если панель должна открываться и закрываться, добавьте соответствующие методы и взаимодействия в AquariumComponent.
Тестирование: Убедитесь, что все компоненты работают корректно вместе, протестируйте аквариум в игре, добавьте/удалите рыбу, управляйте температурой и жидкостью, убедитесь, что кормление работает.
Этот подход упрощает управление логикой и данными, делая код более читаемым и легким в сопровождении.
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Aquarium
{
[RegisterComponent]
public class AquariumComponent : Component
{
public override string Name => "Aquarium";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_type")]
private string _fluidType = "freshwater";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_temp")]
private float _fluidTemp = 20f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("min_fluid_temp")]
private float _minFluidTemp = 5f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("max_fluid_temp")]
private float _maxFluidTemp = 30f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("feeding_interval")]
private float _feedingInterval = 180f; // 3 minutes
private float _lastFeedingTime = 0f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("allow_breeding")]
private bool _allowBreeding = true;
// A list to keep track of fish in the aquarium
private readonly List<IEntity> _fish = new();
protected override void Initialize()
{
base.Initialize();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
float currentTime = IoCManager.Resolve<IGameTiming>().CurTime.TotalSeconds;
if (currentTime >= _lastFeedingTime + _feedingInterval)
{
FeedFish();
_lastFeedingTime = currentTime;
}
}
private void FeedFish()
{
foreach (var fish in _fish)
{
if (fish.TryGetComponent<FishComponent>(out var fishComponent))
{
fishComponent.Feed(); // Implement the feeding logic in the FishComponent
}
}
}
public void AddFish(IEntity fish)
{
_fish.Add(fish);
}
public void RemoveFish(IEntity fish)
{
_fish.Remove(fish);
}
protected override void Shutdown()
{
base.Shutdown();
_fish.Clear();
}
}
}
Шаг 3. Регистрация системы и компонента
Создайте систему для обработки взаимодействий с аквариумом. В папке Systems, создайте файл AquariumSystem.cs.
csharp
using Robust.Shared.GameObjects;
using Content.Shared.Interaction;
namespace Content.Server.Aquarium
{
public class AquariumSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AquariumComponent, InteractHandEvent>(OnHandInteract);
SubscribeLocalEvent<AquariumComponent, InteractUsingEvent>(OnInteractUsing);
}
private void OnHandInteract(EntityUid uid, AquariumComponent component, InteractHandEvent args)
{
// Handle hand interaction with the aquarium (e.g., opening/closing the panel)
if (args.Handled) return;
// Example logic: Toggle panel open/close
// component.TogglePanel();
args.Handled = true;
}
private void OnInteractUsing(EntityUid uid, AquariumComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
// Handle interactions with items (e.g., adding fish feed, upgrading the aquarium)
if (args.Used.TryGetComponent<FishFeedComponent>(out var fishFeed))
{
component.AddFishFeed(fishFeed);
args.Handled = true;
}
}
}
}
Регистрация системы в игровом проекте:
csharp
// В вашем основном классе или конфигурации модуля:
// Content.Server/Entry/ServerEntryPoint.cs или аналогичном
public override void Initialize()
{
base.Initialize();
IoCManager.Resolve<IEntitySystemManager>().LoadSystem<AquariumSystem>();
}
Шаг 4. Тестирование
Соберите проект:
Используйте вашу IDE для сборки проекта. Обычно это кнопка Build или Rebuild.
Запустите сервер:
Запустите сервер SS14, используя командную строку или вашу IDE.
Создайте аквариум в игре:
Используйте admin команды в игре, чтобы создать или заспавнить аквариум, с использованием команды spawn из прототипа, который вы создали.
Протестируйте взаимодействие:
Убедитесь, что аквариум корректно реагирует на взаимодействие, кормление рыбы и другие действия.
Этот пошаговый гид облегчит вам создание и тестирование аквариума в SS14. Если у вас возникнут проблемы или вам понадобятся дополнительные разъяснения, не стесняйтесь задавать вопросы!
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Aquarium
{
[RegisterComponent]
public class AquariumComponent : Component
{
public override string Name => "Aquarium";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_type")]
private string _fluidType = "freshwater";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_temp")]
private float _fluidTemp = 20f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("min_fluid_temp")]
private float _minFluidTemp = 5f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("max_fluid_temp")]
private float _maxFluidTemp = 30f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("feeding_interval")]
private float _feedingInterval = 180f; // 3 minutes
private float _lastFeedingTime = 0f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("allow_breeding")]
private bool _allowBreeding = true;
// A list to keep track of fish in the aquarium
private readonly List<IEntity> _fish = new();
protected override void Initialize()
{
base.Initialize();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
float currentTime = IoCManager.Resolve<IGameTiming>().CurTime.TotalSeconds;
if (currentTime >= _lastFeedingTime + _feedingInterval)
{
FeedFish();
_lastFeedingTime = currentTime;
}
}
private void FeedFish()
{
foreach (var fish in _fish)
{
if (fish.TryGetComponent<FishComponent>(out var fishComponent))
{
fishComponent.Feed(); // Implement the feeding logic in the FishComponent
}
}
}
public void AddFish(IEntity fish)
{
_fish.Add(fish);
}
public void RemoveFish(IEntity fish)
{
_fish.Remove(fish);
}
protected override void Shutdown()
{
base.Shutdown();
_fish.Clear();
}
}
}
Шаг 3. Создание системы для обработки взаимодействий
Создайте файл системы:
В папке Systems, создайте файл AquariumSystem.cs.
Добавьте следующий код в AquariumSystem.cs:
csharp
using Robust.Shared.GameObjects;
using Content.Shared.Interaction;
namespace Content.Server.Aquarium
{
public class AquariumSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AquariumComponent, InteractHandEvent>(OnHandInteract);
SubscribeLocalEvent<AquariumComponent, InteractUsingEvent>(OnInteractUsing);
}
private void OnHandInteract(EntityUid uid, AquariumComponent component, InteractHandEvent args)
{
// Handle hand interaction with the aquarium (e.g., opening/closing the panel)
if (args.Handled) return;
// Example logic: Toggle panel open/close
// component.TogglePanel();
args.Handled = true;
}
private void OnInteractUsing(EntityUid uid, AquariumComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
// Handle interactions with items (e.g., adding fish feed, upgrading the aquarium)
if (args.Used.TryGetComponent<FishFeedComponent>(out var fishFeed))
{
component.AddFish(fishFeed.Owner);
args.Handled = true;
}
}
}
}
Шаг 4. Регистрация системы
Теперь зарегистрируем систему в игре.
Откройте основной файл вашего проекта:
Обычно это файл в папке Entry, например, ServerEntryPoint.cs.
Добавьте код для регистрации системы:
csharp
public override void Initialize()
{
base.Initialize();
IoCManager.Resolve<IEntitySystemManager>().LoadSystem<AquariumSystem>();
}
Шаг 5. Тестирование
Соберите проект: Используйте вашу IDE для сборки проекта. Обычно это кнопка Build или Rebuild.
Запустите сервер: Запустите сервер SS14, используя командную строку или вашу IDE.
Создайте аквариум в игре: Используйте admin команды в игре, чтобы создать или заспавнить аквариум, с использованием команды spawn из прототипа, который вы создали.
Проверьте взаимодействие: Убедитесь, что аквариум корректно реагирует на взаимодействие, кормление рыбы и другие действия.
Если что-то не работает или вам нужно больше информации по какому-то конкретному шагу, не стесняйтесь задавать вопросы!
type: entity
id: GlassBoxLaserOpen
parent: GlassBoxLaser
suffix: AntiqueLaser, Open
components:
Создайте новый файл с именем AquariumComponent.cs.
В этот файл добавьте следующие данные:
csharp
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Aquarium
{
[RegisterComponent]
public class AquariumComponent : Component
{
public override string Name => "Aquarium";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_type")]
private string _fluidType = "freshwater";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_temp")]
private float _fluidTemp = 20f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("min_fluid_temp")]
private float _minFluidTemp = 5f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("max_fluid_temp")]
private float _maxFluidTemp = 30f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("feeding_interval")]
private float _feedingInterval = 180f; // 3 minutes
private float _lastFeedingTime = 0f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("allow_breeding")]
private bool _allowBreeding = true;
// A list to keep track of fish in the aquarium
private readonly List<IEntity> _fish = new();
protected override void Initialize()
{
base.Initialize();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
float currentTime = IoCManager.Resolve<IGameTiming>().CurTime.TotalSeconds;
if (currentTime >= _lastFeedingTime + _feedingInterval)
{
FeedFish();
_lastFeedingTime = currentTime;
}
}
private void FeedFish()
{
foreach (var fish in _fish)
{
if (fish.TryGetComponent<FishComponent>(out var fishComponent))
{
fishComponent.Feed(); // Implement the feeding logic in the FishComponent
}
}
}
public void AddFish(IEntity fish)
{
_fish.Add(fish);
}
public void RemoveFish(IEntity fish)
{
_fish.Remove(fish);
}
protected override void Shutdown()
{
base.Shutdown();
_fish.Clear();
}
}
}
Шаг 3. Создание системы для обработки взаимодействий
Создайте файл AquariumSystem.cs:
В папке Content.Server/Systems/, создайте файл AquariumSystem.cs.
В этот файл добавьте следующие данные:
csharp
using Robust.Shared.GameObjects;
using Content.Shared.Interaction;
namespace Content.Server.Aquarium
{
public class AquariumSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AquariumComponent, InteractHandEvent>(OnHandInteract);
SubscribeLocalEvent<AquariumComponent, InteractUsingEvent>(OnInteractUsing);
}
private void OnHandInteract(EntityUid uid, AquariumComponent component, InteractHandEvent args)
{
// Handle hand interaction with the aquarium (e.g., opening/closing the panel)
if (args.Handled) return;
// Example logic: Toggle panel open/close
// component.TogglePanel();
args.Handled = true;
}
private void OnInteractUsing(EntityUid uid, AquariumComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
// Handle interactions with items (e.g., adding fish feed, upgrading the aquarium)
if (args.Used.TryGetComponent<FishFeedComponent>(out var fishFeed))
{
component.AddFish(args.Used);
args.Handled = true;
}
}
}
}
Шаг 4. Регистрация системы
Откройте основной файл вашего проекта:
Откройте ServerEntryPoint.cs или аналогичный файл в папке Entry.
Добавьте код, чтобы зарегистрировать систему:
csharp
public override void Initialize()
{
base.Initialize();
IoCManager.Resolve<IEntitySystemManager>().LoadSystem<AquariumSystem>();
}
Шаг 5. Тестирование
Соберите проект: Используйте вашу IDE для сборки проекта (кнопка Build или Rebuild).
Запустите сервер: Запустите сервер SS14 через командную строку или IDE.
Создайте аквариум в игре: Используйте команду spawn в игре, чтобы создать объект аквариума из прототипа.
Проверьте взаимодействие: Убедитесь, что аквариум корректно реагирует на взаимодействия, как указано в компоненте и системе.
Эти шаги помогут создать и настроить аквариум с разными состояниями в игре SS14. Если у вас возникнут вопросы или проблемы на каком-либо этапе, не стесняйтесь спрашивать!
Если реагенты не нужны, мы можем упростить и C# компонент. Давайте обновим его.
Откройте AquariumComponent.cs и убедитесь, что он выглядит следующим образом:
csharp
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Aquarium
{
[RegisterComponent]
public class AquariumComponent : Component
{
public override string Name => "Aquarium";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_type")]
private string _fluidType = "water";
[ViewVariables(VVAccess.ReadWrite)]
[DataField("fluid_temp")]
private float _fluidTemp = 20f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("min_fluid_temp")]
private float _minFluidTemp = 5f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("max_fluid_temp")]
private float _maxFluidTemp = 30f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("feeding_interval")]
private float _feedingInterval = 180f; // 3 minutes
private float _lastFeedingTime = 0f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("allow_breeding")]
private bool _allowBreeding = true;
// A list to keep track of fish in the aquarium
private readonly List<IEntity> _fish = new();
protected override void Initialize()
{
base.Initialize();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
float currentTime = IoCManager.Resolve<IGameTiming>().CurTime.TotalSeconds;
if (currentTime >= _lastFeedingTime + _feedingInterval)
{
FeedFish();
_lastFeedingTime = currentTime;
}
}
private void FeedFish()
{
foreach (var fish in _fish)
{
if (fish.TryGetComponent<FishComponent>(out var fishComponent))
{
fishComponent.Feed(); // Implement the feeding logic in the FishComponent
}
}
}
public void AddFish(IEntity fish)
{
_fish.Add(fish);
}
public void RemoveFish(IEntity fish)
{
_fish.Remove(fish);
}
protected override void Shutdown()
{
base.Shutdown();
_fish.Clear();
}
}
}
Шаг 3. Обновление системы для обработки взаимодействий
Обновляем систему для обработки взаимодействий, убирая упоминания нестандартных реагентов:
Откройте AquariumSystem.cs и убедитесь, что он выглядит следующим образом:
csharp
using Robust.Shared.GameObjects;
using Content.Shared.Interaction;
namespace Content.Server.Aquarium
{
public class AquariumSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AquariumComponent, InteractHandEvent>(OnHandInteract);
SubscribeLocalEvent<AquariumComponent, InteractUsingEvent>(OnInteractUsing);
}
private void OnHandInteract(EntityUid uid, AquariumComponent component, InteractHandEvent args)
{
// Handle hand interaction with the aquarium (e.g., opening/closing the panel)
if (args.Handled) return;
// Example logic: Toggle panel open/close
// component.TogglePanel();
args.Handled = true;
}
private void OnInteractUsing(EntityUid uid, AquariumComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
// Handle interactions with items (e.g., adding fish feed, upgrading the aquarium)
// Example: if an item is tagged as FishFeed, add it to the aquarium
if (args.Used.TryGetComponent<FishFeedComponent>(out var fishFeed))
{
component.AddFish(args.Used);
args.Handled = true;
}
}
}
}
Шаг 4. Регистрация системы
Откройте ServerEntryPoint.cs или аналогичный основной файл проекта:
Добавьте следующий код для регистрации системы:
csharp
public override void Initialize()
{
base.Initialize();
IoCManager.Resolve<IEntitySystemManager>().LoadSystem<AquariumSystem>();
}
Шаг 5. Тестирование
Соберите проект: Используйте вашу IDE (нажимаете Build или Rebuild).
Запустите сервер: Запустите сервер SS14 через командную строку или через IDE.
Создайте аквариум в игре: Используйте команду spawn в игре, чтобы создать аквариум из прототипа.
Проверьте взаимодействие: Убедитесь, что аквариум корректно реагирует на взаимодействие с предметами.
Если у вас возникнут проблемы или вам понадобится больше информации по какому-то из шагов, не стесняйтесь задавать вопросы!