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

FREE HomesGUI : 1.0.2 1.0.2

Нет прав для скачивания
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Oxide.Game.Rust.Cui;
using Oxide.Core;
using Oxide.Core.Plugins;

namespace Oxide.Plugins
{
    [Info("HomesGUI", "Enigma", "1.0.2")]

    class HomesGUI : RustPlugin
    {
        static HomesGUI Instance;
        const string permUse = "homesgui.use";
        Dictionary<BasePlayer, bool> guiOpen = new Dictionary<BasePlayer, bool>();
        GameObject cmObject;

        [PluginReference]
        Plugin Economics;
        [PluginReference]
        Plugin ServerRewards;

        #region Classes

        class GamePos
        {
            public float x;
            public float y;
            public float z;

            public GamePos(float x, float y, float z)
            {
                this.x = x;
                this.y = y;
                this.z = z;
            }

            public static explicit operator GamePos(Vector3 v) => new GamePos(v.x, v.y, v.z);

            public Vector3 ToVector() => new Vector3(x, y, z);
        }

        class HomeTeleporter : MonoBehaviour
        {
            BasePlayer player { get { return GetComponentInParent<BasePlayer>(); } }
            int timeUntilTeleport;
            public Vector3 pos;
            public string homeName;

            public void Go()
            {
                Instance.SendReply(player, Instance.GetMessage("TeleportingTo").Replace("{0}", homeName).Replace("{1}", timeUntilTeleport.ToString()));
                InvokeRepeating("TimerTick", 0, 1.0f);
            }

            void Awake()
            {
                name = "HomeTeleporter";
                timeUntilTeleport = Instance.GetConfig<int>("Время ожидания телепорта");
            }

            void TimerTick()
            {
                if (timeUntilTeleport == 0)
                {
                    Teleport();
                    GameObject.Destroy(this);
                }
                timeUntilTeleport--;
            }

            public void CancelTeleport()
            {
                if (Instance.EconomicsInstalled() && Instance.GetConfig<bool>("Использовать плагин Economics"))
                    Instance.RefundPlayerEconomics(player);
                if (Instance.ServerRewardsInstalled() && Instance.GetConfig<bool>("Использовать плагин ServerRewards"))
                    Instance.RefundServerRewards(player);
                GameObject.Destroy(this);
            }

            void Teleport()
            {
                Instance.Teleport(player, pos);
                Instance.SendReply(player, Instance.GetMessage("TeleportedTo").Replace("{0}", homeName));

                Instance.AssignCooldown(player);
            }
        }

        class CooldownManager : MonoBehaviour
        {
            void Awake()
            {
                name = "CooldownManager";
                InvokeRepeating("TimerTick", 0, 1.0f);
            }

            void TimerTick()
            {
                foreach (var kvp in new Dictionary<ulong, int>(Instance.storedData.cooldowns))
                {
                    Instance.storedData.cooldowns[kvp.Key]--;
                    if (kvp.Value == 0)
                        Instance.storedData.cooldowns.Remove(kvp.Key);
                }
            }
        }

        class StoredData
        {
            public Dictionary<ulong, Dictionary<string, GamePos>> homes = new Dictionary<ulong, Dictionary<string, GamePos>>();
            public Dictionary<ulong, int> cooldowns = new Dictionary<ulong, int>();
        }
        StoredData storedData;

        #endregion

        #region Oxide Hooks

        void Init()
        {
            //Register permissions
            permission.RegisterPermission(permUse, this);
            foreach (string perm in GetConfig<Dictionary<string, object>>("Перезагрузка телепорта с привилегией").Keys)
                if (!permission.PermissionExists(perm))
                    permission.RegisterPermission(perm, this);
            foreach (string perm in GetConfig<Dictionary<string, object>>("Количество домов с привилегией").Keys)
                if (!permission.PermissionExists(perm))
                    permission.RegisterPermission(perm, this);

            //Register lang
			lang.RegisterMessages(new Dictionary<string, string>()
            {
                { "NoPermission", "У Вас нет разрешения на использование этой команды" },
                { "HomesTitle", "Телепорт домой" },
                { "SetHome-Usage", "Ошибка ввода! Наберите <color=#FFA500>/sethome {имя}</color>" },
                { "HomeAlreadyExists", "У Вас уже есть дом с названием <color=#FFA500>{0}</color>" },
                { "HomeCreated", "Дом <color=#FFA500>{0}</color> установлен" },
                { "DelHome-Usage", "Ошибка ввода! Наберите: <color=#FFA500>/delhome {имя}</color>" },
                { "HomeDoesntExist", "Дом <color=#FFA500>{0}</color> не существует" },
                { "HomeDeleted", "Дом <color=#FFA500>{0}</color> удален" },
                { "HomeInBuildBlock", "Вы не можете установить дом в зоне действия чужого шкафа!" },
                { "NoHomesSet", "У Вас нет сохраненных домов." },
                { "HomesList", "{0}" },
                { "TeleportingTo", "Телепорт в Ваш дом <color=#FFA500>{0}</color> через <color=#FFA500>{1}</color> сек." },
                { "TeleportedTo", "Вы осуществили телепорт в Ваш дом <color=#FFA500>{0}</color>" },
                { "HomeLimitedReached", "Вы достигли лимита сохраняемых домов!" },
                { "TeleportWhilstBuildBlock", "Вы не можете использовать телепорт в зоне действия чужого шкафа" },
                { "TeleportWhilstBleeding", "Вы не можете использовать телепорт при кровотечении" },
                { "TeleportWhilstCrafting", "Вы не можете использовать телепорт при крафте" },
                { "OnCooldown", "Телепорт на перезагрузке! Воспользуйтесь через <color=#FFA500>{0}</color> сек." },
                { "YouTookDamage", "Телепорт отменен так как Вы получили урон" },
                { "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>" },
                { "MustBeOnFoundation", "Вы должны быть на фундаменте чтобы установить дом" },
                { "MustBeOnFoundationOrFloor", "Вы должны быть на фундаменте или этаже чтобы установить дом." },
                { "HomeBuildBlockDestroyed", "Здание, на котором был установлен ваш дом, разрушено" }
            }, this);

            //Register command alises
            foreach (string cmdAlias in GetConfig<List<object>>("Альтернативные команды"))
                cmd.AddChatCommand(cmdAlias, this, "homeCommand");
        }

        void OnServerInitialized()
        {
            Instance = this;

            ReadData();

            cmObject = new GameObject();
            cmObject.AddComponent<CooldownManager>();

            if (Economics == null && GetConfig<bool>("Использовать плагин Economics"))
            {
                Debug.LogError("[HomesGUI] Плагин Economics не установлен! Пожалуйста установите плагин Economics или запретите его использование в файле конфигурации!");
            }

            if (ServerRewards == null && GetConfig<bool>("Использовать плагин ServerRewards"))
            {
                Debug.LogError("[HomesGUI] Плагин ServerRewards не установлен! Пожалуйста установите плагин ServerRewards или запретите его использование в файле конфигурации!");
            }
        }

        void OnPlayerInit(BasePlayer player)
        {
            if (GetConfig<bool>("Использовать бинды"))
                player.SendConsoleCommand($"bind {GetConfig<string>("Клавиша бинда")} homegui");
        }

        void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo info)
        {
            if (!(entity is BasePlayer)) return;
            BasePlayer player = entity as BasePlayer;

            if (HasComponent<HomeTeleporter>(player))
            {
                player.GetComponent<HomeTeleporter>().CancelTeleport();
                SendReply(player, GetMessage("YouTookDamage"));
            }
        }

        void Unload()
        {
            foreach (BasePlayer player in BasePlayer.activePlayerList)
                HideUI(player);

            SaveData();

            GameObject.Destroy(cmObject);
        }

        protected override void LoadDefaultConfig()
        {
            PrintWarning("Создание нового файла конфигурации...");

            Config["Разрешить префикс"] = true;
            Config["Префикс"] = "<color=orange>Телепорт: </color>";
            Config["Время ожидания телепорта"] = 10;
            Config["Альтернативные команды"] = new List<string>() { };
            Config["Перезагрузка телепорта"] = 180;
            Config["Перезагрузка телепорта с привилегией"] = new Dictionary<string, int>()
            {
                { "homesgui.vip", 90 },
                { "homesgui.elite", 60 },
                { "homesgui.gold", 30 },
                { "homesgui.admin", 0 }
            };
            Config["Количество домов"] = 2;
            Config["Количество домов с привилегией"] = new Dictionary<string, int>()
            {
                { "homesgui.vip", 4 },
                { "homesgui.elite", 6 },
                { "homesgui.gold", 8 },
                { "homesgui.admin", 0 }
            };
            Config["Использовать бинды"] = false;
            Config["Клавиша бинда"] = "h";
            Config["Разрешить телепорт при крафте"] = false;			
            Config["Разрешить телепорт при кровотечении"] = false;
            Config["Разрешить телепорт из блока строительства"] = false;
            Config["Использовать плагин Economics"] = false;
            Config["Цена с Economics"] = 10;
            Config["Использовать плагин ServerRewards"] = false;
            Config["Цена с ServerRewards"] = 1;
            Config["Быстрый телепорт у админа"] = false;
            Config["Установить дом на этаже"] = false;
            Config["Установить дом на фундаменте"] = true;
            Config["Установить дом в блоке строительства"] = false;
            Config["Проверить здание на наличие точек ТП"] = true;
        }

        #endregion

        #region Commands

        [ChatCommand("home")]
        void homeCommand(BasePlayer player, string command, string[] args)
        {
            if (!HasPerm(player))
            {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }

            if (args.Length > 0)
            {
                if (!storedData.homes.ContainsKey(player.userID))
                    storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

                if (!storedData.homes[player.userID].ContainsKey(args[0]))
                {
                    SendReply(player, GetMessage("HomeDoesntExist").Replace("{0}", args[0]));
                    return;
                }

                Vector3 pos = storedData.homes[player.userID][args[0]].ToVector();

                object canTP = AllowedToTeleport(player, pos);
                if (canTP is string)
                {
                    SendReply(player, canTP.ToString());
                    return;
                }

                HomeTeleporter ht = player.gameObject.AddComponent<HomeTeleporter>();
                ht.pos = pos;
                ht.homeName = args[0];//Do time until teleport
                ht.Go();
                return;
            }

            ShowHomesUI(player);
        }

        [ChatCommand("sethome")]
        void setHomeCommand(BasePlayer player, string command, string[] args)
        {
            if (!HasPerm(player))
            {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }

            if (args.Length < 1)
            {
                SendReply(player, GetMessage("SetHome-Usage"));
                return;
            }

            if (!storedData.homes.ContainsKey(player.userID))
                storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

            if (storedData.homes[player.userID].ContainsKey(args[0]))
            {
                SendReply(player, GetMessage("HomeAlreadyExists").Replace("{0}", args[0]));
                return;
            }

            if (!CheckMaxHomes(player))
            {
                SendReply(player, GetMessage("HomeLimitedReached"));
                return;
            }

            if (!GetConfig<bool>("Установить дом в блоке строительства") && !player.CanBuild())
            {
                SendReply(player, GetMessage("HomeInBuildBlock"));
                return;
            }

            if (GetConfig<bool>("Установить дом на фундаменте"))
            {
                if (!GetConfig<bool>("Установить дом на этаже"))
                {
                    if (!CheckFoundation(player.transform.position))
                    {
                        SendReply(player, GetMessage("MustBeOnFoundation"));
                        return;
                    }
                }
                else
                {
                    if (!CheckFoundation(player.transform.position) && !CheckFloor(player.transform.position))
                    {
                        SendReply(player, GetMessage("MustBeOnFoundationOrFloor"));
                        return;
                    }
                }
            }

            storedData.homes[player.userID].Add(args[0], (GamePos)player.transform.position);
            SaveData();
            SendReply(player, GetMessage("HomeCreated").Replace("{0}", args[0]));
        }

        [ChatCommand("delhome")]
        void delHomeCommand(BasePlayer player, string command, string[] args)
        {
            if (!HasPerm(player))
            {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }

            if (args.Length < 1)
            {
                SendReply(player, GetMessage("DelHome-Usage"));
                return;
            }

            if (!storedData.homes.ContainsKey(player.userID))
                storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

            if (!storedData.homes[player.userID].ContainsKey(args[0]))
            {
                SendReply(player, GetMessage("HomeDoesntExist").Replace("{0}", args[0]));
                return;
            }

            storedData.homes[player.userID].Remove(args[0]);
            SaveData();
            SendReply(player, GetMessage("HomeDeleted").Replace("{0}", args[0]));
        }

        [ChatCommand("listhomes")]
        void listHomesCommand(BasePlayer player, string command, string[] args)
        {
            if (!HasPerm(player))
            {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }

            if (!storedData.homes.ContainsKey(player.userID))
                storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

            if (storedData.homes[player.userID].Count() == 0)
            {
                SendReply(player, GetMessage("NoHomesSet"));
                return;
            }

            string homes = string.Join(", ", storedData.homes[player.userID].Keys.ToArray());
            SendReply(player, GetMessage("HomesList").Replace("{0}", homes));
        }

        [ConsoleCommand("homegui")]
        void homeGUICommand(ConsoleSystem.Arg arg)
        {
            if (arg.Player() == null) return;
            BasePlayer player = arg.Player();

            string[] args = (arg.Args == null) ? new string[] { } : arg.Args;

            if (!HasPerm(player))
            {
                SendReply(player, GetMessage("NoPermission"));
                return;
            }

            if (args.Length == 0)
            {
                ShowHomesUI(player);
                return;
            }			

            if (args[0] == "True")
            {
                ShowHomesUI(player);
                return;
            }

            if (args[0] == "close")
            {
                ShowHomesUI(player);
                return;
            }

            if (args[0] == "to")
            {
                if (!storedData.homes.ContainsKey(player.userID))
                    storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

                if (!storedData.homes[player.userID].ContainsKey(args[1]))
                {
                    SendReply(player, GetMessage("HomeDoesntExist").Replace("{0}", args[1]));
                    return;
                }

                Vector3 pos = storedData.homes[player.userID][args[1]].ToVector();

                object canTP = AllowedToTeleport(player, pos);
                if (canTP is string)
                {
                    SendReply(player, canTP.ToString());
                    ShowHomesUI(player);
                    return;
                }

                if (GetConfig<bool>("Быстрый телепорт у Админа") && player.IsAdmin)
                {
                    ShowHomesUI(player);
                    SendReply(player, GetMessage("TeleportedTo").Replace("{0}", args[1]));
                    Teleport(player, pos);
                    return;
                }
                else
                {
                    ShowHomesUI(player);
                    HomeTeleporter ht = player.gameObject.AddComponent<HomeTeleporter>();
                    ht.pos = storedData.homes[player.userID][args[1]].ToVector();
                    ht.homeName = args[1];
                    ht.Go();
                }
                return;
            }
        }

        #endregion

        #region HomesGUI

        void ShowHomesUI(BasePlayer player)
        {
            if (!guiOpen.ContainsKey(player))
                guiOpen.Add(player, false);

            if (!guiOpen[player])
            {
                ShowUI(player);
                guiOpen[player] = true;
                return;
            }

            if (guiOpen[player])
            {
                HideUI(player);
                guiOpen[player] = false;
                return;
            }
        }

        void ShowUI(BasePlayer player)
        {
            var GUIElement = new CuiElementContainer();

            var wholePanel = GUIElement.Add(new CuiPanel
            {
                RectTransform =
                {
                    AnchorMin = "0.3 0.3",
                    AnchorMax = "0.7 0.75"
                },
                Image =
                {
                    Color = "0 0 0 0.75"
                },
                CursorEnabled = true
            }, "Hud", "homesGUI");

            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
                }
            }, wholePanel);

            GUIElement.Add(new CuiLabel
            {
                Text =
                {
                    Text = lang.GetMessage("HomesTitle", this),
                    FontSize = 20,
                    Align = TextAnchor.MiddleCenter
                },
                RectTransform =
                {
                    AnchorMin = "0 0",
                    AnchorMax = "1 1"
                }
            }, titleBar);

            GUIElement.Add(new CuiButton
            {
                RectTransform =
                {
                    AnchorMin = "0.935 0",
                    AnchorMax = "0.998 0.97"
                },
                Button =
                {
                    Command = "homegui close",
                    Color = "1 0 0 1"
                },
                Text =
                {
                    Text = "X",
                    FontSize = 20,
                    Align = TextAnchor.MiddleCenter,
                    Color = "1 1 1 1"
                }
            }, titleBar);

            var homesList = GUIElement.Add(new CuiPanel
            {
                Image =
                {
                    Color = "0 0 0 0"
                },
                RectTransform =
                {
                    AnchorMin = "0 0",
                    AnchorMax = "1 0.9"
                }
            }, wholePanel);

            const float columnWidth = 0.2f;
            const float rowWidth = 0.2f;

            int homeCount = 0;
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    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"
                        }
                    }, homesList);

                    string homeName = "";
                    if (storedData.homes.ContainsKey(player.userID))
                    {
                        if (storedData.homes[player.userID].Count() > homeCount)
                        {
                            var items = from pair in storedData.homes[player.userID]
                                        orderby pair.Key ascending
                                        select pair;
                            homeName = items.ToArray()[homeCount].Key;
                        }
                    }
                    GUIElement.Add(new CuiButton
                    {
                        RectTransform =
                        {
                            AnchorMin = "0 0",
                            AnchorMax = "1 1"
                        },
                        Text =
                        {
                            Text = homeName,
                            Align = TextAnchor.MiddleCenter,
                            FontSize = 18,
                            Color = "1 1 1 1",
                            Font = "robotocondensed-regular.ttf"
                        },
                        Button =
                        {
                            Command = $"homegui to {homeName}",
                            Color = "0 0 0 0"
                        }
                    }, panel);
                    homeCount++;
                }
            }

            int count = 0;
            if (storedData.homes.ContainsKey(player.userID))
                count = storedData.homes[player.userID].Count();
            if (count == 0)
            {
                GUIElement.Add(new CuiLabel
                {
                    Text =
                    {
                        Text = lang.GetMessage("NoHomesSet", this),
                        FontSize = 20,
                        Align = TextAnchor.MiddleCenter
                    },
                    RectTransform =
                    {
                        AnchorMin = "0 0.1",
                        AnchorMax = "1 1"
                    }
                }, homesList);
            }

            CuiHelper.AddUi(player, GUIElement);
        }

        void HideUI(BasePlayer player)
        {
            CuiHelper.DestroyUi(player, "homesGUI");
        }

        #endregion

        #region Custom Functions

        bool CheckFoundation(Vector3 homePos) => FindBuildBlock(homePos, "foundation") || FindBuildBlock(homePos, "foundation.triangle");

        bool CheckFloor(Vector3 homePos) => FindBuildBlock(homePos, "floor") || FindBuildBlock(homePos, "floor.triangle");

        bool FindBuildBlock(Vector3 pos, string BlockName)
        {
            pos += new Vector3(0, 1f, 0);
            RaycastHit[] hits = Physics.RaycastAll(new Ray(pos, Vector3.down), 2f);
            if (hits.Count() == 0) return false;
            foreach (var hit in hits)
            {
                var buildBlockName = hit.GetEntity()?.GetComponent<BuildingBlock>()?.ShortPrefabName;
                if (buildBlockName != null && buildBlockName == BlockName) return true;
            }
            return false;
        }

        bool CheckMaxHomes(BasePlayer player)
        {
            if (!storedData.homes.ContainsKey(player.userID))
                storedData.homes.Add(player.userID, new Dictionary<string, GamePos>());

            int maxHomes = GetConfig<int>("Количество домов");
            foreach (var kvp in GetConfig<Dictionary<string, object>>("Количество домов с привилегией"))
            {
                if (permission.UserHasPermission(player.UserIDString, kvp.Key))
                {
                    int homes = Int32.Parse(kvp.Value.ToString());
                    if (homes == 0) return true;
                    if (homes > maxHomes) maxHomes = homes;
                }
            }

            int homesCount = storedData.homes[player.userID].Count();
            return (homesCount < maxHomes);
        }

        object AllowedToTeleport(BasePlayer player, Vector3 homePos)
        {
            if (storedData.cooldowns.ContainsKey(player.userID))
                return GetMessage("OnCooldown").Replace("{0}", storedData.cooldowns[player.userID].ToString());

            if (!GetConfig<bool>("Разрешить телепорт из блока строительства"))
                if (!player.CanBuild())
                    return GetMessage("TeleportWhilstBuildBlock");

            if (!GetConfig<bool>("Разрешить телепорт при кровотечении"))
                if (player.metabolism.bleeding.value > 0f)
                    return GetMessage("TeleportWhilstBleeding");

            if (GetConfig<bool>("Разрешить телепорт при крафте"))
                if (IsCrafting(player))
                    return GetMessage("TeleportWhilstCrafting");

            if (GetConfig<bool>("Использовать плагин Economics") && EconomicsInstalled())
            {
                if (!CanAffordEconomics(player))
                    return GetMessage("CantAffordEconomics").Replace("{0}", GetConfig<double>("Цена с Economics").ToString());
                SendReply(player, GetMessage("EconomicsYouSpent").Replace("{0}", GetConfig<double>("Цена с Economics").ToString()));
            }

            if (GetConfig<bool>("Использовать плагин ServerRewards") && ServerRewardsInstalled())
            {
                if (!CanAffordServerRewards(player))
                    return GetMessage("CantAffordServerRewards").Replace("{0}", GetConfig<double>("Цена с ServerRewards").ToString());
                SendReply(player, GetMessage("ServerRewardsYouSpent").Replace("{0}", GetConfig<double>("Цена с ServerRewards").ToString()));
            }

            var call = Interface.Oxide.CallHook("CanTeleport", player);
            if (call != null) return call.ToString();

            if (GetConfig<bool>("Установить дом на фундаменте"))
            {
                if (GetConfig<bool>("Установить дом на этаже"))
                    if (!CheckFloor(homePos) && !CheckFoundation(homePos))
                        return GetMessage("HomeBuildBlockDestroyed");
                else if (!CheckFoundation(homePos))
                    return GetMessage("HomeBuildBlockDestroyed");
            }

            return true;
        }

        void AssignCooldown(BasePlayer player)
        {
            int cooldown = GetConfig<int>("Перезагрузка телепорта");
            foreach (var kvp in GetConfig<Dictionary<string, object>>("Перезагрузка телепорта с привилегией"))
            {
                if (permission.UserHasPermission(player.UserIDString, kvp.Key))
                {
                    int cd = Int32.Parse(kvp.Value.ToString());
                    if (cd < cooldown) cooldown = cd;
                }
            }
            if (storedData.cooldowns.ContainsKey(player.userID))
                storedData.cooldowns[player.userID] = cooldown;
            else storedData.cooldowns.Add(player.userID, cooldown);
            SaveData();
        }
		
        #endregion		

        #region Server Rewards/Economics

        bool EconomicsInstalled() => Economics != null;

        bool ServerRewardsInstalled() => ServerRewards != null;

        bool CanAffordEconomics(BasePlayer player)
        {
            double price = GetConfig<double>("Цена с Economics");
            double playerMoney = (double)Economics.Call("GetPlayerMoney", player.userID);

            if (playerMoney - price >= 0)
            {
                Economics?.Call("Set", player.userID, playerMoney - price);
                return true;
            }
            return false;
        }

        bool CanAffordServerRewards(BasePlayer player)
        {
            int price = GetConfig<int>("Цена с ServerRewards");
            int currentPoints;
            var call = ServerRewards?.Call("CheckPoints", player.userID);
            if (call == null) currentPoints = 0;
            else currentPoints = (int)call;

            if (currentPoints - price >= 0)
            {
                ServerRewards.Call("TakePoints", player.userID, price);
                return true;
            }
            return false;
        }

        void RefundPlayerEconomics(BasePlayer player)
        {
            double price = GetConfig<double>("Цена с Economics");
            double playerMoney = (double)Economics.Call("GetPlayerMoney", player.userID);
            Economics?.Call("Set", player.userID, playerMoney + price);
            SendReply(player, GetMessage("EconomicsRefunded").Replace("{0}", price.ToString()));
        }

        void RefundServerRewards(BasePlayer player)
        {
            int price = GetConfig<int>("Цена с ServerRewards");
            ServerRewards.Call("AddPoints", player.userID, price);
            SendReply(player, GetMessage("ServerRewardsRefunded").Replace("{0}", price.ToString()));
        }

        void Teleport(BasePlayer player, Vector3 pos)
        {
            if (player.net?.connection != null)
                player.ClientRPCPlayer(null, player, "StartLoading", null, null, null, null, null);
            StartSleeping(player);
            player.MovePosition(pos);
            if (player.net?.connection != null)
                player.ClientRPCPlayer(null, player, "ForcePositionTo", pos);
            if (player.net?.connection != null)
                player.SetPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot, true);
            player.UpdateNetworkGroup();
            player.SendNetworkUpdateImmediate(false);
            if (player.net?.connection == null) return;
            try { player.ClearEntityQueue(null); } catch { }
            player.SendFullSnapshot();
        }

        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");
        }
		
		#endregion

        #region Helpers

        bool HasPerm(BasePlayer player) => (permission.UserHasPermission(player.UserIDString, permUse) || player.IsAdmin);

        bool IsCrafting(BasePlayer player) => player.inventory.crafting.queue.Count() > 0;

        T GetConfig<T>(string key)
        {
            if (Config[key] == null)
            {
                return default(T);
            }
            return (T)Convert.ChangeType(Config[key], typeof(T));
        }

        string GetMessage(string key)
        {
            string message = "";
            if (GetConfig<bool>("Разрешить префикс"))
                message += GetConfig<string>("Префикс");
            message += lang.GetMessage(key, this);
            return message;
        }

        bool HasComponent<T>(BasePlayer player) => (player.GetComponent<T>() != null);

        void SaveData() { Interface.Oxide.DataFileSystem?.WriteObject<StoredData>(this.Title, storedData); }
        void ReadData() { storedData = Interface.Oxide.DataFileSystem.ReadObject<StoredData>(this.Title); }

        #endregion
    }
}

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