Esempio n. 1
0
        static void Postfix(Starmap __instance)
        {
            try {
                WIIC.modLog.Info?.Write($"Patching starmap with new owners (setActiveFactionsForAllSystems: {WIIC.settings.setActiveFactionsForAllSystems})");
                int count        = 0;
                int controlCount = 0;
                foreach (StarSystem system in WIIC.sim.StarSystems)
                {
                    if (WIIC.settings.setActiveFactionsForAllSystems)
                    {
                        Utilities.setActiveFactions(system);
                    }

                    // Check if a previous flareup flipped control of the system
                    if (WIIC.systemControl.ContainsKey(system.ID))
                    {
                        FactionValue ownerFromTag = Utilities.controlFromTag(WIIC.systemControl[system.ID]);
                        WIIC.modLog.Info?.Write($"Found new owner {ownerFromTag.Name} at {system.Name}");

                        Utilities.applyOwner(system, ownerFromTag, false);
                        controlCount++;
                    }
                    count++;
                }
                Utilities.redrawMap();
                WIIC.modLog.Info?.Write($"Finished patching starmap (checked {count} systems, flipped control of {controlCount})");
            } catch (Exception e) {
                WIIC.modLog.Error?.Write(e);
            }
        }
 [ClientRpc] public void RpcSpawnGalaxy(int gw, int gh)
 {
     if (starmap == null)
     {
         starmap = new Starmap(gw, gh);
     }
 }
        static void Postfix(Starmap __instance, SimGameState simGame)
        {
            Settings settings = Helper.LoadSettings();

            if (settings.Mode == 2)
            {
                foreach (StarSystem system in simGame.StarSystems)
                {
                    StarSystem capital = simGame.StarSystems.Find(x => x.Name.Equals(Helper.GetCapital(system.Owner)));
                    if (capital != null)
                    {
                        StarSystemNode   systemByID        = __instance.GetSystemByID(system.ID);
                        StarSystemNode   systemByID2       = __instance.GetSystemByID(capital.ID);
                        AStar.PathFinder starmapPathfinder = new AStar.PathFinder();
                        starmapPathfinder.InitFindPath(systemByID, systemByID2, 1, 1E-06f, new Action <AStar.AStarResult>(OnPathfindingComplete));
                        while (!starmapPathfinder.IsDone)
                        {
                            starmapPathfinder.Step();
                        }
                    }
                    else
                    {
                        AccessTools.Field(typeof(StarSystemDef), "DefaultDifficulty").SetValue(system.Def, 1);
                    }
                    AccessTools.Field(typeof(StarSystemDef), "DifficultyList").SetValue(system.Def, new List <int>());
                    AccessTools.Field(typeof(StarSystemDef), "DifficultyModes").SetValue(system.Def, new List <SimGameState.SimGameType>());
                }
            }
        }
Esempio n. 4
0
 // only call to this function is from StarmapScreen.Update()
 // intercept and check shift status
 public static void Postfix(Starmap __instance, StarSystemNode __result)
 {
     if (__result != null && __result != __instance.CurSelected && __result != __instance.CurPlanet &&
         (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
     {
         ShiftClickMove.NextSelectIsShiftClick = true;
     }
 }
Esempio n. 5
0
        public static LegacyStarMap CreateStarMapFromFileCore(
            Random random,
            string starMapPath)
        {
            Starmap s = new Starmap();

            StarMapXmlUtility.LoadStarmapFromXml(starMapPath, ref s);
            return(LegacyStarMap.CreateStarMap(random, s));
        }
    private void OnSubmitButtonPressed()
    {
        if (solved || !activated)
        {
            return;
        }
        Unselect();
        Debug.LogFormat("[Starmap Reconstruction #{0}] Submit pressed", moduleId);
        Starmap map = new Starmap(stars.Length);

        foreach (StarComponent star in stars)
        {
            int expectedAdjacentsCount = StarmapReconstructionData.GetAdjacentStarsCount(star.Race, star.Regime, BombInfo);
            int actualAdjacentsCount   = star.connectedStars.Count;
            if (expectedAdjacentsCount != actualAdjacentsCount)
            {
                Debug.LogFormat("[Starmap Reconstruction #{0}] STRIKE: Star {1} has {2} connected stars. Expected: {3}", moduleId, star.Name, actualAdjacentsCount,
                                expectedAdjacentsCount);
                Module.HandleStrike();
                return;
            }
            foreach (StarComponent other in star.connectedStars)
            {
                map.Add(star.Id, other.Id);
            }
        }
        Debug.LogFormat("[Starmap Reconstruction #{0}] Submitted map: {1}", moduleId, map.ToShortString());
        foreach (StarComponent star in stars)
        {
            KeyValuePair <string, int>?requiredDistance = StarmapReconstructionData.GetRequiredDistanceFrom(star.Name);
            if (requiredDistance == null)
            {
                continue;
            }
            string to = requiredDistance.Value.Key;
            int    expectedDistance = requiredDistance.Value.Value;
            int    otherIndex       = stars.IndexOf(s => s.Name == to);
            if (otherIndex < 0)
            {
                continue;
            }
            StarComponent other          = stars[otherIndex];
            int           actualDistance = map.GetDistance(star.Id, other.Id);
            if (expectedDistance != actualDistance)
            {
                Debug.LogFormat("[Starmap Reconstruction #{0}] STRIKE: Distance from {1} to {2} is {3}. Expected: {4}", moduleId, star.Name, other.Name, actualDistance,
                                expectedDistance);
                Module.HandleStrike();
                return;
            }
        }
        Debug.LogFormat("[Starmap Reconstruction #{0}] Module solved", moduleId);
        solved = true;
        Audio.PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.CorrectChime, transform);
        Module.HandlePass();
    }
Esempio n. 7
0
 static void Prefix(Starmap __instance, SimGameState simGame)
 {
     if (DCECore.settings.diffMode == EDifficultyType.Company || DCECore.settings.diffMode == EDifficultyType.LegacyCompany)
     {
         foreach (StarSystem system in simGame.StarSystems)
         {
             AccessTools.Field(typeof(StarSystemDef), "DefaultDifficulty").SetValue(system.Def, 0);
             AccessTools.Field(typeof(StarSystemDef), "DifficultyList").SetValue(system.Def, new List <int>());
             AccessTools.Field(typeof(StarSystemDef), "DifficultyModes").SetValue(system.Def, new List <SimGameState.SimGameType>());
         }
     }
 }
    public void Init()
    {
        starmap = new Starmap();

        Sector sector = starmap.sectors[0, 0];

        sector.name = "Zakasi Space";

        Planet planet;

        planet                       = new Planet();
        planet.name                  = "Zakaas";
        planet.spriteIndex           = 0;
        planet.starSystemSpriteIndex = 0;
        planet.shortDescription      = "Zakaas II is the Homeworld of the Zakasi. Because the atmosphere is thin and the surface primarily liquid water, most sentient residents inhabit the hollow interiors of the sunken continents";
        planet.sector                = sector;
        planet.x                     = 115;
        planet.y                     = 116;
        starmap.sectors[0, 0].planets.Add(planet);

        planet                       = new Planet();
        planet.name                  = "Karkirraas";
        planet.spriteIndex           = 1;
        planet.starSystemSpriteIndex = 1;
        planet.shortDescription      = "Karkirraas V is a dark and toxic planet with oceans of sulphuric acid and an atmosphere dense enough to block out the light from its star. Notable for its uranium mines.";
        planet.sector                = sector;
        planet.x                     = 245;
        planet.y                     = 83;
        starmap.sectors[0, 0].planets.Add(planet);

        planet                       = new Planet();
        planet.name                  = "Arrikshaar";
        planet.spriteIndex           = 2;
        planet.starSystemSpriteIndex = 2;
        planet.shortDescription      = "Arrikshaar III is a dusty and desolate world. It is notable for its large quantities of sodium-chloride and other chloride salts covering the crust and dissolved within its oceans.";
        planet.sector                = sector;
        planet.x                     = 256;
        planet.y                     = 167;
        starmap.sectors[0, 0].planets.Add(planet);

        planet                       = new Planet();
        planet.name                  = "Varrazaar";
        planet.spriteIndex           = 3;
        planet.starSystemSpriteIndex = 3;
        planet.shortDescription      = "Varrazaar III is world of fog and sea. Its relatively mild climate and oceans of water make it a hospitable world for many carbon-based lifeforms.";
        planet.sector                = sector;
        planet.x                     = 118;
        planet.y                     = 250;
        starmap.sectors[0, 0].planets.Add(planet);

        SyncGalaxy();
    }
Esempio n. 9
0
        public static LegacyStarMap CreateStarMap(Random random, Starmap starmapParams)
        {
            LegacyStarMap map = new LegacyStarMap();

            foreach (Feature feature in starmapParams.Features)
            {
                map.AddRange(LegacyStarMap.CreateFeature(random, feature.LocalSpace, feature, map, (LegacyTerrain)null));
            }
            map._nodelines.AddRange((IEnumerable <NodeLine>)starmapParams.NodeLines);
            map._provinces.AddRange((IEnumerable <Province>)starmapParams.Provinces);
            map.FixPlanetTypes();
            return(map);
        }
Esempio n. 10
0
        static void Prefix(Starmap __instance, SimGameState simGame)
        {
            Settings settings = Helper.LoadSettings();

            if (settings.Mode == 0)
            {
                foreach (StarSystem system in simGame.StarSystems)
                {
                    AccessTools.Field(typeof(StarSystemDef), "DefaultDifficulty").SetValue(system.Def, 0);
                    AccessTools.Field(typeof(StarSystemDef), "DifficultyList").SetValue(system.Def, new List <int>());
                    AccessTools.Field(typeof(StarSystemDef), "DifficultyModes").SetValue(system.Def, new List <SimGameState.SimGameType>());
                }
            }
        }
Esempio n. 11
0
    public Starmap TransformIds(int[] newIds)
    {
        Starmap result = new Starmap(_size);

        for (int i = 0; i < _size; i++)
        {
            for (int j = i + 1; j < _size; j++)
            {
                if (!_data[i][j])
                {
                    continue;
                }
                result.Add(newIds[i], newIds[j]);
            }
        }
        return(result);
    }
Esempio n. 12
0
        public static bool HandleClickSystem(Starmap starmap, StarSystemNode system)
        {
            if (!NextSelectIsShiftClick)
            {
                return(true);
            }

            NextSelectIsShiftClick = false;

            var plannedPath = Traverse.Create(starmap.Screen).Field("_plannedPath").GetValue <LineRenderer>();

            if (starmap.PotentialPath == null || starmap.PotentialPath.Count == 0 || plannedPath == null ||
                plannedPath.positionCount == 0)
            {
                Main.HBSLog.Log("Shift clicked system but had no previous route");
                return(true);
            }

            // set CurSelected to the new end of the route that we're making
            Traverse.Create(starmap).Property("CurSelected").SetValue(system);

            var prevPath          = new List <INavNode>(starmap.PotentialPath.ToArray());
            var prevPathLast      = prevPath.Last();
            var starmapPathfinder = Traverse.Create(starmap).Field("starmapPathfinder").GetValue <AStar.PathFinder>();

            starmapPathfinder.InitFindPath(prevPathLast, system, 1, 1E-06f, result =>
            {
                if (result.status != PathStatus.Complete)
                {
                    Main.HBSLog.LogError("Something went wrong with pathfinding!");
                    return;
                }

                result.path.Remove(prevPathLast);
                result.path.InsertRange(0, prevPath);

                Main.HBSLog.Log($"Created new hybrid route of size {result.path.Count}");
                Traverse.Create(starmap).Method("OnPathfindingComplete", result).GetValue();
            });

            return(false);
        }
Esempio n. 13
0
    public string ToShortString()
    {
        Starmap       loggedCorridors = new Starmap(_size);
        List <string> result          = new List <string>();
        int           i = 0;

        while (i < _size)
        {
            List <int> path = new List <int>(new[] { i });
            while (true)
            {
                int from = path.Last();
                for (int to = 0; to < _size; to++)
                {
                    if (_data[from][to] && !loggedCorridors._data[from][to])
                    {
                        path.Add(to);
                        loggedCorridors.Add(from, to);
                        break;
                    }
                }
                if (from == path.Last())
                {
                    break;
                }
            }
            if (path.Count == 1)
            {
                i++;
            }
            else
            {
                result.Add(path.Join("-"));
            }
        }
        return(result.Join("; "));
    }
    private void OnValidate()
    {
        if (validateTempToColor)
        {
            if (temperature != temperatureValidate)
            {
                color = Starmap.GetColorFromTemperature(temperature);
            }

            if (tempGradPreview.colorKeys.Length <= 1 || temperature != temperatureValidate)
            {
                var gcks = new GradientColorKey[8];
                for (int i = 0; i < gcks.Length; i++)
                {
                    gcks[i].time  = i / (float)(gcks.Length - 1);
                    gcks[i].color = Starmap.GetColorFromTemperature(temperature * gcks[i].time);
                }
                tempGradPreview           = new Gradient();
                tempGradPreview.colorKeys = gcks;
            }

            temperatureValidate = temperature;
        }
    }
Esempio n. 15
0
 public static bool Prefix(Starmap __instance, StarSystemNode node)
 {
     return(ShiftClickMove.HandleClickSystem(__instance, node));
 }
Esempio n. 16
0
 public static bool HasStarSystemBeenVisited(this Starmap starmap, string systemID)
 {
     return(starmap.GetSimGameState().HasStarSystemBeenVisited(systemID));
 }
Esempio n. 17
0
            private static void Postfix(Starmap __instance)
            {
                LogDebug("PopulateMap");

                var go = new GameObject();

                go.AddComponent <DeploymentIndicator>();

                if (Globals.ModInitialized)
                {
                    return;
                }

                Globals.Sim = __instance.sim;
                Globals.SimGameInterruptManager = Globals.Sim.InterruptQueue;
                Globals.GaWSystems = Globals.Sim.StarSystems.Where(x =>
                                                                   !Globals.Settings.ImmuneToWar.Contains(x.OwnerValue.Name)).ToList();
                if (Globals.Sim.IsCampaign && !Globals.Sim.CompanyTags.Contains("story_complete"))
                {
                    LogDebug("Aborting GaW loading.");
                    return;
                }

                // thanks to mpstark for this
                var fonts = Resources.FindObjectsOfTypeAll(typeof(TMP_FontAsset));

                foreach (var o in fonts)
                {
                    var font = (TMP_FontAsset)o;
                    if (font.name == "UnitedSansSemiExt-Light")
                    {
                        Globals.Font = font;
                    }
                }

                if (Globals.Settings.ResetMap)
                {
                    LogDebug("Resetting map due to settings.");
                    Spawn();
                    return;
                }

                // is there a tag?  does it deserialize properly?
                var gawTag = Globals.Sim.CompanyTags.FirstOrDefault(x => x.StartsWith("GalaxyAtWarSave"));

                if (!string.IsNullOrEmpty(gawTag))
                {
                    DeserializeWar();
                    // cleaning up old tag data
                    ValidateState();
                    // copied from WarStatus - establish any systems that are new
                    AddNewStarSystems();

                    // fixes the Order not appearing after load.  The tag has it, but the game needs to re-add it
                    if (Globals.WarStatusTracker.EscalationOrder is not null)
                    {
                        SetupEscalationOrder();
                    }

                    // try to recover from negative DR
                    // temporary code
                    //foreach (var systemStatus in Globals.WarStatusTracker.Systems)
                    //{
                    //    if (systemStatus.DefenseResources < 0 || systemStatus.AttackResources < 0)
                    //    {
                    //        systemStatus.AttackResources = GetTotalAttackResources(systemStatus.StarSystem);
                    //        systemStatus.DefenseResources = GetTotalDefensiveResources(systemStatus.StarSystem);
                    //        systemStatus.TotalResources = systemStatus.AttackResources + systemStatus.DefenseResources;
                    //        systemStatus.PirateActivity = 0;
                    //    }
                    //}

                    if (Globals.WarStatusTracker.Systems.Count == 0)
                    {
                        LogDebug("Found tag but it's broken and being respawned:");
                        Spawn();
                    }
                    else
                    {
                        RebuildState();
                        Globals.WarStatusTracker.FirstTickInitialization = true;
                    }
                }
                else
                {
                    Spawn();
                }

                Globals.ModInitialized = true;
            }
Esempio n. 18
0
 void Update()
 {
     camera.backgroundColor = Starmap.GetColorFromTemperature(temperature);
 }
Esempio n. 19
0
        static void Postfix(Starmap __instance, SimGameState simGame)
        {
            try {
                Fields.currentMap = Web.GetStarMap();
                List <StarSystem> needUpdates = new List <StarSystem>();
                if (Fields.currentMap == null)
                {
                    SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(simGame);
                    interruptQueue.QueueGenericPopup_NonImmediate("Connection Failure", "Map could not be downloaded", true);
                    return;
                }
                List <string> changes = new List <string>();
                foreach (ParseSystem system in Fields.currentMap.systems)
                {
                    if (system.activePlayers > 0)
                    {
                        GameObject starObject = GameObject.Find(system.name);
                        Transform  argoMarker = starObject.transform.Find("ArgoMarker");
                        argoMarker.gameObject.SetActive(true);
                        argoMarker.localScale = new Vector3(4f, 4f, 4f);
                        argoMarker.GetComponent <MeshRenderer>().material.color = Color.grey;
                        GameObject playerNumber = new GameObject();
                        playerNumber.transform.parent = argoMarker;
                        playerNumber.name             = "PlayerNumberText";
                        playerNumber.layer            = 25;
                        TextMeshPro textComponent = playerNumber.AddComponent <TextMeshPro>();
                        textComponent.SetText(system.activePlayers.ToString());
                        textComponent.transform.localPosition = new Vector3(0, -0.35f, -0.05f);
                        textComponent.fontSize  = 6;
                        textComponent.alignment = TextAlignmentOptions.Center;
                        textComponent.faceColor = Color.black;
                        textComponent.fontStyle = FontStyles.Bold;
                    }
                    StarSystem system2 = simGame.StarSystems.Find(x => x.Name.Equals(system.name));
                    if (system2 != null)
                    {
                        Faction newOwner = system.controlList.OrderByDescending(x => x.percentage).First().faction;
                        Faction oldOwner = system2.Owner;
                        AccessTools.Method(typeof(StarSystemDef), "set_Owner").Invoke(system2.Def, new object[] {
                            newOwner
                        });
                        AccessTools.Method(typeof(StarSystemDef), "set_ContractEmployers").Invoke(system2.Def, new object[] {
                            Helper.GetEmployees(system2, simGame)
                        });
                        AccessTools.Method(typeof(StarSystemDef), "set_ContractTargets").Invoke(system2.Def, new object[] {
                            Helper.GetTargets(system2, simGame)
                        });
                        system2.Tags.Remove(Helper.GetFactionTag(oldOwner));
                        system2.Tags.Add(Helper.GetFactionTag(newOwner));

                        if (Helper.IsBorder(system2, simGame) && simGame.Starmap != null)
                        {
                            system2.Tags.Add("planet_other_battlefield");
                        }
                        else
                        {
                            system2.Tags.Remove("planet_other_battlefield");
                        }
                        system2 = Helper.ChangeWarDescription(system2, simGame, system);
                        if (newOwner != oldOwner)
                        {
                            changes.Add(Helper.GetFactionShortName(newOwner, simGame.DataManager) + " took " + system2.Name + " from " + Helper.GetFactionShortName(oldOwner, simGame.DataManager));
                            foreach (StarSystem changedSystem in simGame.Starmap.GetAvailableNeighborSystem(system2))
                            {
                                if (!needUpdates.Contains(changedSystem))
                                {
                                    needUpdates.Add(changedSystem);
                                }
                            }
                        }
                    }
                }
                foreach (StarSystem changedSystem in needUpdates)
                {
                    AccessTools.Method(typeof(StarSystemDef), "set_ContractEmployers").Invoke(changedSystem.Def, new object[] {
                        Helper.GetEmployees(changedSystem, simGame)
                    });
                    AccessTools.Method(typeof(StarSystemDef), "set_ContractTargets").Invoke(changedSystem.Def, new object[] {
                        Helper.GetTargets(changedSystem, simGame)
                    });
                    ParseSystem system = Fields.currentMap.systems.FirstOrDefault(x => x.name.Equals(changedSystem.Name));
                    if (system != null)
                    {
                        AccessTools.Method(typeof(StarSystemDef), "set_Description").Invoke(changedSystem.Def, new object[] {
                            Helper.ChangeWarDescription(changedSystem, simGame, system).Def.Description
                        });
                    }
                }
                if (changes.Count > 0 && !Fields.firstpass)
                {
                    SimGameInterruptManager interruptQueue2 = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(simGame);
                    interruptQueue2.QueueGenericPopup_NonImmediate("War Activities", string.Join("\n", changes.ToArray()), true);
                }
                else
                {
                    Fields.firstpass = false;
                }
            }
            catch (Exception e) {
                Logger.LogError(e);
            }
        }
Esempio n. 20
0
    public static void GenerateStarmap(KMBombInfo bomb, out StarInfo[] stars, out Starmap answerExample)
    {
        KeyValuePair <int, int>[] corridorsCount = CorridorsCountVariants.PickRandom().Select((a, i) => new KeyValuePair <int, int>(a, i)).ToArray();
        Debug.LogFormat("<Starmap Reconstruction> Generator: corridors counts: {0}", corridorsCount.Select(kv => kv.Key).Join(""));
        Starmap           map = new Starmap(corridorsCount.Length);
        int               n   = corridorsCount.Length - 1;
        Action <int, int> add = (int i, int j) => {
            map.Add(corridorsCount[i].Value, corridorsCount[j].Value);
            corridorsCount[i] = new KeyValuePair <int, int>(corridorsCount[i].Key - 1, corridorsCount[i].Value);
            corridorsCount[j] = new KeyValuePair <int, int>(corridorsCount[j].Key - 1, corridorsCount[j].Value);
        };

        while (true)
        {
            Array.Sort(corridorsCount, (a, b) => b.Key - a.Key);
            for (int i = 0; i < corridorsCount.Length; i++)
            {
                for (int j = i + 1; j < corridorsCount.Length; j++)
                {
                    if (corridorsCount[i].Key != corridorsCount[j].Key)
                    {
                        continue;
                    }
                    if (Random.Range(0, 2) == 0)
                    {
                        continue;
                    }
                    KeyValuePair <int, int> temp = corridorsCount[i];
                    corridorsCount[i] = corridorsCount[j];
                    corridorsCount[j] = temp;
                }
            }
            // Debug.LogFormat("<Starmap Reconstruction> Generator: corridors counts: {0}", corridorsCount.Select(kv => kv.Key).Join(""));
            while (n > 0 && corridorsCount[n].Key == 0)
            {
                n--;
            }
            if (n == 0)
            {
                break;
            }
            if (corridorsCount[n].Key == 1)
            {
                int pos = 0;
                for (int i = 0; i < n; i++)
                {
                    if ((corridorsCount[i].Key % 2 == 1) && (corridorsCount[i].Key > 1))
                    {
                        pos = i;
                        break;
                    }
                }
                if (corridorsCount[pos].Key == 1 && n > 1)
                {
                    throw new Exception("Unable to create starmap: left corridors eq 1");
                }
                add(pos, n);
                continue;
            }
            if (corridorsCount[n].Key != 2)
            {
                throw new Exception("Unable to create starmap: corridors counts gt 2");
            }
            if (n < 2)
            {
                throw new Exception("Unable to create starmap: lt 2 corridors left");
            }
            if (corridorsCount[0].Key == 2)
            {
                for (int i = 0; i < n - 1; i++)
                {
                    add(i, i + 1);
                }
                add(0, n);
                continue;
            }
            if (corridorsCount[n - 1].Key != 2)
            {
                throw new Exception("Unable to create starmap: only one corridor eq 2");
            }
            add(n - 1, n);
            add(n, 0);
            add(0, n - 1);
        }
        Dictionary <int, HashSet <KeyValuePair <string, string> > > infos = new Dictionary <int, HashSet <KeyValuePair <string, string> > >();

        foreach (string race in Races)
        {
            foreach (string regime in Regimes)
            {
                int adj = GetAdjacentStarsCount(race, regime, bomb);
                if (!infos.ContainsKey(adj))
                {
                    infos[adj] = new HashSet <KeyValuePair <string, string> >();
                }
                infos[adj].Add(new KeyValuePair <string, string>(race, regime));
            }
        }
        HashSet <int>    unnamedStars = new HashSet <int>(Enumerable.Range(0, 8));
        HashSet <string> usedNames    = new HashSet <string>();

        string[] starNames = Enumerable.Range(0, 8).Select(_ => "").ToArray();
        while (unnamedStars.Count > 0)
        {
            int starId = unnamedStars.PickRandom();
            unnamedStars.Remove(starId);
            HashSet <int> otherStars = new HashSet <int>(unnamedStars);
            while (otherStars.Count > 0)
            {
                int otherStarId = otherStars.PickRandom();
                otherStars.Remove(otherStarId);
                int dist = map.GetDistance(starId, otherStarId);
                IEnumerable <Distance> pairs = Distances.Where(d => d.distance == dist && !usedNames.Contains(d.from) && !usedNames.Contains(d.to));
                if (pairs.Count() == 0)
                {
                    continue;
                }
                Distance pair = pairs.PickRandom();
                starNames[starId]      = pair.from;
                starNames[otherStarId] = pair.to;
                usedNames.Add(pair.from);
                usedNames.Add(pair.to);
                unnamedStars.Remove(otherStarId);
                break;
            }
        }
        for (int i = 0; i < 8; i++)
        {
            if (starNames[i] != "")
            {
                continue;
            }
            starNames[i] = _randomStarNames.Where(s => !usedNames.Contains(s)).PickRandom();
            usedNames.Add(starNames[i]);
        }
        int[] idTransform = Enumerable.Range(0, 8).ToArray().Shuffle();
        Debug.LogFormat("<Starmap Reconstruction> Generator: ID transform: {0}", idTransform.Join(""));
        stars = Enumerable.Range(0, 8).Select(id => {
            int adj = map.GetAdjacentNodesCount(id);
            KeyValuePair <string, string> info = infos[adj].PickRandom();;
            return(new StarInfo(idTransform[id], starNames[id], info.Key, info.Value));
        }).ToArray();
        Array.Sort(stars, (a, b) => a.id - b.id);
        answerExample = map.TransformIds(idTransform);
    }
Esempio n. 21
0
 public static SimGameState GetSimGameState(this Starmap starmap)
 {
     return(starmap.GetFieldValue <SimGameState>("sim"));
 }
Esempio n. 22
0
 public static bool HasStarSystemBeenVisited(this Starmap starmap, StarSystemNode node)
 {
     return(starmap.HasStarSystemBeenVisited(node.System.ID));
 }
Esempio n. 23
0
        static void Postfix(Starmap __instance, SimGameState simGame)
        {
            try {
                PersistentMapClient.Logger.LogIfDebug($"methodSetOwner is:({methodSetOwner})");
                PersistentMapClient.Logger.LogIfDebug($"methodSetContractEmployers is:({methodSetContractEmployers})");
                PersistentMapClient.Logger.LogIfDebug($"methodSetContractTargets is:({methodSetContractTargets})");
                PersistentMapClient.Logger.LogIfDebug($"methodSetDescription is:({methodSetDescription})");
                PersistentMapClient.Logger.LogIfDebug($"fieldSimGameInterruptManager is:({fieldSimGameInterruptManager})");
                Fields.currentMap = Web.GetStarMap();
                if (Fields.currentMap == null)
                {
                    PersistentMapClient.Logger.LogIfDebug("Map not found");
                    SimGameInterruptManager interruptQueue = (SimGameInterruptManager)fieldSimGameInterruptManager.GetValue(simGame);
                    interruptQueue.QueueGenericPopup_NonImmediate("Connection Failure", "Map could not be downloaded", true);
                    return;
                }

                List <string>     changeNotifications             = new List <string>();
                List <StarSystem> transitiveContractUpdateTargets = new List <StarSystem>();

                foreach (PersistentMapAPI.System system in Fields.currentMap.systems)
                {
                    if (system == null)
                    {
                        PersistentMapClient.Logger.Log("System in map null");
                    }
                    if (system.activePlayers > 0)
                    {
                        AddActivePlayersBadgeToSystem(system);
                    }

                    StarSystem system2 = simGame.StarSystems.Find(x => x.Name.Equals(system.name));
                    if (system2 != null)
                    {
                        if (system2.Tags == null)
                        {
                            PersistentMapClient.Logger.Log(system2.Name + ": Has no Tags");
                        }
                        Faction newOwner = system.controlList.OrderByDescending(x => x.percentage).First().faction;
                        Faction oldOwner = system2.Owner;
                        // Update control to the new faction
                        methodSetOwner.Invoke(system2.Def, new object[] { newOwner });
                        system2.Tags.Remove(Helper.GetFactionTag(oldOwner));
                        system2.Tags.Add(Helper.GetFactionTag(newOwner));
                        system2 = Helper.ChangeWarDescription(system2, simGame, system);

                        // Update the contracts on the system
                        methodSetContractEmployers.Invoke(system2.Def, new object[] { Helper.GetEmployees(system2, simGame) });
                        methodSetContractTargets.Invoke(system2.Def, new object[] { Helper.GetTargets(system2, simGame) });

                        // If the system is next to enemy factions, update the map to show the border
                        if (Helper.IsBorder(system2, simGame) && simGame.Starmap != null)
                        {
                            system2.Tags.Add("planet_other_battlefield");
                        }
                        else
                        {
                            system2.Tags.Remove("planet_other_battlefield");
                        }

                        // If the owner changes, add a notice to the player and mark neighbors for contract updates
                        if (newOwner != oldOwner)
                        {
                            string newOwnerName = Helper.GetFactionShortName(newOwner, simGame.DataManager);
                            string oldOwnerName = Helper.GetFactionShortName(oldOwner, simGame.DataManager);
                            changeNotifications.Add($"{newOwnerName} took {system2.Name} from {oldOwnerName}");
                            foreach (StarSystem changedSystem in simGame.Starmap.GetAvailableNeighborSystem(system2))
                            {
                                if (!transitiveContractUpdateTargets.Contains(changedSystem))
                                {
                                    transitiveContractUpdateTargets.Add(changedSystem);
                                }
                            }
                        }
                    }
                }

                // For each system neighboring a system whose ownership changed, update their contracts as well
                foreach (StarSystem changedSystem in transitiveContractUpdateTargets)
                {
                    methodSetContractEmployers.Invoke(changedSystem.Def, new object[] { Helper.GetEmployees(changedSystem, simGame) });
                    methodSetContractTargets.Invoke(changedSystem.Def, new object[] { Helper.GetTargets(changedSystem, simGame) });

                    // Update the description on these systems to show the new contract options
                    PersistentMapAPI.System system = Fields.currentMap.systems.FirstOrDefault(x => x.name.Equals(changedSystem.Name));
                    if (system != null)
                    {
                        methodSetDescription.Invoke(changedSystem.Def,
                                                    new object[] { Helper.ChangeWarDescription(changedSystem, simGame, system).Def.Description });
                    }
                }

                if (changeNotifications.Count > 0 && !Fields.firstpass)
                {
                    SimGameInterruptManager interruptQueue2 = (SimGameInterruptManager)fieldSimGameInterruptManager.GetValue(simGame);
                    interruptQueue2.QueueGenericPopup_NonImmediate("War Activities", string.Join("\n", changeNotifications.ToArray()), true);
                }
                else
                {
                    Fields.firstpass = false;
                }
            }
            catch (Exception e) {
                PersistentMapClient.Logger.LogError(e);
            }
        }