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

FREE NpcRaiders : 1.3.27 1.3.27

Нет прав для скачивания
C#:
using System.Collections.Generic;
using System.Collections;
using Oxide.Core.Configuration;
using Newtonsoft.Json;
using Oxide.Core.Plugins;
using UnityEngine;
using System.Linq;
using Oxide.Core;
using System;
using Oxide.Game.Rust.Cui;
using UnityEngine.SceneManagement;
using System.Text.RegularExpressions;
using Color = UnityEngine.Color;
using UnityEngine.AI;
using Facepunch;
using VLB;
using System.Globalization;
using ProtoBuf;
using Newtonsoft.Json.Linq;
namespace Oxide.Plugins {
    [Info("NpcRaiders", "Razor", "1.3.27", ResourceId = 107)]
    [Description("Spawn Npc to raid your base.")]
    public class NpcRaiders : RustPlugin {
#region Loading
        public static bool debug = false;
        [PluginReference]
        private Plugin Kits, TruePVE, ServerRewards, Economics, LifeSupport;
        PlayerEntity pcdData;
        private DynamicConfigFile PCDDATA;
        PlayerStats statsData;
        private DynamicConfigFile STATSDATA;
        public static NpcRaiders _;
        private Dictionary<BasePlayer, eventList> EventList = new Dictionary<BasePlayer, eventList>();
        private Dictionary<ulong, List<ulong>> corpsLock = new Dictionary<ulong, List<ulong>>();
        public static double GrabCurrentTime() => DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
        public static List<MLRS> mlrs = new List<MLRS>();
        private static int groundLayer;
        private static int terainLayer;
        private static int BuildingLayer;
        private static Vector3 Vector3Down;
        private Color backgroundColor;
        private Color PanelColor;
        private static string usePerm = "npcraiders.use";
        private static string coolPerm = "npcraiders.nocooldown";
        private static string adminPerm = "npcraiders.admin";
        private static string bypassPerm = "npcraiders.bypass";
        private static string bypassCost = "npcraiders.nocost";
        private float nextTime;
        private string chatComand = "raidme";
        public class eventList {
            public string type;
            public Vector3 location;
            public BuildingPrivlidge priv;
        }
        private void Init() {
            ColorExtensions.TryParseHexString("#2b2b2b", out backgroundColor);
            ColorExtensions.TryParseHexString("#404141F2", out PanelColor);
            if (!string.IsNullOrEmpty(configData.settings.chatcommand)) {
                chatComand = configData.settings.chatcommand;
                cmd.AddChatCommand(configData.settings.chatcommand, this, "cmdChatStartRaid");
            }
            else {
                cmd.AddChatCommand("raidme", this, "cmdChatStartRaid");
            }
            PCDDATA = Interface.Oxide.DataFileSystem.GetFile(Name + "/PlayerCooldowns");
            STATSDATA = Interface.Oxide.DataFileSystem.GetFile(Name + "/PlayerStats");
            LoadData();
            _ = this;
            permission.RegisterPermission(usePerm, this);
            permission.RegisterPermission(coolPerm, this);
            permission.RegisterPermission(adminPerm, this);
            permission.RegisterPermission(bypassPerm, this);
            permission.RegisterPermission(bypassCost, this);
        }
        private void OnServerInitialized() {
            if (TruePVE != null) {
                Unsubscribe("OnEntityTakeDamage");
                Unsubscribe("CanBeTargeted");
            }
            groundLayer = LayerMask.GetMask("Construction", "Terrain", "World");
            terainLayer = LayerMask.GetMask("Terrain", "World", "Water");
            BuildingLayer = LayerMask.GetMask("Construction");
            Vector3Down = new Vector3(0f, -1f, 0f);
            if (configData.raidSettings.raidTypes.Count <= 0) {
                if (configData.raidBuyOptions.BuyOptions.Count <= 0) {
                    configData.raidBuyOptions.BuyOptions.Add("easy", new raidBuy("-932201673", 500));
                    configData.raidBuyOptions.BuyOptions.Add("medium", new raidBuy("-932201673", 1000));
                    configData.raidBuyOptions.BuyOptions.Add("hard", new raidBuy("-932201673", 1500));
                    configData.raidBuyOptions.BuyOptions.Add("expert", new raidBuy("-932201673", 1500));
                    configData.raidBuyOptions.BuyOptions.Add("nightmare", new raidBuy("-932201673", 1500));
                }
                if (configData.raidRewardOptions.RewardOptions.Count <= 0) {
                    configData.raidRewardOptions.RewardOptions.Add("easy", new raidReward("-932201673", 500));
                    configData.raidRewardOptions.RewardOptions.Add("medium", new raidReward("-932201673", 1000));
                    configData.raidRewardOptions.RewardOptions.Add("hard", new raidReward("-932201673", 1500));
                    configData.raidRewardOptions.RewardOptions.Add("expert", new raidReward("-932201673", 1500));
                    configData.raidRewardOptions.RewardOptions.Add("nightmare", new raidReward("-932201673", 1500));
                }
                configData.raidSettings.raidTypes.Add("easy", new raidConfig(10, true, 100, 640, new List<string>(), new List<string>() {
                    "explosive.timed", "explosive.satchel"
                }
                , 2, "npcraiders.easy", 15000, 1.0));
                configData.raidSettings.raidTypes.Add("medium", new raidConfig(15, true, 200, 900, new List<string>(), new List<string>() {
                    "explosive.timed", "explosive.satchel"
                }
                , 3, "npcraiders.medium", 30000, 1.0));
                configData.raidSettings.raidTypes.Add("hard", new raidConfig(20, true, 400, 1200, new List<string>(), new List<string>() {
                    "explosive.timed", "explosive.satchel"
                }
                , 4, "npcraiders.hard", 50000, 1.0));
                configData.raidSettings.raidTypes.Add("expert", new raidConfig(30, true, 400, 1500, new List<string>(), new List<string>() {
                    "explosive.timed", "explosive.satchel"
                }
                , 4, "npcraiders.expert", 65000, 1.0));
                configData.raidSettings.raidTypes.Add("nightmare", new raidConfig(30, true, 400, 2100, new List<string>(), new List<string>() {
                    "explosive.timed", "explosive.satchel"
                }
                , 5, "npcraiders.nightmare", 100000, 1.0));
                SaveConfig();
            }
            if (configData.raidVipOptions == null) {
                configData.raidVipOptions = new ConfigData.RaidVipOptions();
                configData.raidVipOptions.VipOptions = new Dictionary<string, raidVip>();
                configData.raidVipOptions.VipOptions.Add("npcraiders.vip1", new raidVip(3600, 43200));
                configData.raidVipOptions.VipOptions.Add("npcraiders.vip2", new raidVip(3600, 43200));
                configData.raidVipOptions.VipOptions.Add("npcraiders.vip3", new raidVip(3600, 43200));
                SaveConfig();
            }
            timer.Every(10f, () => {
                if (EventList.Count <= 0) return;
                if (EventRaidManager._AllRaids.Count < configData.settings.MaxRaids) {
                    foreach (var key in EventList.ToList()) {
                        if (key.Key == null) {
                            EventList.Remove(key.Key);
                            continue;
                        }
                        if (key.Value.priv == null) {
                            if (key.Key != null) SendReply(key.Key, lang.GetMessage("TcWasAlreadyDestroyed", this, key.Key.UserIDString));
                            continue;
                        }
                        if (key.Key != null) SendReply(key.Key, lang.GetMessage("waitingToStart", this, key.Key.UserIDString));
                        timer.Once(59, () => startRaidForPlayer(key.Key, key.Value.location, key.Value.priv, key.Value.type));
                        EventList.Remove(key.Key);
                        break;
                    }
                }
            }
            );
            foreach (var perm in configData.raidSettings.raidTypes) {
                if (!String.IsNullOrEmpty(perm.Value.Permission) && !permission.PermissionExists(perm.Value.Permission, this)) permission.RegisterPermission(perm.Value.Permission, this);
            }
            //MLRS
            foreach (MLRS d in BaseNetworkable.serverEntities.Where(x => x is MLRS)) mlrs.Add(d);
            if (configData.raidVipOptions != null && configData.raidVipOptions.VipOptions.Count > 0) foreach (var perms in configData.raidVipOptions.VipOptions) if (!String.IsNullOrEmpty(perms.Key) && !permission.PermissionExists(perms.Key, this)) permission.RegisterPermission(perms.Key, this);
        }
        private void Unload() {
            foreach (var eventRunning in EventRaidManager._AllRaids) eventRunning.Destroy();
            EventRaidManager._AllRaids.Clear();
            _ = null;
            foreach (BasePlayer player in BasePlayer.activePlayerList.ToList()) {
                CuiHelper.DestroyUi(player, UIMain);
            }
        }
#endregion Loading
#region Data
        private void LoadData() {
            try {
                pcdData = Interface.GetMod().DataFileSystem.ReadObject<PlayerEntity>(Name + "/PlayerCooldowns");
            }
            catch {
                PrintWarning("Couldn't load Player data, creating new Playerfile");
                pcdData = new PlayerEntity();
            }
            try {
                statsData = Interface.GetMod().DataFileSystem.ReadObject<PlayerStats>(Name + "/PlayerStats");
            }
            catch {
                PrintWarning("Couldn't load Player stats, creating new Player stats file");
                statsData = new PlayerStats();
            }
        }
        public class PlayerEntity {
            public Dictionary<ulong, PCDInfo> pEntity = new Dictionary<ulong, PCDInfo>();
        }
        public class PCDInfo {
            public int total;
            public long cooldown;
            public Dictionary<uint, long> tcCooldown = new Dictionary<uint, long>();
        }
        public void SaveData() {
            PCDDATA.WriteObject(pcdData);
        }
        public class PlayerStats {
            public Dictionary<ulong, StatsInfo> pEntity = new Dictionary<ulong, StatsInfo>();
        }
        public class StatsInfo {
            public string name;
            public int played;
            public int lost;
            public int won;
            public int killed;
            public int deaths;
        }
        public void SaveStats() {
            STATSDATA.WriteObject(statsData);
        }
        public class LootEntity {
            public int MaxItems;
            public int MinItems;
            public List<itemInfo> items = new List<itemInfo>();
        }
        public class itemInfo {
            public string item;
            public ulong skin;
            public int amountMax;
            public int amountMin;
            public string location;
        }
        public static bool HasSaveFile(string id) => Interface.Oxide.DataFileSystem.ExistsDatafile(_.Name + "/LootProfiles/" + id);
        private static void SaveLootData<T>(T data, string filename = null) => Interface.Oxide.DataFileSystem.WriteObject(filename ?? _.Name, data);
        private static void LoadLootData<T>(out T data, string filename = null) => data = Interface.Oxide.DataFileSystem.ReadObject<T>(filename ?? _.Name);
#endregion Data
#region Config
        private ConfigData configData;
        class ConfigData {
            [JsonProperty(PropertyName = "Random settings")]
            public Settings settings {
                get;
                set;
            }
            [JsonProperty(PropertyName = "All Raid Types")]
            public RaidSettings raidSettings {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Raid Buy Options")]
            public RaidBuyOptions raidBuyOptions {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Raid Reward Options")]
            public RaidRewardOptions raidRewardOptions {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Raid Vip Options")]
            public RaidVipOptions raidVipOptions {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Block raid in colider")]
            public BlockedColliders blockedColliders {
                get;
                set;
            }
            public class Settings {
                [JsonProperty(PropertyName = "Chat command")]
                public string chatcommand {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "The Maxum amount of raid events that can go on at once")]
                public int MaxRaids {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "Cooldown before you can call in another raid")]
                public int cooldownSeconds {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "Cooldown after authorising on a tc be for you can start a raid")]
                public int TcAuthCooldown {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "The maxum amount of time a rocket will fly before exploding")]
                public float RocketExplodeTime {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "Limit the damage to players building")]
                public bool DamagePlayerBuilding {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "Npc spawn damage delay")]
                public float damageDelay {
                    get;
                    set;
                }
                [JsonProperty(PropertyName = "Log raidme buy chat command")]
                public bool logToFile {
                    get;
                    set;
                }
            }
            public class RaidSettings {
                [JsonProperty(PropertyName = "Raid types must be in lowercase")]
                public Dictionary<string, raidConfig> raidTypes {
                    get;
                    set;
                }
            }
            public class RaidBuyOptions {
                public Dictionary<string, raidBuy> BuyOptions {
                    get;
                    set;
                }
            }
            public class RaidRewardOptions {
                public Dictionary<string, raidReward> RewardOptions {
                    get;
                    set;
                }
            }
            public class RaidVipOptions {
                public Dictionary<string, raidVip> VipOptions {
                    get;
                    set;
                }
            }
            public class BlockedColliders {
                public List<string> Blocked {
                    get;
                    set;
                }
            }
            public Oxide.Core.VersionNumber Version {
                get;
                set;
            }
        }
        protected override void LoadConfig() {
            base.LoadConfig();
            configData = Config.ReadObject<ConfigData>();
            if (configData.Version < Version) UpdateConfigValues();
            Config.WriteObject(configData, true);
        }
        protected override void LoadDefaultConfig() => configData = GetBaseConfig();
        private ConfigData GetBaseConfig() {
            return new ConfigData {
                settings = new ConfigData.Settings {
                    chatcommand = "raidme", MaxRaids = 6, cooldownSeconds = 3600, TcAuthCooldown = 86400, RocketExplodeTime = 4.0f, DamagePlayerBuilding = false, damageDelay = 2f, logToFile = false
                }
                , raidSettings = new ConfigData.RaidSettings {
                    raidTypes = new Dictionary<string, raidConfig>()
                }
                , raidBuyOptions = new ConfigData.RaidBuyOptions {
                    BuyOptions = new Dictionary<string, raidBuy>()
                }
                , raidRewardOptions = new ConfigData.RaidRewardOptions {
                    RewardOptions = new Dictionary<string, raidReward>()
                }
                , raidVipOptions = new ConfigData.RaidVipOptions {
                    VipOptions = new Dictionary<string, raidVip>()
                }
                , blockedColliders = new ConfigData.BlockedColliders {
                    Blocked = new List<string>() {
                        "iceberg", "ice_berg", "ice_sheet", "icesheet"
                    }
                }
                , Version = Version
            }
            ;
        }
        protected override void SaveConfig() => Config.WriteObject(configData, true);
        private void UpdateConfigValues() {
            PrintWarning("Version update detected!");
            ConfigData baseConfig = GetBaseConfig();
            if (configData.Version < new VersionNumber(1, 0, 0)) {
                configData = baseConfig;
                PrintWarning("Config update was needed and now completed!");
            }
            configData.Version = Version;
            PrintWarning("Version update completed!");
        }
        public class raidConfig {
            [JsonProperty(PropertyName = "The Permission")]
            public string Permission;
            [JsonProperty(PropertyName = "Total npcs per wave")]
            public int TotalNpcs;
            [JsonProperty(PropertyName = "How many extra waves")]
            public int TotalNpcWaves;
            [JsonProperty(PropertyName = "Seconds untell next wave")]
            public int NextWaveSeconds;
            [JsonProperty(PropertyName = "Npc fires Mlrs at base")]
            public bool FireMlrs;
            [JsonProperty(PropertyName = "Total event time in seconds")]
            public int RunTimeSeconds;
            [JsonProperty(PropertyName = "Block event players from repairing")]
            public bool canNotRepair;
            [JsonProperty(PropertyName = "Npc drop loot on death")]
            public bool NpcDropLoot;
            [JsonProperty(PropertyName = "Npc drop loot config names")]
            public List<string> NpcDropLootConfig;
            [JsonProperty(PropertyName = "Spawn health of the npc")]
            public float Health;
            [JsonProperty(PropertyName = "Rocket damage scale")]
            public double DamageScale;
            [JsonProperty(PropertyName = "Player damage scale from npc")]
            public float playerDamage;
            [JsonProperty(PropertyName = "Auto turret damage scale to npc")]
            public float AutoTurretDamage;
            [JsonProperty(PropertyName = "External Tc Scan Range")]
            public float ExternalTcRange;
            [JsonProperty(PropertyName = "Explosive item shortnames")]
            public List<string> explosive;
            [JsonProperty(PropertyName = "Names to give the npcs")]
            public List<string> NpcNames;
            [JsonProperty(PropertyName = "Spawn kits for the npcs")]
            public List<string> kits;
            public raidConfig(int TotalNpcs, bool OnlyAuthedMembers, float Health, int RunTimeSeconds, List<string> kits, List<string> explosive, int waves, string perms, int reward, double damage) {
                this.TotalNpcs = TotalNpcs;
                this.NpcDropLoot = OnlyAuthedMembers;
                this.Health = Health;
                this.kits = kits;
                this.RunTimeSeconds = RunTimeSeconds;
                this.explosive = explosive;
                this.TotalNpcWaves = waves;
                this.NextWaveSeconds = 120;
                this.Permission = perms;
                this.NpcNames = new List<string>() {
                    "Cobalt Scientist"
                }
                ;
                this.DamageScale = damage;
                this.AutoTurretDamage = 1.0f;
                this.NpcDropLootConfig = new List<string>();
                this.FireMlrs = false;
                this.canNotRepair = false;
                this.playerDamage = 1.0f;
                this.ExternalTcRange = 150f;
            }
        }
        public class raidBuy {
            public string BuyType;
            public object BuyAmmount;
            public raidBuy(string thetipe, object needed) {
                this.BuyType = thetipe;
                this.BuyAmmount = needed;
            }
        }
        public class raidReward {
            public bool enabled;
            public bool rewardAll;
            public string RewardType;
            public object RewardAmmount;
            public raidReward(string thetipe, object needed) {
                this.enabled = false;
                this.rewardAll = false;
                this.RewardType = thetipe;
                this.RewardAmmount = needed;
            }
        }
        public class raidVip {
            public int cooldownSeconds;
            public int TcAuthCooldown;
            public raidVip(int cool, int tcCool) {
                this.cooldownSeconds = cool;
                this.TcAuthCooldown = tcCool;
            }
        }
#endregion Config
#region Event
        public class RaidThinkManager : MonoBehaviour {
            EventRaidManager RM {
                get;
                set;
            }
            public void Setup(EventRaidManager R) {
                RM = R;
            }
            public void Update() {
                if (RM != null && !RM.isDestroyed) RM.update();
                else if (this.gameObject != null) Destroy(this);
            }
        }
        public class EventRaidManager {
            internal static List<EventRaidManager> _AllRaids = new List<EventRaidManager>();
            internal static List<ulong> _AllPlayers = new List<ulong>();
            internal static List<NpcRaider> _AllMembers = new List<NpcRaider>();
            internal static bool isFireingMlrs;
            internal List<NpcRaider> members;
            internal List<ulong> authorizedPlayers;
            internal bool isDestroyed = false;
            internal Vector3 location;
            internal raidConfig config;
            internal string waveType;
            internal BasePlayer player;
            internal ulong playerID;
            internal BuildingPrivlidge priv;
            internal bool newWave;
            internal Coroutine QueuedRoutine;
            internal BuildingPrivlidge building;
            internal BaseCombatEntity tc;
            internal RaidThinkManager timerObject;
            internal float EndEventTime;
            internal float nextWaveTime = 0;
            internal int totalWaves = 0;
            internal float MlrsEventTime;
            internal bool active = false;
            internal int totalCopters = 3;
            internal GameObject thetimerObject;
            internal static EventRaidManager Create(BasePlayer p, ulong id, Vector3 l, raidConfig c, string t, RaidThinkManager timer, BuildingPrivlidge pr, GameObject gobj) {
                EventRaidManager manager = new EventRaidManager {
                    members = Pool.GetList<NpcRaider>(), authorizedPlayers = Pool.GetList<ulong>(), newWave = true, config = c, waveType = t, player = p, playerID = id, location = l, timerObject = timer, building = pr, thetimerObject = gobj
                }
                ;
                _AllRaids.Add(manager);
                return manager;
            }
            internal void Start() {
                Interface.Oxide.CallHook("NpcRaidersEventStart", player, playerID, waveType, location, this);
                MlrsEventTime = Time.time + UnityEngine.Random.Range(15f, 30f);
                EndEventTime = Time.time + config.RunTimeSeconds;
                nextWaveTime = Time.time + 3800;
                if (building != null) foreach (var user in building.authorizedPlayers.ToList()) {
                    if (!authorizedPlayers.Contains(user.userid)) authorizedPlayers.Add(user.userid);
                    if (config.canNotRepair && !_AllPlayers.Contains(user.userid)) _AllPlayers.Add(user.userid);
                }
                QueuedRoutine = ServerMgr.Instance.StartCoroutine(GenerateEventMembers());
            }
            // Thanks to HellFire on UMOD
            internal static void setupMlrs(EventRaidManager man) {
                if (isFireingMlrs || man == null || man.building == null) return;
                _.timer.Repeat(0.5f, 6, () => {
                    if (man == null || man.building == null) return;
                    float baseGravity;
                    Vector3 posUP = man.building.transform.position;
                    posUP.y = posUP.y + 240f;
                    Vector3 posFire = new Vector3(man.building.transform.position.x + UnityEngine.Random.Range(-10.0f, 10.0f), man.building.transform.position.y, man.building.transform.position.z + UnityEngine.Random.Range(-10.0f, 10.0f));
                    Vector3 aimToTarget = GetAimToTarget(posUP, man.building.transform.position, out baseGravity);
                    var startPoint = posUP;
                    startPoint.y += 15f;
                    ServerProjectile projectile;
                    if (CreateAndSpawnRocket(startPoint, aimToTarget, out projectile) == false) return;
                    TimedExplosive component = projectile.GetComponent<TimedExplosive>();
                    component.creatorEntity = man.player;
                    projectile.gravityModifier = baseGravity / (0f - Physics.gravity.y);
                }
                );
            }
            internal static Vector3 GetAimToTarget(Vector3 startPosition, Vector3 targetPos, out float baseGravity) {
                Vector3 vector = targetPos - startPosition;
                float num = 90f;
                float num2 = vector.Magnitude2D();
                float y = vector.y;
                float num5 = 40f;
                baseGravity = MLRS.ProjectileDistToGravity(Mathf.Max(num2, 50f), y, num5, num);
                vector.Normalize();
                vector.y = 0f;
                Vector3 axis = Vector3.Cross(vector, Vector3.up);
                vector = Quaternion.AngleAxis(num5, axis) * vector;
                return vector;
            }
            internal static bool CreateAndSpawnRocket(Vector3 firingPos, Vector3 firingDir, out ServerProjectile mlrsRocketProjectile) {
                RaycastHit hitInfo;
                float launchOffset = 0f;
                if (Physics.Raycast(firingPos, firingDir, out hitInfo, launchOffset, 1236478737)) launchOffset = hitInfo.distance - 0.1f;
                var mlrsRocketEntity = GameManager.server.CreateEntity("assets/content/vehicles/mlrs/rocket_mlrs.prefab", firingPos + firingDir * launchOffset);
                if (mlrsRocketEntity == null) {
                    mlrsRocketProjectile = null;
                    return false;
                }
                mlrsRocketProjectile = mlrsRocketEntity.GetComponent<ServerProjectile>();
                var velocityVector = mlrsRocketProjectile.initialVelocity + firingDir * mlrsRocketProjectile.speed;
                mlrsRocketProjectile.InitializeVelocity(velocityVector);
                var mlrsRocket = mlrsRocketEntity as MLRSRocket;
                if (mlrsRocket == null) return false;
                ExecuteMLRSRocketModfications(ref mlrsRocket);
                mlrsRocket.Spawn();
                return true;
            }
            internal static void ExecuteMLRSRocketModfications(ref MLRSRocket mlrsRocket) {
                // mlrsRocket.explosionRadius *= mConfig.HellfireRocketExplosiveRadiusModifier;
                //mlrsRocket.damageTypes = GetDamageOfHellfireRocket(mlrsRocket).damageTypes;
            }
            internal void update() {
                ulong id = 0UL;
                if (isDestroyed || !active) return;
                if (EndEventTime < Time.time) {
                    Destroy();
                    return;
                }
                if (config.FireMlrs && MlrsEventTime < Time.time && !EventRaidManager.isFireingMlrs && MlrsEventTime != 0) {
                    MlrsEventTime = 0;
                    setupMlrs(this);
                }
                if (config.TotalNpcWaves > 0 && totalWaves <= config.TotalNpcWaves && nextWaveTime < Time.time) {
                    nextWaveTime = Time.time + config.NextWaveSeconds;
                    if (QueuedRoutine != null) stopSpawning();
                    QueuedRoutine = ServerMgr.Instance.StartCoroutine(GenerateEventMembers());
                    return;
                }
                if ((totalWaves - 1) == config.TotalNpcWaves && members.Count <= 0) {
                    Destroy(true);
                    return;
                }
                if ((totalWaves - 1) < config.TotalNpcWaves) {
                    if (!notify && (nextWaveTime - Time.time) <= 30) {
                        notify = true;
                        notifyWaveTime = totalWaves;
                        notifyWave();
                    }
                    else if (!notify60 && (nextWaveTime - Time.time) <= 60 ) {
                        notify60 = true;
                        notifyWaveTime = totalWaves;
                        notifyWave();
                    }
                    else if (notifyWaveTime != totalWaves && members.Count <= 0) {
                        notifyWaveTime = totalWaves;
                        notifyWave();
                    }
                }
                if (!notifyEnd && (EndEventTime - 60) <= Time.time) {
                    notifyEnd = true;
                    string EndTime = _.FormatTime((long)(EndEventTime - Time.time));
                    for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                        id = authorizedPlayers[i];
                        if (id != 0UL) {
                            BasePlayer TCplayer = BasePlayer.FindByID(id);
                            if (TCplayer != null) _.SendReply(TCplayer, _.lang.GetMessage("EventEndINTime", _, player.UserIDString), EndTime);
                        }
                    }
                }
                else if (!notifyEnd1 && (EndEventTime - 30) <= Time.time) {
                    notifyEnd1 = true;
                    string EndTime = _.FormatTime((long)(EndEventTime - Time.time));
                    for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                        id = authorizedPlayers[i];
                        if (id != 0UL) {
                            BasePlayer TCplayer = BasePlayer.FindByID(id);
                            if (TCplayer != null) _.SendReply(TCplayer, _.lang.GetMessage("EventEndINTime", _, player.UserIDString), EndTime);
                        }
                    }
                }
            }
            internal bool notify {
                get;
                set;
            }
            internal bool notify60 {
                get;
                set;
            }
            internal bool notifyEnd {
                get;
                set;
            }
            internal bool notifyEnd1 {
                get;
                set;
            }
            internal int notifyWaveTime = 0;
            internal void notifyWave() {
                ulong id = 0UL;
                string waveWaitTime = _.FormatTime((long)(nextWaveTime - Time.time));
                for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                    id = authorizedPlayers[i];
                    if (id != 0UL) {
                        BasePlayer TCplayer = BasePlayer.FindByID(id);
                        if (TCplayer != null) _.SendReply(TCplayer, _.lang.GetMessage("ArivalTimeNext", _, player.UserIDString), config.TotalNpcWaves + 1, totalWaves + 1, waveWaitTime);
                    }
                }
            }
            internal void RemoveNpc(NpcRaider player) {
                if (members != null && members.Contains(player)) members.Remove(player);
                if (_AllMembers != null && _AllMembers.Contains(player)) _AllMembers.Remove(player);
            }
            internal void Destroy(bool win = false) {
                if (isDestroyed) return;
                ulong id = 0UL;
                active = false;
                isDestroyed = true;
                MlrsEventTime = 1;
                Interface.Oxide.CallHook("NpcRaidersEventEnd", player, playerID, waveType, location);
                stopSpawning();
                for (int i = members.Count - 1; i >= 0; i--) {
                    NpcRaider npc = members[i];
                    if (npc != null && !npc.IsDestroyed && !npc.isMounted) {
                        npc.Kill();
                    }
                }
                for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                    id = authorizedPlayers[i];
                    if (id != 0UL) {
                        BasePlayer TCplayer = BasePlayer.FindByID(id);
                        if (TCplayer != null) {
                            if (win) {
                                _.SendReply(TCplayer, _.lang.GetMessage("eventOverWin", _, TCplayer.UserIDString));
                                if (!_.statsData.pEntity.ContainsKey(id)) _.statsData.pEntity.Add(id, new StatsInfo() {
                                    name = TCplayer.displayName
                                }
                                );
                                _.statsData.pEntity[id].played++;
                                _.statsData.pEntity[id].won++;
                                _.SaveStats();
                            }
                            else {
                                _.SendReply(TCplayer, _.lang.GetMessage("eventOver", _, TCplayer.UserIDString));
                                if (!_.statsData.pEntity.ContainsKey(id)) _.statsData.pEntity.Add(id, new StatsInfo() {
                                    name = TCplayer.displayName
                                }
                                );
                                _.statsData.pEntity[id].played++;
                                _.statsData.pEntity[id].lost++;
                                _.SaveStats();
                            }
                        }
                    }
                }
                if (win && player != null) {
                    if (_.configData.raidRewardOptions.RewardOptions.ContainsKey(waveType)) {
                        rewardPlayers(_.configData.raidRewardOptions.RewardOptions[waveType]);
                    }
                }
                foreach (ulong privey in authorizedPlayers.ToList()) {
                    if (_AllPlayers.Contains(privey)) _AllPlayers.Remove(privey);
                }
                if (thetimerObject != null) {
                    UnityEngine.GameObject.DestroyImmediate(thetimerObject, true);
                }
                _.NextTick(() => {
                    members.Clear();
                    Pool.FreeList(ref members);
                    authorizedPlayers.Clear();
                    Pool.FreeList(ref authorizedPlayers);
                    _AllRaids.Remove(this);
                }
                );
            }
            internal void rewardPlayers(raidReward reward) {
                ItemDefinition def = null;
                var ids = default(int);
                object totals = reward.RewardAmmount;
                List<string> kitList = new List<string>();
                if (int.TryParse(reward.RewardType, out ids)) {
                    def = ItemManager.FindItemDefinition(ids);
                }
                if (def != null) {
                    if (reward.rewardAll) {
                        foreach (var playerid in authorizedPlayers.ToList()) {
                            BasePlayer RewardPlayer = BasePlayer.FindAwakeOrSleeping(playerid.ToString());
                            if (RewardPlayer == null || !RewardPlayer.IsConnected) continue;
                            giveItem(RewardPlayer, ids, Convert.ToInt32(totals));
                            _.SendReply(RewardPlayer, String.Format(_.lang.GetMessage("RewardedItem", _), Convert.ToInt32(totals), def.displayName.english));
                        }
                    }
                    else if (player != null) {
                        giveItem(player, ids, Convert.ToInt32(totals));
                        _.SendReply(player, String.Format(_.lang.GetMessage("RewardedItem", _), Convert.ToInt32(totals), def.displayName.english));
                    }
                }
                else if (def == null) {
                    int totalPlayers = 0;
                    List<BasePlayer> onlinePlayer = new List<BasePlayer>();
                    object totalsSplit = 0;
                    foreach (var playerid in authorizedPlayers.ToList()) {
                        BasePlayer RewardPlayer = BasePlayer.FindAwakeOrSleeping(playerid.ToString());
                        if (RewardPlayer == null || !RewardPlayer.IsConnected) continue;
                        totalPlayers++;
                        onlinePlayer.Add(RewardPlayer);
                    }
                    if (reward.rewardAll && totalPlayers > 1) {
                        foreach (var RewardPlayer in onlinePlayer.ToList()) {
                            if (RewardPlayer == null || !RewardPlayer.IsConnected) continue;
                            if (reward.RewardType.ToLower() == "serverrewards") {
                                totalsSplit = ((Convert.ToInt32(totals)) / totalPlayers);
                                _.ServerRewards?.Call("AddPoints", RewardPlayer.userID, Convert.ToInt32(totalsSplit));
                                _.SendReply(RewardPlayer, String.Format(_.lang.GetMessage("MoneyIssued", _), Convert.ToInt32(totalsSplit), RewardPlayer.displayName));
                            }
                            else if (reward.RewardType.ToLower() == "economics") {
                                totalsSplit = ((Convert.ToInt32(totals)) / totalPlayers);
                                _.Economics?.Call("Deposit", RewardPlayer.userID, Convert.ToDouble(totalsSplit));
                                _.SendReply(RewardPlayer, String.Format(_.lang.GetMessage("MoneyIssued", _), Convert.ToDouble(totalsSplit), RewardPlayer.displayName));
                            }
                            else if (reward.RewardType.ToLower() == "kits" || reward.RewardType.ToLower() == "kit") {
                                kitList = getObjects(totals);
                                if (totals is string) {
                                    if (!string.IsNullOrEmpty(Convert.ToString(totals))) {
                                        object success = _.Kits?.Call("GiveKit", RewardPlayer, Convert.ToString(totals));
                                        if (success == null) _.PrintWarning($"Unable to find a kit with the name {Convert.ToString(totals)}");
                                        else if (success is string) {
                                            _.SendReply(RewardPlayer, (string)success, _);
                                            _.PrintWarning($"Ops {(string)success}");
                                        }
                                    }
                                    else _.PrintWarning($"Invalid kitname in RewardAmmount");
                                }
                                else if (kitList != null) {
                                    if (kitList.Count <= 0) continue;
                                    string rand = kitList.GetRandom();
                                    object success = _.Kits?.Call("GiveKit", RewardPlayer, rand);
                                    if (success == null) _.PrintWarning($"Unable to find a kit with the name {rand}");
                                    else if (success is string) {
                                        _.SendReply(RewardPlayer, (string)success, _);
                                        _.PrintWarning($"Ops {(string)success}");
                                    }
                                }
                            }
                        }
                    }
                    else {
                        if (player != null) {
                            if (reward.RewardType.ToLower() == "serverrewards") {
                                _.ServerRewards?.Call("AddPoints", player.userID, Convert.ToInt32(totals));
                                _.SendReply(player, String.Format(_.lang.GetMessage("MoneyIssued", _), Convert.ToInt32(totals), player.displayName));
                            }
                            else if (reward.RewardType.ToLower() == "economics") {
                                _.Economics?.Call("Deposit", player.userID, Convert.ToDouble(totals));
                                _.SendReply(player, String.Format(_.lang.GetMessage("MoneyIssued", _), Convert.ToDouble(totals), player.displayName));
                            }
                            else if (reward.RewardType.ToLower() == "kits" || reward.RewardType.ToLower() == "kit") {
                                kitList = getObjects(totals);
                                if (totals is string) {
                                    if (!string.IsNullOrEmpty(Convert.ToString(totals))) {
                                        object success = _.Kits?.Call("GiveKit", player, Convert.ToString(totals));
                                        if (success == null) _.PrintWarning($"Unable to find a kit with the name {Convert.ToString(totals)}");
                                        else if (success is string) {
                                            _.SendReply(player, (string)success, _);
                                            _.PrintWarning($"Ops {(string)success}");
                                        }
                                    }
                                    else _.PrintWarning($"Invalid kitname in RewardAmmount");
                                }
                                else if (kitList != null && kitList.Count > 0) {
                                    if (kitList.Count <= 0) return;
                                    string rand = kitList.GetRandom();
                                    object success = _.Kits?.Call("GiveKit", player, rand);
                                    if (success == null) _.PrintWarning($"Unable to find a kit with the name {rand}");
                                    else if (success is string) {
                                        _.SendReply(player, (string)success, _);
                                        _.PrintWarning($"Ops {(string)success}");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            private List<string> getObjects(object name) {
                List<string> kitObject = new List<string>();
                if (name is string || name is int || name is float) return kitObject;
                var json = JsonConvert.SerializeObject(name);
                if (json != null) kitObject = JsonConvert.DeserializeObject<List<string>>(json) as List<string>;
                return kitObject;
            }
            internal static void giveItem(BasePlayer RPlayer, int itemID, int total) {
                var item = ItemManager.CreateByItemID(itemID, total, 0);
                if (item == null) return;
                if (item.MoveToContainer(RPlayer.inventory.containerBelt, -1, true)) return;
                else if (item.MoveToContainer(RPlayer.inventory.containerMain, -1, true)) return;
                Vector3 velocity = Vector3.zero;
                item.Drop(RPlayer.transform.position + new Vector3(0.5f, 1f, 0), velocity);
                _.SendReply(RPlayer, _.lang.GetMessage("RewardDropedOnGround", _));
            }
            internal void stopSpawning() {
                if (QueuedRoutine != null) ServerMgr.Instance.StopCoroutine(QueuedRoutine);
                QueuedRoutine = null;
                float newTime = config.NextWaveSeconds + (config.TotalNpcs * 0.1f) + 12f;
                nextWaveTime = Time.time + newTime;
                totalWaves++;
                notify = false;
                notify60 = false;
            }
            internal NpcRaider hookSpawnMember(Vector3 position, bool mounted = false, bool driver = false) {
                NpcRaider theNewGuy = SpawnNPC(position);
                if (theNewGuy != null) {
                    members.Add(theNewGuy);
                    return theNewGuy;
                }
                return null;
            }
            internal IEnumerator GenerateEventMembers() {
                Interface.Oxide.CallHook("NpcRaidersGenerateEventMembers", player, playerID, waveType, totalWaves, location, this);
                ulong id = 0UL;
                if (newWave) {
                    for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                        id = authorizedPlayers[i];
                        if (id != 0UL) {
                            BasePlayer TCplayer = BasePlayer.FindByID(id);
                            if (TCplayer != null && TCplayer.IsConnected) _.SendReply(TCplayer, _.lang.GetMessage("start", _, player.UserIDString));
                        }
                    }
                    _.PrintWarning($"EventStarted for {player.displayName}");
                }
                else {
                    for (int i = authorizedPlayers.Count - 1; i >= 0; i--) {
                        id = authorizedPlayers[i];
                        if (id != 0UL) {
                            BasePlayer TCplayer = BasePlayer.FindByID(id);
                            if (TCplayer != null && TCplayer.IsConnected) {
                                _.SendReply(TCplayer, _.lang.GetMessage("nextWave", _, TCplayer.UserIDString));
                                if (!_.statsData.pEntity.ContainsKey(id)) _.statsData.pEntity.Add(id, new StatsInfo() {
                                    name = TCplayer.displayName
                                }
                                );
                                _.statsData.pEntity[id].played++;
                            }
                        }
                    }
                    _.SaveStats();
                }
                newWave = false;
                int totalNpc = 0;
                float spawnDictance = 40;
                if (config == null) {
                    stopSpawning();
                }
                List<Vector3> positions = generateSpawnList(location, spawnDict
// ... [Code preview truncated due to length. Full source in attached file] ...

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