public void MoveShipImageWithDelay(Action<StarSystem, Image, System.Drawing.Point, double> action, StarSystem system, Image shipImage, System.Drawing.Point targetLoc, double rotationAngle, int delay = 100) { try { var dispatcherTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Render); EventHandler handler = null; handler = (sender, e) => { // Stop the timer so it won't keep executing every X seconds // and also avoid keeping the handler in memory. dispatcherTimer.Tick -= handler; dispatcherTimer.Stop(); // Perform the action. action(system, shipImage, targetLoc, rotationAngle); // Start the next animation NextAnimation(); }; dispatcherTimer.Tick += handler; dispatcherTimer.Interval = TimeSpan.FromMilliseconds(delay); dispatcherTimer.Start(); } catch (Exception ex) { if (LogEverything) Logger(ex); } }
public void TravelTo(IStarship ship, StarSystem destination) { var startLocation = ship.Location; if (!startLocation.NeighbourStarSystems.ContainsKey(destination)) { throw new LocationOutOfRangeException( string.Format( "Cannot travel directly from {0} to {1}", startLocation.Name, destination.Name)); } double requiredFuel = startLocation.NeighbourStarSystems[destination]; if (ship.Fuel < requiredFuel) { throw new InsufficientFuelException( string.Format( "Not enough fuel to travel to {0} - {1}/{2}", destination.Name, ship.Fuel, requiredFuel)); } ship.Fuel -= requiredFuel; ship.Location = destination; }
private static void AddWarpPointToSystem(Game result, StarSystem system) { StarSystem targetSystem = new StarSystem(); int counter = 0; while (targetSystem.GalacticCoordinates.X == -1 && counter<25) { targetSystem = NearestSystemNotConnected(result, system); counter++; } if (targetSystem.GalacticCoordinates.X != -1) { // create points and assign opposite systems WarpPoint thisSide = new WarpPoint(); WarpPoint thatSide = new WarpPoint(); // This side of the Warp Point thisSide.StrategicPosition = WarpPointLocation(system); thisSide.Name = targetSystem.Name; thisSide.StrategicSystem = system; thisSide.LinkedSystem = targetSystem; thisSide.LinkedWarpPoint = thatSide; system.StrategicLocations[thisSide.StrategicPosition.X, thisSide.StrategicPosition.Y].Stellars.Add(thisSide); // Other side of the Warp Point thatSide.StrategicPosition = WarpPointLocation(targetSystem); thatSide.Name = system.Name; thatSide.StrategicSystem = targetSystem; thatSide.LinkedSystem = system; thatSide.LinkedWarpPoint = thisSide; targetSystem.StrategicLocations[thatSide.StrategicPosition.X, thatSide.StrategicPosition.Y].Stellars.Add(thatSide); } }
public void RunOutOfEnergy() { var game = new Game(); var system = new StarSystem(); system.RandomlySpawnEnemies = false; game.Add(system); var ship = new Ship(); system.AddEntity(ship); ship.ShieldsEngaged = false; ship.ImpulsePercentage = 100; Assert.IsTrue(ship.Energy > 0, "Ship didn't have any energy"); var oldVelocity = ship.Velocity; Assert.AreEqual(0, ship.Velocity.Magnitude(), "Ship should be at rest at first"); for (int i = 0; i < 200; i++) { game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); Assert.IsTrue(oldVelocity.Magnitude() < ship.Velocity.Magnitude(), "The ship didn't increase in speed"); oldVelocity = ship.Velocity; } Assert.AreEqual(0, ship.Energy, "The ship didn't run out of energy"); ship.Update(TimeSpan.FromSeconds(1)); Assert.AreEqual(oldVelocity, ship.Velocity, "The ship should not have been able to increase it's velocity without energy."); }
public SitRepItem(Screen screen, StarSystem system, Planet planet, Point point, string message) { ScreenEventIsIn = screen; SystemEventOccuredAt = system; PlanetEventOccuredAt = planet; PointEventOccuredAt = point; EventMessage = message; }
public Dreadnought(string name, StarSystem location) : base(name, DreadnoughtHealth, DreadnoughtShields, DreadnoughtDamage, DreadnoughtFuel, location) { }
public Frigate(string name, StarSystem location) : base(name, FrigateHealth, FrigateShields, FrigateDamage, FrigateFuel, location) { }
public Cruiser(string name, StarSystem location) : base(name, CruiserHealth, CruiserShields, CruiserDamage, CruiserFuel, location) { }
/// <summary> /// Initializes a new instance of the <see cref="Starship"/> class. /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="health"> /// The health. /// </param> /// <param name="shields"> /// The shields. /// </param> /// <param name="damage"> /// The damage. /// </param> /// <param name="fuel"> /// The fuel. /// </param> /// <param name="location"> /// The location. /// </param> protected Starship(string name, int health, int shields, int damage, double fuel, StarSystem location) { this.Name = name; this.Health = health; this.Shields = shields; this.Damage = damage; this.Fuel = fuel; this.Location = location; this.enhancements = new List<Enhancement>(); }
protected Starship(string name, int health, int shields, int damage, double fuel, StarSystem location, IEnumerable<Enhancement> enhancements) { this.Enhancements = enhancements; this.Name = name; this.Shields = shields; this.Health = health; this.Damage = damage; this.Fuel = fuel; this.Location = location; this.ProjectilesFired = InitialProjectilesFired; }
public BalancingStarSystem( StarSystem star ) { attachedStarSystem = star; inRangeSystems = new List<StarSystem>(); balancingPlanets = new List<BalancingPlanet>(); foreach (Planet p in attachedStarSystem.Planets) { balancingPlanets.Add(new BalancingPlanet(p)); } }
public static int CountInterestingConnections(StarSystem star) { return star.warps().Count((w) => { return (!w.isWormhole) && ( (w.starA.region == w.starB.region) || (!w.starA.region.isSpawn()) || (!w.starB.region.isSpawn()) ); } ); }
/// <summary> /// Constructor for the form object. /// </summary> public CelestialNavigation() { ourSystem = new StarSystem(); velvetBag = new Dice(); InitializeComponent(); starTable = new DataTable("starTable"); starTable.Columns.Add("Current Mass (sol mass)", typeof(double)); starTable.Columns.Add("Name", typeof(string)); starTable.Columns.Add("Order", typeof(string)); starTable.Columns.Add("Spectral Type", typeof(string)); starTable.Columns.Add("Current Luminosity (sol lumin)", typeof(double)); starTable.Columns.Add("Effective Temperature(K)", typeof(double)); starTable.Columns.Add("Orbital Radius (AU)", typeof(double)); starTable.Columns.Add("Gas Giant", typeof(string)); starTable.Columns.Add("Color", typeof(string)); starTable.Columns.Add("Stellar Evolution Stage", typeof(string)); starTable.Columns.Add("Flare Star", typeof(string)); starTable.Columns.Add("Orbital Details", typeof(string)); planetTable = new DataTable("planetTable"); planetTable.Columns.Add("Name", typeof(string)); planetTable.Columns.Add("Size (Type)", typeof(string)); planetTable.Columns.Add("Diameter (KM)", typeof(double)); planetTable.Columns.Add("Orbital Radius (AU)", typeof(double)); planetTable.Columns.Add("Gravity (m/s)", typeof(double)); planetTable.Columns.Add("Atmosphere Pressure (atm)", typeof(string)); planetTable.Columns.Add("Atmosphere Notes", typeof(string)); planetTable.Columns.Add("Hydrographic Coverage", typeof(string)); planetTable.Columns.Add("Climate Data", typeof(string)); planetTable.Columns.Add("Resource Indicator", typeof(string)); //assign the source. We do it this way to allow for refreshing things. starSource = new BindingSource(); starSource.DataSource = this.starTable; createStarsFinished = false; planetSource = new BindingSource(); planetSource.DataSource = this.planetTable; createPlanetsFinished = false; dgvStars.DataSource = starSource; dgvPlanets.DataSource = planetSource; dgvPlanets.Columns[2].Width = 130; dgvPlanets.Columns[3].Width = 100; dgvPlanets.Columns[5].Width = 160; dgvPlanets.Columns[6].Width = 150; dgvPlanets.Columns[7].Width = 100; dgvPlanets.Columns[8].Width = 195; }
public StarSystem GetNextSystemBFS(StarSystem startingSystem, StarSystem targetSystem) { // Players might call for path to current system if (startingSystem == targetSystem) return startingSystem; // Queue needs to store path-thus-far and current system Queue<Tuple<List<StarSystem>, StarSystem>> StarSystemQueue = new Queue<Tuple<List<StarSystem>, StarSystem>>(); // Need to track visited systems to prevent infinite loops List<StarSystem> visitedSystems = new List<StarSystem>(); // Starting system is already visited visitedSystems.Add(startingSystem); // For connected systems that we haven't already visited foreach (StarSystem system in startingSystem.GetConnectedStarSystems().Where(f => !visitedSystems.Contains(f))) { List<StarSystem> pathList = new List<StarSystem>(); pathList.Add(system); // Add to visited systems so it's not evaluated in the loop visitedSystems.Add(system); // Enqueue the path & system StarSystemQueue.Enqueue(new Tuple<List<StarSystem>, StarSystem>(pathList, system)); } // Loop til there's an answer or all paths are exausted while(StarSystemQueue.Count>0) { // Grab current from the queue Tuple<List<StarSystem>,StarSystem> currentSystem = StarSystemQueue.Dequeue(); // If current is the target, return the first system from the path if (currentSystem.Item2 == targetSystem) return currentSystem.Item1.First(); // For connected systems that we haven't already visited foreach (StarSystem system in currentSystem.Item2.GetConnectedStarSystems().Where(f => !visitedSystems.Contains(f))) { // rebuild path list to prevent changing other paths by reference List<StarSystem> pathList = new List<StarSystem>(); foreach (var previous in currentSystem.Item1) pathList.Add(previous); pathList.Add(system); // add new system to path visitedSystems.Add(system); // add new system to visited // Enqueue the path & system StarSystemQueue.Enqueue(new Tuple<List<StarSystem>, StarSystem>(pathList, system)); } } // No valid answer at this point, return starting system and handle in outer code return startingSystem; }
/// <summary> /// The create ship. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="name"> /// The name. /// </param> /// <param name="location"> /// The location. /// </param> /// <returns> /// The <see cref="IStarship"/>. /// </returns> /// <exception cref="NotSupportedException"> /// </exception> public IStarship CreateShip(StarshipType type, string name, StarSystem location) { switch (type) { case StarshipType.Frigate: return new Frigate(name, location); case StarshipType.Cruiser: return new Cruiser(name, location); case StarshipType.Dreadnought: return new Dreadnought(name, location); default: throw new NotSupportedException("Starship type not supported."); } }
protected ShipBase( string name, int health, int shields, int damage, double fuel, StarSystem location) { this.Name = name; this.Health = health; this.Shields = shields; this.Damage = damage; this.Fuel = fuel; this.Location = location; }
void OnJoin(StarSystem starSystem) { Debug.Log("Joining " + starSystem); if(starSystem.data.id == "") { Debug.LogError("Missing star system id"); return; } joinSystem = starSystem; starCamera.TargetSystem = starSystem; GameClient.Instance.sceneTransition.startDelay = 2.25f; GameClient.Instance.sceneTransition.TransitionOut(); GameClient.Instance.sceneTransition.Message = "Joining " + starSystem.data.name; elapsed = 0; }
public void DestroyShip() { var game = new Game(); var system = new StarSystem(); system.RandomlySpawnEnemies = false; game.Add(system); var ship = new Ship(); system.AddEntity(ship); ship.ImpulsePercentage = 100; Assert.IsTrue(ship.Energy > 0, "Ship didn't have any energy"); var oldVelocity = ship.Velocity; Assert.AreEqual(0, ship.Velocity.Magnitude(), "Ship should be at rest at first"); for (int i = 0; i < 20; i++) { game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); Assert.IsTrue(oldVelocity.Magnitude() < ship.Velocity.Magnitude(), "The ship didn't increase in speed"); oldVelocity = ship.Velocity; } var missile = new Projectile(); system.AddEntity(missile); missile.Target = ship; oldVelocity = missile.Velocity; Assert.AreEqual(0, missile.Velocity.Magnitude(), "Missile should be at rest at first."); for (int i = 0; i < 9; i++) { game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); Assert.IsFalse(missile.IsDestroyed, "the missile got destroyed."); Assert.IsTrue(oldVelocity.Magnitude() < missile.Velocity.Magnitude(), "The missile didn't increase in speed"); oldVelocity = missile.Velocity; } game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); Assert.IsTrue(missile.IsDestroyed, "the missile didn't get destroyed."); oldVelocity = missile.Velocity; game.Update(TimeSpan.FromSeconds(0.25)); Assert.AreEqual(oldVelocity.Magnitude(), missile.Velocity.Magnitude(), "The (dead) missile didn't increase in speed"); }
public StrategicWindow(Game gameState, Player currentPlayer = null, StarSystem currentSystem = null, System.Drawing.Point currentSystemLoc = new System.Drawing.Point(), Ship currentShip = null) { InitializeComponent(); #region Bindings lbxTargetShips.ItemsSource = SelectedShipList; #endregion initImages(); this.GameState = gameState; this.currentPlayer = currentPlayer; this.currentSystem = currentSystem; this.currentShip = currentShip; initGalaxyMap(); ShowSystemMap(currentSystem); scrollGalaxyGridToSystem(currentSystem); highlightSelectedSystem(currentSystem); selectSystemCoordinates(currentSystemLoc); }
public void LaunchMissileTowardTarget() { var game = new Game(); var system = new StarSystem(); game.Add(system); var enemy = new Ship(); system.AddEntity(enemy); var attacker = new Ship() { Tubes = 3 }; system.AddEntity(attacker); game.Update(TimeSpan.FromSeconds(0.25)); attacker.LoadProjectile(0, ProjectileType.Torpedo); enemy.ImpulsePercentage = 100; game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); game.Update(TimeSpan.FromSeconds(0.25)); Assert.AreNotEqual(0, enemy.Position.X, "The enemy should have moved along the x axis"); Assert.AreEqual(0, attacker.Position.X, "the attacker was not at the center"); var missile = attacker.LaunchProjectile(0, enemy); Assert.AreEqual(0, missile.Position.X, "the missile was not at the center"); var oldDiff = enemy.Position.X - missile.Position.X; missile.Update(TimeSpan.FromSeconds(0.25)); var newDiff = enemy.Position.X - missile.Position.X; Assert.IsTrue(newDiff < oldDiff, "The missile didn't get closer to the ship"); }
public Planet(StarSystem parentSystem, float starDistance, int seed) { // distance in AU (0.2 to 40) this.Distance = starDistance; this.Seed = seed; Random.seed = seed; this.Blueprint = GetPlanetBlueprint(parentSystem); GeneratePlanetProperties(this.Blueprint); Heightmap = GeneratePlanetHeightmap(this.Blueprint); this.textureDiffuse = GeneratePlanetDiffuseMap(this.Blueprint, this.Heightmap); this.textureIllumination = GeneratePlanetIlluminationMap(this.Blueprint, this.Heightmap); this.textureNormal = GeneratePlanetNormalmap(this.Blueprint, this.Heightmap); GeneratePlanetResources(this.Blueprint); Debug.Log(this); }
private string CreateHeader(StarSystem system, int found, int totalValue, int totalHonkValue, string nextSystem = null) { double percentage = 0.00; var totalValueString = string.Format("{0:n0}", totalValue); var totalHonkValueString = string.Format("{0:n0}", totalHonkValue); if (system.TotalBodies > 0) { var division = found / (double)system.TotalBodies; percentage = division * 100.00; } var output = new StringBuilder() .AppendLine("Elite: Dangerous >> Galactic Positioning System || Created By: ComputerMaster1st") .AppendLine() .AppendFormat("Current System : {0} {1}", system.Name, string.IsNullOrEmpty(nextSystem) ? "" : $"=> Jumping To {nextSystem}").AppendLine() .AppendFormat("Co-ordinates : Latitude ({0}) | Longitude ({1}) | Elevation ({2})", system.Latitude, system.Longitude, system.Elevation).AppendLine() .AppendFormat("Distance (Ly) : {0} (Sol)", string.Format("{0:n2}", Math.Round(Math.Pow(Math.Pow(system.Longitude, 2) + Math.Pow(system.Latitude, 2) + Math.Pow(system.Elevation, 2), 0.5), 2))).AppendLine() .AppendFormat("System Scan : {0}% Complete{1}{2}", Math.Round(percentage, 0), system.IsHonked ? "" : AddBrackets("Awaiting FSS Discovery Scan"), system.IsComplete ? AddBrackets("System Scan Complete") : "").AppendLine() .AppendFormat("Expected Bodies : {0} ({1} non-bodies){2}", system.TotalBodies, system.TotalNonBodies, AddBrackets($"System Value+Honk: {totalValueString}+{totalHonkValueString} cr")).AppendLine() .AppendLine("════════════════════════════════════════════════════════════════════════════════════════════════════"); return(output.ToString()); }
public override void Execute(string[] commandArgs) { string shipName = commandArgs[1]; string destinationName = commandArgs[2]; IStarship ship = null; ship = this.GameEngine.Starships.FirstOrDefault(s => s.Name == shipName); this.ValidateAlive(ship); var previousLocation = ship.Location; StarSystem destionation = null; destionation = this.GameEngine.Galaxy.StarSystems.FirstOrDefault(ss => ss.Name == destinationName); if (previousLocation == destionation) { throw new ShipException(string.Format(Messages.ShipAlreadyInStarSystem, destinationName)); } this.GameEngine.Galaxy.TravelTo(ship, destionation); Console.WriteLine(Messages.ShipTraveled, shipName, previousLocation.Name, destinationName); }
static void Postfix(Contract __instance, MissionResult result) { try { GameInstance game = LazySingletonBehavior <UnityGameInstance> .Instance.Game; StarSystem system = game.Simulation.StarSystems.Find(x => x.ID == __instance.TargetSystem); Faction oldOwner = system.Def.Owner; if (result == MissionResult.Victory) { system = Helper.PlayerAttackSystem(system, game.Simulation, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, true); } else { system = Helper.PlayerAttackSystem(system, game.Simulation, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, false); } if (system.Def.Owner != oldOwner) { SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation); interruptQueue.QueueGenericPopup_NonImmediate("Conquered", Helper.GetFactionName(system.Def.Owner, game.Simulation.DataManager) + " took " + system.Name + " from " + Helper.GetFactionName(oldOwner, game.Simulation.DataManager), true, null); } } catch (Exception e) { Logger.LogError(e); } }
public static void cleanupSystem(StarSystem system) { if (flareups.ContainsKey(system.ID)) { modLog.Debug?.Write($"Removing flareup at {system.ID}"); flareups.Remove(system.ID); } if (system == sim.CurSystem) { modLog.Debug?.Write($"Player was participating in flareup at {system.ID}; Removing company tags"); sim.CompanyTags.Remove("WIIC_helping_attacker"); sim.CompanyTags.Remove("WIIC_helping_defender"); } // Revert system description to the default if (fluffDescriptions.ContainsKey(system.ID)) { modLog.Debug?.Write($"Reverting map description for {system.ID}"); AccessTools.Method(typeof(DescriptionDef), "set_Details").Invoke(system.Def.Description, new object[] { fluffDescriptions[system.ID] }); } Utilities.redrawMap(); }
public void TestStarSystemData() { // Test system & body data in a complete star system StarSystem starSystem = DataProviderService.GetSystemData("Sol"); Assert.AreEqual("Sol", starSystem.name); Assert.AreEqual(17072, starSystem.EDDBID); Assert.AreEqual((decimal)0, starSystem.x); Assert.AreEqual((decimal)0, starSystem.y); Assert.AreEqual((decimal)0, starSystem.z); Assert.IsNotNull(starSystem.population); Assert.IsNotNull(starSystem.Faction); Assert.IsNotNull(starSystem.Faction.Allegiance.invariantName); Assert.IsNotNull(starSystem.Faction.Government.invariantName); Assert.IsNotNull(starSystem.Faction.FactionState.invariantName); Assert.IsNotNull(starSystem.Faction.name); Assert.IsNotNull(starSystem.securityLevel.invariantName); Assert.IsNotNull(starSystem.primaryeconomy); Assert.AreEqual("Common", starSystem.Reserve.invariantName); Assert.IsNotNull(starSystem.stations.Count); Assert.IsNotNull(starSystem); Assert.IsNotNull(starSystem.bodies); Assert.IsFalse(starSystem.bodies.Count == 0); }
public static void SetCurrentSystemPrefix(StarSystem system, bool force = false, bool timeSkip = false) { try { WIIC.modLog.Debug?.Write($"Entering system {system.ID} from {WIIC.sim.CurSystem.ID}"); if (WIIC.flareups.ContainsKey(WIIC.sim.CurSystem.ID)) { WIIC.modLog.Debug?.Write($"Found flareup from previous system, cleaning up contracts"); // Clean up participation contracts for the system we've just left Flareup prevFlareup = WIIC.flareups[WIIC.sim.CurSystem.ID]; prevFlareup.removeParticipationContracts(); } if (WIIC.flareups.ContainsKey(system.ID)) { WIIC.modLog.Debug?.Write($"Found flareup for new system, adding contracts"); // Create new participation contracts for the system we're entering Flareup flareup = WIIC.flareups[system.ID]; flareup.spawnParticipationContracts(); } } catch (Exception e) { WIIC.modLog.Error?.Write(e); } }
public void Start(bool build = false) { _reader.OnAllBodiesFound += OnAllBodiesFound; _reader.OnBodyScan += OnBodyScan; _reader.OnDssScan += OnSurfaceScan; _reader.OnFsdJump += OnEnteringNewSystem; _reader.OnFssDiscoveryScan += OnSystemHonk; _reader.OnReady += OnReady; _reader.OnShutdown += OnShutdown; _reader.OnStartJump += OnEnteringHyperspace; _system = StarSystem.Load() ?? new StarSystem("Waiting...", new List <double>() { 0, 0, 0 }); Console.Title = $"Elite: Dangerous | Galactic Positioning System | {_system.Name}"; _writer.Write(_system); if (build) { _reader.Build(); } _reader.Start(); }
public static void Postfix(SGContractsWidget __instance, Contract contract, LocalizableText ___ContractLocationField, GameObject ___ContractLocation, GameObject ___ContractLocationArrow, GameObject ___TravelContractBGFill, GameObject ___TravelIcon, GameObject ___PriorityMissionStoryObject) { try { // Only for "normal" contracts with no negotiations if (contract.IsOpportunityMission()) { Logger.Debug($"[SGContractsWidget_PopulateContract_POSTFIX] {contract.Override.ID} is an opportunity mission"); StarSystem targetSystem = contract.GameContext.GetObject(GameContextObjectTagEnum.TargetStarSystem) as StarSystem; ___ContractLocationField.SetText("Opportunity Mission at {0}", new object[] { targetSystem.Name }); ___ContractLocation.SetActive(true); ___ContractLocationArrow.SetActive(false); //___TravelContractBGFill.SetActive(false); ___TravelIcon.SetActive(false); __instance.ForceRefreshImmediate(); } } catch (Exception e) { Logger.Error(e); } }
private static void TryAddOrUpdateSystem(StarSystem system, bool shouldUpdate = true) { DbContextOptionsBuilder <EliteDbContext> config = new DbContextOptionsBuilder <EliteDbContext>(); config.UseNpgsql(_connectionString); using (EliteDbContext context = new EliteDbContext(config.Options)) { long i = context.StarSystem.Where(ss => ss.Name == system.Name).Select(ss => ss.Id).FirstOrDefault(); if (i == 0)// && system.IsPopulated) { context.StarSystem.Add(system); context.SaveChanges(); Console.WriteLine($"Added '{system.Name}'"); } else if (shouldUpdate) { system.Id = i; context.StarSystem.Update(system); context.SaveChanges(); Console.WriteLine($"Updated '{system.Name}'"); } } }
public override void Execute(string[] commandArgs) { string shipType = commandArgs[1]; string shipName = commandArgs[2]; string starSystemName = commandArgs[3]; if (base.GameEngine.Starships.Any(ship => ship.Name == shipName)) { throw new ShipException(Messages.DuplicateShipName); } StarshipType starshipType = (StarshipType)Enum.Parse(typeof(StarshipType), shipType); StarSystem starSystem = base.GameEngine.Galaxy.GetStarSystemByName(starSystemName); IStarship starship = base.GameEngine.ShipFactory.CreateShip(starshipType, shipName, starSystem); if (commandArgs.Length > 4) { string[] enhancements = commandArgs.Skip(4).ToArray(); foreach (string enhancementStr in enhancements) { EnhancementType enhancementType = (EnhancementType)Enum.Parse(typeof(EnhancementType), enhancementStr); Enhancement enhancement = base.GameEngine.EnhancementFactory.Create(enhancementType); starship.AddEnhancement(enhancement); } } base.GameEngine.Starships.Add(starship); starSystem.Starships.Add(starship); Console.WriteLine(string.Format(Messages.CreatedShip, shipType, shipName)); }
static bool Prefix(StarSystem __instance) { try { if (__instance.CurBreadcrumbOverride > 0) { ReflectionHelper.InvokePrivateMethode(__instance, "set_CurMaxBreadcrumbs", new object[] { __instance.CurBreadcrumbOverride }); } else { int num = __instance.MissionsCompleted; if (num < __instance.Sim.Constants.Story.MissionsForFirstBreadcrumb) { return(false); } ReflectionHelper.InvokePrivateMethode(__instance, "set_CurMaxBreadcrumbs", new object[] { __instance.Sim.Constants.Story.MaxBreadcrumbsPerSystem }); } return(false); } catch (Exception e) { Logger.LogError(e); return(false); } }
private void ImportExportSystem(StarSystem system) { string jsonString = SerializationManager.Export(_game, system); int entityCount = system.SystemManager.GetAllEntitiesWithDataBlob <SystemBodyInfoDB>(_smAuthToken).Count; _game = TestingUtilities.CreateTestUniverse(0); _smAuthToken = new AuthenticationToken(_game.SpaceMaster); StarSystem importedSystem = SerializationManager.ImportSystemJson(_game, jsonString); Assert.AreEqual(system.Guid, importedSystem.Guid); // See that the entities were imported. Assert.AreEqual(entityCount, importedSystem.SystemManager.GetAllEntitiesWithDataBlob <SystemBodyInfoDB>(_smAuthToken).Count); // Ensure the system was added to the game's system list. List <StarSystem> systems = _game.GetSystems(_smAuthToken); Assert.AreEqual(1, systems.Count); // Ensure the returned value references the same system as the game's system list system = _game.GetSystem(_smAuthToken, system.Guid); Assert.AreEqual(importedSystem, system); }
private string BuildScanScript(StarSystem system) { string script = string.Format(_scanPhraseBook.GetRandomPhrase(), system.Celestials.Count()); var celestialsByCategory = system.Celestials .Where(c => !c.Scanned) .GroupBy(c => c.Clasification) .ToDictionary(grp => grp.Key, grp => grp.Count()); int counter = 0; bool single = celestialsByCategory.First().Value == 1; script += single ? $"{_isPhrase} " : $"{_arePhrase} "; foreach (var item in celestialsByCategory) { counter++; if (counter == celestialsByCategory.Count() && celestialsByCategory.Count() > 1) { script += $"{_andPhrase} "; } script += $"{item.Value} {item.Key}"; if (item.Value > 1) { script += $"{_puralPhrase} "; } script += ", "; } return(script); }
private SystemState(StarSystem system) { StarSystem = system; //SystemContacts = system.FactionSensorContacts[faction.ID]; //_sensorChanges = SystemContacts.Changes.Subscribe(); PulseMgr = system.ManagerSubpulses; foreach (var entityItem in system.GetAllEntitiesWithDataBlob <NameDB>()) { var entityState = new EntityState(entityItem);// { Name = "Unknown" }; entityState.Name = entityItem.GetDataBlob <NameDB>().DefaultName; EntityStatesWithNames.Add(entityItem.Guid, entityState); if (entityItem.HasDataBlob <PositionDB>()) { EntityStatesWithPosition.Add(entityItem.Guid, entityState); } else if (entityItem.HasDataBlob <ColonyInfoDB>()) { EntityStatesColonies.Add(entityItem.Guid, entityState); } } var listnerblobs = new List <int>(); listnerblobs.Add(EntityManager.DataBlobTypes[typeof(PositionDB)]); AEntityChangeListner changeListner = new EntityChangeListnerSM(StarSystem);//, listnerblobs); _changeListner = changeListner; /* * foreach (SensorContact sensorContact in SystemContacts.GetAllContacts()) * { * var entityState = new EntityState(sensorContact) { Name = "Unknown" }; * EntityStates.Add(sensorContact.ActualEntity.ID, entityState); * }*/ }
private static List <StarSystem> ParseEddbSystemsAsync(List <object> responses) { List <Task <StarSystem> > starSystemTasks = new List <Task <StarSystem> >(); foreach (object response in responses) { starSystemTasks.Add(Task.Run(() => ParseEddbSystem(response))); } Task.WhenAll(starSystemTasks.ToArray()); List <StarSystem> systems = new List <StarSystem>(); foreach (Task <StarSystem> task in starSystemTasks) { StarSystem system = task.Result; if (system != null) { systems.Add(system); } ; } return(systems); }
private StarSystem GetSystemExtras(StarSystem starSystem, bool showInformation, bool showBodies, bool showStations, bool showFactions) { if (starSystem != null) { if (showBodies) { List <Body> bodies = edsmService.GetStarMapBodies(starSystem.systemname) ?? new List <Body>(); foreach (Body body in bodies) { body.systemname = starSystem.systemname; body.systemAddress = starSystem.systemAddress; body.systemEDDBID = starSystem.EDDBID; } starSystem.AddOrUpdateBodies(bodies); } if (starSystem?.population > 0) { List <Faction> factions = new List <Faction>(); if (showFactions || showStations) { factions = edsmService.GetStarMapFactions(starSystem.systemname); starSystem.factions = factions; } if (showStations) { List <Station> stations = edsmService.GetStarMapStations(starSystem.systemname); starSystem.stations = SetStationFactionData(stations, factions); starSystem.stations = stations; } } starSystem = LegacyEddpService.SetLegacyData(starSystem, showInformation, showBodies, showStations); } return(starSystem); }
/// <summary> /// Kick off the game thread /// </summary> /// <param name="server"></param> /// <param name="log"></param> public DPGameRunner(DPServer server, ILogController log, uint base_objid, StarSystem system) { Server = server; this.Log = log; this._baseObjid = base_objid; _lastAllocatedObjid = base_objid; this.system = system; foreach (var s in system.Solars) { Objects[s.Key] = s.Value; s.Value.Runner = this; if (s.Value.Loadout != null) { AddTimer(s.Value); } } // Start the game simulation thread var game_thread = new Thread(GameThreadRun); game_thread.Start(); }
/// <summary> /// The seed star systems. /// </summary> /// <param name="galaxy"> /// The galaxy. /// </param> public static void SeedStarSystems(Galaxy galaxy) { var artemisTau = new StarSystem("Artemis-Tau"); var serpentNebula = new StarSystem("Serpent-Nebula"); var hadesGamma = new StarSystem("Hades-Gamma"); var keplerVerge = new StarSystem("Kepler-Verge"); galaxy.StarSystems.Add(artemisTau); galaxy.StarSystems.Add(serpentNebula); galaxy.StarSystems.Add(hadesGamma); galaxy.StarSystems.Add(keplerVerge); artemisTau.NeighbourStarSystems.Add(serpentNebula, 50); artemisTau.NeighbourStarSystems.Add(keplerVerge, 120); serpentNebula.NeighbourStarSystems.Add(artemisTau, 50); serpentNebula.NeighbourStarSystems.Add(hadesGamma, 360); hadesGamma.NeighbourStarSystems.Add(serpentNebula, 360); hadesGamma.NeighbourStarSystems.Add(keplerVerge, 145); keplerVerge.NeighbourStarSystems.Add(hadesGamma, 145); keplerVerge.NeighbourStarSystems.Add(artemisTau, 120); }
public static bool IsRandomTravelBorder(StarSystem system, SimGameState Sim) { try { bool result = false; if (Sim.Starmap != null) { foreach (StarSystem neigbourSystem in Sim.Starmap.GetAvailableNeighborSystem(system)) { if (system.OwnerDef.ID != neigbourSystem.OwnerDef.ID) { result = true; break; } } } return(result); } catch (Exception ex) { PersistentMapClient.Logger.LogError(ex); return(false); } }
public static void syncEdsmLogBatch(Dictionary <string, StarMapLogInfo> systems, Dictionary <string, string> comments) { List <StarSystem> batchSystems = new List <StarSystem>(); string[] batchNames = systems.Select(x => x.Key).ToArray(); List <StarSystem> starSystems = StarSystemSqLiteRepository.Instance.GetOrCreateStarSystems(batchNames, false); foreach (string name in batchNames) { StarSystem CurrentStarSystem = starSystems.FirstOrDefault(s => s.name == name); if (CurrentStarSystem == null) { continue; } CurrentStarSystem.visits = systems[name].visits; CurrentStarSystem.lastvisit = systems[name].lastVisit; if (comments.ContainsKey(name)) { CurrentStarSystem.comment = comments[name]; } batchSystems.Add(CurrentStarSystem); } saveFromStarMapService(batchSystems); }
public void Handle(IEvent @event) { string currentSystem = _playerStatus.Location; StarSystem system = _navigator.GetSystem(currentSystem); if (system == null) { _communicator.Communicate(_skipPhrases.GetRandomPhrase()); return; } Celestial nextToScan = system.Celestials .Where(c => c.Scanned == false) .OrderBy(r => r.ShortName) .FirstOrDefault(); if (nextToScan == null) { _communicator.Communicate(_completePhrases.GetRandomPhrase()); return; } _communicator.Communicate(_nextScanPhrases.GetRandomPhraseWith(nextToScan.ShortName)); }
public void ScanEvent_WithSameCelestialScanned_ShouldDoNothing() { IDataStore <StarSystemDocument> dataStore = CreateDataStore(); Navigator navigator = CreateNavigator(dataStore); PlayerStatusRepository playerStatus = CreatePlayerStatusRepository(); CelestialScanCommand sut = CreateSut(navigator, playerStatus, _phrases); Celestial celestial = Build.A.Celestial; StarSystem currentSystem = Build.A.StarSystem.WithCelestial(celestial); List <StarSystem> starSystems = Build.Many.StarSystems(currentSystem); navigator.PlanExpedition(starSystems); playerStatus.SetLocation(currentSystem.Name); TestEvent testEvent = Build.An.Event.WithEvent(sut.SupportedCommand) .WithPayload(_payloadKey, celestial.Name); sut.Handle(testEvent); var storedSystem = dataStore.FindOne(s => s.Name == currentSystem.Name); storedSystem.Scanned.Should().BeTrue(); storedSystem.Celestials.Single().Scanned.Should().BeTrue(); }
/// <summary> /// Gets the connection endpoint. /// </summary> /// <param name="map">The map.</param> /// <param name="end">The end.</param> /// <returns></returns> /// <exception cref="GalaxyMapBuildingException">If endpoint cannot be found.</exception> private WormholeEndpoint GetConnectionEndpoint(GalaxyMap map, GalaxyMapConnectionEnd end) { StarSystem starSystem = map[end.StarSystemName]; if (starSystem == null) { throw new GalaxyMapBuildingException( String.Format("Invalid connection: {0}, star system '{1}' not found.", this, end.StarSystemName) ); } WormholeEndpoint endpoint = starSystem.WormholeEndpoints[end.WormholeEndpointId]; if (endpoint == null) { throw new GalaxyMapBuildingException( String.Format("Invalid connection: {0}, wormhole endpoint '{1}' not found in star system '{2}'.", this, end.WormholeEndpointId, end.StarSystemName) ); } return(endpoint); }
public static void MaterialTradersEddb(Client client, string systemName, string type) { // https://eddb.io/station?h=has_material_trader&i=1&r=10340&e=4 Manufactured // https://eddb.io/station?h=has_material_trader&i=1&r=10340&e=2 Raw // https://eddb.io/station?h=has_material_trader&i=1&r=10340&e=3 Data var economy = 0; if ("manufactured".CompareTo(type) == 0) { economy = 4; } if ("raw".CompareTo(type) == 0) { economy = 2; } if ("data".CompareTo(type) == 0) { economy = 3; } StarSystem starSystem = StarSystemSqLiteRepository.Instance.GetOrCreateStarSystem(systemName, true); string url; if (economy > 0) { url = $"https://eddb.io/station?h=has_material_trader&i=1&r={starSystem.EDDBID}&e={economy}"; } else { url = $"https://eddb.io/station?h=has_material_trader&i=1&r={starSystem.EDDBID}"; } client.NewChromeTab(url, 800); }
public Dictionary<int,StarSystem> BuildCollection() { String systemDataSet = ReadData.ReadSystem(); Dictionary<int, StarSystem> starSystemCollection = new Dictionary<int, StarSystem>(); dynamic readSystem = JsonConvert.DeserializeObject(systemDataSet); int collectionCounter = 0; foreach (var systemData in readSystem) { starSystemCollection[collectionCounter] = new StarSystem(); starSystemCollection[collectionCounter].id = systemData.id; starSystemCollection[collectionCounter].name = systemData.name; starSystemCollection[collectionCounter].X = systemData.x; starSystemCollection[collectionCounter].Y = systemData.y; starSystemCollection[collectionCounter].Z = systemData.z; starSystemCollection[collectionCounter].faction = systemData.faction; starSystemCollection[collectionCounter].population = systemData.population; starSystemCollection[collectionCounter].government = systemData.government; starSystemCollection[collectionCounter].allegiance = systemData.allegiance; starSystemCollection[collectionCounter].state = systemData.state; starSystemCollection[collectionCounter].security = systemData.security; starSystemCollection[collectionCounter].primary_economy = systemData.primary_economy; starSystemCollection[collectionCounter].power = systemData.power; starSystemCollection[collectionCounter].power_state = systemData.power_state; starSystemCollection[collectionCounter].simbad_ref = systemData.simbad_ref; collectionCounter += 1; } return starSystemCollection; }
public Frigate(string name, StarSystem location) : base(name, location, health: 60, shileds: 50, damage: 30, fuel: 220) { this.ProjectilesFired = 0; this.Type = StarshipType.Frigate; }
public void Enter(App app) { this._app = app; if (this._app.GameDatabase == null) { this._app.NewGame(); } app.Game.SetLocalPlayer(app.GetPlayer(1)); this._set = new GameObjectSet(app); this._postLoadedObjects = new List <IGameObject>(); this._set.Add((IGameObject) new Sky(app, SkyUsage.InSystem, new Random().Next())); if (ScriptHost.AllowConsole) { this._input = this._set.Add <CombatInput>(); } this._camera = this._set.Add <OrbitCameraController>(); this._camera.SetAttractMode(true); this._camera.TargetPosition = new Vector3(500000f, 0.0f, 0.0f); this._camera.MinDistance = 1f; this._camera.MaxDistance = 11000f; this._camera.DesiredDistance = 11000f; this._camera.DesiredPitch = MathHelper.DegreesToRadians(-2f); this._camera.DesiredYaw = MathHelper.DegreesToRadians(45f); int systemId = 0; IEnumerable <HomeworldInfo> homeworlds = this._app.GameDatabase.GetHomeworlds(); HomeworldInfo homeworldInfo = homeworlds.FirstOrDefault <HomeworldInfo>((Func <HomeworldInfo, bool>)(x => x.PlayerID == app.LocalPlayer.ID)); if (homeworldInfo != null) { systemId = homeworldInfo.SystemID; } else if (homeworlds.Count <HomeworldInfo>() > 0) { systemId = homeworlds.ElementAt <HomeworldInfo>(new Random().NextInclusive(0, homeworlds.Count <HomeworldInfo>() - 1)).SystemID; } this._starsystem = new StarSystem(this._app, 1f, systemId, new Vector3(0.0f, 0.0f, 0.0f), false, (CombatSensor)null, true, 0, false, true); this._set.Add((IGameObject)this._starsystem); this._starsystem.PostSetProp("InputEnabled", false); this._starsystem.PostSetProp("RenderSuroundingItems", false); Vector3 vector1 = new Vector3(); float num1 = 10000f; IEnumerable <PlanetInfo> infosOrbitingStar = this._app.GameDatabase.GetPlanetInfosOrbitingStar(systemId); bool flag1 = false; foreach (PlanetInfo planetInfo in infosOrbitingStar) { if (planetInfo != null) { ColonyInfo colonyInfoForPlanet = this._app.GameDatabase.GetColonyInfoForPlanet(planetInfo.ID); if (colonyInfoForPlanet != null && colonyInfoForPlanet.PlayerID == this._app.LocalPlayer.ID) { vector1 = this._app.GameDatabase.GetOrbitalTransform(planetInfo.ID).Position; num1 = StarSystemVars.Instance.SizeToRadius(planetInfo.Size); flag1 = true; break; } } } if (!flag1) { PlanetInfo[] array = infosOrbitingStar.ToArray <PlanetInfo>(); if (array.Length > 0) { PlanetInfo planetInfo = array[new Random().Next(array.Length)]; vector1 = this._app.GameDatabase.GetOrbitalTransform(planetInfo.ID).Position; num1 = StarSystemVars.Instance.SizeToRadius(planetInfo.Size); } } this._camera.DesiredYaw = -(float)Math.Atan2((double)vector1.Z, (double)vector1.X); this._camera.TargetPosition = vector1; Matrix rotationYpr = Matrix.CreateRotationYPR(this._camera.DesiredYaw, 0.0f, 0.0f); Vector3[] shuffledPlayerColors = Player.GetShuffledPlayerColors(this._rand); foreach (string index in this._players.Keys.ToList <string>()) { this._players[index] = new Player(app, app.Game, new PlayerInfo() { FactionID = app.GameDatabase.GetFactionIdFromName(index), AvatarAssetPath = string.Empty, BadgeAssetPath = app.AssetDatabase.GetRandomBadgeTexture(index, this._rand), PrimaryColor = shuffledPlayerColors[0], SecondaryColor = new Vector3(this._rand.NextSingle(), this._rand.NextSingle(), this._rand.NextSingle()) }, Player.ClientTypes.AI); this._set.Add((IGameObject)this._players[index]); } Vector3 zero = Vector3.Zero; double num2 = (double)Vector3.Cross(vector1, new Vector3(0.0f, 1f, 0.0f)).Normalize(); float num3 = 500f; int num4 = 4; float num5 = num3 * (float)num4; Vector3 vector3_1 = new Vector3(-num5, 0.0f, -num5); Vector3 vector3_2 = vector1 + -rotationYpr.Forward * (num1 + 2000f + num5); List <Vector3> vector3List1 = new List <Vector3>(); for (int index = 0; index < 81; ++index) { int num6 = index % 5; int num7 = index / 5; Vector3 vector3_3 = new Vector3(vector3_1.X + (float)num7 * num3, 0.0f, vector3_1.Z + (float)num6 * num3); vector3_3 += vector3_2; vector3List1.Add(vector3_3); } List <Vector3> vector3List2 = new List <Vector3>(); foreach (Vector3 pos in vector3List1) { if (this.PositionCollidesWithObject(pos, 400f)) { vector3List2.Add(pos); } } foreach (Vector3 vector3_3 in vector3List2) { vector3List1.Remove(vector3_3); } int num8 = this._rand.NextInclusive(6, 12); List <int> intList = new List <int>(); for (int index1 = 0; index1 < num8; ++index1) { int index2 = 0; bool flag2 = true; for (int index3 = 0; flag2 && index3 < vector3List1.Count; ++index3) { index2 = this._rand.NextInclusive(0, Math.Max(vector3List1.Count - 1, 0)); flag2 = intList.Contains(index2); if (intList.Count == vector3List1.Count) { break; } } Vector3 off = vector3List1.Count > 0 ? vector3List1[index2] : vector1; if (index1 < 3) { zero += this.CreateRandomShip(off, "loa", index1 == 0); } else { zero += this.CreateRandomShip(off, "", false); } if (!intList.Contains(index2)) { intList.Add(index2); } } if (num8 <= 0) { return; } Vector3 vector3_4 = zero / (float)num8; }
public GLStarSystemViewModel() { CurrentStarSystem = GameState.Instance.StarSystems.FirstOrDefault(); StarSystems = GameState.Instance.StarSystems; }
/* * Types currently supported: * CrewMember * Gadget * HighScoreRecord * Shield * StarSystem * Weapon * * If an array of a type not listed is converted using ArrayToArrayList, the type * needs to be added here. */ public static STSerializableObject[] ArrayListToArray(ArrayList list, string type) { STSerializableObject[] array = null; if (list != null) { switch (type) { case "CrewMember": array = new CrewMember[list.Count]; break; case "Gadget": array = new Gadget[list.Count]; break; case "HighScoreRecord": array = new HighScoreRecord[list.Count]; break; case "Shield": array = new Shield[list.Count]; break; case "StarSystem": array = new StarSystem[list.Count]; break; case "Weapon": array = new Weapon[list.Count]; break; } for (int index = 0; index < list.Count; index++) { Hashtable hash = (Hashtable)list[index]; STSerializableObject obj = null; if (hash != null) { switch (type) { case "CrewMember": obj = new CrewMember(hash); break; case "Gadget": obj = new Gadget(hash); break; case "HighScoreRecord": obj = new HighScoreRecord(hash); break; case "Shield": obj = new Shield(hash); break; case "StarSystem": obj = new StarSystem(hash); break; case "Weapon": obj = new Weapon(hash); break; } } array[index] = obj; } } return array; }
// constructor protected Starship(string name, int health, int shields, int damage, double fuel, StarSystem location) { this.Name = name; this.Health = health; this.Shields = shields; this.Damage = damage; this.Fuel = fuel; this.Location = location; this.enhancements = new List <Enhancement>(); }
public Point3D GetStarSystemLocation(StarSystem currentSystem) { return currentSystem.Location; }
private static string BuildInfluenceString(StarSystem starSystem) { var factionString = new StringBuilder(); if (Core.WarStatus.FlashpointSystems.Contains(starSystem.Name) || Core.Settings.ImmuneToWar.Contains(starSystem.OwnerValue.Name)) { factionString.AppendLine("<b>" + starSystem.Name + " ***System Immune to War***</b>"); return(factionString.ToString()); } else if (starSystem.OwnerValue.Name == Core.WarStatus.ComstarAlly) { factionString.AppendLine("<b>" + starSystem.Name + " ***" + Core.Settings.GaW_Police + " Supported System***</b>"); } else if (Core.WarStatus.AbandonedSystems.Contains(starSystem.Name)) { factionString.AppendLine("<b>" + starSystem.Name + " ***Abandoned***</b>"); } else { factionString.AppendLine("<b>" + starSystem.Name + "</b>"); } string SubString = "("; if (Core.WarStatus.HomeContendedStrings.Contains(starSystem.Name)) { SubString += "*Valuable Target*"; } if (Core.WarStatus.LostSystems.Contains(starSystem.Name)) { SubString += " *Owner Changed*"; } if (Core.WarStatus.PirateHighlight.Contains(starSystem.Name)) { SubString += " *ARRRRRGH!*"; } SubString += ")"; if (SubString.Length > 2) { SubString += "\n"; } else { SubString = ""; } factionString.AppendLine(SubString); var tracker = Core.WarStatus.systems.Find(x => x.name == starSystem.Name); foreach (var influence in tracker.influenceTracker.OrderByDescending(x => x.Value)) { string number; if (influence.Value < 1) { continue; } if (Math.Abs(influence.Value - 100) < 0.999) { number = "100%"; } //else if (influence.Value < 1) // number = "< 1%"; else if (influence.Value > 99) { number = "> 99%"; } else { number = $"{influence.Value:#.0}%"; } factionString.AppendLine($"{number,-15}{Core.Settings.FactionNames[influence.Key]}"); } factionString.AppendLine($"\nPirate Activity: {tracker.PirateActivity:#0.0}%"); factionString.AppendLine("\n\nAttack Resources: " + ((100 - tracker.PirateActivity) * tracker.AttackResources / 100).ToString("0.0") + " Defense Resources: " + ((100 - tracker.PirateActivity) * tracker.DefenseResources / 100).ToString("0.0")); string BonusString = "Escalation Bonuses:"; if (tracker.BonusCBills) { BonusString = BonusString + "\n\t20% Bonus C-Bills per Mission"; } if (tracker.BonusXP) { BonusString = BonusString + "\n\t20% Bonus XP per Mission"; } if (tracker.BonusSalvage) { BonusString = BonusString + "\n\t+1 Priority Salvage per Mission"; } factionString.AppendLine("\n\n" + BonusString); return(factionString.ToString()); }
private static Contract CreateProceduralContract( StarSystem system, bool usingBreadcrumbs, MapAndEncounters level, SimGameState.MapEncounterContractData MapEncounterContractData, GameContext gameContext) { var flatContracts = MapEncounterContractData.FlatContracts; Globals.Sim.FilterContracts(flatContracts); var next = flatContracts.GetNext(); var id = next.contractOverride.ContractTypeValue.ID; MapEncounterContractData.Encounters[id].Shuffle(); var encounterLayerGuid = MapEncounterContractData.Encounters[id][0].EncounterLayerGUID; var contractOverride = next.contractOverride; var employer = next.employer; var target = next.target; var employerAlly = next.employerAlly; var targetAlly = next.targetAlly; var neutralToAll = next.NeutralToAll; var hostileToAll = next.HostileToAll; var contract = usingBreadcrumbs ? CreateTravelContract( level.Map.MapName, level.Map.MapPath, encounterLayerGuid, next.contractOverride.ContractTypeValue, contractOverride, gameContext, employer, target, targetAlly, employerAlly, neutralToAll, hostileToAll, false, actualDifficulty) : new Contract( level.Map.MapName, level.Map.MapPath, encounterLayerGuid, next.contractOverride.ContractTypeValue, Globals.Sim.BattleTechGame, contractOverride, gameContext, true, actualDifficulty); Globals.Sim.mapDiscardPile.Add(level.Map.MapID); Globals.Sim.contractDiscardPile.Add(contractOverride.ID); PrepContract(contract, employer, employerAlly, target, targetAlly, neutralToAll, hostileToAll, level.Map.BiomeSkinEntry.BiomeSkin, contract.Override.travelSeed, system); return(contract); }
public Cruiser(string name, StarSystem location, IEnumerable<Enhancement> enhancements) : base(name, DefaultHealth, DefaultShields, DefaultDamage, DefaultFuel, location, enhancements) { }
public void LoadExploredSystem(StarSystem system) { _informationText.SetText(string.Format("{0} System has been explored", system.Name)); _informationText.MoveTo(_xPos + 200 - (int)(_informationText.GetWidth() / 2), _yPos + 50 - (int)(_informationText.GetHeight() / 2)); }
public void LoadFleetAndSystem(Fleet fleet) { _colonizingFleet = fleet; _starSystem = fleet.AdjacentSystem; _colonyShips = new List<Ship>(); foreach (var ship in _colonizingFleet.OrderedShips) { foreach (var special in ship.Specials) { if (special == null) { continue; } if (special.Technology.Colony >= _starSystem.Planets[0].ColonyRequirement) { _colonyShips.Add(ship); break; } } } //TODO: Add scrollbar to support more than 4 different colony ship designs _maxShips = _colonyShips.Count > 4 ? 4 : _colonyShips.Count; for (int i = 0; i < _maxShips; i++) { _shipButtons[i].SetText(_colonyShips[i].Name + (_colonizingFleet.Ships[_colonyShips[i]] > 1 ? " (" + _colonizingFleet.Ships[_colonyShips[i]] + ")" : string.Empty)); } _shipButtons[0].Selected = true; _systemNameLabel.SetText(_starSystem.Name); _systemNameLabel.MoveTo(_xPos + 300 - (int)(_systemNameLabel.GetWidth() / 2), _yPos + 130 - (int)(_systemNameLabel.GetHeight() / 2)); }
public void LoadSystem(StarSystem system, Empire currentEmpire) { _currentSystem = system; _currentEmpire = currentEmpire; if (_currentSystem.IsThisSystemExploredByEmpire(_currentEmpire)) { _isExplored = true; var planet = _currentSystem.Planets[0]; _name.SetText(_currentSystem.Name); _isOwnedSystem = _currentSystem.Planets[0].Owner == _currentEmpire; _name.SetTextAttributes(_currentSystem.Planets[0].Owner != null ? _currentSystem.Planets[0].Owner.EmpireColor : System.Drawing.Color.White, System.Drawing.Color.Empty); _popLabel.SetText(planet.Owner != null ? string.Format("{0:0.0}/{1:0} B", planet.TotalPopulation, planet.TotalMaxPopulation - planet.Waste) : string.Format("{0:0} B", planet.TotalMaxPopulation - planet.Waste)); _terrainLabel.SetText(Utility.PlanetTypeToString(_currentSystem.Planets[0].PlanetType)); if (_isOwnedSystem) { _name.SetReadOnly(false); _productionLabel.SetText(string.Format("{0:0.0} ({1:0.0}) Industry", _currentSystem.Planets[0].ActualProduction, _currentSystem.Planets[0].TotalProduction)); _infrastructureLabel.SetText(_currentSystem.Planets[0].InfrastructureStringOutput); _researchLabel.SetText(_currentSystem.Planets[0].ResearchStringOutput); _environmentLabel.SetText(_currentSystem.Planets[0].EnvironmentStringOutput); _defenseLabel.SetText(_currentSystem.Planets[0].DefenseStringOutput); _constructionLabel.SetText(_currentSystem.Planets[0].ConstructionStringOutput); _infrastructureSlider.TopIndex = planet.InfrastructureAmount; _researchSlider.TopIndex = planet.ResearchAmount; _environmentSlider.TopIndex = planet.EnvironmentAmount; _defenseSlider.TopIndex = planet.DefenseAmount; _constructionSlider.TopIndex = planet.ConstructionAmount; _infrastructureLockButton.Selected = planet.InfrastructureLocked; _infrastructureSlider.SetEnabledState(!planet.InfrastructureLocked); _researchLockButton.Selected = planet.ResearchLocked; _researchSlider.SetEnabledState(!planet.ResearchLocked); _environmentLockButton.Selected = planet.EnvironmentLocked; _environmentSlider.SetEnabledState(!planet.EnvironmentLocked); _defenseLockButton.Selected = planet.DefenseLocked; _defenseSlider.SetEnabledState(!planet.DefenseLocked); _constructionLockButton.Selected = planet.ConstructionLocked; _constructionSlider.SetEnabledState(!planet.ConstructionLocked); if (_currentSystem.Planets[0].TransferSystem.Key.StarSystem != null) { _transferLabel.SetText("Moving " + _currentSystem.Planets[0].TransferSystem.Value + " Pop"); _transferLabel.MoveTo(_xPos + 10, _yPos + 440); } else { _transferLabel.SetText(string.Empty); } } else if (_currentSystem.Planets[0].Owner != null) { _generalPurposeText.SetText("Colonized by " + _currentSystem.Planets[0].Owner.EmpireRace.RaceName + " Empire"); _name.SetReadOnly(true); } else { _generalPurposeText.SetText("No colony"); _name.SetReadOnly(true); } } else { _isExplored = false; _name.SetText("Unexplored"); _name.SetTextAttributes(System.Drawing.Color.White, System.Drawing.Color.Empty); _generalPurposeText.SetText(_currentSystem.Description); _popLabel.SetText(string.Empty); _terrainLabel.SetText(string.Empty); _productionLabel.SetText(string.Empty); _infrastructureLabel.SetText(string.Empty); _researchLabel.SetText(string.Empty); _environmentLabel.SetText(string.Empty); _defenseLabel.SetText(string.Empty); _constructionLabel.SetText(string.Empty); _name.SetReadOnly(true); } }
public StarSystem GetCurrentSystem(string systemName) { StarSystem currentStarSystem = new StarSystem(); foreach (var result in starSystemSet.Where(sysName => sysName.Value.name == systemName)) { currentStarSystem = result.Value; currentSystemID = result.Value.id; break; } return currentStarSystem; }
public StarSystem GetCurrentSystem(int systemID) { StarSystem currentStarSystem = new StarSystem(); foreach (var result in starSystemSet.Where(sysID => sysID.Value.id == systemID)) { currentStarSystem = result.Value; currentSystemID = result.Value.id; break; } return currentStarSystem; }