Иконка ресурса

FREE TeleportGUI : 1.0.2 1.0.2

Нет прав для скачивания
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Oxide.Core.Plugins;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins {
    [Info("TeleportGUI", "Enigma", "1.0.2")]
    class TeleportGUI : RustPlugin {
        const string permUse = "teleportgui.use";
        const string permCancel = "teleportgui.tpcancel";
        const string permBack = "teleportgui.tpback";
        const string permHere = "teleportgui.tphere";
        public static TeleportGUI Instance;
        Dictionary<BasePlayer, bool> guiOpen = new Dictionary<BasePlayer, bool>();
        Dictionary<BasePlayer, Vector3> lastTeleport = new Dictionary<BasePlayer, Vector3>();
        List<GameObject> gameObjects = new List<GameObject>();
        bool debuggingMode = false;
        [PluginReference]
        Plugin Economics;
        [PluginReference]
        Plugin ServerRewards;
#region Classes
        class TeleportRequest : MonoBehaviour {
            GameObject GameObject;
            int Time;
            public BasePlayer From;
            public BasePlayer To;
            public static void Create(BasePlayer From, BasePlayer To, int TimeoutTime) {
                TeleportRequest tr = new TeleportRequest();
                tr.GameObject = new GameObject();
                tr = tr.GameObject.AddComponent<TeleportRequest>();
                tr.Time = TimeoutTime;
                tr.From = From;
                tr.To = To;
                Instance.gameObjects.Add(tr.GameObject);
            }
            void Start() {
                Instance.SendReply(From, Instance.GetMessage("RequestSent").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("RequestRecieved").Replace("{0}", From.displayName));
                PendingRequest pr = To.gameObject.AddComponent<PendingRequest>();
                pr.From = From;
                pr.TeleportRequest = this;
                InvokeRepeating("TimerTick", 0, 1.0f);
            }
            void TimerTick() {
                if (Time == 0) RequestTimeOut();
                Time--;
            }
            public void RequestAccepted() {
                int timeUntilTeleport = Instance.GetLowest(Instance.GetConfig<Dictionary<string, object>>("Время ожидания телепорта с привилегией"), From, Instance.GetConfig<int>("Время ожидания телепорта"));
                Instance.SendReply(From, Instance.GetMessage("RequestToAccepted").Replace("{0}", To.displayName).Replace("{1}", timeUntilTeleport.ToString()));
                Instance.SendReply(To, Instance.GetMessage("RequestFromAccepted").Replace("{0}", From.displayName).Replace("{1}", timeUntilTeleport.ToString()));
                int cooldown = Instance.GetLowest(Instance.GetConfig<Dictionary<string, object>>("Перезагрузка телепорта с привилегией"), From, Instance.GetConfig<int>("Перезагрузка телепорта"));
                Instance.storedData.Cooldowns.Add(From.userID, cooldown + timeUntilTeleport);
                if (Instance.GetConfig<int>("Дневной лимит телепортов") != -1) {
                    int usesRemaining = Instance.IncrementUses(From);
                    Instance.SendReply(From, Instance.GetMessage("TeleportsRemaining").Replace("{0}", usesRemaining.ToString()));
                }
                Teleporter teleporter = From.gameObject.AddComponent<Teleporter>();
                teleporter.Create(From, To, timeUntilTeleport);
                PendingRequest pr = To.gameObject.GetComponent<PendingRequest>();
                if (pr != null) GameObject.Destroy(pr);
                CancelInvoke();
                GameObject.Destroy(this.gameObject);
            }
            public void RequestDeclined() {
                Instance.SendReply(From, Instance.GetMessage("RequestToDenied").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("RequestFromDenied").Replace("{0}", From.displayName));
                if (Instance.EconomicsInstalled() && Instance.GetConfig<bool>("Использовать плагин Economics")) Instance.RefundPlayerEconomics(From);
                if (Instance.ServerRewardsInstalled() && Instance.GetConfig<bool>("Использовать плагин ServerRewards")) Instance.RefundServerRewards(From);
                PendingRequest pr = To.gameObject.GetComponent<PendingRequest>();
                if (pr != null) GameObject.Destroy(pr);
                GameObject.Destroy(this.gameObject);
            }
            public void RequestCancelled() {
                Instance.SendReply(From, Instance.GetMessage("TeleportRequestToCancelled").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("TeleportRequestFromCancelled").Replace("{0}", From.displayName));
                if (Instance.EconomicsInstalled() && Instance.GetConfig<bool>("Использовать плагин Economics")) Instance.RefundPlayerEconomics(From);
                if (Instance.ServerRewardsInstalled() && Instance.GetConfig<bool>("Использовать плагин ServerRewards")) Instance.RefundServerRewards(From);
                PendingRequest pr = To.gameObject.GetComponent<PendingRequest>();
                if (pr != null) GameObject.Destroy(pr);
                GameObject.Destroy(this.gameObject);
            }
            void RequestTimeOut() {
                Instance.SendReply(From, Instance.GetMessage("RequestToTimedOut").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("RequestFromTimedOut").Replace("{0}", From.displayName));
                if (Instance.EconomicsInstalled() && Instance.GetConfig<bool>("Использовать плагин Economics")) Instance.RefundPlayerEconomics(From);
                if (Instance.ServerRewardsInstalled() && Instance.GetConfig<bool>("Использовать плагин ServerRewards")) Instance.RefundServerRewards(From);
                PendingRequest pr = To.gameObject.GetComponent<PendingRequest>();
                if (pr != null) GameObject.Destroy(pr);
                GameObject.Destroy(this.gameObject);
            }
            void CancelRequest() {
                Instance.SendReply(From, Instance.GetMessage("BlockTPTakeDamage"));
                if (Instance.EconomicsInstalled() && Instance.GetConfig<bool>("Использовать плагин Economics")) Instance.RefundPlayerEconomics(From);
                if (Instance.ServerRewardsInstalled() && Instance.GetConfig<bool>("Использовать плагин ServerRewards")) Instance.RefundServerRewards(From);
                PendingRequest pr = To.gameObject.GetComponent<PendingRequest>();
                if (pr != null) GameObject.Destroy(pr);
                GameObject.Destroy(this.gameObject);
            }
            void OnDestroy() {
                CancelInvoke();
                Instance.gameObjects.Remove(GameObject);
            }
        }
        class PendingRequest : MonoBehaviour {
            public BasePlayer From;
            public TeleportRequest TeleportRequest;
        }
        class Teleporter : MonoBehaviour {
            GameObject GameObject;
            int TimeUntilTeleport;
            BasePlayer From;
            BasePlayer To;
            public void Create(BasePlayer from, BasePlayer to, int timeUntilTeleport) {
                this.GameObject = new GameObject();
                this.TimeUntilTeleport = timeUntilTeleport;
                this.From = from;
                this.To = to;
                Instance.gameObjects.Add(GameObject);
            }
            void Start() => InvokeRepeating("TimerTick", 0, 1.0f);
            void TimerTick() {
                if (TimeUntilTeleport == 0) Teleport();
                TimeUntilTeleport--;
            }
            void Teleport() {
                Vector3 currentPos = From.transform.position;
                Instance.RecordLastTP(From, currentPos);
                Instance.Teleport(From, To);
                Instance.SendReply(From, Instance.GetMessage("YouTeleportedTo").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("TeleportedToYou").Replace("{0}", From.displayName));
                GameObject.Destroy(this.gameObject.GetComponent<Teleporter>());
            }
            public void CancelTeleport() {
                Instance.SendReply(From, Instance.GetMessage("TeleportToCancelled").Replace("{0}", To.displayName));
                Instance.SendReply(To, Instance.GetMessage("TeleportFromCancelled").Replace("{0}", From.displayName));
                GameObject.Destroy(this.gameObject.GetComponent<Teleporter>());
            }
            void StartSleeping(BasePlayer player) {
                if (player.IsSleeping()) return;
                player.SetPlayerFlag(BasePlayer.PlayerFlags.Sleeping, true);
                if (!BasePlayer.sleepingPlayerList.Contains(player)) BasePlayer.sleepingPlayerList.Add(player);
                player.CancelInvoke("InventoryUpdate");
            }
            void OnDestory() {
                CancelInvoke();
                Instance.gameObjects.Remove(GameObject);
            }
        }
        class CooldownManager : MonoBehaviour {
            GameObject GameObject;
            public static void Create() {
                CooldownManager cm = new CooldownManager();
                cm.GameObject = new GameObject();
                cm.GameObject.AddComponent<CooldownManager>();
                Instance.gameObjects.Add(cm.GameObject);
            }
            void Start() {
                InvokeRepeating("TimerTick", 0, 1.0f);
            }
            void TimerTick() {
                if (Instance?.storedData?.Cooldowns == null) return;
                Dictionary<ulong, int> dict = new Dictionary<ulong, int>(Instance.storedData.Cooldowns);
                foreach (KeyValuePair<ulong, int> kvp in dict) {
                    Instance.storedData.Cooldowns[kvp.Key]--;
                    if (kvp.Value == 0) Instance.storedData.Cooldowns.Remove(kvp.Key);
                }
            }
            void OnDestroy() {
                Instance?.SaveData();
                CancelInvoke();
                Instance.gameObjects.Remove(GameObject);
            }
        }
        class StoredData {
            public Dictionary<ulong, int> Cooldowns = new Dictionary<ulong, int>();
            public Dictionary<ulong, int> UsesToday = new Dictionary<ulong, int>();
        }
        StoredData storedData;
#endregion
#region Oxide Hooks
        void Init() {
            //Register permissions
            permission.RegisterPermission(permUse, this);
            permission.RegisterPermission(permCancel, this);
            permission.RegisterPermission(permBack, this);
            permission.RegisterPermission(permHere, this);
            foreach (string perm in GetConfig<Dictionary<string, object>>("Перезагрузка телепорта с привилегией").Keys) permission.RegisterPermission(perm, this);
            //Register lang
            lang.RegisterMessages(new Dictionary<string, string>() {
                {
                    "NoPermission", "У Вас нет разрешения на использование этой команды"
                }
                , {
                    "TeleportTitle", "Телепорт для игрока"
                }
                , {
                    "RequestSent", "Запрос телепорта к <color=#FFA500>{0}</color> отправлен"
                }
                , {
                    "RequestRecieved", "Запрос телепорта от <color=#FFA500>{0}</color> Откройте меню, набрав <color=#FFA500>/tp</color> и примите его"
                }
                , {
                    "RequestToTimedOut", "Время вашего запроса телепорта к <color=#FFA500>{0}</color> истекло"
                }
                , {
                    "RequestFromTimedOut", "Время запроса телепорта от <color=#FFA500>{0}</color> истекло"
                }
                , {
                    "HasPendingRequest", "У <color=#FFA500>{0}</color> уже есть в ожидании запрос телепорта"
                }
                , {
                    "RequestFrom", "Запрос от <color=#FFA500>{0}</color>"
                }
                , {
                    "RequestToAccepted", "Ваш запрос телепорта к <color=#FFA500>{0}</color> принят. Телепорт через <color=#FFA500>{1}</color> сек."
                }
                , {
                    "RequestFromAccepted", "Запрос телепорта от <color=#FFA500>{0}</color> принят. Телепорт через <color=#FFA500>{1}</color> сек."
                }
                , {
                    "RequestToDenied", "Ваш запрос телепорта к <color=#FFA500>{0}</color> отклонен."
                }
                , {
                    "RequestFromDenied", "Запрос телепорта от <color=#FFA500>{0}</color> отклонен"
                }
                , {
                    "YouTeleportedTo", "Вы осуществили телепорт к <color=#FFA500>{0}</color>"
                }
                , {
                    "TeleportedToYou", "Игрок <color=#FFA500>{0}</color> осуществил телепорт к вам"
                }
                , {
                    "OnCooldown", "Телепорт на перезагрузке! Воспользуйтесь через <color=#FFA500>{0}</color> сек."
                }
                , {
                    "NoPendingRequests", "У Вас нет ожидающих запросов."
                }
                , {
                    "SyntaxTPR", "Ошибка ввода! Наберите: <color=#FFA500>/tpr {имя}</color>"
                }
                , {
                    "PlayerNotFound", "Игрок <color=#FFA500>{0}</color> не найден"
                }
                , {
                    "MultiplePlayersFound", "С именем <color=#FFA500>{0}</color> найдено несколько игроков"
                }
                , {
                    "CantTeleportToSelf", "Вы не можете осуществить телепорт к самому себе"
                }
                , {
                    "PlayerIsBuildBlocked", "Вы не можете использовать телепорт в зоне действия чужого шкафа"
                }
                , {
                    "TargetIsBuildBlocked", "Вы не можете использовать телепорт! Игрок находится в зоне действия чужого шкафа"
                }
                , {
                    "PlayerIsBleeding", "Вы не можете использовать телепорт при кровотечении"
                }
                , {
                    "CantAffordEconomics", "Вы не можете себе это позволить! Цена: <color=#FFA500>${0} coins</color>"
                }
                , {
                    "EconomicsYouSpent", "Вы потратили <color=#FFA500>${0} coins</color> на этот телепорт"
                }
                , {
                    "EconomicsRefunded", "Вам были возвращены <color=#FFA500>${0} coins</color>"
                }
                , {
                    "CantAffordServerRewards", "Вы не можете себе это позволить! Цена: <color=#FFA500>{0} RP</color>"
                }
                , {
                    "ServerRewardsYouSpent", "Вы потратили <color=#FFA500>{0} RP</color> на этот телепорт"
                }
                , {
                    "ServerRewardsRefunded", "Вам были возвращены <color=#FFA500>{0} RP</color>"
                }
                , {
                    "BlockTPCrafting", "Вы не можете использовать телепорт при крафте"
                }
                , {
                    "MaxTeleportsReached", "Вы достигли максимального количества телепортов на сегодня"
                }
                , {
                    "TeleportsRemaining", "На сегодня осталось  телепортов: <color=#FFA500>{0}</color>"
                }
                , {
                    "TeleportRequestFromCancelled", "Запрос телепорта от <color=#FFA500>{0}</color> отменен"
                }
                , {
                    "TeleportRequestToCancelled", "Запрос телепорта к <color=#FFA500>{0}</color> отменен"
                }
                , {
                    "TeleportRequestCancelled", "Запрос телепорта отменен"
                }
                , {
                    "TeleportToCancelled", "Телепорт к <color=#FFA500>{0}</color> отменен"
                }
                , {
                    "TeleportFromCancelled", "Телепорт от <color=#FFA500>{0}</color> отменен"
                }
                , {
                    "NothingToCancel", "У Вас нет заросов для отмены"
                }
                , {
                    "NoBackLocation", "У Вас нет прежнего места для возвращения"
                }
                , {
                    "TeleportedBack", "Телепорт обратно в предыдущую локацию"
                }
                , {
                    "SummonedToYou", "Вы осуществили телепорт игрока <color=#FFA500>{0}</color> к себе"
                }
                , {
                    "SummonedTo", "Вы осуществили телепорт к <color=#FFA500>{0}</color>"
                }
                , {
                    "SyntaxTPHere", "Ошибка ввода! Наберите: <color=#FFA500>/tphere {имя}</color>"
                }
                , {
                    "TPPos-InvalidSyntax", "Ошибка ввода! Наберите: <color=#FFA500>/tp {x} {y} {z}</color>"
                }
                , {
                    "TPToPos", "Телепорт на координаты: <color=#FFA500>{x}, {y}, {z}</color>"
                }
            }
            , this, "en");
            ReadData();
            foreach (string cmdAlias in GetConfig<List<object>>("Альтернативные команды")) cmd.AddChatCommand(cmdAlias, this, "tpCommand");
            timer.Once(TimeUntilMidnight(), () => ResetDailyUses());
            if (debuggingMode) BasePlayer.activePlayerList.ForEach(x => ShowTeleportUI(x));
        }
        void OnServerInitialized() {
            Instance = this;
            CooldownManager.Create();
            if (Economics == null && GetConfig<bool>("Использовать плагин Economics")) {
                Debug.LogError("[TeleportGUI] Плагин Economics не установлен! Пожалуйста установите плагин Economics или запретите его использование в файле конфигурации!");
            }
            if (ServerRewards == null && GetConfig<bool>("Использовать плагин ServerRewards")) {
                Debug.LogError("[TeleportGUI] Плагин ServerRewards не установлен! Пожалуйста установите плагин ServerRewards или запретите его использование в файле конфигурации!");
            }
        }
        void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo info) {
            if (!(entity is BasePlayer)) return;
            BasePlayer player = entity as BasePlayer;
            if (player == null) return;
            if (!HasComponent<Teleporter>(player)) return;
            if (!GetConfig<bool>("Отменить телепорт при получении урона")) return;
            var teleporter = player.gameObject.GetComponent<Teleporter>();
            teleporter.CancelTeleport();
        }
        void Unload() {
            foreach (GameObject go in gameObjects) {
                if (go == null) continue;
                if (HasComponent<Teleporter>(go) || HasComponent<PendingRequest>(go) || HasComponent<CooldownManager>(go)) GameObject.Destroy(go);
            }
            gameObjects.Clear();
            foreach (BasePlayer player in BasePlayer.activePlayerList) CloseUI(player);
            SaveData();
        }
        protected override void LoadDefaultConfig() {
            PrintWarning("Создание нового файла конфигурации...");
            Config["Разрешить префикс"] = true;
            Config["Префикс"] = "<color=orange>Телепорт: </color>";
            Config["Время ожидания телепорта"] = 10;
            Config["Время ожидания телепорта с привилегией"] = new Dictionary<string, int>() {
                {
                    "teleportgui.vip", 8
                }
                , {
                    "teleportgui.elite", 6
                }
                , {
                    "teleportgui.gold", 4
                }
                , {
                    "teleportgui.admin", 0
                }
            }
            ;
            Config["Альтернативные команды"] = new List<string>() {
                "teleport"
            }
            ;
            Config["Время ожидания ответа на запрос"] = 30;
            Config["Перезагрузка телепорта"] = 180;
            Config["Перезагрузка телепорта с привилегией"] = new Dictionary<string, int>() {
                {
                    "teleportgui.vip", 90
                }
                , {
                    "teleportgui.elite", 60
                }
                , {
                    "teleportgui.gold", 30
                }
                , {
                    "teleportgui.admin", 0
                }
            }
            ;
            Config["Дневной лимит телепортов"] = 25;
            Config["Дневной лимит телепортов с привилегией"] = new Dictionary<string, int>() {
                {
                    "teleportgui.vip", 50
                }
                , {
                    "teleportgui.elite", 70
                }
                , {
                    "teleportgui.gold", 90
                }
                , {
                    "teleportgui.admin", 9999
                }
            }
            ;
            Config["Тихий телепорт у админа"] = true;
            Config["Разрешить телепорт админу"] = true;
            Config["Разрешить специальные символы"] = false;
            Config["Разрешить телепорт при крафте"] = false;
            Config["Разрешить телепорт при кровотечении"] = false;
            Config["Разрешить телепорт в зону блока строительства"] = false;
            Config["Разрешить телепорт из зоны блока строительства"] = false;
            Config["Отменить телепорт при получении урона"] = true;
            Config["Использовать плагин Economics"] = false;
            Config["Цена с Economics"] = 10;
            Config["Использовать плагин ServerRewards"] = false;
            Config["Цена с ServerRewards"] = 1;
        }
#endregion
#region Commands
        [ChatCommand("tp")]
        void TPCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            if (player.IsAdmin) {
                if (args.Length < 3) {
                    SendReply(player, GetMessage("TPPos-InvalidSyntax"));
                    return;
                }
                float x, y, z;
                if (!float.TryParse(args[0], out x) || !float.TryParse(args[1], out y) || !float.TryParse(args[2], out z)) {
                    SendReply(player, GetMessage("TPPos-InvalidSyntax"));
                    return;
                }
                Teleport(player, new Vector3(x, y, z));
                SendReply(player, GetMessage("TPToPos") .Replace("{x}", x.ToString("N1")) .Replace("{y}", y.ToString("N1")) .Replace("{z}", z.ToString("N1")));
                return;
            }
            ShowTeleportUI(player);
        }
        [ChatCommand("tpr")]
        void TPRCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            if (args.Length < 1) {
                SendReply(player, GetMessage("SyntaxTPR"));
                return;
            }
            string name = args[0];
            for (int i = 1; i < args.Length; i++) name += " " + args[i];
            List<BasePlayer> matches = FindByNameMulti(name);
            if (matches.Count() == 0) {
                SendReply(player, GetMessage("PlayerNotFound").Replace("{0}", name));
                return;
            }
            else if (matches.Count() > 1) {
                SendReply(player, GetMessage("MultiplePlayersFound").Replace("{0}", name));
                return;
            }
            BasePlayer targetPlayer = matches.First();
            if (targetPlayer == player && !debuggingMode) {
                SendReply(player, GetMessage("CantTeleportToSelf"));
                return;
            }
            TPR(player, targetPlayer);
            return;
        }
        [ChatCommand("tpa")]
        void TPACommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            TeleportRequest tr = player.gameObject.GetComponent<PendingRequest>()?.TeleportRequest;
            if (tr == null) {
                SendReply(player, GetMessage("NoPendingRequests"));
                return;
            }
            tr.RequestAccepted();
            CloseUI(player);
        }
        [ChatCommand("tpd")]
        void TPDCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            TeleportRequest tr = player.gameObject.GetComponent<PendingRequest>()?.TeleportRequest;
            if (tr == null) {
                SendReply(player, GetMessage("NoPendingRequests"));
                return;
            }
            tr.RequestDeclined();
            CloseUI(player);
        }
        [ChatCommand("tpc")]
        void TPCCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player, permCancel)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            TPC(player);
        }
        [ChatCommand("tpb")]
        void TPBCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player, permBack)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            TPB(player);
        }
        [ChatCommand("tphere")]
        void TPHereCommand(BasePlayer player, string command, string[] args) {
            if (!HasPerm(player, permHere)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            if (args.Length < 1) {
                SendReply(player, GetMessage("SyntaxTPHere"));
                return;
            }
            TPHere(player, args[0]);
        }
        [ConsoleCommand("tpgui")]
        void TPGuiCommand(ConsoleSystem.Arg arg) {
            if (arg.Player() == null) return;
            BasePlayer player = arg.Player();
            string[] args = arg.Args ?? new string[] {
            }
            ;
            if (!HasPerm(player)) {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }
            if (args.Length == 0) {
                ShowTeleportUI(player);
                return;
            }
            if (args[0] == "True")  //Because apparently bind b tpgui runs "tpgui True" -.-
            {
                ShowTeleportUI(player);
                return;
            }
            if (args[0] == "page") {
                if (args.Length < 2) return;
                int page;
                if (!Int32.TryParse(args[1], out page)) return;
                bool here = false;
                if (args.Length == 3) here = args[2] == bool.TrueString;
                BigUI(player, page, here);
                return;
            }
            if (args[0] == "close") {
                CloseUI(player);
                return;
            }
            if (args[0] == "to") {
                if (args.Length < 2) return;
                CloseUI(player);
                string name = args[1];
                for (int i = 2; i < args.Length; i++) name += " " + args[i];
                BasePlayer targetPlayer = FindByName(name);
                if (targetPlayer == null) {
                    SendReply(player, GetMessage("PlayerNotFound").Replace("{0}", name));
                    return;
                }
                TPR(player, targetPlayer);
                return;
            }
            if (args[0] == "accept") {
                TeleportRequest tr = player.gameObject.GetComponent<PendingRequest>().TeleportRequest;
                tr.RequestAccepted();
                CloseUI(player);
                return;
            }
            if (args[0] == "decline") {
                TeleportRequest tr = player.gameObject.GetComponent<PendingRequest>().TeleportRequest;
                tr.RequestDeclined();
                CloseUI(player);
                return;
            }
            if (args[0] == "back") {
                if (!HasPerm(player, permBack)) {
                    SendReply(player, GetMessage("NoPermission"));
                    return;
                }
                TPB(player);
                CloseUI(player);
            }
            if (args[0] == "cancel") {
                if (!HasPerm(player, permCancel)) {
                    SendReply(player, GetMessage("NoPermission"));
                    return;
                }
                TPC(player);
                CloseUI(player);
            }
            if (args[0] == "heretoggle") {
                if (!HasPerm(player, permHere)) {
                    SendReply(player, GetMessage("NoPermission"));
                    return;
                }
                if (args.Length < 2) return;
                bool here = args[1] == bool.TrueString;
                UIChooser(player, here);
            }
            if (args[0] == "heretp") {
                if (!HasPerm(player, permHere)) {
                    SendReply(player, GetMessage("NoPermission"));
                    return;
                }
                if (args.Length < 2) return;
                TPHere(player, args[1]);
            }
        }
        [ConsoleCommand("resetdatafile")]
        void ResetAllCommand(ConsoleSystem.Arg arg) {
            if (arg.Player() != null) return;
            if (!debuggingMode) {
                Debug.LogError("[TeleportGUI]  Предупреждение: Вы не можете использовать эту команду, она непроверена и возможно опасна! Пожалуйста, не игнорируйте это предупреждение!");
                return;
            }
            storedData.Cooldowns.Clear();
            storedData.UsesToday.Clear();
            SaveData();
            Puts("Очистка и сохранение файла дата...");
        }
#endregion
#region TeleportGUI
        void ShowTeleportUI(BasePlayer player) {
            if (!guiOpen.ContainsKey(player)) guiOpen.Add(player, false);
            if (guiOpen[player]) {
                CloseUI(player);
                guiOpen[player] = false;
                return;
            }
            guiOpen[player] = true;
            UIChooser(player);
        }
        void UIChooser(BasePlayer player, bool tpHere = false) {
            if (BasePlayer.activePlayerList.Count() < 25) SmallUI(player, tpHere);
            else BigUI(player, 1, tpHere);
        }
        void CloseUI(BasePlayer player) {
            if (!guiOpen.ContainsKey(player)) guiOpen.Add(player, false);
            guiOpen[player] = false;
            CuiHelper.DestroyUi(player, "smallTeleportGUI");
            CuiHelper.DestroyUi(player, "bigTeleportGUI");
        }
        void SmallUI(BasePlayer player, bool tpHere = false) {
            var GUIElement = new CuiElementContainer();
            List<BasePlayer> players = new List<BasePlayer>(BasePlayer.activePlayerList);
            if (!debuggingMode) players.Remove(player);
            //if (debuggingMode) players.AddRange(SpareNames());
            players = players.OrderBy(x => x.displayName).ToList();
            var smallTeleportGUI = GUIElement.Add(new CuiPanel {
                Image = {
                    Color = "0 0 0 0.75"
                }
                , RectTransform = {
                    AnchorMin = "0.3 0.3",  //Left Bottom
                    AnchorMax = "0.7 0.75"  // Right Top
                }
                , CursorEnabled = true
            }
            , "Hud", "smallTeleportGUI");
            var titleBar = GUIElement.Add(new CuiPanel {
                Image = {
                    Color = "0 0 0 0.75"
                }
                , RectTransform = {
                    AnchorMin = "0 0.9",  //Left Bottom
                    AnchorMax = "0.998 0.999"  // Right Top
                }
            }
            , smallTeleportGUI);
            bool pendingRequest = (player.gameObject.GetComponent<PendingRequest>() != null);
            string requestFrom = player.gameObject.GetComponent<PendingRequest>()?.From.displayName;
            if (pendingRequest) {
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0 0", AnchorMax = "0.12 0.96"
                    }
                    , Button = {
                        Command = "tpgui accept", Color = "0 1 0 1",
                    }
                    , Text = {
                        Text = "Accept", FontSize = 18, Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                }
                , titleBar);
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0.122 0", AnchorMax = "0.24 0.96"
                    }
                    , Button = {
                        Command = "tpgui decline", Color = "1 0 0 1",
                    }
                    , Text = {
                        Text = "Decline", FontSize = 18, Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                }
                , titleBar);
                GUIElement.Add(new CuiLabel {
                    Text = {
                        Text = lang.GetMessage("RequestFrom", this).Replace("{0}", requestFrom), FontSize = 16, Align = TextAnchor.MiddleLeft
                    }
                    , RectTransform = {
                        AnchorMin = "0.26 0", AnchorMax = "1 1"
                    }
                }
                , titleBar);
            }
            if (!pendingRequest) {
                GUIElement.Add(new CuiLabel {
                    Text = {
                        Text = lang.GetMessage("TeleportTitle", this), FontSize = 20, Align = TextAnchor.MiddleCenter
                    }
                    , RectTransform = {
                        AnchorMin = "0 0", AnchorMax = "1 1"
                    }
                }
                , titleBar);
            }
            if (HasPerm(player, permHere)) {
                string colour = (tpHere) ? "0 1 0 1" : "0.5 0.5 0.5 1";
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0.68 0", AnchorMax = "0.76 0.97"
                    }
                    , Text = {
                        Text = "Сюда", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                    , Button = {
                        Command = $"tpgui heretoggle {!tpHere}", Color = colour
                    }
                }
                , titleBar);
            }
            if (HasPerm(player, permBack)) {
                if (lastTeleport.ContainsKey(player)) {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.76 0", AnchorMax = "0.84 0.97"
                        }
                        , Text = {
                            Text = "Назад", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "tpgui back", Color = "0.15 0.15 1 1"
                        }
                    }
                    , titleBar);
                }
                else {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.76 0", AnchorMax = "0.84 0.97"
                        }
                        , Text = {
                            Text = "Назад", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "", Color = "0.5 0.5 0.5 1"
                        }
                    }
                    , titleBar);
                }
            }
            if (HasPerm(player, permCancel)) {
                if (HasPendingTeleport(player)) {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.84 0", AnchorMax = "0.934 0.97"
                        }
                        , Text = {
                            Text = "Отмена", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "tpgui cancel", Color = "1 0.5 0 1"
                        }
                    }
                    , titleBar);
                }
                else {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.84 0", AnchorMax = "0.934 0.97"
                        }
                        , Text = {
                            Text = "Отмена", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "", Color = "0.5 0.5 0.5 1"
                        }
                    }
                    , titleBar);
                }
            }
            GUIElement.Add(new CuiButton {
                RectTransform = {
                    AnchorMin = "0.935 0", AnchorMax = "0.998 0.97"
                }
                , Button = {
                    Command = "tpgui close", Color = "1 0 0 1"
                }
                , Text = {
                    Text = "X", FontSize = 20, Align = TextAnchor.MiddleCenter, Color = "1 1 1 1"
                }
            }
            , titleBar);
            var playerList = GUIElement.Add(new CuiPanel {
                Image = {
                    Color = "0 0 0 0"
                }
                , RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 0.9"
                }
            }
            , smallTeleportGUI);
            const float columnWidth = 0.2f;
            const float rowWidth = 0.2f;
            int playerCount = 0;
            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < 5; j++) {
                    if (players.ToArray().Length <= playerCount) continue;
                    var panel = GUIElement.Add(new CuiPanel {
                        RectTransform = {
                            AnchorMin = (columnWidth * j).ToString() + " " + (1f - (rowWidth * i) - rowWidth).ToString(), AnchorMax = ((columnWidth * j) + columnWidth).ToString() + " " + (1f - (rowWidth * i)).ToString()
                        }
                        , Image = {
                            Color = "0 0 0 0"
                        }
                    }
                    , playerList);
                    string playerName = players.ToArray()[playerCount].displayName;
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0 0", AnchorMax = "1 1"
                        }
                        , Text = {
                            Text = CleanText(playerName), Align = TextAnchor.MiddleCenter, FontSize = 18, Color = "1 1 1 1", Font = "robotocondensed-regular.ttf"
                        }
                        , Button = {
                            Command = $"tpgui to {playerName}", Color = "0 0 0 0"
                        }
                    }
                    , panel);
                    if (tpHere) {
                        GUIElement.Add(new CuiButton {
                            RectTransform = {
                                AnchorMin = "0.7 0.005", AnchorMax = "0.97 0.2"
                            }
                            , Text = {
                                Text = "Сюда", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter, FontSize = 12
                            }
                            , Button = {
                                Command = $"tpgui heretp {playerName}", Color = "0 1 0 0.5"
                            }
                        }
                        , panel);
                    }
                    playerCount++;
                }
            }
            if (players.Count() == 0) {
                GUIElement.Add(new CuiLabel {
                    Text = {
                        Text = "Скорее всего Вы единственный выживший!", FontSize = 20, Align = TextAnchor.MiddleCenter
                    }
                    , RectTransform = {
                        AnchorMin = "0 0.1", AnchorMax = "1 1"
                    }
                }
                , playerList);
            }
            CuiHelper.DestroyUi(player, "smallTeleportGUI");
            CuiHelper.AddUi(player, GUIElement);
        }
        void BigUI(BasePlayer player, int page = 1, bool tpHere = false) {
            var GUIElement = new CuiElementContainer();
            List<BasePlayer> players = new List<BasePlayer>(BasePlayer.activePlayerList);
            if (!debuggingMode) players.Remove(player);
            //if (debuggingMode) players.AddRange(SpareNames());
            players = players.OrderBy(x => x.displayName).ToList();
            int maxPages = CalculatePages(players.Count);
            var bigTeleportGUI = GUIElement.Add(new CuiPanel {
                Image = {
                    Color = "0 0 0 0.75"
                }
                , RectTransform = {
                    AnchorMin = "0.2 0.125",  //Left Bottom
                    AnchorMax = "0.8 0.9"  // Right Top
                }
                , CursorEnabled = true
            }
            , "Hud", "bigTeleportGUI");
            var titleBar = GUIElement.Add(new CuiPanel {
                Image = {
                    Color = "0 0 0 0.75"
                }
                , RectTransform = {
                    AnchorMin = "0 0.91",  //Left Bottom
                    AnchorMax = "0.997 1.0"  // Right Top
                }
            }
            , bigTeleportGUI);
            bool pendingRequest = (player.gameObject.GetComponent<PendingRequest>() != null);
            string requestFrom = player.gameObject.GetComponent<PendingRequest>()?.From.displayName;
            if (pendingRequest) {
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0 0.01", AnchorMax = "0.16 0.98"
                    }
                    , Button = {
                        Command = "tpgui accept", Color = "0 1 0 1",
                    }
                    , Text = {
                        Text = "Accept", FontSize = 18, Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                }
                , titleBar);
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0.1615 0.01", AnchorMax = "0.32 0.98"
                    }
                    , Button = {
                        Command = "tpgui decline", Color = "1 0 0 1",
                    }
                    , Text = {
                        Text = "Decline", FontSize = 18, Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                }
                , titleBar);
                GUIElement.Add(new CuiLabel {
                    Text = {
                        Text = lang.GetMessage("RequestFrom", this).Replace("{0}", requestFrom), FontSize = 18, Align = TextAnchor.MiddleLeft
                    }
                    , RectTransform = {
                        AnchorMin = "0.34 0", AnchorMax = "1 1"
                    }
                }
                , titleBar);
            }
            if (!pendingRequest) {
                string pageNum = (maxPages > 1) ? $" - {page.ToString()}" : "";
                GUIElement.Add(new CuiLabel {
                    Text = {
                        Text = lang.GetMessage("TeleportTitle", this) + pageNum, FontSize = 20, Align = TextAnchor.MiddleCenter
                    }
                    , RectTransform = {
                        AnchorMin = "0 0", AnchorMax = "1 1"
                    }
                }
                , titleBar);
            }
            if (HasPerm(player, permHere)) {
                string colour = (tpHere) ? "0 1 0 1" : "0.5 0.5 0.5 1";
                GUIElement.Add(new CuiButton {
                    RectTransform = {
                        AnchorMin = "0.70 0", AnchorMax = "0.78 0.97"
                    }
                    , Text = {
                        Text = "Here", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                    }
                    , Button = {
                        Command = $"tpgui page {page} {!tpHere}", Color = colour
                    }
                }
                , titleBar);
            }
            if (HasPerm(player, permBack)) {
                if (lastTeleport.ContainsKey(player)) {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.78 0", AnchorMax = "0.86 0.97"
                        }
                        , Text = {
                            Text = "Back", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "tpgui back", Color = "0.15 0.15 1 1"
                        }
                    }
                    , titleBar);
                }
                else {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.78 0", AnchorMax = "0.86 0.97"
                        }
                        , Text = {
                            Text = "Back", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter
                        }
                        , Button = {
                            Command = "", Color = "0.5 0.5 0.5 1"
                        }
                    }
                    , titleBar);
                }
            }
            if (HasPerm(player, permCancel)) {
                if (HasPendingTeleport(player)) {
                    GUIElement.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0.86 0", AnchorMax = "0.9385 0.98"
                        }
                        , Text = {
                            Text = "Cancel", Color = "1 1 1 1", Align = TextAnchor.MiddleCenter, FontSize = 16
                        }
                        , Button = {
                            Command = "tpgui cancel", Color = "1 0.5 0 1"
                        }
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху