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

FREE Kits : 1.2.5 1.2.5

Нет прав для скачивания
C#:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
namespace Oxide.Plugins {
    [Info("Kits", "Own3r", "1.2.5")]
    [Description("Kits релиз не для продажи")]
    class Kits : RustPlugin {
        [PluginReference]
        private Plugin ImageLibrary;
        private List<Kit> _kits;
        private static Dictionary < string, Dictionary < int, List < KitItem >>> RandomList = new Dictionary < string, Dictionary < int, List < KitItem >>> ();
        private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
        private static double CurrentTime() => DateTime.UtcNow.Subtract(epoch).TotalSeconds;
        private static Dictionary < int, List < ulong >> skinCache = new Dictionary < int, List < ulong >> ();
        private static ConfigData configData;
        private class ConfigData {
            public string background = "0 0 0 0.5";
            public string kitBackground = "0.4392 0.5215 0.2980 0.9";
            public string kitDisabledBackground = "0.7882 0.2666 0.1882 0.9";
            public int kitsPerRow = 8;
            public float kitHeight = 0.1f;
            public float kitWidth = 0.12f;
            public float kitBetween = 0.01f;
            public string kitImageAnchorMin = "0.1 0.1";
            public string kitImageAnchorMax = "0.4 0.9";
            public string kitImageTransparency = "0.9";
            public bool logusage = false;
            public Dictionary < string, KeyValuePair < string, int >> weaponAmmunition = new Dictionary < string, KeyValuePair < string, int >> () {
                {
                    "bow.hunting", new KeyValuePair < string, int > ("arrow.wooden", 50)
                }
                , {
                    "crossbow", new KeyValuePair < string, int > ("arrow.wooden", 50)
                }
                , {
                    "pistol.eoka", new KeyValuePair < string, int > ("ammo.handmade.shell", 50)
                }
                , {
                    "pistol.revolver", new KeyValuePair < string, int > ("ammo.pistol", 50)
                }
                , {
                    "pistol.semiauto", new KeyValuePair < string, int > ("ammo.pistol", 50)
                }
                , {
                    "pistol.python", new KeyValuePair < string, int > ("ammo.pistol", 50)
                }
                , {
                    "pistol.m92", new KeyValuePair < string, int > ("ammo.pistol", 50)
                }
                , {
                    "shotgun.waterpipe", new KeyValuePair < string, int > ("ammo.shotgun.fire", 30)
                }
                , {
                    "shotgun.double", new KeyValuePair < string, int > ("ammo.shotgun.fire", 50)
                }
                , {
                    "shotgun.pump", new KeyValuePair < string, int > ("ammo.shotgun.fire", 50)
                }
                , {
                    "shotgun.spas12", new KeyValuePair < string, int > ("ammo.shotgun.fire", 50)
                }
                , {
                    "smg.thompson", new KeyValuePair < string, int > ("ammo.pistol", 60)
                }
                , {
                    "smg.2", new KeyValuePair < string, int > ("ammo.pistol", 60)
                }
                , {
                    "smg.mp5", new KeyValuePair < string, int > ("ammo.pistol", 60)
                }
                , {
                    "rifle.bolt", new KeyValuePair < string, int > ("ammo.rifle", 20)
                }
                , {
                    "rifle.semiauto", new KeyValuePair < string, int > ("ammo.rifle", 40)
                }
                , {
                    "lmg.m249", new KeyValuePair < string, int > ("ammo.rifle", 100)
                }
                , {
                    "rifle.ak", new KeyValuePair < string, int > ("ammo.rifle", 60)
                }
                , {
                    "rifle.lr300", new KeyValuePair < string, int > ("ammo.rifle", 60)
                }
            }
            ;
            public Dictionary<string, string> customItemSkins = new Dictionary<string, string>() {
                {
                    "surveycharge_1668267050", "https://i.imgur.com/dlNBdyJ.png"
                }
            }
            ;
        }
        protected override void LoadDefaultConfig() {
            var config = new ConfigData() {
            }
            ;
            SaveConfig(config);
        }
        private void SaveConfig(ConfigData config) => Config.WriteObject(config, true);
        public List < KitItem > itemss = new List < KitItem > ();
        public List < ItemContent > cont = new List < ItemContent > ();
        private class KitItemGroup {
            public int pickCountFromGroup = 0;
            public bool giveAmmoForWeapon = false;
            public List < KitItem > items = new List < KitItem > ();
        }
        internal class KitItem {
            public int itemid;
            public string name;
            public string itemname = "";
            public string container;
            public int randomChance = 100;
            public int minamount;
            public int maxamount;
            public float condition;
            public ulong skinid = 0;
            public bool randomskin = false;
            public int blueprintTarget = 0;
            public List < ItemContent > contents;
            public Weapon weapon;
        }
        internal class Weapon {
            public string ammoType;
            public int ammoAmount;
        }
        internal class ItemContent {
            public string ShortName;
            public float Condition;
            public int Amount;
            public ItemContent(string ShortName, float Condition, int Amount) {
                this.ShortName = ShortName;
                this.Condition = Condition;
                this.Amount = Amount;
            }
        }
        class Kit {
            public int priority;
            public string name;
            public string image = "";
            [JsonIgnore]
            public string imageID = "";
            public bool isautokit = false;
            public string description;
            public bool isRandom = false;
            public bool randomskin = false;
            public int max;
            public double cooldown;
            public double cooldownFromWipe = 0;
            public bool hide = true;
            public string permission = "";
            public List < KitItemGroup > itemgroups;
            [JsonIgnore]
            public int beltCount;
            [JsonIgnore]
            public int mainCount;
            [JsonIgnore]
            public int wearCount;
            [JsonIgnore]
            public int totalCount;
        }
        private List < Kit > autokits = new List < Kit > ();
        private StoredData storedData = new StoredData();
        private class StoredData {
            public Dictionary < string, Dictionary < string, string >> lang = new Dictionary < string, Dictionary < string, string >> ();
            public Dictionary < string, Kit > kits = new Dictionary < string, Kit > ();
        }
        private static Dictionary < ulong, Dictionary < string, KitData >> kitsData;
        private class KitData {
            public int max;
            public double cooldown;
        }
        private void SaveKitsData() => Interface.Oxide.DataFileSystem.WriteObject(this.Title + "_Data", kitsData);
        private void SaveData() => Interface.Oxide.DataFileSystem.WriteObject(this.Title, storedData);
        private void Init() {
            permission.RegisterPermission("kits.ignorelimits", this);
            configData = Config.ReadObject < ConfigData > ();
            SaveConfig(configData);
            mainUI = mainUI.Replace("{background}", configData.background);
            try {
                kitsData = Interface.Oxide.DataFileSystem.ReadObject < Dictionary < ulong, Dictionary < string, KitData >>> (this.Title + "_Data");
            }
            catch {
                kitsData = new Dictionary < ulong, Dictionary < string, KitData >> ();
            }
            try {
                storedData = Interface.Oxide.DataFileSystem.ReadObject < StoredData > (this.Title);
            }
            catch {
                storedData = new StoredData();
            }
        }
        private void OnServerInitialized() {
            if (ImageLibrary != null) {
                foreach(var pair in configData.customItemSkins) {
                    var name = pair.Key.Substring(0, pair.Key.IndexOf("_"));
                    var skin = pair.Key.Substring(pair.Key.IndexOf("_") + 1, pair.Key.Length - pair.Key.IndexOf("_")-1);
                    ImageLibrary.Call("AddImage", pair.Value, name, (ulong)Convert.ToInt64(skin));
                }
            }
            InitKits();
        }
        private void OnPlayerRespawned(BasePlayer player) {
            var thereturn = Interface.Oxide.CallHook("canRedeemKit", player);
            if (thereturn == null) {
                foreach(Kit kit in autokits) {
                    var success = CanRedeemKit(player, kit.name, true) as string;
                    if (success != null) continue;
                    player.inventory.Strip();
                    success = GiveKit(player, kit.name) as string;
                    if (success != null) continue;
                    proccessKitGiven(player, kit.name);
                    return;
                }
            }
        }
        private void Unload() {
            SaveKitsData();
            SaveLogs();
            foreach(var player in BasePlayer.activePlayerList) CuiHelper.DestroyUi(player, "KitsUI");
        }
        private void OnServerSave() {
            SaveKitsData();
            SaveLogs();
        }
        private void OnNewSave() {
            kitsData = new Dictionary < ulong, Dictionary < string, KitData >> ();
            SaveKitsData();
        }
        private void SaveLogs() {
            foreach(var x in logging) {
                if (x.Value != "") {
                    LogToFile(x.Key, $"[{DateTime.Now}] {x.Value}", this);
                }
            }
            logging.Clear();
        }
        [ConsoleCommand("screate")]
        private void cmdConsoleGiveKit2(ConsoleSystem.Arg arg) {
            var player = arg.Player();
            if (player == null) return;
            var sc = ItemManager.CreateByName("surveycharge", 10, 1668267050);
            sc.MoveToContainer(player.inventory.containerMain, -1, false);
        }
        [ConsoleCommand("kit")]
        private void cmdConsoleGiveKit(ConsoleSystem.Arg arg) {
            if (arg.Connection == null) {
                SendReply(arg, "You can't use this command from the server console");
                return;
            }
            var player = arg.Player();
            if (player == null) return;
            TryGiveKit(player, arg.Args[0]);
            CuiHelper.DestroyUi(player, "KitsUI");
        }
        [ConsoleCommand("kits.open")]
        private void cmdConsoleKitGui(ConsoleSystem.Arg arg) {
            if (arg.Connection == null) {
                SendReply(arg, "You can't use this command");
                return;
            }
            var player = arg.Player();
            if (player == null) return;
            ShowUI(player);
        }
        [ChatCommand("kit")]
        private void CommandChatKit(BasePlayer player, string command, string[] args) {
            if (player == null) return;
            if (args.Length == 0) {
                ShowUI(player);
                return;
            }
            if (player.net.connection.authLevel < 2) {
                TryGiveKit(player, args[0].ToLower());
                return;
            }
            switch (args[0].ToLower()) {
                case "resetdata" : OnNewSave();
                break;
                case "add" : case "new" : if (args.Length < 2) SendReply(player, GetMsg("Help", player.userID));
                else {
                    if (storedData.kits.ContainsKey(args[1].ToLower())) {
                        SendReply(player, GetMsg("Kit Already Exists", player.userID));
                        break;
                    }
                    var kit = new Kit();
                    kit.priority = storedData.kits.Count < 1 ? 1 : storedData.kits.OrderByDescending(k => k.Value.priority).FirstOrDefault().Value.priority + 1;
                    kit.name = args[1].ToLower();
                    storedData.kits.Add(args[1].ToLower(), kit);
                    kit.itemgroups = GetPlayerItems(player);
                    SendReply(player, GetMsg("Kit Added", player.userID));
                }
                break;
                case "replace" : if (args.Length < 2) SendReply(player, GetMsg("Help", player.userID));
                else if (!storedData.kits.ContainsKey(args[1].ToLower())) {
                    SendReply(player, GetMsg("No Kit Found", player.userID));
                    break;
                }
                storedData.kits[args[1].ToLower()].itemgroups = GetPlayerItems(player);
                SendReply(player, GetMsg("Kit Replaced", player.userID));
                break;
                case "remove" : if (args.Length < 2) SendReply(player, GetMsg("Help", player.userID));
                else {
                    if (!storedData.kits.Remove(args[1].ToLower())) {
                        SendReply(player, GetMsg("No Kit Found", player.userID));
                        break;
                    }
                    SendReply(player, GetMsg("Kit Removed", player.userID));
                    break;
                }
                break;
                case "edit" : if (args.Length < 2 || args.Length % 2 != 0) SendReply(player, GetMsg("Help", player.userID));
                else {
                    if (!storedData.kits.ContainsKey(args[1].ToLower())) {
                        SendReply(player, GetMsg("No Kit Found", player.userID));
                        break;
                    }
                    Kit kit = storedData.kits[args[1].ToLower()];
                    for (var i = 2; i < args.Length; i = i + 2) {
                        switch (args[i].ToLower()) {
                            case "name" : kit.name = args[i + 1];
                            break;
                            case "permission" : kit.permission = args[i + 1];
                            break;
                            case "image" : kit.image = args[i + 1];
                            break;
                            case "priority" : int prior = -1;
                            if (!int.TryParse(args[i + 1], out prior)) break;
                            foreach(var k in storedData.kits) {
                                if (k.Value.priority >= prior) k.Value.priority += 1;
                            }
                            kit.priority = prior;
                            break;
                            case "hide" : kit.hide = GetBoolValue(args[i + 1]);
                            break;
                            case "isautokit" : kit.isautokit = GetBoolValue(args[i + 1]);
                            break;
                            case "israndom" : kit.isRandom = GetBoolValue(args[i + 1]);
                            break;
                            case "randomskin" : kit.isautokit = GetBoolValue(args[i + 1]);
                            break;
                            case "max" : kit.max = Convert.ToInt32(args[i + 1]);
                            break;
                            case "cooldown" : kit.cooldown = Convert.ToSingle(args[i + 1]);
                            break;
                            case "wipe" : kit.cooldownFromWipe = Convert.ToSingle(args[i + 1]);
                            break;
                        }
                    }
                    SendReply(player, GetMsg("Kit edited", player.userID));
                }
                break;
                default : TryGiveKit(player, args[0].ToLower());
                return;
            }
            InitKits();
            SaveData();
        }
        [HookMethod("GetKitInfo")]
        public object GetKitInfo(string kitname) {
            if (storedData.kits.ContainsKey(kitname.ToLower())) {
                Kit kit = storedData.kits[kitname.ToLower()];
                JObject obj = new JObject();
                obj["name"] = kit.name;
                obj["permission"] = kit.permission;
                obj["max"] = kit.max;
                obj["image"] = kit.image;
                obj["hide"] = kit.hide;
                obj["description"] = kit.description;
                obj["cooldown"] = kit.cooldown;
                JArray items = new JArray();
                foreach(var g in kit.itemgroups) {
                    foreach(var itemEntry in g.items) {
                        JObject item = new JObject();
                        item["amount"] = itemEntry.minamount;
                        item["container"] = itemEntry.container;
                        item["itemid"] = itemEntry.itemid;
                        item["skinid"] = itemEntry.skinid;
                        item["weapon"] = itemEntry.weapon != null ? true : false;
                        item["blueprint"] = itemEntry.blueprintTarget > 0;
                        JArray mods = new JArray();
                        if (itemEntry.contents != null) {
                            foreach(var mod in itemEntry.contents) mods.Add(mod.ShortName);
                            item["mods"] = mods;
                        }
                        items.Add(item);
                    }
                }
                obj["items"] = items;
                return obj;
            }
            return null;
        }
        private bool TryGiveKit(BasePlayer player, string kitname, bool force = false) {
            var success = CanRedeemKit(player, kitname, force) as string;
            if (success != null) {
                OnScreen(player, success, "1 0 0 0.5");
                return false;
            }
            success = GiveKit(player, kitname) as string;
            if (success != null) {
                OnScreen(player, success, "1 0 0 0.5");
                return false;
            }
            OnScreen(player, GetMsg("KitRedeemed", player.userID), "0 1 0 0.5");
            if (!force) proccessKitGiven(player, kitname);
            return true;
        }
        private void proccessKitGiven(BasePlayer player, string kitname) {
            if (string.IsNullOrEmpty(kitname)) return;
            Kit kit;
            if (!storedData.kits.TryGetValue(kitname, out kit)) return;
            var kitData = GetKitData(player.userID, kitname);
            if (kit.max > 0) kitData.max += 1;
            if (kit.cooldown > 0) kitData.cooldown = CurrentTime() + kit.cooldown;
            if (configData.logusage && !kit.isautokit) Log($"{player.displayName} {player.userID} got kit {kit.name}");
        }
        private object GiveKit(BasePlayer player, string kitname, bool toInventory = true, ItemContainer inventory = null) {
            if (player == null && inventory != null) return GiveKit(inventory, kitname);
            if (string.IsNullOrEmpty(kitname)) return GetMsg("Empty kit name", player.userID);
            kitname = kitname.ToLower();
            Kit kit;
            if (!storedData.kits.TryGetValue(kitname, out kit)) return GetMsg("No Kit Found", player.userID);
            if (kit.isRandom) {
                foreach(var group in RandomList[kitname]) {
                    foreach(KitItem item in group.Value) {
                        if (kit.itemgroups[group.Key].pickCountFromGroup > 0) {
                            for (int j = 1; j <= kit.itemgroups[group.Key].pickCountFromGroup; j++) {
                                KitItem kitem = group.Value.GetRandom();
                                Item itemGive = BuildItem(kitem, kit.randomskin);
                                GiveItem(player.inventory, itemGive, kitem.container == "belt" ? player.inventory.containerBelt : kitem.container == "wear" ? player.inventory.containerWear : player.inventory.containerMain);
                                if (kit.itemgroups[group.Key].giveAmmoForWeapon && itemGive.info.category.ToString() == "Weapon") {
                                    if (configData.weaponAmmunition.ContainsKey(kitem.name)) {
                                        Item gitem = ItemManager.CreateByName(configData.weaponAmmunition[kitem.name].Key, configData.weaponAmmunition[kitem.name].Value);
                                        if (!gitem.MoveToContainer(player.inventory.containerMain)) gitem.Drop(player.inventory.containerMain.dropPosition, player.inventory.containerMain.dropVelocity, new Quaternion());
                                    }
                                }
                            }
                            break;
                        }
                        else {
                            if (item.randomChance != 100) {
                                if (UnityEngine.Random.Range(0, 100) <= item.randomChance) {
                                    GiveItem(player.inventory, BuildItem(item, kit.randomskin), item.container == "belt" ? player.inventory.containerBelt : item.container == "wear" ? player.inventory.containerWear : player.inventory.containerMain);
                                }
                            }
                            else {
                                GiveItem(player.inventory, BuildItem(item, kit.randomskin), item.container == "belt" ? player.inventory.containerBelt : item.container == "wear" ? player.inventory.containerWear : player.inventory.containerMain);
                            }
                        }
                    }
                }
            }
            else foreach(var g in kit.itemgroups) {
                foreach(var kitem in g.items) {
                    GiveItem(player.inventory, BuildItem(kitem, kit.randomskin), kitem.container == "belt" ? player.inventory.containerBelt : kitem.container == "wear" ? player.inventory.containerWear : player.inventory.containerMain);
                }
            }
            return true;
        }
        private object GiveKit(ItemContainer inventory, string kitname) {
            if (string.IsNullOrEmpty(kitname)) return false;
            kitname = kitname.ToLower();
            Kit kit;
            if (!storedData.kits.TryGetValue(kitname, out kit)) return false;
            if (kit.isRandom) {
                foreach(var group in RandomList[kitname]) {
                    foreach(KitItem item in group.Value) {
                        if (kit.itemgroups[group.Key].pickCountFromGroup > 0) {
                            for (int j = 1; j <= kit.itemgroups[group.Key].pickCountFromGroup; j++) {
                                KitItem kitem = group.Value.GetRandom();
                                Item itemGive = BuildItem(kitem, kit.randomskin);
                                if (!GiveItem(inventory, itemGive)) itemGive.Drop(inventory.dropPosition, inventory.dropVelocity, new Quaternion());
                                if (kit.itemgroups[group.Key].giveAmmoForWeapon) {
                                    if (configData.weaponAmmunition.ContainsKey(kitem.name) && itemGive.info.category.ToString() == "Weapon") {
                                        Item gitem = ItemManager.CreateByName(configData.weaponAmmunition[kitem.name].Key, configData.weaponAmmunition[kitem.name].Value);
                                        if (!gitem.MoveToContainer(inventory)) gitem.Drop(inventory.dropPosition, inventory.dropVelocity, new Quaternion());
                                    }
                                }
                            }
                            break;
                        }
                        else {
                            Item gitem = BuildItem(item, kit.randomskin);
                            if (!GiveItem(inventory, gitem)) gitem.Drop(inventory.dropPosition, inventory.dropVelocity, new Quaternion());
                        }
                    }
                }
            }
            else foreach(var g in kit.itemgroups) {
                foreach(var kitem in g.items) {
                    Item gitem = BuildItem(kitem, kit.randomskin);
                    if (!GiveItem(inventory, gitem)) gitem.Drop(inventory.dropPosition, inventory.dropVelocity, new Quaternion());
                }
            }
            return true;
        }
        private ulong uzero = 0U;
        private void InitKits() {
            Dictionary < int, Kit > tempautokits = new Dictionary < int, Kit > ();
            Dictionary < string, string > newLoadOrder = new Dictionary < string, string > ();
            foreach(var k in storedData.kits) {
                if (!string.IsNullOrEmpty(k.Value.image)) {
                    string imname = "kit" + k.Key;
                    newLoadOrder.Add(imname, k.Value.image);
                }
                if (!storedData.lang.ContainsKey("en")) storedData.lang.Add("en", new Dictionary < string, string > ());
                if (!storedData.lang.ContainsKey("ru")) storedData.lang.Add("ru", new Dictionary < string, string > ());
                if (!storedData.lang["en"].ContainsKey(k.Value.name)) {
                    storedData.lang["en"].Add(k.Value.name, k.Value.name);
                    storedData.lang["ru"].Add(k.Value.name, k.Value.name);
                }
                if (k.Value.isautokit) tempautokits.Add(k.Value.priority, k.Value);
                if (!string.IsNullOrEmpty(k.Value.permission) && !permission.PermissionExists("kits." + k.Value.permission, this)) permission.RegisterPermission("kits." + k.Value.permission, this);
                foreach(var g in k.Value.itemgroups) {
                    k.Value.beltCount = g.items.Where(i => i.container == "belt").Count();
                    k.Value.wearCount = g.items.Where(i => i.container == "wear").Count();
                    k.Value.mainCount = g.items.Where(i => i.container == "main").Count();
                    if (g.pickCountFromGroup > 0) {
                        if (k.Value.beltCount > g.pickCountFromGroup) k.Value.beltCount = g.pickCountFromGroup;
                        if (k.Value.wearCount > g.pickCountFromGroup) k.Value.wearCount = g.pickCountFromGroup;
                        if (k.Value.mainCount > g.pickCountFromGroup) k.Value.mainCount = g.pickCountFromGroup;
                    }
                    k.Value.totalCount = k.Value.beltCount + k.Value.wearCount + k.Value.mainCount;
                    foreach(var item in g.items) {
                        if (item.randomskin || k.Value.randomskin) {
                            if (!skinCache.ContainsKey(item.itemid)) {
                                var skins = ItemSkinDirectory.ForItem(ItemManager.FindItemDefinition(item.itemid));
                                if (skins.Length > 1) {
                                    var list = new List < ulong > ();
                                    list.Add(0U);
                                    foreach(var s in skins) {
                                        list.Add((ulong) s.id);
                                    }
                                    skinCache.Add(item.itemid, list);
                                }
                            }
                        }
                    }
                }
                if (k.Value.isRandom && !RandomList.ContainsKey(k.Value.name)) {
                    RandomList.Add(k.Value.name, new Dictionary < int, List < KitItem >> ());
                    int i = 0;
                    foreach(KitItemGroup itemgroup in k.Value.itemgroups) {
                        RandomList[k.Value.name].Add(i, new List < KitItem > ());
                        foreach(KitItem item in itemgroup.items) {
                            if (item.randomChance > 0) {
                                if (itemgroup.pickCountFromGroup > 0) {
                                    for (int j = 1; j <= item.randomChance; j++) {
                                        RandomList[k.Value.name][i].Add(item);
                                    }
                                }
                                else {
                                    RandomList[k.Value.name][i].Add(item);
                                }
                            }
                        }
                        Shuffle(RandomList[k.Value.name][i]);
                        i++;
                    }
                }
            }
            if (newLoadOrder.Count > 0) ImageLibrary?.CallHook("ImportImageList", Title, newLoadOrder, uzero, true);
            storedData.kits = storedData.kits.OrderBy(k => k.Value.priority).ToDictionary(x => x.Key, x => x.Value);
            autokits = tempautokits.OrderBy(k => k.Key).ToDictionary(x => x.Key, x => x.Value).Values.ToList();
            if (autokits.Count < 1) Unsubscribe(nameof(OnPlayerRespawned));
            GetKitImages();
            SaveData();
        }
        public System.Random rnd = new System.Random();
        private void Shuffle(List < KitItem > list) {
            int n = list.Count;
            while (n > 1) {
                n--;
                int k = rnd.Next(n + 1);
                KitItem value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
        private void GetKitImages() {
            if (!(bool)(ImageLibrary?.CallHook("IsReady") ?? false)) {
                PrintWarning("Waiting for ImageLibrary to finish image processing!");
                timer.In(10, GetKitImages);
                return;
            }
            foreach(var k in storedData.kits) {
                if (!string.IsNullOrEmpty(k.Value.image)) {
                    string imname = "kit" + k.Key;
                    k.Value.imageID = (string)(ImageLibrary?.CallHook("GetImage", imname, uzero) ?? "");
                }
            }
        }
        private Dictionary < string, string > logging = new Dictionary < string, string > ();
        private void Log(string text, string filename = "log") {
            if (!logging.ContainsKey(filename)) logging.Add(filename, text + "\r\n");
            else logging[filename] += text + "\r\n";
        }
        private string FormatShortTime(double seconds) {
            string result = "";
            TimeSpan time = TimeSpan.FromSeconds(seconds);
            if (time.Days != 0) result += $"{time.Days} д.";
            if (time.Hours != 0) result += $"{time.Hours} ч.";
            if (time.Minutes != 0) result += $"{time.Minutes} м.";
            if (time.Seconds != 0) result += $"{time.Seconds} с.";
            return result;
        }
        private bool CanRedeemKitUI(BasePlayer player, Kit kit) {
            if (kit.hide || kit.isautokit) return false;
            if (!string.IsNullOrEmpty(kit.permission)) if (!permission.UserHasPermission(player.UserIDString, "kits." + kit.permission)) return false;
            var kitData = GetKitData(player.userID, kit.name);
            if (kit.max > 0) if (kitData.max >= kit.max) return false;
            return true;
        }
        private object CanRedeemKit(BasePlayer player, string kitname, bool skipAuth = false) {
            if (string.IsNullOrEmpty(kitname)) return GetMsg("Empty kit name", player.userID);
            kitname = kitname.ToLower();
            Kit kit;
            if (!storedData.kits.TryGetValue(kitname, out kit)) return GetMsg("No Kit Found", player.userID);
            if (!skipAuth && (kit.hide || kit.isautokit) && player.net.connection.authLevel < 2) return GetMsg("No Kit Found", player.userID);
            object thereturn = Interface.Oxide.CallHook("canRedeemKit", player);
            if (thereturn != null) {
                if (thereturn is string) return thereturn;
                return GetMsg("CantRedeemNow", player.userID);
            }
            if (!skipAuth && !string.IsNullOrEmpty(kit.permission) && !permission.UserHasPermission(player.UserIDString, "kits." + kit.permission)) return GetMsg("NoPermKit", player.userID);
            var kitData = GetKitData(player.userID, kitname);
            if (!skipAuth && kit.max > 0 && !permission.UserHasPermission(player.UserIDString, "kits.ignorelimits")) if (kitData.max >= kit.max) return GetMsg("NoRemainingUses", player.userID);
            if (kit.cooldownFromWipe > 0 && !permission.UserHasPermission(player.UserIDString, "kits.ignorelimits")) {
                double secsFromWipe = DateTime.UtcNow.Subtract(SaveRestore.SaveCreatedTime).TotalSeconds;
                if (secsFromWipe < kit.cooldownFromWipe) return string.Format(GetMsg("CooldownMessage", player.userID), FormatShortTime(kit.cooldownFromWipe - secsFromWipe));
            }
            if (!skipAuth && kit.cooldown > 0 && !permission.UserHasPermission(player.UserIDString, "kits.ignorelimits")) {
                var ct = CurrentTime();
                if (kitData.cooldown > ct && kitData.cooldown != 0.0) return string.Format(GetMsg("CooldownMessage", player.userID), FormatShortTime(Math.Abs(Math.Ceiling(kitData.cooldown - ct))));
            }
            if ((player.inventory.containerBelt.capacity - player.inventory.containerBelt.itemList.Count) < kit.beltCount || (player.inventory.containerWear.capacity - player.inventory.containerWear.itemList.Count) < kit.wearCount || (player.inventory.containerMain.capacity - player.inventory.containerMain.itemList.Count) < kit.mainCount) if (kit.totalCount > (player.inventory.containerMain.capacity - player.inventory.containerMain.itemList.Count)) return GetMsg("NoInventorySpace", player.userID);
            return true;
        }
        private bool GiveItem(ItemContainer container, Item item) {
            if (container == null) return false;
            return item.MoveToContainer(container, -1, true);
        }
        private bool GiveItem(PlayerInventory inv, Item item, ItemContainer container = null) {
            if (item == null) {
                return false;
            }
            int position = -1;
            return (((container != null) && item.MoveToContainer(container, position, true)) || (item.MoveToContainer(inv.containerMain, -1, true) || item.MoveToContainer(inv.containerBelt, -1, true)));
        }
        private Item BuildItem(KitItem kitem, bool kitRandomSkin = false) {
            int amount = kitem.minamount;
            if (kitem.minamount < kitem.maxamount) amount = UnityEngine.Random.Range(kitem.minamount, kitem.maxamount);
            ulong skin = kitem.skinid;
            if (kitem.randomskin || kitRandomSkin) {
                if (skinCache.ContainsKey(kitem.itemid)) {
                    skin = skinCache[kitem.itemid].GetRandom();
                }
            }
            Item item = ItemManager.CreateByName(kitem.name, amount, skin);
            if (kitem.itemname != "") item.name = kitem.itemname;
            item.condition = kitem.condition;
            if (kitem.blueprintTarget != 0) item.blueprintTarget = kitem.blueprintTarget;
            if (kitem.weapon != null) {
                var weapon = item.GetHeldEntity() as BaseProjectile;
                if (weapon != null) {
                    (item.GetHeldEntity() as BaseProjectile).primaryMagazine.contents = kitem.weapon.ammoAmount;
                    (item.GetHeldEntity() as BaseProjectile).primaryMagazine.ammoType = ItemManager.FindItemDefinition(kitem.weapon.ammoType);
                }
            }
            if (kitem.contents != null) {
                foreach(var cont in kitem.contents) {
                    Item new_cont = ItemManager.CreateByName(cont.ShortName, cont.Amount);
                    new_cont.condition = cont.Condition;
                    new_cont.MoveToContainer(item.contents);
                }
            }
            return item;
        }
        private KitData GetKitData(ulong userID, string kitname) {
            if (!kitsData.ContainsKey(userID)) kitsData.Add(userID, new Dictionary < string, KitData > ());
            if (!kitsData[userID].ContainsKey(kitname)) kitsData[userID].Add(kitname, new KitData());
            return kitsData[userID][kitname];
        }
        private static List < KitItemGroup > GetPlayerItems(BasePlayer player) {
            List < KitItemGroup > kitgroups = new List < KitItemGroup > ();
            var kitgroup = new KitItemGroup();
            var kititems = kitgroup.items;
            kitgroups.Add(kitgroup);
            foreach(Item item in player.inventory.containerWear.itemList) {
                if (item != null) {
                    var iteminfo = ProcessItem(item, "wear");
                    kititems.Add(iteminfo);
                }
            }
            foreach(Item item in player.inventory.containerMain.itemList) {
                if (item != null) {
                    var iteminfo = ProcessItem(item, "main");
                    kititems.Add(iteminfo);
                }
            }
            foreach(Item item in player.inventory.containerBelt.itemList) {
                if (item != null) {
                    var iteminfo = ProcessItem(item, "belt");
                    kititems.Add(iteminfo);
                }
            }
            return kitgroups;
        }
        private static KitItem ProcessItem(Item item, string container) {
            KitItem iItem = new KitItem();
            iItem.minamount = item.amount;
            iItem.maxamount = item.amount;
            iItem.container = container;
            iItem.condition = item.condition;
            iItem.skinid = item.skin;
            iItem.itemid = item.info.itemid;
            iItem.name = item.info.shortname;
            iItem.blueprintTarget = item.blueprintTarget;
            if (item.info.category.ToString() == "Weapon") {
                BaseProjectile weapon = item.GetHeldEntity() as BaseProjectile;
                if (weapon != null) {
                    if (weapon.primaryMagazine != null) {
                        iItem.weapon = new Weapon();
                        iItem.weapon.ammoType = weapon.primaryMagazine.ammoType.shortname;
                        iItem.weapon.ammoAmount = weapon.primaryMagazine.contents;
                    }
                }
            }
            if (item.contents != null) {
                iItem.contents = new List < ItemContent > ();
                foreach(var mod in item.contents.itemList) {
                    if (mod.info.itemid != 0) {
                        iItem.contents.Add(new ItemContent(mod.info.shortname, mod.condition, mod.amount));
                    }
                }
            }
            return iItem;
        }
        private static bool GetBoolValue(string value) {
            if (string.IsNullOrEmpty(value)) return false;
            value = value.Trim().ToLower();
            switch (value) {
                case "t" : case "true" : case "1" : case "yes" : case "y" : case "on" : return true;
                default : return false;
            }
        }
        private string GetMsg(string key, object steamid = null) => lang.GetMessage(key, this, steamid == null ? null : steamid.ToString());
        private string GetKitName(string key, string lang) {
            if (!storedData.lang.ContainsKey(lang)) lang = "en";
            if (!storedData.lang.ContainsKey(lang)) return key;
            if (storedData.lang[lang].ContainsKey(key)) return storedData.lang[lang][key];
            return key;
        }
        private static Dictionary < string, string > langEN = new Dictionary < string, string > () {
            {
                "Help", "/kit new name - добавить кит с текущим инвентарём\n/kit replace name - заменить кит инветарём\n/kit remove name - удалить кит\n/kit edit name flags - редактировать кит, флаги: \nname newname\nisautokit true|false\nisrandom true|false\nrandomskin true|false\nmax maxlimit\ncooldown time_in_seconds\nwipe wipetime_in_seconds\nhide true|false"
            }
            , {
                "Kit Already Exists", "Такой кит уже есть"
            }
            , {
                "Kit Added", "Кит добавлен"
            }
            , {
                "No Kit Found", "Такого кита нет"
            }
            , {
                "Kit Replaced", "Вещи в ките заменены"
            }
            , {
                "Kit Removed", "Кит удалён"
            }
            , {
                "KitRedeemed", "Кит получен"
            }
            , {
                "Empty kit name ", "Не указан кит"
            }
            , {
                "CantRedeemNow", "Ты не можешь получить кит сейчас"
            }
            , {
                "NoPermKit", "Нет доступа"
            }
            , {
                "NoRemainingUses", "Не осталось использований"
            }
            , {
                "CooldownMessage", "Подожди еще {0}"
            }
            , {
                "NoInventorySpace", "Недостаточно места в инвентаре"
            }
            , {
                "No kits", "Нет доступных китов"
            }
            , {
                "Kit edited", "Кит отредактирован"
            }
            ,
        }
        ;
        private static Dictionary < string, string > langRU = new Dictionary < string, string > () {
            {
                "Help", "/kit new name - добавить кит с текущим инвентарём\n/kit replace name - заменить кит инветарём\n/kit remove name - удалить кит\n/kit edit name flags - редактировать кит, флаги: \nname newname\nisautokit true|false\nisrandom true|false\nrandomskin true|false\nmax maxlimit\ncooldown time_in_seconds\nwipe wipetime_in_seconds\nhide true|false"
            }
            , {
                "Kit Already Exists", "Такой кит уже есть"
            }
            , {
                "Kit Added", "Кит добавлен"
            }
            , {
                "No Kit Found", "Такого кита нет"
            }
            , {
                "Kit Replaced", "Вещи в ките заменены"
            }
            , {
                "Kit Removed", "Кит удалён"
            }
            , {
                "KitRedeemed", "Кит получен"
            }
            , {
                "Empty kit name ", "Не указан кит"
            }
            , {
                "CantRedeemNow", "Ты не можешь получить кит сейчас"
            }
            , {
                "NoPermKit", "Нет доступа"
            }
            , {
                "NoRemainingUses", "Не осталось использований"
            }
            , {
                "CooldownMessage", "Подожди еще {0}"
            }
            , {
                "NoInventorySpace", "Недостаточно места в инвентаре"
            }
            , {
                "No kits", "Нет доступных китов"
            }
            , {
                "Kit edited", "Кит отредактирован"
            }
            ,
        }
        ;
        protected override void LoadDefaultMessages() {
            lang.RegisterMessages(langEN, this);
            lang.RegisterMessages(langRU, this, "ru");
        }
        private void OnScreen(BasePlayer player, string text, string color) {
            CuiHelper.DestroyUi(player, "KitsAlert");
            CuiHelper.AddUi(player, alertUI.Replace("{text}", text).Replace("{color}", color));
            timer.Once(2, () => CuiHelper.DestroyUi(player, "KitsAlert"));
        }
        private string mainUI = @"[{""name"":""KitsUI"",""parent"":""Overlay"",""components"":[{""type"":""UnityEngine.UI.Image"",""color"":""0 0 0 0""},{""type"":""RectTransform"",""anchormin"":""0 0"",""anchormax"":""1 1""},{""type"":""NeedsCursor""}]},{""name"":""77946099d7304efa942e03f6bc1257ef"",""parent"":""KitsUI"",""components"":[{""type"":""UnityEngine.UI.Button"",""close"":""KitsUI"",""color"":""0 0 0 0""},{""type"":""RectTransform"",""anchormin"":""0 0"",""anchormax"":""1 1""}]},{""name"":""KitsUIPanel_"",""parent"":""KitsUI"",""components"":[{""type"":""UnityEngine.UI.Image"",""color"":""{background}""},{""type"":""RectTransform"",""anchormin"":""{positionMin}"",""anchormax"":""{positionMax}""},{""type"":""NeedsCursor""}]}]";
        private string panelUI = @"[{""name"":""KitsUIPanel{number}"",""parent"":""KitsUIPanel_"",""components"":[{""type"":""UnityEngine.UI.Image"",""color"":""0 0 0 0""},{""type"":""RectTransform"",""anchormin"":""{anchormin}"",""anchormax"":""{anchormax}""},{""type"":""NeedsCursor""}]}]";
        private string alertUI = @"[{""name"":""KitsAlert"",""parent"":""Overlay"",""components"":[{""type"":""UnityEngine.UI.Image"",""color"":""{color}""},{""type"":""RectTransform"",""anchormin"":""0.35 0.8"",""anchormax"":""0.65 0.9""}]},{""parent"":""KitsAlert"",""components"":[{""type"":""UnityEngine.UI.Text"",""text"":""{text}"",""fontSize"":18,""align"":""MiddleCenter"",""color"":""1 1 1 1""},{""type"":""UnityEngine.UI.Outline"",""color"":""0.0 0.0 0.0 1.0"",""distance"":""1 1""},{""type"":""RectTransform"",""anchormin"":""0 0"",""anchormax"":""1 1""}]}]";
        private void ShowUI(BasePlayer player) {
            CuiHelper.DestroyUi(player, "KitsUI");
            int kitCount = 0;
            var kitElements = new CuiElementContainer();
            int panelCount = 1;
            object thereturn = Interface.Oxide.CallHook("canRedeemKit", player);
            if (thereturn == null) {
                Dictionary < string, Dictionary < string, string >> userkits = new Dictionary < string, Dictionary < string, string >> ();
                foreach(var k in storedData.kits) {
                    if (k.Value.hide || !CanRedeemKitUI(player, k.Value)) continue;
                    string kittext = "";
                    double cooldown = 0;
                    double secsFromWipeLeft = 0;
                    int max = 0;
                    KitData kitData = null;
                    if ((k.Value.cooldown > 0 || k.Value.max > 0) && !permission.UserHasPermission(player.UserIDString, "kits.ignorelimits")) {
                        kitData = GetKitData(player.userID, k.Value.name);
                    }
                    if (k.Value.max > 0) {
                        kittext += $"{k.Value.max - kitData.max} осталось";
                    }
                    if (k.Value.cooldown > 0 && !permission.UserHasPermission(player.UserIDString, "kits.ignorelimits")) {
                        var ct = CurrentTime();
                        if (kitData.cooldown > ct && kitData.cooldown != 0.0) {
                            cooldown = Math.Abs(Math.Ceiling(kitData.cooldown - ct));
                            if (kittext != "") kittext += "\n";
                            kittext += FormatShortTime(cooldown);
                        }
                    }
                    if (k.Value.cooldownFromWipe > 0 && !permission.UserHasPermission(player.Us
// ... [Code preview truncated due to length. Full source in attached file] ...

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