Exemple #1
0
        private void SpawnSmallerMeteors()
        {
            if (!this.m_CanSubDivide || this.m_Meteor.InstantlyKilled)
            {
                return;
            }
            this.m_CanSubDivide = false;
            Random     random             = new Random();
            Vector3    forward            = this.m_Target != null ? this.m_Target.Parameters.Position - this.m_Meteor.Maneuvering.Position : this.m_TargetPosition - this.m_Meteor.Maneuvering.Position;
            double     num1               = (double)forward.Normalize();
            Matrix     world              = Matrix.CreateWorld(this.m_Meteor.Maneuvering.Position, forward, Vector3.UnitY);
            Sphere     shipSphere         = this.m_Meteor.ShipSphere;
            int        numBreakoffMeteors = this.m_Game.AssetDatabase.GlobalMeteorShowerData.NumBreakoffMeteors;
            float      radians            = MathHelper.DegreesToRadians(30f);
            List <int> subMeteorDesignIds = MeteorCombatAIControl.GetAvailableSubMeteorDesignIDs(this.m_Game, this.m_Size);

            if (subMeteorDesignIds.Count <= 0)
            {
                return;
            }
            for (int index = 0; index < numBreakoffMeteors; ++index)
            {
                Vector3 vector3 = new Vector3();
                vector3.X = (random.CoinToss(0.5) ? -1f : 1f) * random.NextInclusive(10f, 85f);
                vector3.Y = (random.CoinToss(0.5) ? -1f : 1f) * random.NextInclusive(10f, 85f);
                vector3.Z = (random.CoinToss(0.5) ? -1f : 1f) * random.NextInclusive(10f, 85f);
                double num2 = (double)vector3.Normalize();
                vector3 *= random.NextInclusive(shipSphere.radius * 0.1f, shipSphere.radius);
                Matrix worldMat = Matrix.PolarDeviation(random, radians);
                worldMat.Position = vector3;
                worldMat         *= world;
                int designId = subMeteorDesignIds[random.NextInclusive(0, subMeteorDesignIds.Count - 1)];
                this.m_Game.CurrentState.AddGameObject((IGameObject)CombatAIController.CreateNewShip(this.m_Game.Game, worldMat, designId, 0, this.m_Meteor.InputID, this.m_Meteor.Player.ObjectID), true);
            }
        }
Exemple #2
0
        public void CoinToss()
        {
            // Type
            var @this = new Random();

            // Examples
            bool value = @this.CoinToss(); // return true or false at random.
        }
        public void CoinTossTest()
        {
            var random = new Random();
            var actual = random.CoinToss();

            actual.Should()
            .Be(actual);
        }
Exemple #4
0
        private static void demoRandomExtensions()
        {
            Random rand = new Random();

            bool luckyDay = rand.CoinToss();

            luckyDay.ToString().DebugLog();

            string iLike = rand.OneOf("C#", "VB.NET", "BASTA!");

            "I like {0}".With(iLike).DebugLog();
        }
Exemple #5
0
        public static void AddSuperNovas(GameSession game, GameDatabase gamedb, AssetDatabase assetdb)
        {
            if (!gamedb.HasEndOfFleshExpansion() || game.ScriptModules.SuperNova == null || gamedb.GetTurnCount() < assetdb.GlobalSuperNovaData.MinTurns)
            {
                return;
            }
            string nameValue1 = game.GameDatabase.GetNameValue("GMCount");

            if (string.IsNullOrEmpty(nameValue1))
            {
                game.GameDatabase.InsertNameValuePair("GMCount", "0");
                nameValue1 = game.GameDatabase.GetNameValue("GMCount");
            }
            int nameValue2 = game.GameDatabase.GetNameValue <int>("GSGrandMenaceCount");
            int num1       = int.Parse(nameValue1);

            if (num1 >= nameValue2)
            {
                return;
            }
            Random safeRandom = App.GetSafeRandom();

            if (!safeRandom.CoinToss(assetdb.GlobalSuperNovaData.Chance))
            {
                return;
            }
            List <StarSystemInfo> list1   = gamedb.GetStarSystemInfos().ToList <StarSystemInfo>();
            List <SuperNovaInfo>  list2   = gamedb.GetSuperNovaInfos().ToList <SuperNovaInfo>();
            List <int>            intList = new List <int>();

            foreach (StarSystemInfo starSystemInfo in list1)
            {
                StarSystemInfo ssi          = starSystemInfo;
                StellarClass   stellarClass = new StellarClass(ssi.StellarClass);
                if ((stellarClass.Type == StellarType.O || stellarClass.Type == StellarType.B) && !list2.Any <SuperNovaInfo>((Func <SuperNovaInfo, bool>)(x => x.SystemId == ssi.ID)))
                {
                    intList.Add(ssi.ID);
                }
            }
            if (intList.Count <= 0)
            {
                return;
            }
            game.ScriptModules.SuperNova.AddInstance(gamedb, assetdb, safeRandom.Choose <int>((IList <int>)intList));
            int num2;

            game.GameDatabase.UpdateNameValuePair("GMCount", (num2 = num1 + 1).ToString());
        }
Exemple #6
0
        private void FindSafestNodeIndex()
        {
            int[] numArray = new int[this.m_NumEvadeNodes];
            for (int index = 0; index < this.m_NumEvadeNodes; ++index)
            {
                foreach (Ship enemy in this.m_Enemies)
                {
                    if ((double)(enemy.Position - this.m_EvadeLocations[index]).LengthSquared < 25000000.0)
                    {
                        ++numArray[index];
                    }
                }
            }
            if (numArray[this.m_CurrEvadeNodeIndex] == 0)
            {
                return;
            }
            Random random = new Random();
            int    index1 = this.m_CurrEvadeNodeIndex - 1;
            int    index2 = this.m_CurrEvadeNodeIndex + 1;
            int    num1   = this.m_NumEvadeNodes / 2;
            bool   flag   = false;

            for (int index3 = 0; index3 < num1; ++index3)
            {
                if (index1 < 0)
                {
                    index1 = this.m_NumEvadeNodes - 1;
                }
                if (index2 >= this.m_NumEvadeNodes)
                {
                    index2 = 0;
                }
                if (numArray[index1] == 0 && numArray[index2] == 0)
                {
                    this.m_CurrEvadeNodeIndex = random.CoinToss(0.5) ? index1 : index2;
                    flag = true;
                    break;
                }
                if (numArray[index1] == 0)
                {
                    this.m_CurrEvadeNodeIndex = index1;
                    flag = true;
                    break;
                }
                if (numArray[index2] == 0)
                {
                    this.m_CurrEvadeNodeIndex = index2;
                    flag = true;
                    break;
                }
                ++index2;
                --index1;
            }
            if (flag)
            {
                return;
            }
            int   num2 = 500;
            float num3 = float.MaxValue;

            for (int index3 = 0; index3 < this.m_NumEvadeNodes; ++index3)
            {
                float lengthSquared = (this.m_EvadeLocations[index3] - this.m_SwarmerQueenLarva.Position).LengthSquared;
                if (num2 == numArray[index3] && (double)lengthSquared < (double)num3 || num2 < numArray[index3])
                {
                    num3 = lengthSquared;
                    num2 = numArray[index3];
                    this.m_CurrEvadeNodeIndex = index3;
                }
            }
        }
Exemple #7
0
        private static void UpdateShipsKilled(
            GameSession game,
            Random rand,
            Dictionary <FleetInfo, List <ShipInfo> > aiPlayerShips,
            int randomsPlayerID,
            int numToKill)
        {
            int num1 = numToKill;

            for (int index = 0; index < numToKill && num1 > 0 && aiPlayerShips.Keys.Count > 0; ++index)
            {
                bool flag = false;
                while (!flag && aiPlayerShips.Keys.Count > 0)
                {
                    int num2 = 0;
                    foreach (KeyValuePair <FleetInfo, List <ShipInfo> > aiPlayerShip in aiPlayerShips)
                    {
                        num2 += aiPlayerShip.Value.Count;
                        foreach (ShipInfo shipInfo in aiPlayerShip.Value)
                        {
                            ShipInfo ship = shipInfo;
                            if (rand.CoinToss(50))
                            {
                                num1 -= CombatAI.GetShipStrength(ship.DesignInfo.Class) / 3;
                                if (ship.DesignInfo.IsSuulka())
                                {
                                    TurnEvent turnEvent = game.GameDatabase.GetTurnEventsByTurnNumber(game.GameDatabase.GetTurnCount(), aiPlayerShip.Key.PlayerID).FirstOrDefault <TurnEvent>((Func <TurnEvent, bool>)(x => x.ShipID == ship.ID));
                                    if (turnEvent != null)
                                    {
                                        game.GameDatabase.RemoveTurnEvent(turnEvent.ID);
                                    }
                                    game.GameDatabase.InsertTurnEvent(new TurnEvent()
                                    {
                                        EventType    = TurnEventType.EV_SUULKA_DIES,
                                        EventMessage = TurnEventMessage.EM_SUULKA_DIES,
                                        PlayerID     = randomsPlayerID,
                                        SystemID     = aiPlayerShip.Key.SystemID,
                                        ShipID       = ship.ID,
                                        DesignID     = ship.DesignID,
                                        TurnNumber   = game.GameDatabase.GetTurnCount(),
                                        ShowsDialog  = false
                                    });
                                    SuulkaInfo suulkaByShipId = game.GameDatabase.GetSuulkaByShipID(ship.ID);
                                    if (suulkaByShipId != null)
                                    {
                                        game.GameDatabase.RemoveSuulka(suulkaByShipId.ID);
                                    }
                                }
                                game.GameDatabase.RemoveShip(ship.ID);
                                aiPlayerShip.Value.Remove(ship);
                                flag = true;
                                break;
                            }
                        }
                        if (flag)
                        {
                            if (aiPlayerShip.Value.Count == 0)
                            {
                                CombatSimulatorRandoms.FleetDestroyed(game, randomsPlayerID, aiPlayerShip.Key, (ShipInfo)null);
                                game.GameDatabase.RemoveFleet(aiPlayerShip.Key.ID);
                                aiPlayerShips.Remove(aiPlayerShip.Key);
                                break;
                            }
                            break;
                        }
                    }
                    if (num2 == 0)
                    {
                        break;
                    }
                }
            }
            foreach (KeyValuePair <FleetInfo, List <ShipInfo> > aiPlayerShip in aiPlayerShips)
            {
                if (aiPlayerShip.Value.Count > 0)
                {
                    CombatSimulatorRandoms.CheckFleetCommandPoints(game, aiPlayerShip.Key, aiPlayerShip.Value);
                }
            }
        }
Exemple #8
0
        /// <summary>
        ///       Generates a random logical filename based on the given directory
        /// </summary>
        /// <param name="base">The directory to sample for generation</param>
        public static FileInfo Generate(DirectoryInfo @base)
        {
            if (@base.Exists == false)   //for nonexisting
            {
                @base.EnsureDirectoryExists();
                return(Generate(@base)); //create and retry
            }

            DirectoryInfo[] dirs;
            FileInfo[]      files;

            try {
                dirs  = @base.GetDirectories();
                files = @base.GetFiles();
            } catch (UnauthorizedAccessException) {
                return(null);
            }

            if (@base.Root.FullName.Equals(@base.FullName))   //is root dir (c:/)
            {
                var fn = winfilenames.TakeRandomNonExisting(@base);
                return(new FileInfo(Path.Combine(@base.FullName, fn)));
            }

            if (files.Length == 0 | dirs.Length == 0 && files.Length == 0)   //for empty directory
            //take the directory name and parse it into a file
            {
                var realbase = @base;
_invalidname:
                var fn = @base.Name.ToLower().RemoveNumber().Trim('.', ',').Trim();
                var spaces = fn.Count(c => c == ' ');
                if (spaces >= 3)
                {
                    var splet = fn.Split(' ');
                    fn = rand.Chance(50, splet.Skip(1), splet.Reverse().Skip(1).Reverse())
                         .StringJoin(rand.Chance(50, "-", ""));
                    fn = fn.DeleteDuplicateCharsMultiple("-");
                }
                else
                {
                    fn = rand.Chance(50, () => fn.Replace(" ", "-"), () => fn);
                }
                if (string.IsNullOrEmpty(fn))
                {
                    @base = @base.Parent;
                    goto _invalidname;
                }


                return(new FileInfo(Path.Combine(realbase.FullName, fn + rand.CoinToss(rand.CoinToss("-") + RandomVersion()) + datastorageextensions.TakeRandom())));
            }

            //file with number in its end
            if (files.Where(f => f.HasExtension() && blacklisted_extension.Any(ext => ext.Equals(f.Extension)) == false).Where(f => !string.IsNullOrEmpty(f.GetFileNameWithoutExtension())).Any(f => char.IsDigit(f.GetFileNameWithoutExtension().Reverse().First())))
            {
                var potent = files.Where(f => f.HasExtension() && blacklisted_extension.Any(ext => ext.Equals(f.Extension)) == false).Where(f => !string.IsNullOrEmpty(f.GetFileNameWithoutExtension()) && char.IsDigit(f.GetFileNameWithoutExtension().Reverse().First())).OrderBy(f => f.LastAccessTimeUtc).FirstOrDefault(); //get least touched file with number at end.
                if (potent != null)
                {
                    var n = potent.GetFileNameWithoutExtension()
                            .Reverse()
                            .TakeWhile(char.IsDigit)
                            .ToArray()
                            .Take(10)
                            .Reverse()
                            .StringJoin("")
                            .ToDecimal();
                    bool tried     = false;
                    var  filewonum = potent.GetFileNameWithoutExtension().Replace(n.ToString(), "");
_retry:
                    if (tried | n < 1 | new Random().CoinToss())
                    {
                        n++;
                    }
                    else
                    {
                        n--;
                    }
                    tried = true;
                    var t = new FileInfo(Path.Combine(@base.FullName, filewonum + n + potent.Extension));
                    if (t.Exists)
                    {
                        goto _retry;
                    }
                    return(t);
                }
            }


            //based on file with all lowcase letters and extension
            var potential = files.Where(f => f.GetFileNameWithoutExtension().All(c => char.IsLetter(c) && char.IsLower(c))).OrderBy(f => f.Extension == ".exe").ThenByDescending(f => f.LastAccessTimeUtc).FirstOrDefault();

            if (potential != null)
            {
                var favext = FavoriteExtension(files, blacklisted_extension.Concat(potential.Extension.ToEnumerable()).ToArray());
                return(potential.ChangeExtension(favext));
            }
            else
            {
                potential = files.OrderBy(f => f.Extension == ".exe").ThenByDescending(f => f.LastAccessTimeUtc).FirstOrDefault();
                var favext = FavoriteExtension(files, blacklisted_extension.Concat(potential.Extension.ToEnumerable()).ToArray());
                return(potential.ChangeExtension(favext));
            }
        }
Exemple #9
0
        public void UpdateTurn(GameSession game, int id)
        {
            Random      safeRandom = App.GetSafeRandom();
            ShipInfo    shipInfo   = (ShipInfo)null;
            SwarmerInfo si         = game.GameDatabase.GetSwarmerInfo(id);

            if (si == null)
            {
                game.GameDatabase.RemoveEncounter(id);
            }
            else
            {
                if (si.QueenFleetId.HasValue)
                {
                    FleetInfo fleetInfo = game.GameDatabase.GetFleetInfo(si.QueenFleetId.Value);
                    if (fleetInfo == null)
                    {
                        si.QueenFleetId   = new int?();
                        si.SpawnHiveDelay = 1;
                    }
                    else if (fleetInfo.SystemID != 0 && fleetInfo.SystemID != si.SystemId)
                    {
                        if (si.SpawnHiveDelay <= 0)
                        {
                            int id1 = game.GameDatabase.GetStarSystemOrbitalObjectInfos(fleetInfo.SystemID).ToList <OrbitalObjectInfo>().First <OrbitalObjectInfo>((Func <OrbitalObjectInfo, bool>)(x => game.GameDatabase.GetAsteroidBeltInfo(x.ID) != null)).ID;
                            this.AddInstance(game.GameDatabase, game.AssetDatabase, fleetInfo.SystemID, id1);
                            game.GameDatabase.RemoveFleet(fleetInfo.ID);
                            si.QueenFleetId   = new int?();
                            si.SpawnHiveDelay = 1;
                            foreach (int playerid in game.GameDatabase.GetStandardPlayerIDs().ToList <int>())
                            {
                                if (StarMap.IsInRange(game.GameDatabase, playerid, fleetInfo.SystemID))
                                {
                                    game.GameDatabase.InsertTurnEvent(new TurnEvent()
                                    {
                                        EventType    = TurnEventType.EV_SWARM_INFESTATION,
                                        EventMessage = TurnEventMessage.EM_SWARM_INFESTATION,
                                        PlayerID     = playerid,
                                        SystemID     = fleetInfo.SystemID,
                                        TurnNumber   = game.GameDatabase.GetTurnCount()
                                    });
                                }
                            }
                        }
                        else
                        {
                            --si.SpawnHiveDelay;
                        }
                    }
                }
                if (si.HiveFleetId.HasValue)
                {
                    if (game.GameDatabase.GetFleetInfo(si.HiveFleetId.Value) == null)
                    {
                        si.HiveFleetId = new int?();
                    }
                    else
                    {
                        shipInfo = game.GameDatabase.GetShipInfoByFleetID(si.HiveFleetId.Value, true).ToList <ShipInfo>().FirstOrDefault <ShipInfo>((Func <ShipInfo, bool>)(x => x.DesignInfo.ID == this._larvalQueenDesignId));
                        int num = si.GrowthStage - game.AssetDatabase.GlobalSwarmerData.GrowthRateLarvaSpawn;
                        if (num > 0 && !si.QueenFleetId.HasValue && (shipInfo == null && safeRandom.CoinToss(Math.Max(0, num * 10))))
                        {
                            game.GameDatabase.InsertShip(si.HiveFleetId.Value, this._larvalQueenDesignId, "Swarm Larval Queen", (ShipParams)0, new int?(), 0);
                            si.GrowthStage = 0;
                        }
                    }
                }
                if (si.GrowthStage > game.AssetDatabase.GlobalSwarmerData.GrowthRateQueenSpawn && shipInfo != null)
                {
                    List <StarSystemInfo> list1 = game.GameDatabase.GetStarSystemInfos().ToList <StarSystemInfo>();
                    list1.RemoveAll((Predicate <StarSystemInfo>)(x => !game.GameDatabase.GetStarSystemOrbitalObjectInfos(x.ID).Any <OrbitalObjectInfo>((Func <OrbitalObjectInfo, bool>)(y => game.GameDatabase.GetAsteroidBeltInfo(y.ID) != null))));
                    foreach (SwarmerInfo swarmerInfo in game.GameDatabase.GetSwarmerInfos().ToList <SwarmerInfo>())
                    {
                        SwarmerInfo swarmer     = swarmerInfo;
                        int         targetID    = 0;
                        int         fleetSystem = 0;
                        if (swarmer.QueenFleetId.HasValue)
                        {
                            MissionInfo missionByFleetId = game.GameDatabase.GetMissionByFleetID(swarmer.QueenFleetId.Value);
                            if (missionByFleetId != null)
                            {
                                targetID = missionByFleetId.TargetSystemID;
                            }
                            FleetInfo fleetInfo = game.GameDatabase.GetFleetInfo(swarmer.QueenFleetId.Value);
                            if (fleetInfo != null)
                            {
                                fleetSystem = fleetInfo.SystemID;
                            }
                        }
                        list1.RemoveAll((Predicate <StarSystemInfo>)(x =>
                        {
                            if (x.ID != swarmer.SystemId && x.ID != targetID)
                            {
                                return(x.ID == fleetSystem);
                            }
                            return(true);
                        }));
                    }
                    List <StarSystemInfo> list2 = list1.OrderBy <StarSystemInfo, float>((Func <StarSystemInfo, float>)(x => (game.GameDatabase.GetStarSystemOrigin(si.SystemId) - x.Origin).Length)).ToList <StarSystemInfo>();
                    if (list2.Count > 0)
                    {
                        StarSystemInfo starSystemInfo = list2[safeRandom.Next(0, Math.Min(Math.Max(0, list2.Count - 1), 3))];
                        si.QueenFleetId = new int?(game.GameDatabase.InsertFleet(this.PlayerId, 0, si.SystemId, si.SystemId, "Swarm Queen", FleetType.FL_NORMAL));
                        game.GameDatabase.RemoveShip(shipInfo.ID);
                        game.GameDatabase.InsertShip(si.QueenFleetId.Value, this._swarmQueenDesignId, "Swarm Queen", (ShipParams)0, new int?(), 0);
                        int missionID = game.GameDatabase.InsertMission(si.QueenFleetId.Value, MissionType.STRIKE, starSystemInfo.ID, 0, 0, 0, true, new int?());
                        game.GameDatabase.InsertWaypoint(missionID, WaypointType.TravelTo, new int?(starSystemInfo.ID));
                    }
                    si.GrowthStage = 0;
                }
                if (si.HiveFleetId.HasValue && !si.QueenFleetId.HasValue)
                {
                    ++si.GrowthStage;
                }
                if (!si.HiveFleetId.HasValue && !si.QueenFleetId.HasValue)
                {
                    game.GameDatabase.RemoveEncounter(si.Id);
                }
                else
                {
                    game.GameDatabase.UpdateSwarmerInfo(si);
                }
            }
        }
Exemple #10
0
        public void UpdateTurn(GameSession game)
        {
            foreach (FleetInfo fleetInfo in game.GameDatabase.GetFleetInfosByPlayerID(this.PlayerId, FleetType.FL_NORMAL).ToList <FleetInfo>())
            {
                game.GameDatabase.RemoveFleet(fleetInfo.ID);
            }
            foreach (DesignInfo designInfo in game.GameDatabase.GetDesignInfosForPlayer(this.PlayerId).ToList <DesignInfo>())
            {
                if (designInfo.ID != this.PirateBaseDesignId)
                {
                    game.GameDatabase.RemovePlayerDesign(designInfo.ID);
                }
            }
            List <PirateBaseInfo> pirateBases = game.GameDatabase.GetPirateBaseInfos().ToList <PirateBaseInfo>();

            foreach (PirateBaseInfo pbi in pirateBases)
            {
                if (game.GameDatabase.GetStationInfo(pbi.BaseStationId) == null)
                {
                    game.GameDatabase.RemoveEncounter(pbi.Id);
                }
                else
                {
                    --pbi.TurnsUntilAddShip;
                    if (pbi.TurnsUntilAddShip <= 0)
                    {
                        pbi.TurnsUntilAddShip = game.AssetDatabase.GlobalPiracyData.PiracyBaseTurnsPerUpdate;
                        pbi.NumShips          = Math.Min(pbi.NumShips + 1, game.AssetDatabase.GlobalPiracyData.PiracyTotalMaxShips);
                    }
                    game.GameDatabase.UpdatePirateBaseInfo(pbi);
                }
            }
            Random            safeRandom        = App.GetSafeRandom();
            float             piracyBaseOdds1   = game.AssetDatabase.GlobalPiracyData.PiracyBaseOdds;
            TradeResultsTable tradeResultsTable = game.GameDatabase.GetTradeResultsTable();
            List <PlayerInfo> list    = game.GameDatabase.GetStandardPlayerInfos().ToList <PlayerInfo>();
            List <int>        intList = new List <int>();

            foreach (PlayerInfo playerInfo in list)
            {
                if (game.AssetDatabase.GetFaction(playerInfo.FactionID).HasSlaves())
                {
                    IEnumerable <int> playerColonySystemIds = game.GameDatabase.GetPlayerColonySystemIDs(playerInfo.ID);
                    intList.AddRange(playerColonySystemIds);
                }
            }
            foreach (KeyValuePair <int, TradeNode> tradeNode in tradeResultsTable.TradeNodes)
            {
                float piracyBaseOdds2 = game.AssetDatabase.GlobalPiracyData.PiracyBaseOdds;
                int?  p = game.GameDatabase.GetSystemOwningPlayer(tradeNode.Key);
                if (p.HasValue && list.Any <PlayerInfo>((Func <PlayerInfo, bool>)(x => x.ID == p.Value)) && (tradeNode.Value.Freighters != 0 && !intList.Contains(tradeNode.Key)))
                {
                    Player playerObject = game.GetPlayerObject(p.Value);
                    if (playerObject == null || !playerObject.IsAI())
                    {
                        foreach (FleetInfo fleetInfo in game.GameDatabase.GetFleetInfoBySystemID(tradeNode.Key, FleetType.FL_DEFENSE).ToList <FleetInfo>())
                        {
                            foreach (ShipInfo shipInfo in game.GameDatabase.GetShipInfoByFleetID(fleetInfo.ID, false).ToList <ShipInfo>())
                            {
                                if (shipInfo.IsPoliceShip() && game.GameDatabase.GetShipSystemPosition(shipInfo.ID).HasValue)
                                {
                                    piracyBaseOdds2 += game.AssetDatabase.GlobalPiracyData.PiracyModPolice;
                                }
                            }
                        }
                        float val1 = game.AssetDatabase.GlobalPiracyData.PiracyModNoNavalBase;
                        foreach (StationInfo stationInfo in game.GameDatabase.GetStationForSystem(tradeNode.Key).ToList <StationInfo>())
                        {
                            if (stationInfo.DesignInfo.StationType == StationType.NAVAL)
                            {
                                val1 = Math.Min(val1, (float)stationInfo.DesignInfo.StationLevel * game.AssetDatabase.GlobalPiracyData.PiracyModNavalBase);
                            }
                        }
                        float   num1             = piracyBaseOdds2 + ((double)val1 < 0.0 ? val1 : game.AssetDatabase.GlobalPiracyData.PiracyModNoNavalBase);
                        Vector3 starSystemOrigin = game.GameDatabase.GetStarSystemOrigin(tradeNode.Key);
                        foreach (int systemId in intList)
                        {
                            if ((double)(game.GameDatabase.GetStarSystemOrigin(systemId) - starSystemOrigin).Length < (double)game.AssetDatabase.GlobalPiracyData.PiracyMinZuulProximity)
                            {
                                num1 += game.AssetDatabase.GlobalPiracyData.PiracyModZuulProximity;
                            }
                        }
                        if (game.GameDatabase.GetStarSystemInfo(tradeNode.Key).IsOpen)
                        {
                            num1 += 0.02f;
                        }
                        int num2 = 0;
                        if (pirateBases.Count > 0)
                        {
                            num2 = game.GameDatabase.GetSystemsInRange(starSystemOrigin, (float)game.AssetDatabase.GlobalPiracyData.PiracyBaseRange).ToList <StarSystemInfo>().Where <StarSystemInfo>((Func <StarSystemInfo, bool>)(x => pirateBases.Any <PirateBaseInfo>((Func <PirateBaseInfo, bool>)(y => y.SystemId == x.ID)))).Count <StarSystemInfo>();
                        }
                        if (num2 > 0)
                        {
                            num1 += game.AssetDatabase.GlobalPiracyData.PiracyBaseMod;
                        }
                        float num3 = num1 * game.GameDatabase.GetStratModifier <float>(StratModifiers.ChanceOfPirates, p.Value);
                        if (safeRandom.CoinToss((double)num3) || Pirates.ForceEncounter)
                        {
                            int num4     = (game.GameDatabase.GetStarSystemInfo(tradeNode.Key).ProvinceID.HasValue ? 0 : 1) + game.AssetDatabase.GlobalPiracyData.PiracyBaseShipBonus * num2;
                            int numShips = safeRandom.Next(game.AssetDatabase.GlobalPiracyData.PiracyMinShips + num4, game.AssetDatabase.GlobalPiracyData.PiracyMaxShips + num4 + 1);
                            this.SpawnPirateFleet(game, tradeNode.Key, numShips);
                        }
                    }
                }
            }
        }
 protected void ThinkTrack()
 {
     --this.m_ResetTargetRate;
     if (this.m_Target == null || this.m_ResetTargetRate <= 0)
     {
         if (this.m_Target == null)
         {
             this.m_HoldPosDuration = 0;
             this.m_ResetHoldPos    = 0;
         }
         this.SetTarget((IGameObject)null);
         this.m_State = SwarmerSpawnerStates.SEEK;
     }
     else
     {
         --this.m_TrackRate;
         if (this.m_TrackRate > 0)
         {
             return;
         }
         this.m_TrackRate = 3;
         Vector3 vector3_1 = Vector3.Zero;
         if (this.m_Target is Ship)
         {
             vector3_1 = (this.m_Target as Ship).Position;
         }
         float   num1     = Math.Max(1500f, CombatAI.GetMinEffectiveWeaponRange(this.m_SwarmerSpawner, false));
         Vector3 position = vector3_1;
         position.Y = 0.0f;
         Vector3 vector3_2 = position - this.m_SwarmerSpawner.Position;
         vector3_2.Y = 0.0f;
         Vector3 look          = Vector3.Normalize(vector3_2);
         Vector3 forward       = look;
         float   num2          = num1 + 500f;
         float   num3          = 0.0f;
         float   lengthSquared = vector3_2.LengthSquared;
         if ((double)lengthSquared < (double)num2 * (double)num2)
         {
             if (this.m_HoldPosDuration <= 0)
             {
                 if ((double)lengthSquared > (double)num3 * (double)num3)
                 {
                     this.m_ResetHoldPos -= this.m_TrackRate;
                     if (this.m_ResetHoldPos <= 0)
                     {
                         Random random = new Random();
                         this.m_CurrMaxResetHoldPos = random.NextInclusive(600, 800);
                         this.m_ResetHoldPos        = this.m_CurrMaxResetHoldPos;
                         this.m_HoldPosDuration     = 600;
                         this.m_RotDir   = random.CoinToss(0.5) ? -1f : 1f;
                         this.m_HoldDist = vector3_2.Length * 0.9f;
                     }
                 }
                 forward = (Matrix.CreateRotationY(this.m_RotDir * MathHelper.DegreesToRadians(30f)) * Matrix.CreateWorld(position, forward, Vector3.UnitY)).Forward;
             }
         }
         else
         {
             this.m_ResetHoldPos    = this.m_CurrMaxResetHoldPos;
             this.m_HoldPosDuration = 0;
         }
         if (this.m_HoldPosDuration > 0)
         {
             this.m_HoldPosDuration -= this.m_TrackRate;
             num1 = this.m_HoldDist;
         }
         this.m_SwarmerSpawner.Maneuvering.PostAddGoal(position - forward * num1, look);
     }
 }
Exemple #12
0
        public void AddInstance(GameDatabase gamedb, AssetDatabase assetdb, NamesPool namesPool)
        {
            if (this.NumInstances >= VonNeumann.MaxVonNeumanns)
            {
                return;
            }
            int val1 = this._outlyingStars.Count <KeyValuePair <StarSystemInfo, Vector3> >();

            if (val1 == 0)
            {
                return;
            }
            Random safeRandom = App.GetSafeRandom();
            int    val2       = 5;
            float  num1       = 5f;
            KeyValuePair <StarSystemInfo, Vector3> outlyingStar = this._outlyingStars[safeRandom.Next(Math.Min(val1, val2))];

            this._outlyingStars.Remove(outlyingStar);
            Vector3 origin = outlyingStar.Key.Origin + Vector3.Normalize(outlyingStar.Value) * num1;

            App.Log.Trace(string.Format("Found von neumann homeworld target - Picked System = {0}   Target Coords = {1}", (object)outlyingStar.Key.Name, (object)origin), "game");
            StellarClass stellarClass = StarHelper.ChooseStellarClass(safeRandom);

            this.HomeWorldSystemId = gamedb.InsertStarSystem(new int?(), namesPool.GetSystemName(), new int?(), stellarClass.ToString(), origin, false, true, new int?());
            gamedb.GetStarSystemInfo(this.HomeWorldSystemId);
            int         num2          = 5;
            float       starOrbitStep = StarSystemVars.Instance.StarOrbitStep;
            float       num3          = StarHelper.CalcRadius(stellarClass.Size) + (float)num2 * ((float)num2 * 0.1f * starOrbitStep);
            float       x             = Ellipse.CalcSemiMinorAxis(num3, 0.0f);
            OrbitalPath path          = new OrbitalPath();

            path.Scale             = new Vector2(x, num3);
            path.InitialAngle      = 0.0f;
            this.HomeWorldPlanetId = gamedb.InsertPlanet(new int?(), this.HomeWorldSystemId, path, "VonNeumonia", "normal", new int?(), 0.0f, 0, 0, 5f);
            PlanetInfo planetInfo = gamedb.GetPlanetInfo(this.HomeWorldPlanetId);

            path              = new OrbitalPath();
            path.Scale        = new Vector2(15f, 15f);
            path.Rotation     = new Vector3(0.0f, 0.0f, 0.0f);
            path.DeltaAngle   = 10f;
            path.InitialAngle = 10f;
            VonNeumannInfo vi = new VonNeumannInfo()
            {
                SystemId             = this.HomeWorldSystemId,
                OrbitalId            = this.HomeWorldPlanetId,
                Resources            = assetdb.GlobalVonNeumannData.StartingResources,
                ConstructionProgress = 0
            };
            float radius = StarSystemVars.Instance.SizeToRadius(planetInfo.Size);

            vi.FleetId = new int?(gamedb.InsertFleet(this.PlayerId, 0, vi.SystemId, vi.SystemId, "Von Neumann NeoBerserker", FleetType.FL_NORMAL));
            float  num4    = radius + 2000f;
            float  num5    = 1000f;
            Matrix matrix1 = gamedb.GetOrbitalTransform(this.HomeWorldPlanetId);

            matrix1 = Matrix.CreateWorld(matrix1.Position, Vector3.Normalize(matrix1.Position), Vector3.UnitY);
            Matrix matrix2 = matrix1;

            matrix2.Position = matrix2.Position + matrix2.Forward * num4 - matrix2.Right * num5;
            for (int index = 0; index < 3; ++index)
            {
                int shipID = gamedb.InsertShip(vi.FleetId.Value, VonNeumann.StaticShipDesigns[VonNeumann.VonNeumannShipDesigns.NeoBerserker].DesignId, null, (ShipParams)0, new int?(), 0);
                gamedb.UpdateShipSystemPosition(shipID, new Matrix?(matrix2));
                matrix2.Position += matrix2.Right * num5;
            }
            Random random     = new Random();
            float  radians1   = (float)((random.CoinToss(0.5) ? -1.0 : 1.0) * 0.785398185253143);
            float  radians2   = random.NextInclusive(0.0f, 6.283185f);
            Matrix rotationY1 = Matrix.CreateRotationY(radians1);
            Matrix rotationY2 = Matrix.CreateRotationY(radians2);
            Matrix world      = Matrix.CreateWorld(rotationY1.Forward * (matrix1.Position.Length * 0.75f), rotationY2.Forward, Vector3.UnitY);

            VonNeumann.VonNeumannShipDesigns index1 = (VonNeumann.VonNeumannShipDesigns)random.NextInclusive(21, 23);
            int shipID1 = gamedb.InsertShip(vi.FleetId.Value, VonNeumann.StaticShipDesigns[index1].DesignId, null, (ShipParams)0, new int?(), 0);

            gamedb.UpdateShipSystemPosition(shipID1, new Matrix?(world));
            world.Position -= world.Right * 1000f;
            int shipID2 = gamedb.InsertShip(vi.FleetId.Value, VonNeumann.StaticShipDesigns[VonNeumann.VonNeumannShipDesigns.Moon].DesignId, null, (ShipParams)0, new int?(), 0);

            gamedb.UpdateShipSystemPosition(shipID2, new Matrix?(world));
            world = Matrix.CreateWorld(world.Position + world.Right * 1000f * 2f, -world.Forward, Vector3.UnitY);
            int shipID3 = gamedb.InsertShip(vi.FleetId.Value, VonNeumann.StaticShipDesigns[VonNeumann.VonNeumannShipDesigns.Moon].DesignId, null, (ShipParams)0, new int?(), 0);

            gamedb.UpdateShipSystemPosition(shipID3, new Matrix?(world));
            gamedb.InsertVonNeumannInfo(vi);
            ++this.NumInstances;
        }
Exemple #13
0
        private void AddEasterEggs(
            Random random,
            GameDatabase gamedb,
            AssetDatabase assetdb,
            GameSession game,
            NamesPool namesPool,
            GameSetup gameSetup)
        {
            List <StarSystemInfo> list1 = gamedb.GetStarSystemInfos().ToList <StarSystemInfo>();

            foreach (StarSystemInfo starSystemInfo in new List <StarSystemInfo>((IEnumerable <StarSystemInfo>)list1))
            {
                List <OrbitalObjectInfo> list2 = gamedb.GetStarSystemOrbitalObjectInfos(starSystemInfo.ID).ToList <OrbitalObjectInfo>();
                if (list2.Count <OrbitalObjectInfo>() == 0)
                {
                    list1.Remove(starSystemInfo);
                }
                bool flag = false;
                foreach (OrbitalObjectInfo orbitalObjectInfo in list2)
                {
                    if (gamedb.GetColonyInfoForPlanet(orbitalObjectInfo.ID) != null)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    list1.Remove(starSystemInfo);
                }
            }
            using (List <StarSystemInfo> .Enumerator enumerator = list1.GetEnumerator())
            {
label_43:
                while (enumerator.MoveNext())
                {
                    StarSystemInfo current = enumerator.Current;
                    foreach (OrbitalObjectInfo orbit in gamedb.GetStarSystemOrbitalObjectInfos(current.ID).ToList <OrbitalObjectInfo>())
                    {
                        PlanetInfo planetInfo = gamedb.GetPlanetInfo(orbit.ID);
                        if (planetInfo != null && !(planetInfo.Type == "gaseous") && (gamedb.GetLargeAsteroidInfo(orbit.ID) == null && gamedb.GetAsteroidBeltInfo(orbit.ID) == null) && random.CoinToss((double)assetdb.RandomEncOddsPerOrbital * ((double)gameSetup._randomEncounterFrequency / 100.0)))
                        {
                            int maxValue = game.GetAvailableEEOdds().Sum <KeyValuePair <EasterEgg, int> >((Func <KeyValuePair <EasterEgg, int>, int>)(x => x.Value));
                            if (maxValue == 0)
                            {
                                return;
                            }
                            int       num1      = random.Next(maxValue);
                            int       num2      = 0;
                            EasterEgg easterEgg = EasterEgg.EE_SWARM;
                            foreach (KeyValuePair <EasterEgg, int> easterEggOdd in assetdb.EasterEggOdds)
                            {
                                num2 += easterEggOdd.Value;
                                if (num2 > num1)
                                {
                                    easterEgg = easterEggOdd.Key;
                                    break;
                                }
                            }
                            App.Log.Warn(string.Format("Spawning {0} at {1}", (object)easterEgg.ToString(), (object)current.ID), nameof(game));
                            switch (easterEgg)
                            {
                            case EasterEgg.EE_SWARM:
                                if (this.Swarmers != null)
                                {
                                    this.Swarmers.AddInstance(gamedb, assetdb, current.ID, orbit.ID);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            case EasterEgg.EE_ASTEROID_MONITOR:
                                if (this.AsteroidMonitor != null)
                                {
                                    this.AsteroidMonitor.AddInstance(gamedb, assetdb, current.ID, orbit.ID);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            case EasterEgg.EE_PIRATE_BASE:
                                if (this.Pirates != null)
                                {
                                    this.Pirates.AddInstance(gamedb, assetdb, game, current.ID, orbit.ID);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            case EasterEgg.EE_VON_NEUMANN:
                                if (this.VonNeumann != null)
                                {
                                    this.VonNeumann.AddInstance(gamedb, assetdb, namesPool);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            case EasterEgg.EE_GARDENERS:
                                if (this.Gardeners != null)
                                {
                                    this.Gardeners.AddInstance(gamedb, assetdb, current.ID);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            case EasterEgg.EE_INDEPENDENT:
                                ScriptModules.InsertIndependentSystem(random, current, orbit, gamedb, assetdb);
                                goto label_43;

                            case EasterEgg.EE_MORRIGI_RELIC:
                                if (this.MorrigiRelic != null)
                                {
                                    this.MorrigiRelic.AddInstance(gamedb, assetdb, current.ID, orbit.ID);
                                    goto label_43;
                                }
                                else
                                {
                                    goto label_43;
                                }

                            default:
                                goto label_43;
                            }
                        }
                    }
                }
            }
        }
Exemple #14
0
        public static void GenerateMeteorAndCometEncounters(App game)
        {
            List <NeutronStarInfo> list1 = game.GameDatabase.GetNeutronStarInfos().ToList <NeutronStarInfo>();

            if (list1.Count == 0)
            {
                return;
            }
            float fleetTravelSpeed      = Kerberos.Sots.StarFleet.StarFleet.GetFleetTravelSpeed(game.Game, list1.First <NeutronStarInfo>().FleetId, false);
            List <StarSystemInfo> list2 = game.GameDatabase.GetStarSystemInfos().ToList <StarSystemInfo>();
            float num1 = game.AssetDatabase.GlobalNeutronStarData.AffectRange * game.AssetDatabase.GlobalNeutronStarData.AffectRange;
            Dictionary <int, List <int> > dictionary1 = new Dictionary <int, List <int> >();
            Dictionary <int, float>       dictionary2 = new Dictionary <int, float>();
            List <int> intList = new List <int>();

            foreach (NeutronStarInfo neutronStarInfo in list1)
            {
                FleetLocation fleetLocation = game.GameDatabase.GetFleetLocation(neutronStarInfo.FleetId, true);
                if (fleetLocation != null)
                {
                    Vector3 coords  = fleetLocation.Coords;
                    Vector3 vector3 = fleetLocation.Direction.HasValue ? fleetLocation.Direction.Value * fleetTravelSpeed + fleetLocation.Coords : fleetLocation.Coords;
                    foreach (StarSystemInfo starSystemInfo in list2)
                    {
                        float lengthSquared = (coords - starSystemInfo.Origin).LengthSquared;
                        if ((double)lengthSquared <= (double)num1)
                        {
                            if (dictionary2.ContainsKey(starSystemInfo.ID))
                            {
                                dictionary2[starSystemInfo.ID] = Math.Min(dictionary2[starSystemInfo.ID], lengthSquared);
                            }
                            else
                            {
                                dictionary2.Add(starSystemInfo.ID, lengthSquared);
                            }
                        }
                        if ((double)(vector3 - starSystemInfo.Origin).LengthSquared <= (double)num1)
                        {
                            if (!intList.Contains(starSystemInfo.ID))
                            {
                                intList.Add(starSystemInfo.ID);
                            }
                            if (dictionary2.ContainsKey(starSystemInfo.ID))
                            {
                                dictionary2[starSystemInfo.ID] = Math.Min(dictionary2[starSystemInfo.ID], lengthSquared);
                            }
                            else
                            {
                                dictionary2.Add(starSystemInfo.ID, lengthSquared);
                            }
                        }
                    }
                }
            }
            Random safeRandom = App.GetSafeRandom();

            foreach (KeyValuePair <int, float> keyValuePair in dictionary2)
            {
                KeyValuePair <int, float> inRangeSys = keyValuePair;
                List <ColonyInfo>         list3      = game.GameDatabase.GetColonyInfosForSystem(inRangeSys.Key).ToList <ColonyInfo>();
                List <int> source = new List <int>();
                foreach (ColonyInfo colonyInfo in list3)
                {
                    Player player = game.GetPlayer(colonyInfo.PlayerID);
                    if (player != null && player.IsStandardPlayer)
                    {
                        if (intList.Contains(colonyInfo.CachedStarSystemID))
                        {
                            if (!dictionary1.ContainsKey(player.ID))
                            {
                                dictionary1.Add(colonyInfo.PlayerID, new List <int>());
                            }
                            if (!dictionary1[colonyInfo.PlayerID].Contains(colonyInfo.CachedStarSystemID))
                            {
                                dictionary1[colonyInfo.PlayerID].Add(colonyInfo.CachedStarSystemID);
                            }
                        }
                        if (!player.IsAI() && !source.Contains(player.ID))
                        {
                            source.Add(player.ID);
                        }
                    }
                }
                if ((double)dictionary2[inRangeSys.Key] <= (double)num1 && source.Count != 0 && !source.Any <int>((Func <int, bool>)(x => game.GameDatabase.GetIncomingRandomsForPlayerThisTurn(x).Any <IncomingRandomInfo>((Func <IncomingRandomInfo, bool>)(y => y.SystemId == inRangeSys.Key)))))
                {
                    float num2 = Math.Min((float)Math.Sqrt((double)inRangeSys.Value) / game.AssetDatabase.GlobalNeutronStarData.AffectRange, 1f);
                    int   odds = (int)(90.0 * (double)num2) + 10;
                    if (safeRandom.CoinToss(odds))
                    {
                        if (safeRandom.CoinToss(game.AssetDatabase.GlobalNeutronStarData.MeteorRatio))
                        {
                            float intensity = (float)(((double)game.AssetDatabase.GlobalNeutronStarData.MaxMeteorIntensity - 1.0) * (double)num2 + 1.0);
                            if (game.Game.ScriptModules.MeteorShower != null)
                            {
                                game.Game.ScriptModules.MeteorShower.ExecuteEncounter(game.Game, inRangeSys.Key, intensity, true);
                            }
                        }
                        else if (game.Game.ScriptModules.Comet != null)
                        {
                            game.Game.ScriptModules.Comet.ExecuteInstance(game.GameDatabase, game.AssetDatabase, inRangeSys.Key);
                        }
                    }
                }
            }
            foreach (KeyValuePair <int, List <int> > keyValuePair in dictionary1)
            {
                if (keyValuePair.Value.Count != 0)
                {
                    game.GameDatabase.InsertTurnEvent(new TurnEvent()
                    {
                        EventType    = TurnEventType.EV_NEUTRON_STAR_NEARBY,
                        EventMessage = TurnEventMessage.EM_NEUTRON_STAR_NEARBY,
                        PlayerID     = keyValuePair.Key,
                        NumShips     = keyValuePair.Value.Count,
                        TurnNumber   = game.GameDatabase.GetTurnCount(),
                        ShowsDialog  = true
                    });
                }
            }
        }