C#:
using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections;
using System;
using Oxide.Game.Rust.Cui;
using UnityEngine.Events;
using Oxide.Core.Plugins;
using Oxide.Core;
namespace Oxide.Plugins {
[Info("PersonalNPC", "walkinrey", "1.9.1")]
public class PersonalNPC : RustPlugin {
public static PersonalNPC Instance;
private const bool ru = true;
[PluginReference]
private Plugin ImageLibrary, VehicleDeployedLocks, MarkerManager, PNPCAddonHeli, ZoneManager, Friends, Clans, DeployableNature;
private Dictionary<ulong, PlayerBotController> _existsControllers = new Dictionary<ulong, PlayerBotController>();
private Dictionary<ulong, BotOwnerComponent> _existsBots = new Dictionary<ulong, BotOwnerComponent>();
private List<string> _permissionKeys = new List<string>();
private List<ulong> _pendingSpawnBots = new List<ulong>();
private Dictionary<ulong, DateTime> _cooldownInfo = new Dictionary<ulong, DateTime>();
private static string _noCooldownPermission = "personalnpc.nocooldown";
public OnControllerCreatedEvent OnControllerCreated = new OnControllerCreatedEvent();
#region Config
private Configuration _config;
public class Configuration {
[JsonProperty(!ru ? "Control setup" : "Настройки контроллера")]
public ControlsSetup controls = new ControlsSetup();
[JsonProperty(!ru ? "GUI customization" : "Настройки GUI")]
public GUIOptions gui = new GUIOptions();
[JsonProperty(!ru ? "Bot settings by permission" : "Настройки ботов по правам")]
public Dictionary<string, BotSetup> permissionBot = new Dictionary<string, BotSetup>();
[JsonProperty(!ru ? "Bot install by item" : "Установка ботов по предмету")]
public List<ItemInfo> installItem = new List<ItemInfo>();
[JsonProperty(!ru ? "How many seconds will the bot update the information? (affects the performance and operation of the bot)" : "Сколько секунд будет обновлять информацию бот? (влияет на производительность и работу бота)")]
public float mainProcessTimer = 0.01f;
[JsonProperty(!ru ? "Spawn a backpack with his items when a bot dies? (otherwise his corpse will spawn)" : "Создавать рюкзак с его предметами при смерти бота? (иначе его труп будет спавнить)")]
public bool enableBackpackOnDeath = false;
[JsonProperty(!ru ? "Disable bot's backpack/corpse despawn?" : "Отключить деспавн рюкзака/трупа бота?")]
public bool disableBackpackDespawn = false;
[JsonProperty(!ru ? "Despawn bot’s items when owner disconnects?" : "Деспавнить предметы бота при отключении владельца?")]
public bool enableDespawnOnDisconnect = false;
[JsonProperty(!ru ? "Enable ExtraSeating plugin support?" : "Включить поддержку плагина ExtraSeating?")]
public bool enableExtraSeatingSupport = false;
[JsonProperty(!ru ? "Clear console of 'ownerPlayer is not player' spam?" : "Очистить консоль от спама 'ownerPlayer is not player'?")]
public bool clearConsoleOfSpam = true;
[JsonProperty(!ru ? "Auto spawn first available bot on plugin load for every player?" : "Автоматически заспавнить первого доступного бота при загрузке плагина для всех игроков?")]
public bool autoSpawnBot = false;
[JsonProperty(!ru ? "List of prefabs that the bot can loot (useful if the bot attacks loot instead of looting it)" : "Список префабов, которые может собрать бот (полезно если бот атакует предметы вместо того, чтобы собирать их)")]
public List<string> allowedLootPrefabs = new List<string>();
public struct ItemInfo {
[JsonProperty(!ru ? "Item name" : "Название предмета")]
public string name;
[JsonProperty(!ru ? "Item shortname" : "Короткое название предмета")]
public string shortname;
[JsonProperty(!ru ? "Item skin" : "Скин предмета")]
public ulong skin;
[JsonProperty(!ru ? "Return item back if player have despawned the PersonalNPC via command or GUI?" : "Вернуть предмет обратно, если игрок отключил NPC через команду или GUI?")]
public bool returnDespawn;
[JsonProperty(!ru ? "Bot info" : "Информация о боте")]
public BotSetup bot;
}
public class ControlsSetup {
[JsonIgnore]
public BUTTON controlButton = BUTTON.FIRE_THIRD;
[JsonProperty(!ru ? "Which button will assign tasks to the bot, kill/get/collect, etc.(MIDDLE_MOUSE, SECOND_MOUSE, E, RELOAD, SPRINT)" : "Которую кнопку будет использовать бот для выполнения задач, убийства/вытягивания/сбора, и т.п.(MIDDLE_MOUSE, SECOND_MOUSE, E, RELOAD, SPRINT)")]
public string mainControlButton = "MIDDLE_MOUSE";
[JsonProperty(!ru ? "Use point gesture instead of button?" : "Использовать жест точки вместо кнопки?")]
public bool usePointGesture = false;
[JsonProperty(!ru ? "Range of the task assignment button" : "Расстояние кнопки задания задачи")]
public float rayLength = 25f;
[JsonProperty(!ru ? "Display 3D arrows over a target?" : "Отображать 3D стрелки над целью?")]
public bool enableArrowView = true;
[JsonProperty(!ru ? "Show 3D text if owner attacking his bot? (lang key is 'Bot_Notice_HitByOwner')" : "Отображать 3D текст, если владелец атакует своего бота? (ключ языка 'Bot_Notice_HitByOwner')")]
public bool showTextOnHit = false;
//
[JsonProperty(!ru ? "Text display duration" : "Длительность отображения текста")]
public int textViewDuration = 2;
[JsonProperty(!ru ? "Arrow display duration" : "Длительность отображения стрелки")]
public int arrowViewDuration = 2;
[JsonProperty(!ru ? "Distance between owner and bot in follow state" : "Расстояние между владельцем и ботом в состоянии следования")]
public float followDistance = 2f;
[JsonProperty(!ru ? "Distance between owner and bot to recover" : "Расстояние между владельцем и ботом для восстановления")]
public float recoverDistance = 3f;
[JsonProperty(!ru ? "Distance between bot and collectable entity to pickup" : "Расстояние между ботом и подбираемой сущностью для поднятия")]
public float collectableDistance = 2f;
[JsonProperty(!ru ? "Distance between bot and item to pickup" : "Расстояние между ботом и предметом для поднятия")]
public float itemPickupDistance = 2f;
[JsonProperty(!ru ? "Distance between bot and loot container to loot" : "Расстояние между ботом и контейнером с лутом для поиска лута")]
public float lootContainerDistance = 2f;
[JsonProperty(!ru ? "Distance between bot and tree/ore to gather" : "Расстояние между ботом и деревом/руду для сбора")]
public float gatherDistance = 3f;
[JsonProperty(!ru ? "Distance between bot and seat to mount" : "Расстояние между ботом и сиденья для посадки")]
public float mountDistance = 3f;
[JsonProperty(!ru ? "Distance between bot and enemy" : "Расстояние между ботом и врагом")]
public float enemyDistance = 3f;
[JsonProperty(!ru ? "Maximum distance bot will remember target" : "Максимальное расстояние, которое бот помнит цель")]
public float maxDistanceRemember = 30f;
[JsonProperty(!ru ? "Spawn personal bot on player connect?" : "Создавать личного бота при подключении игрока?")]
public bool spawnOnConnect = false;
[JsonProperty(!ru ? "Block bot spawn in safezones" : "Заблокировать создание бота в безопасных зонах")]
public bool blockBotSpawnSafezone = false;
[JsonProperty(!ru ? "Cooldown on PNPC commands" : "Перезарядка на команды PNPC")]
public float pnpcCommandsCooldown = 0.5f;
[JsonProperty(!ru ? "Block bot spawn in ZoneManager zones (enter zone id belove)" : "Заблокировать создание бота в зонах ZoneManager (введите id зоны ниже)")]
public List<string> blockBotZoneManager = new List<string>();
[JsonProperty(!ru ? "Chat commands to execute on player connect (works only if you have enabled spawn personal bot on connect)" : "Команды чата для выполнения при подключении игрока (работает только если вы включили создание личного бота при подключении игрока)")]
public List<string> chatCommandsOnConnect = new List<string>();
[JsonProperty(!ru ? "Chat commands to execute on /pnpc (on personal npc spawn)" : "Команды чата для выполнения при /pnpc (при создании личного NPC)")]
public List<string> chatCommandsOnSpawn = new List<string>();
}
public class GUIOptions {
[JsonProperty(!ru ? "How many seconds to update the GUI?" : "За сколько секунд обновлять GUI")]
public float guiRefreshTime = 6f;
[JsonProperty(!ru ? "Panel layer (Hud, Overlay, Overall, Hud.Menu, Under)" : "Слой панели (Hud, Overlay, Overall, Hud.Menu, Under)")]
public string panelLayer = "Overlay";
[JsonProperty(!ru ? "Send commands to local chat? (required for hardcore mode, where global chat is disabled)" : "Отправлять команды в локальный чат? (требуется для hardcore режима, где глобальный чат отключен)")]
public bool useLocal = false;
[JsonProperty(!ru ? "Panel position adjustment" : "Позиция панели корректировка")]
public CuiRectTransformComponent panelPosition = new CuiRectTransformComponent();
[JsonProperty(!ru ? "1 panel color" : "1 цвет панели")]
public string panelColor1 = "#7f8c8d";
[JsonProperty(!ru ? "2 panel color" : "2 цвет панели")]
public string panelColor2 = "#bdc3c7";
[JsonProperty(!ru ? "Health bar color" : "Цвет полосы здоровья")]
public string panelHealthColor = "#2ecc71";
[JsonProperty(!ru ? "Remove UI material" : "Удалить материал UI")]
public bool removeUIMaterial = false;
[JsonProperty(!ru ? "Show shortcut buttons when bot is spawned?" : "Отображать кнопки быстрого доступа при создании бота?")]
public bool showShortcutButtons = false;
[JsonProperty(!ru ? "Lock shortcut buttons?" : "Заблокировать кнопки быстрого доступа?")]
public bool lockShortcutButtons = false;
[JsonProperty(!ru ? "Hide (minimize) GUI on bot spawn?" : "Скрыть (минимизировать) GUI при создании бота?")]
public bool autoMinimize = false;
[JsonProperty(!ru ? "Shortcut buttons" : "Кнопки быстрого доступа")]
public List<AccessButton> accessButtons = new List<AccessButton>();
public class AccessButton {
[JsonProperty(!ru ? "Text on button" : "Текст на кнопке")]
public string text = "";
[JsonProperty(!ru ? "Executable chat commands" : "Выполняемые команды чата")]
public string[] commands = new string[] {
}
;
public AccessButton(string btnText, string[] btnCommand) {
text = btnText;
commands = btnCommand;
}
}
}
public class BotSetup {
[JsonProperty(!ru ? "Bot spawn delay" : "Задержка создания бота")]
public float cooldown = 300f;
[JsonProperty(!ru ? "The name of the bot to be selected through the command when spawning" : "Имя бота для выбора через команду при создании")]
public string spawnName = "bot1";
[JsonProperty(!ru ? "Bot name" : "Имя бота")]
public string name = "Personal Bot of player %OWNER_NAME%";
[JsonProperty(!ru ? "Bot appearance (0 - random)" : "Внешний вид бота (0 - случайный)")]
public ulong skin = 0;
[JsonProperty(!ru ? "Maximum health" : "Максимальное здоровье")]
public float maxHealth = 150f;
[JsonProperty(!ru ? "Bot speed (slowest, slow, normal, fast)" : "Скорость бота (slowest, slow, normal, fast)")]
public string speed = "normal";
[JsonProperty(!ru ? "Enable infinite ammo for the bot?" : "Включить бесконечное количество патронов для бота?")]
public bool infiniteAmmo = true;
[JsonProperty(!ru ? "Disable item condition loss for weapons?" : "Отключить потерю состояния предметов для оружия?")]
public bool disableWeaponConditionLoss = false;
[JsonProperty(!ru ? "Enable display of the bot on the map? (frankenstein icon)" : "Включить отображение бота на карте? (икона франкенштейна)")]
public bool enableMapView = true;
[JsonProperty(!ru ? "Drop active item on death?" : "Сбросить активный предмет при смерти?")]
public bool dropActiveItem = false;
[JsonProperty(!ru ? "Can player open bot's inventory through '/pnpc inventory' command?" : "Может ли игрок открыть инвентарь бота через команду '/pnpc inventory'?")]
public bool inventoryCommand = false;
[JsonProperty(!ru ? "Can other players loot bot's corpse?" : "Может ли другой игрок забрать тело бота?")]
public bool canLootCorpse = false;
[JsonProperty(!ru ? "Lock bot's corpse main container?" : "Залочить основной контейнер тела бота?")]
public bool lockCorpseMainContainer = false;
[JsonProperty(!ru ? "Lock bot's corpse belt container?" : "Залочить контейнер пояса тела бота?")]
public bool lockCorpseBeltContainer = false;
[JsonProperty(!ru ? "Lock bot's corpse wear container?" : "Залочить контейнер одежды тела бота?")]
public bool lockCorpseWearContainer = false;
[JsonProperty(!ru ? "Teleport bot to owner when clicking follow?" : "Телепортировать бота к владельцу при клике по следовать?")]
public bool teleportFollow = false;
[JsonProperty(!ru ? "Teleport bot to destination if no path is found?" : "Телепортировать бота к месту назначения, если нет пути?")]
public bool teleportNoPath = false;
[JsonProperty(!ru ? "Steam ID for chat icon (leave 0 if not needed)" : "Steam ID для иконки чата (оставьте 0, если не требуется)")]
public string chatIconSteamID = "";
[JsonProperty(!ru ? "Start kit" : "Начальный набор")]
public List<ItemSetup> startKit = new List<ItemSetup>();
[JsonProperty(!ru ? "Functions setup" : "Настройки функций")]
public FunctionsSetup functions = new FunctionsSetup();
[JsonProperty(!ru ? "Gather setup" : "Настройки сбора")]
public GatherSetup gather = new GatherSetup();
[JsonProperty(!ru ? "Damage and interactions setup" : "Настройки урона и взаимодействия")]
public TargetSetup target = new TargetSetup();
[JsonProperty(!ru ? "Death Marker (marker will be only visible for owner)" : "Маркер смерти (маркер будет виден только для владельца)")]
public DeathMarkerSetup deathMarker = new DeathMarkerSetup();
[JsonProperty(!ru ? "Black list of items that cannot be put into the inventory of the bot" : "Черный список предметов, которые не могут быть помещены в инвентарь бота")]
public string[] itemBlacklist = {
"rocket.launcher"
}
;
[JsonProperty(!ru ? "List of prefabs that the bot will ignore if they attack it" : "Список префабов, которые бот игнорирует, если они атакуют его")]
public string[] attackIgnore = {
"assets/prefabs/deployable/bear trap/beartrap.prefab"
}
;
public class DeathMarkerSetup {
[JsonProperty(!ru ? "Show marker on bot's death position?" : "Показывать маркер на позиции смерти бота?")]
public bool enableMarker = false;
[JsonProperty(!ru ? "Display name on map" : "Отображать имя на карте")]
public string displayName = "Bot's death marker";
[JsonProperty(!ru ? "Marker radius" : "Радиус маркера")]
public float radius = 0.35f;
[JsonProperty(!ru ? "Outline color (hex)" : "Цвет контура (хекс)")]
public string outline = "00FFFFFF";
[JsonProperty(!ru ? "Main color (hex)" : "Основной цвет (хекс)")]
public string main = "00FFFF";
[JsonProperty(!ru ? "Alpha" : "Альфа")]
public float alpha = 0.5f;
[JsonProperty(!ru ? "Duration" : "Длительность")]
public int duration = 20;
}
public class TargetSetup {
[JsonProperty(!ru ? "Bot damage rate" : "Скорость урона бота")]
public float botDamageRate = 2f;
[JsonProperty(!ru ? "Bot recive damage rate" : "Скорость получения урона ботом")]
public float botHurtRate = 0.5f;
[JsonProperty(!ru ? "Can players damage the bot?" : "Могут ли игроки наносить урон боту?")]
public bool enablePlayerDamage = true;
[JsonProperty(!ru ? "Can the bot damage players?" : "Может ли бот наносить урон игрокам?")]
public bool enablePlayerHurt = true;
[JsonProperty(!ru ? "Can bot damage other personal npc bots?" : "Может ли бот наносить урон другим персональным NPC ботам?")]
public bool enablePersonalBotHurt = false;
[JsonProperty(!ru ? "Enable no damage to bot's clothes & armor?" : "Включить защиту от урона боту одежды и брони?")]
public bool enableProtectedClothesDamage = false;
[JsonProperty(!ru ? "Can turrets target and kill a bot? (all turrets will not be able to damage the bot)" : "Могут ли турели атаковать и убить бота? (все турели не смогут нанести урон боту)")]
public bool enableTurretTargeting = false;
[JsonProperty(!ru ? "Can BradleyAPC target bot?" : "Может ли Брэдли APC атаковать бота?")]
public bool enableBradleyTargeting = true;
[JsonProperty(!ru ? "Prevent bot owner turrets from aiming and killing the bot? (bot owner's turrets will not be able to damage the bot)" : "Предотвратить, чтобы бот-водитель не мог атаковать и убить бота? (турели бота-водителя не смогут нанести урон боту)")]
public bool blockOwnerTurretTargeting = true;
[JsonProperty(!ru ? "Cooldown before switching to another target (useful when bot is being attacked from multiple enemies)" : "Коэффициент замедления перед переключением на другой объект (полезно, когда бот атакуется несколькими врагами)")]
public float switchTargetCooldown = 3f;
[JsonProperty(!ru ? "Disable drowning damage? (will disable for all Frankensteins on the server too)" : "Отключить ущерб от утопления? (отключит для всех Франкенштейнов на сервере также)")]
public bool noDrowningDamage = false;
[JsonProperty(!ru ? "Disable damage to other players buildings?" : "Отключить ущерб к другим игрокам зданиям?")]
public bool disableDamagePlayerBuildings = false;
[JsonProperty(!ru ? "Disable damage to owner buildings?" : "Отключить ущерб к зданиям владельца?")]
public bool disableDamageOwnerBuildings = false;
[JsonProperty(!ru ? "Target visibility settings" : "Настройки видимости объекта цели")]
public VisibilitySetup visibilitySetup = new VisibilitySetup();
[JsonProperty(!ru ? "Attack aim offset" : "Смещение цели для атаки")]
public Vector3 aimOffset = new Vector3(0, -0.5f, -0.3f);
[JsonProperty(!ru ? "Aim offset when player is wounded" : "Смещение цели при ранении игрока")]
public Vector3 aimWoundedOffset = new Vector3(0, 1f);
[JsonProperty(!ru ? "When attacked ignore all targets except players & NPCs?" : "Когда атакован игрок, игнорировать все цели except игроков и NPC?")]
public bool targetOnlyBasePlayers = false;
[JsonProperty(!ru ? "Blacklist of objects that the bot will ignore when owner selecting a target (short prefab name)" : "Черный список объектов, которые бот игнорирует при выборе владельцем цели (короткое префабное имя)")]
public string[] inputBlacklist = new string[] {
}
;
[JsonProperty(!ru ? "BossMonster names to prevent targeting them (if you've BossMonster plugin)" : "Имена BossMonster, которые предотвращают их цель (если у вас плагин BossMonster)")]
public string[] bossesNames = new string[] {
}
;
public class VisibilitySetup {
[JsonProperty(!ru ? "Visibility distance" : "Дистанция видимости")]
public float distance = Mathf.Infinity;
[JsonProperty(!ru ? "Bot center point offset" : "Смещение центра бота")]
public Vector3 botCenterOffset = new Vector3(0, 0, 0);
[JsonProperty(!ru ? "Target center point offset" : "Смещение центра цели")]
public Vector3 targetCenterOffset = new Vector3(0, 0, 0);
[JsonProperty(!ru ? "Obstacle layers" : "Слои препятствий")]
public string[] obstacleLayers = new string[] {
"Default", "Deployed", "Construction", "World", "Tree", "Terrain", "Clutter", "Debris", "Tree"
}
;
}
}
public class GatherSetup {
[JsonProperty(!ru ? "Shortname of items that can harvest trees" : "Короткое имя предметов, которые можно собирать с деревьев")]
public List<string> toolForTrees = new List<string>();
[JsonProperty(!ru ? "Shortname of items that can mine stones and ore" : "Короткое имя предметов, которые можно добывать камни и руду")]
public List<string> toolForStones = new List<string>();
[JsonProperty(!ru ? "Setting up mining rates" : "Настройка скорости добычи")]
public Dictionary<string, float> gatherRates = new Dictionary<string, float>();
[JsonProperty(!ru ? "Radius to collect/gather resources in auto-mode" : "Радиус сбора ресурсов в автомоде")]
public float autoModeRadius = 50f;
[JsonProperty(!ru ? "Chainsaw fuel consumption rate" : "Скорость расхода топлива бензопилы")]
public float chainsawFuelConsRate = 1f;
[JsonProperty(!ru ? "Gather resources to owner's inventory?" : "Собирать ресурсы в инвентарь владельца?")]
public bool gatherResourcesToOwner = false;
}
public class FunctionsSetup {
[JsonProperty(!ru ? "Can a bot loot crates?" : "Может ли бот открывать ящики?")]
public bool canLootBoxes = true;
[JsonProperty(!ru ? "Can the bot mine trees and stones?" : "Может ли бот добывать деревья и камни?")]
public bool canGatherResources = true;
[JsonProperty(!ru ? "Can the bot pick up resources? (wood, sulfur and metal ore, stones)" : "Может ли бот собирать ресурсы? (дерево, серу и металлическую руду, камни)")]
public bool canCollectResources = true;
[JsonProperty(!ru ? "Should the bot protect the owner?" : "Должен ли бот защищать владельца?")]
public bool canProtectOwner = true;
[JsonProperty(!ru ? "Should the bot defend itself?" : "Должен ли бот защищать себя?")]
public bool canProtectSelf = true;
[JsonProperty(!ru ? "Can the bot travel by car/copter and other vehicles?" : "Может ли бот ездить на машине/вертолете и других транспортных средствах?")]
public bool canMount = true;
[JsonProperty(!ru ? "Can the bot pick up dropped items?" : "Может ли бот собирать упавшие предметы?")]
public bool canCollectDroppedItems = true;
[JsonProperty(!ru ? "Recover the owner from a wounded state" : "Восстановить владельца из раненого состояния")]
public RecoverSetup recoverSetup = new RecoverSetup();
[JsonProperty(!ru ? "Target Setup for Combat mode (/pnpc combat)" : "Настройки цели для режима боя (/pnpc combat)")]
public CombatSetup combatSetup = new ();
[JsonProperty(!ru ? "PVP Mode (/pnpc pvp)" : "Режим PvP (/pnpc pvp)")]
public PVPSetup pvpSetup = new PVPSetup();
[JsonProperty(!ru ? "Loot All (/pnpc loot-all)" : "Лут всех (/pnpc loot-all)")]
public LootAllSetup lootAllSetup = new LootAllSetup();
[JsonProperty(!ru ? "Self Heal" : "Самоисцеление")]
public SelfHealSetup selfHeal = new SelfHealSetup();
[JsonProperty(!ru ? "Can the bot attack other people's buildings?" : "Может ли бот атаковать здания других людей?")]
public bool canAttackEnemyBuildings = true;
[JsonProperty(!ru ? "Can a bot attack its owner's buildings?" : "Может ли бот атаковать здания владельца?")]
public bool canAttackOwnerBuildings = false;
[JsonProperty(!ru ? "Can the bot collect resources within a radius of 50 meters? (/pnpc auto-pickup)" : "Может ли бот собирать ресурсы в радиусе 50 метров? (/pnpc auto-pickup)")]
public bool canAutoPickup = true;
[JsonProperty(!ru ? "Can the bot farm resources within a radius of 50 meters? (/pnpc auto-farm)" : "Может ли бот собирать ресурсы в радиусе 50 метров? (/pnpc auto-farm)")]
public bool canAutoFarm = true;
[JsonProperty(!ru ? "Enable bot's inventory?" : "Включить инвентарь бота?")]
public bool enableBotInventory = true;
[JsonProperty(!ru ? "Lock bot's wear slots?" : "Заблокировать слоты одежды бота?")]
public bool blockWearSlots = false;
[JsonProperty(!ru ? "Lock bot's main slots?" : "Заблокировать основные слоты бота?")]
public bool blockMainSlots = false;
[JsonProperty(!ru ? "Lock bot's equipment slots?" : "Заблокировать слоты оборудования бота?")]
public bool blockEquipmentSlots = false;
[JsonProperty(!ru ? "Can the bot fly on helicopters? (PNPC Heli AI Addon plugin)" : "Может ли бот управлять вертолетом? (PNPC Heli AI Addon плагин)")]
public bool enableHeliAddon = false;
[JsonProperty(!ru ? "Can the bot drive cars? (PNPC Addon Car AI plugin)" : "Может ли бот управлять машиной? (PNPC Addon Car AI плагин)")]
public bool enableCarAddon = false;
[JsonProperty(!ru ? "Can the bot drive boats? (PNPC Addon Boat AI plugin)" : "Может ли бот управлять лодкой? (PNPC Addon Boat AI плагин)")]
public bool enableBoatAddon = false;
[JsonProperty(!ru ? "Can bot collect DeployableNature entities manually?" : "Может ли бот подбирать DeployableNature сущности вручную?")]
public bool canCollectDeployableNatureManually = true;
[JsonProperty(!ru ? "Can bot gather DeployableNature entities manually?" : "Может ли бот собирать DeployableNature сущности вручную?")]
public bool canGatherDeployableNatureManually = true;
[JsonProperty(!ru ? "Can bot collect DeployableNature entities in auto-pickup mode?" : "Может ли бот подбирать DeployableNature сущности в режиме auto-pickup?")]
public bool canCollectDeployableNatureAutoPickup = true;
[JsonProperty(!ru ? "Can bot gather DeployableNature entities in auto-farm mode?" : "Может ли бот собирать DeployableNature сущности в режиме auto-farm?")]
public bool canGatherDeployableNatureAutoFarm = true;
public class SelfHealSetup {
[JsonProperty(!ru ? "Should bot heal himself?" : "Должен ли бот исцелить себя?")]
public bool enableHealing = false;
[JsonProperty(!ru ? "Bot will heal himself when his health is below this value" : "Бот будет исцелить себя, когда его здоровье будет ниже этого значения")]
public float belowValue = 20f;
[JsonProperty(!ru ? "Items to heal (you can set list by priority)" : "Товары для исцеления (вы можете задать список по приоритету)")]
public List<string> healItems = new List<string>();
}
public class LootAllSetup {
[JsonProperty(!ru ? "Enable Loot All command (/pnpc loot-all)" : "Включить команду Loot All (/pnpc loot-all)")]
public bool enableLootAll = false;
[JsonProperty(!ru ? "Resources detect radius" : "Радиус обнаружения ресурсов")]
public float radius = 15f;
[JsonProperty(!ru ? "Loot containers?" : "Исследовать контейнеры?")]
public bool lootContainers = true;
[JsonProperty(!ru ? "Loot corpses?" : "Исследовать трупы?")]
public bool lootCorpses = true;
[JsonProperty(!ru ? "Loot dropped items?" : "Исследовать сброшенные предметы?")]
public bool lootDroppedItems = true;
}
public class PVPSetup {
[JsonProperty(!ru ? "Enable PVP mode (attack all bots and players in radius, /pnpc pvp)" : "Включить режим PVP (атаковать всех ботов и игроков в радиусе, /pnpc pvp)")]
public bool enablePVP = false;
[JsonProperty(!ru ? "Detect radius" : "Радиус обнаружения")]
public float radius = 10f;
[JsonProperty(!ru ? "Ignore bots?" : "Игнорировать ботов?")]
public bool ignoreBots = false;
[JsonProperty(!ru ? "Ignore personal npc bots?" : "Игнорировать личных npc ботов?")]
public bool ignorePersonalNPC = true;
[JsonProperty(!ru ? "Ignore players?" : "Игнорировать игроков?")]
public bool ignorePlayers = true;
[JsonProperty(!ru ? "Ignore by short prefab name" : "Игнорировать по короткому префабу имени")]
public List<string> ignorePrefabs = new List<string>();
}
public class RecoverSetup {
[JsonProperty(!ru ? "Can the bot recover the owner if he is in a wounded state?" : "Может ли бот восстановить владельца, если он находится в раненом состоянии?")]
public bool canRecover = true;
[JsonProperty(!ru ? "Recover time" : "Время восстановления")]
public float _recoverTime = 6f;
[JsonProperty(!ru ? "Can spawn personal bot while owner downed?" : "Может ли бот спавнить личный бот, пока владелец находится в обездвиженном состоянии?")]
public bool blockBotSpawnWhileDowned = false;
}
public class CombatSetup {
[JsonProperty(!ru ? "Can bot attack NPC in combat mode?" : "Может ли бот атаковать NPC в режиме боя?")]
public bool CanAttackedNpc = true;
[JsonProperty(!ru ? "Can bot attack players in combat mode?" : "Может ли бот атаковать игроков в режиме боя?")]
public bool CanAttackedUsers = true;
[JsonProperty(!ru ? "Whitelist of entity prefabs that's allowed to attack in combat mode" : "Белый список префабов сущностей, разрешенных к атаке в режиме боя")]
public List<string> WiteListTarget = new ();
[JsonProperty(!ru ? "Blacklist of entity prefabs that's not allowed to attack in combat mode" : "Черный список префабов сущностей, не разрешенных к атаке в режиме боя")]
public List<string> BlackListTarget = new ();
public bool HasBlackList() => BlackListTarget != null || BlackListTarget.Count > 0;
public bool HasWiteList() => WiteListTarget != null || WiteListTarget.Count > 0;
public bool HasEntityFromList(string prefab, bool black) {
if(black) return CheckList(prefab, BlackListTarget);
else return CheckList(prefab, WiteListTarget);
}
private bool CheckList(string prefab, List<string> list) {
foreach(var name in list) if(prefab.Contains(name)) return true;
return false;
}
}
}
public class ItemSetup {
[JsonProperty(!ru ? "Item name" : "Имя предмета")]
public string name = "";
[JsonProperty(!ru ? "Item shortname" : "Короткое имя предмета")]
public string shortname = "";
[JsonProperty(!ru ? "Item skin" : "Скин предмета")]
public ulong skin = 0;
[JsonProperty(!ru ? "Item amount" : "Количество предмета")]
public int amount = 1;
[JsonProperty(!ru ? "In which container to place? (belt, main, wear)" : "В каком контейнере поместить? (belt, main, wear)")]
public string container = "main";
}
}
}
protected override void LoadDefaultConfig() {
_config = new Configuration();
_config.allowedLootPrefabs.Add("vehicle_parts");
_config.permissionBot.Add("personalnpc.bot1", new Configuration.BotSetup {
name = "Personal bot of player %OWNER_NAME%", startKit = new List<Configuration.BotSetup.ItemSetup> {
new Configuration.BotSetup.ItemSetup {
shortname = "shoes.boots", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "pants", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "hoodie", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "mask.bandana", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "hat.boonie", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "sunglasses", container = "wear"
}
}
, gather = new Configuration.BotSetup.GatherSetup {
toolForTrees = new List<string> {
"hatchet", "chainsaw", "hammer.salvaged", "stonehatchet", "axe.salvaged"
}
, toolForStones = new List<string> {
"pickaxe", "stone.pickaxe", "hammer.salvaged", "jackhammer", "icepick.salvaged"
}
, gatherRates = new Dictionary<string, float> {
["stones"]
= 2f, ["wood"] = 5f
}
}
, target = new Configuration.BotSetup.TargetSetup {
inputBlacklist = new string[] {
"barricade.sandbags"
}
}
, functions = new Configuration.BotSetup.FunctionsSetup {
selfHeal = new Configuration.BotSetup.FunctionsSetup.SelfHealSetup {
healItems = new List<string> {
"largemedkit", "syringe.medical", "bandage",
}
}
}
}
);
_config.installItem.Add(new Configuration.ItemInfo {
name = "PersonalNPC", shortname = "furnace", skin = 2741314889, bot = new Configuration.BotSetup {
name = "Personal bot of player %OWNER_NAME%", startKit = new List<Configuration.BotSetup.ItemSetup> {
new Configuration.BotSetup.ItemSetup {
shortname = "shoes.boots", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "pants", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "hoodie", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "mask.bandana", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "hat.boonie", container = "wear"
}
, new Configuration.BotSetup.ItemSetup {
shortname = "sunglasses", container = "wear"
}
}
, gather = new Configuration.BotSetup.GatherSetup {
toolForTrees = new List<string> {
"hatchet", "chainsaw", "hammer.salvaged", "stonehatchet", "axe.salvaged"
}
, toolForStones = new List<string> {
"pickaxe", "stone.pickaxe", "hammer.salvaged", "jackhammer", "icepick.salvaged"
}
, gatherRates = new Dictionary<string, float> {
["stones"]
= 2f, ["wood"] = 5f
}
}
, target = new Configuration.BotSetup.TargetSetup {
inputBlacklist = new string[] {
"barricade.sandbags"
}
}
}
}
);
_config.gui.panelPosition = new CuiRectTransformComponent {
AnchorMin = "1 1", AnchorMax = "1 1", OffsetMin = "-170 -104", OffsetMax = "-10 -10"
}
;
_config.gui.accessButtons.Add(new Configuration.GUIOptions.AccessButton("Auto-Farm: Wood", new string[] {
"pnpc auto-farm wood", "pnpc auto-farm enable"
}
));
_config.gui.accessButtons.Add(new Configuration.GUIOptions.AccessButton("Auto-Farm: Stone", new string[] {
"pnpc auto-farm stone", "pnpc auto-farm enable"
}
));
_config.gui.accessButtons.Add(new Configuration.GUIOptions.AccessButton("Auto-Pickup: Wood", new string[] {
"pnpc auto-pickup wood", "pnpc auto-pickup enable"
}
));
_config.gui.accessButtons.Add(new Configuration.GUIOptions.AccessButton("Auto-Pickup: Stone", new string[] {
"pnpc auto-pickup stone", "pnpc auto-pickup enable"
}
));
}
protected override void LoadConfig() {
base.LoadConfig();
try {
_config = Config.ReadObject<Configuration>();
if (_config == null) throw new Exception();
SaveConfig();
}
catch (Exception ex) {
PrintError("{0}", ex);
LoadDefaultConfig();
}
}
protected override void SaveConfig() => Config.WriteObject(_config);
#endregion
#region Loc
protected override void LoadDefaultMessages() {
lang.RegisterMessages(new Dictionary<string, string> {
["ChatCommand_Success_Despawn"]
= "Ваш персональный бот успешно задеспавнен!", ["ChatCommand_Success_Spawn"] = "Ваш персональный бот успешно заспавнен!", ["ChatCommand_Notice_Ignore_Activated"] = "Бот теперь игнорирует тех, кто атакует его и хозяина", ["ChatCommand_Notice_Ignore_Deactivated"] = "Бот теперь не игнорирует тех, кто атакует его и хозяина", ["ChatCommand_Notice_Combat_Activated"] = "Бот теперь атакует тех, кого атакует хозяин", ["ChatCommand_Notice_Combat_Deactivated"] = "Бот теперь не атакует тех, кого атакует хозяин", ["ChatCommand_Notice_PVP_Activated"] = "Бот теперь атакует всех ботов и игроков которых нет в команде хозяин", ["ChatCommand_Notice_PVP_Deactivated"] = "Бот больше не атакует всех ботов и игроков которых нет в команде хозяина", ["ChatCommand_Notice_Cooldown"] = "Вам нужно подождать {0} секунд, прежде чем повторно заспавнить бота!", ["ChatCommand_Notice_Location"] = "Ваш бот находится в квадрате: {0}, расстояние до бота: {1}", ["ChatCommand_Notice_Health"] = "Здоровье вашего бота: {0}/{1}", ["ChatCommand_Notice_Follow"] = "Бот теперь следует за вами!", ["ChatCommand_Notice_AvailableBots"] = "<size=16>Доступные боты:</size>\n{BOTS}\n\nВведите /pnpc [короткое название бота], чтобы заспавнить!", ["ChatCommand_Error_AutoPickup"] = "<size=16>Авто-подбор ресурсов</size>\n\nБот начнет собирать все ресурсы в радиусе 50 метров от его первоначальной точки.\n\nДоступные режимы: all, wood, stone, metal, sulfur, hemp, berries, pumpkin, potato, mushroom, corn\nОтключить - /pnpc auto-pickup disable", ["ChatCommand_Error_AutoFarm"] = "<size=16>Авто-фарм ресурсов</size>\n\nБот начнет фармить все ресурсы в радиусе 50 метров от его первоначальной точки.\n\nДоступные режимы: all, wood, stone, metal, sulfur\nОтключить - /pnpc auto-farm disable", ["ChatCommand_Error_NoPermission"] = "У вас нет разрешения на спавн персонального бота", ["ChatCommand_Error_CannotUse"] = "Ваш бот не обладает такой функцией, вы не можете ее использовать!", ["ChatCommand_Error_NoBot"] = "У вас нет персонального бота!", ["ChatCommand_Error_NotFounded"] = "Бот не найден!", ["ChatCommand_Error_Blacklist"] = "Этот предмет добавлен в черный список, вы не можете дать его боту!", ["ChatCommand_Error_Contents_Blacklist"] = "У предмета есть содержимое, которое добавлено в черный список.Вы не можете дать этот предмет боту!", ["ChatCommand_Error_NoSpawnHere"] = "Вы не можете заспавнить персонального бота здесь!", ["ChatCommand_Notice_AutoPickup_Status"] = "Авто-подбор ресурсов: {0}\nРесурсы для сбора: {1}", ["ChatCommand_Notice_AutoFarm_Status"] = "Авто-фарм ресурсов: {0}\nРесурсы для фарма: {1}", ["ChatCommand_Tugboat_Drive"] = "Введите /pnpc tugboat если вы хотите чтобы ваш персональный бот управлял буксиром за вас!", ["ChatCommand_Tugboat_NoAuth"] = "У вас нет авторизации в этом буксире!", ["ChatCommand_Tugboat_TooFar"] = "Бот слишком далеко от буксира чтобы сесть!", ["ChatCommand_AutoMode_Resources_All"] = "все", ["ChatCommand_AutoMode_Resources_Wood"] = "дерево", ["ChatCommand_AutoMode_Resources_Stone"] = "камень", ["ChatCommand_AutoMode_Resources_Sulfur"] = "сера", ["ChatCommand_AutoMode_Resources_Metal"] = "металл", ["ChatCommand_AutoMode_Resources_Hemp"] = "ткань", ["ChatCommand_AutoMode_Resources_Berries"] = "ягоды", ["ChatCommand_AutoMode_Resources_Corn"] = "кукуруза", ["ChatCommand_AutoMode_Resources_Mushroom"] = "гриб", ["ChatCommand_AutoMode_Resources_Pumpkin"] = "тыква", ["ChatCommand_AutoMode_Resources_Barrels"] = "бочки", ["ChatCommand_AutoMode_Status_Disabled"] = "отключён", ["ChatCommand_AutoMode_Status_Enabled"] = "включён", ["Chat_Commands_TooFast"] = "Вы вводите команды слишком быстро, подождите немного!", ["Bot_Notice_Recover"] = "Поднял вас, возвращаюсь к заданию!", ["Bot_Notice_MissionCompleted"] = "Цель выполнена, возвращаюсь к вам!", ["Bot_Notice_GoingCollect"] = "Иду собирать ресурс!", ["Bot_Notice_GoingFarm"] = "Иду добывать ресурс!", ["Bot_Notice_GoingLootBox"] = "Иду лутать ящик!", ["Bot_Notice_Following"] = "Следую за вами!", ["Bot_Notice_Staying"] = "Стою на позиции.", ["Bot_Notice_StartedAttack"] = "Начинаю атаку!", ["Bot_Notice_GoingCollectItem"] = "Иду подбирать предмет!", ["Bot_Notice_GoingPosition"] = "Иду на позицию.", ["Bot_Notice_GoingLootCorpse"] = "Иду лутать труп!", ["Bot_Notice_HitByOwner"] = "Вы атакуете меня!", ["Bot_Error_NoTool"] = "Нечем добывать ресурс!", ["Bot_Error_NoWeapon"] = "Нет оружия чтобы атаковать!", ["Bot_Error_PickupBrokenItem"] = "Нельзя подбирать сломанные вещи!", ["Bot_Error_NoAmmo"] = "Нет патрон у оружия чтобы атаковать!", ["Bot_Error_NoResourcesAround"] = "Нет ресурсов поблизости!", ["Bot_Error_Chainsaw_NoFuel"] = "Нет топлива в бензопиле!", ["Bot_Error_AutoFarm_NoResourcesAroundOrNoTool"] = "Нет ресурсов поблизости либо нет инструмента чтобы добыть ресурс!", ["Bot_Error_Dead_NotOwner"] = "Вы не являетесь владельцом этого бота и не можете его залутать!", ["Bot_Error_Loot_HackableCrate"] = "Ящик еще не взломан!", ["Bot_Error_FlyAddon_NoPlayerToFollow"] = "Игрок для слежки не найден!", ["GUI_Header"] = "Управление NPC", ["GUI_Follow"] = "Следовать", ["GUI_Kill"] = "Убить",
}
, this, "ru");
lang.RegisterMessages(new Dictionary<string, string> {
["ChatCommand_Success_Despawn"]
= "Your personal bot has been successfully deleted!", ["ChatCommand_Success_Spawn"] = "Your personal bot has been successfully spawned!", ["ChatCommand_Notice_Ignore_Activated"] = "The bot now ignores those who attack it and the owner", ["ChatCommand_Notice_Ignore_D
// ... [Code preview truncated due to length. Full source in attached file] ...