示例#1
0
        /// <summary>
        /// Updates the player's resources each tick - This uses the calculations generated from all planets.
        /// </summary>
        /// <param name="player">The player to update.</param>
        /// <param name="totalPlanetValue">The calculated values from all planets.</param>
        /// <param name="settings">Settings used for this galaxy.</param>
        public static void Update(this Player player, PlanetValue totalPlanetValue, GalaxySettings settings)
        {
            var tickValue = player.TickValue;

            // Decay
            var decay = settings.Decay;

            tickValue.DecayedCash   = player.TotalNetValue.Cash * decay;
            tickValue.DecayedEnergy = player.TotalNetValue.Energy * decay;
            tickValue.DecayedFood   = player.TotalNetValue.Food * decay;
            tickValue.DecayedIron   = player.TotalNetValue.Iron * decay;
            tickValue.DecayedMana   = player.TotalNetValue.Mana * decay;

            // Produced
            tickValue.Buildings = totalPlanetValue.EntityCount;
            tickValue.Units     = player.UnitCount;
            tickValue.ProducedCashFactoryCash = totalPlanetValue.CashFactoryCash;
            tickValue.ProducedPopulationCash  = totalPlanetValue.PopulationCash;
            tickValue.ProducedTaxOfficeCash   = totalPlanetValue.TaxOfficeCash;
            tickValue.ProducedCash            = totalPlanetValue.Cash;
            tickValue.ProducedEnergy          = totalPlanetValue.Energy;
            tickValue.ProducedFood            = totalPlanetValue.Food;
            tickValue.ProducedIron            = totalPlanetValue.Iron;
            tickValue.ProducedPopulation      = totalPlanetValue.Population;
            tickValue.ProducedResearch        = totalPlanetValue.Research;

            // Decay existing values from last tick
            player.TotalNetValue.Cash   -= tickValue.DecayedCash;
            player.TotalNetValue.Energy -= tickValue.DecayedEnergy;
            player.TotalNetValue.Food   -= tickValue.DecayedFood;
            player.TotalNetValue.Iron   -= tickValue.DecayedIron;
            player.TotalNetValue.Mana   -= tickValue.DecayedMana;

            // Add new values
            player.TotalNetValue.Add(totalPlanetValue);

            player.TotalNetValue.Population = totalPlanetValue.Population;

            // let them eat cake! -- but not so much cake that it goes below zero...
            player.TotalNetValue.Food -= (player.TotalNetValue.Population / 10.0) + player.UnitCount;

            if (player.TotalNetValue.Food < 0)
            {
                player.TotalNetValue.Food      = 0;
                player.TotalNetValue.Cash     -= totalPlanetValue.Cash / 2;
                tickValue.IsPopulationStarving = true;
            }

            // building maintainance & unit upkeep
            player.TotalNetValue.Cash = Math.Max(0, player.TotalNetValue.Cash - (player.TotalNetValue.EntityCount + player.UnitCount));

            // TODO - allocate the research points...
        }
示例#2
0
        /// <summary>
        /// Update a planet and determine population for tick.
        /// </summary>
        /// <param name="planet">The planet to update.</param>
        /// <param name="settings">Settings for the current Galaxy.</param>
        /// <param name="bonuses">Bonuses for the player based on their race.</param>
        /// <returns>The calculated values from the planet.</returns>
        public static PlanetValue Update(this Planet planet, GalaxySettings settings, PlayerBonuses bonuses)
        {
            var output = new PlanetValue();

            output.EntityCount = planet.TotalBuildings;

            // Set the base population
            if (Math.Abs(planet.Population - 0) < settings.BasePopulation)
            {
                planet.Population = settings.BasePopulation;
            }

            // multiply by 0.01 to convert to percentage
            var min1 = planet.Population * (1 + (settings.PopulationGrowth * bonuses.WelfareBonus * 0.01));

            var min2 = settings.BasePopulation + (settings.MaxPopulationPerBuildings * planet.BuildingCapacity)
                       + (planet.LivingQuartersCount * settings.PeoplePerLivingQuarter * bonuses.WelfareBonus);

            // cap the population
            output.Population = Math.Min(min1, min2);

            planet.PopulationGrowth = output.Population - planet.Population;
            planet.Population       = output.Population;

            // cash calculations
            var cashBonus = bonuses.EconomyBonus * planet.CashBonus;

            // so the user always makes cash
            var positiveIncome = settings.PositiveIncomeCash * cashBonus;
            var buildingCount  = Math.Max(output.EntityCount, 1);

            output.CashFactoryCash = planet.CashFactoryCount * settings.CashOutput * cashBonus;
            output.PopulationCash  = planet.Population / settings.PopulationCashDivider * cashBonus;
            output.TaxOfficeCash   = (double)planet.TaxOfficeCount / buildingCount
                                     * (positiveIncome + output.CashFactoryCash + output.PopulationCash);

            output.Cash = positiveIncome + output.CashFactoryCash + output.PopulationCash + output.TaxOfficeCash;

            output.Energy = planet.EnergyLabCount * planet.EnergyBonus;
            output.Food   = settings.FoodOutput * planet.FarmCount * planet.FoodBonus;
            output.Iron   = planet.MineCount * planet.IronBonus;
            output.Mana   = planet.ManaCount * planet.ManaBonus;

            output.Research = settings.ResearchOutput * planet.ResearchLabCount * planet.ResearchBonus * bonuses.ResearchBonus;

            return(output);
        }
示例#3
0
            public void WillUpdateThePlanetTaxOfficeCash()
            {
                var planet = new Planet {
                    CashBonus = 1, TaxOfficeCount = 1
                };

                var galaxySettings = new GalaxySettings {
                    PopulationCashDivider = 1, PositiveIncomeCash = 1
                };

                var playerBonuses = new PlayerBonuses {
                    EconomyBonus = 1
                };

                var output = planet.Update(galaxySettings, playerBonuses);

                Assert.AreEqual(output.TaxOfficeCash, 1);
            }
示例#4
0
            public void WillUpdateThePlanetPopulationCash()
            {
                var planet = new Planet {
                    CashBonus = 1, Population = 1
                };

                var galaxySettings = new GalaxySettings {
                    PopulationCashDivider = 1, BasePopulation = 1
                };

                var playerBonuses = new PlayerBonuses {
                    EconomyBonus = 1
                };

                var output = planet.Update(galaxySettings, playerBonuses);

                Assert.AreEqual(output.PopulationCash, 1);
            }
示例#5
0
            public void WillUpdateThePlanetCashFactoryCash()
            {
                var planet = new Planet {
                    CashBonus = 1, CashFactoryCount = 1
                };

                var galaxySettings = new GalaxySettings {
                    CashOutput = 2
                };

                var playerBonuses = new PlayerBonuses {
                    EconomyBonus = 1
                };

                var output = planet.Update(galaxySettings, playerBonuses);

                Assert.AreEqual(output.CashFactoryCash, 2);
            }
示例#6
0
            public void WillCreateSolarSystemWithoutEntities()
            {
                var galaxySettings = new GalaxySettings
                {
                    SolarSystemConstants = new SolarSystemConstants
                    {
                        SpatialEntityProbabilities = new Collection <SpatialEntityProbabilities>()
                    }
                };

                var solarSystemRepository = new Mock <ISolarSystemRepository>();

                solarSystemRepository.Setup(ssr => ssr.Create()).Returns(new SolarSystem());

                var game        = new Game(null, null, null, solarSystemRepository.Object, null, null);
                var solarSystem = game.CreateSolarSystem(galaxySettings);

                Assert.IsNotNull(solarSystem);
                Assert.AreEqual(solarSystem.SpatialEntities.Count, 0);
            }
示例#7
0
            public void WillCreateSolarSystemWithOnePlanet()
            {
                var galaxySettings = new GalaxySettings
                {
                    Width  = 1,
                    Height = 1,
                    SolarSystemConstants = new SolarSystemConstants
                    {
                        MaximumEntities            = 1,
                        MinimumEntities            = 1,
                        SpatialEntityProbabilities = new Collection <SpatialEntityProbabilities>
                        {
                            new SpatialEntityProbabilities
                            {
                                Type = SpatialEntityType.Planet,
                                SpawningProbability = 1
                            }
                        }
                    }
                };

                var solarSystemRepository = new Mock <ISolarSystemRepository>();

                solarSystemRepository.Setup(ssr => ssr.Create()).Returns(new SolarSystem());

                var planetRepository = new Mock <IPlanetRepository>();

                planetRepository.Setup(pr => pr.Create()).Returns(new Planet());

                var game        = new Game(null, null, null, solarSystemRepository.Object, planetRepository.Object, null);
                var solarSystem = game.CreateSolarSystem(galaxySettings);

                Assert.IsNotNull(solarSystem);
                Assert.AreEqual(solarSystem.SpatialEntities.Count, 1);
                Assert.AreEqual(solarSystem.Planets.Count, 1);
            }
示例#8
0
        public void SaveAs(string path)
        {
            foreach (var item in _components)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetComponent(item.Key)));
            }
            foreach (var item in _devices)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetDevice(item.Key)));
            }
            foreach (var item in _weapons)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetWeapon(item.Key)));
            }
            foreach (var item in _ammunition)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetAmmunition(item.Key)));
            }
            foreach (var item in _ammunitionObsolete)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetAmmunitionObsolete(item.Key)));
            }
            foreach (var item in _droneBays)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetDroneBay(item.Key)));
            }
            foreach (var item in _ships)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetShip(item.Key)));
            }
            foreach (var item in _shipBuilds)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetShipBuild(item.Key)));
            }
            foreach (var item in _satellites)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetSatellite(item.Key)));
            }
            foreach (var item in _satelliteBuilds)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetSatelliteBuild(item.Key)));
            }
            foreach (var item in _technologies)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetTechnology(item.Key)));
            }
            foreach (var item in _skills)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetSkill(item.Key)));
            }
            foreach (var item in _componentStats)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetComponentStats(item.Key)));
            }
            foreach (var item in _componentMods)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetComponentMod(item.Key)));
            }
            foreach (var item in _factions)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetFaction(item.Key)));
            }
            foreach (var item in _loot)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetLoot(item.Key)));
            }
            foreach (var item in _quests)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetQuest(item.Key)));
            }
            foreach (var item in _fleets)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetFleet(item.Key)));
            }
            foreach (var item in _characters)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetCharacter(item.Key)));
            }
            foreach (var item in _questItems)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetQuestItem(item.Key)));
            }
            foreach (var item in _bulletPrefabs)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetBulletPrefab(item.Key)));
            }
            foreach (var item in _visualEffects)
            {
                item.Value.Save(Cleanup(_jsonDatabase.GetVisualEffect(item.Key)));
            }

            ShipSettings.Save(Cleanup(_jsonDatabase.ShipSettings));
            GalaxySettings.Save(Cleanup(_jsonDatabase.GalaxySettings));

            _jsonDatabase.SaveData(path);
        }
示例#9
0
            public void Load()
            {
                foreach (var item in _content.AmmunitionObsoleteList)
                {
                    if (!item.Disabled && !_database._ammunitionObsoleteMap.ContainsKey(item.Id))
                    {
                        AmmunitionObsolete.Create(item, this);
                    }
                }
                foreach (var item in _content.ComponentList)
                {
                    if (!item.Disabled && !_database._componentMap.ContainsKey(item.Id))
                    {
                        Component.Create(item, this);
                    }
                }
                foreach (var item in _content.ComponentModList)
                {
                    if (!item.Disabled && !_database._componentModMap.ContainsKey(item.Id))
                    {
                        ComponentMod.Create(item, this);
                    }
                }
                foreach (var item in _content.ComponentStatsList)
                {
                    if (!item.Disabled && !_database._componentStatsMap.ContainsKey(item.Id))
                    {
                        ComponentStats.Create(item, this);
                    }
                }
                foreach (var item in _content.DeviceList)
                {
                    if (!item.Disabled && !_database._deviceMap.ContainsKey(item.Id))
                    {
                        Device.Create(item, this);
                    }
                }
                foreach (var item in _content.DroneBayList)
                {
                    if (!item.Disabled && !_database._droneBayMap.ContainsKey(item.Id))
                    {
                        DroneBay.Create(item, this);
                    }
                }
                foreach (var item in _content.FactionList)
                {
                    if (!item.Disabled && !_database._factionMap.ContainsKey(item.Id))
                    {
                        Faction.Create(item, this);
                    }
                }
                foreach (var item in _content.SatelliteList)
                {
                    if (!item.Disabled && !_database._satelliteMap.ContainsKey(item.Id))
                    {
                        Satellite.Create(item, this);
                    }
                }
                foreach (var item in _content.SatelliteBuildList)
                {
                    if (!item.Disabled && !_database._satelliteBuildMap.ContainsKey(item.Id))
                    {
                        SatelliteBuild.Create(item, this);
                    }
                }
                foreach (var item in _content.ShipList)
                {
                    if (!item.Disabled && !_database._shipMap.ContainsKey(item.Id))
                    {
                        Ship.Create(item, this);
                    }
                }
                foreach (var item in _content.ShipBuildList)
                {
                    if (!item.Disabled && !_database._shipBuildMap.ContainsKey(item.Id))
                    {
                        ShipBuild.Create(item, this);
                    }
                }
                foreach (var item in _content.SkillList)
                {
                    if (!item.Disabled && !_database._skillMap.ContainsKey(item.Id))
                    {
                        Skill.Create(item, this);
                    }
                }
                foreach (var item in _content.TechnologyList)
                {
                    if (!item.Disabled && !_database._technologyMap.ContainsKey(item.Id))
                    {
                        Technology.Create(item, this);
                    }
                }
                foreach (var item in _content.CharacterList)
                {
                    if (!item.Disabled && !_database._characterMap.ContainsKey(item.Id))
                    {
                        Character.Create(item, this);
                    }
                }
                foreach (var item in _content.FleetList)
                {
                    if (!item.Disabled && !_database._fleetMap.ContainsKey(item.Id))
                    {
                        Fleet.Create(item, this);
                    }
                }
                foreach (var item in _content.LootList)
                {
                    if (!item.Disabled && !_database._lootMap.ContainsKey(item.Id))
                    {
                        LootModel.Create(item, this);
                    }
                }
                foreach (var item in _content.QuestList)
                {
                    if (!item.Disabled && !_database._questMap.ContainsKey(item.Id))
                    {
                        QuestModel.Create(item, this);
                    }
                }
                foreach (var item in _content.QuestItemList)
                {
                    if (!item.Disabled && !_database._questItemMap.ContainsKey(item.Id))
                    {
                        QuestItem.Create(item, this);
                    }
                }
                foreach (var item in _content.AmmunitionList)
                {
                    if (!item.Disabled && !_database._ammunitionMap.ContainsKey(item.Id))
                    {
                        Ammunition.Create(item, this);
                    }
                }
                foreach (var item in _content.BulletPrefabList)
                {
                    if (!item.Disabled && !_database._bulletPrefabMap.ContainsKey(item.Id))
                    {
                        BulletPrefab.Create(item, this);
                    }
                }
                foreach (var item in _content.VisualEffectList)
                {
                    if (!item.Disabled && !_database._visualEffectMap.ContainsKey(item.Id))
                    {
                        VisualEffect.Create(item, this);
                    }
                }
                foreach (var item in _content.WeaponList)
                {
                    if (!item.Disabled && !_database._weaponMap.ContainsKey(item.Id))
                    {
                        Weapon.Create(item, this);
                    }
                }

                foreach (var item in _content.Images)
                {
                    if (!_database._images.ContainsKey(item.Key))
                    {
                        _database._images.Add(item.Key, item.Value);
                    }
                }

                foreach (var item in _content.AudioClips)
                {
                    if (!_database._audioClips.ContainsKey(item.Key))
                    {
                        _database._audioClips.Add(item.Key, item.Value);
                    }
                }

                foreach (var item in _content.Localizations)
                {
                    if (!_database._localizations.ContainsKey(item.Key))
                    {
                        _database._localizations.Add(item.Key, item.Value);
                    }
                }

                if (_database.DatabaseSettings == null)
                {
                    _database.DatabaseSettings = DatabaseSettings.Create(_content.DatabaseSettings ?? new Serializable.DatabaseSettingsSerializable {
                        ItemType = Enums.ItemType.DatabaseSettings
                    }, this);
                }
                if (_database.ExplorationSettings == null)
                {
                    _database.ExplorationSettings = ExplorationSettings.Create(_content.ExplorationSettings ?? new Serializable.ExplorationSettingsSerializable {
                        ItemType = Enums.ItemType.ExplorationSettings
                    }, this);
                }
                if (_database.GalaxySettings == null)
                {
                    _database.GalaxySettings = GalaxySettings.Create(_content.GalaxySettings ?? new Serializable.GalaxySettingsSerializable {
                        ItemType = Enums.ItemType.GalaxySettings
                    }, this);
                }
                if (_database.ShipSettings == null)
                {
                    _database.ShipSettings = ShipSettings.Create(_content.ShipSettings ?? new Serializable.ShipSettingsSerializable {
                        ItemType = Enums.ItemType.ShipSettings
                    }, this);
                }
            }
        /// <summary>
        /// Executes the strategy to initialize the database for the given context.
        /// </summary>
        /// <param name="context">The context.</param>
        protected override void Seed(EntityFrameworkDbContext context)
        {
            base.Seed(context);
            if (!context.Database.Exists() || !context.Database.CompatibleWithModel(true))
            {
                return;
            }

            var galaxySettings = new GalaxySettings
            {
                Width  = 10,
                Height = 10,
                SystemGenerationProbability = 0.94,
                OrbitSpeedMaximum           = 100000.0,
                OrbitSpeedMinimum           = 30000.0,
                SolarSystemScalar           = 1,
                Decay                     = 0.005,
                PopulationGrowth          = 5,
                MaxPopulationPerBuildings = 40,
                BasePopulation            = 250,
                CashOutput                = 8,
                FoodOutput                = 100,
                PopulationCashDivider     = 30,
                PeoplePerLivingQuarter    = 650,
                ResearchOutput            = 20,
            };

            var solarSystemConstants = new SolarSystemConstants {
                MaximumEntities = 25, MinimumEntities = 10
            };

            var planetProbabilities = SystemTypes.EnumToList <SpatialEntityType>()
                                      .Select(type => new SpatialEntityProbabilities
            {
                Type        = type, MaximumMass = 1, MaximumRadius = 1,
                MinimumMass = 1, MinimumRadius = 1, SpawningProbability = .5
            }).ToList();

            var star = planetProbabilities.First(o => o.Type == SpatialEntityType.Star);

            star.MaximumMass = star.MinimumMass = 2;
            var planet = planetProbabilities.First(o => o.Type == SpatialEntityType.Planet);

            planet.SpawningProbability = 5;

            solarSystemConstants.SpatialEntityProbabilities = planetProbabilities;
            galaxySettings.SolarSystemConstants             = solarSystemConstants;

            var buildingCosts = new List <BuildingCosts>
            {
                new BuildingCosts
                {
                    Type   = BuildingType.CashFactory,
                    Cash   = 120,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 10,
                    Mana   = 0,
                    Time   = 5
                },
                new BuildingCosts
                {
                    Type   = BuildingType.EnergyLab,
                    Cash   = 160,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 3,
                    Mana   = 0,
                    Time   = 12
                },
                new BuildingCosts
                {
                    Type   = BuildingType.Farm,
                    Cash   = 300,
                    Energy = 0,
                    Food   = 0,
                    Iron   = 20,
                    Mana   = 0,
                    Time   = 10
                },
                new BuildingCosts
                {
                    Type   = BuildingType.Laser,
                    Cash   = 700,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 35,
                    Mana   = 0,
                    Time   = 8
                },
                new BuildingCosts
                {
                    Type   = BuildingType.LivingQuarters,
                    Cash   = 200,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 25,
                    Mana   = 0,
                    Time   = 8
                },
                new BuildingCosts
                {
                    Type   = BuildingType.Mine,
                    Cash   = 200,
                    Energy = 1,
                    Food   = 5,
                    Iron   = 0,
                    Mana   = 0,
                    Time   = 12
                },
                new BuildingCosts
                {
                    Type   = BuildingType.Portal,
                    Cash   = 15000,
                    Energy = 110,
                    Food   = 0,
                    Iron   = 400,
                    Mana   = 80,
                    Time   = 40
                },
                new BuildingCosts
                {
                    Type   = BuildingType.ResearchLab,
                    Cash   = 100,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 0,
                    Mana   = 0,
                    Time   = 14
                },
                new BuildingCosts
                {
                    Type   = BuildingType.TaxOffice,
                    Cash   = 200,
                    Energy = 1,
                    Food   = 0,
                    Iron   = 15,
                    Mana   = 0,
                    Time   = 16
                },
            };

            galaxySettings.BuildingCosts = buildingCosts;

            context.GalaxySettings.Add(galaxySettings);

            context.SaveChanges();
        }
示例#11
0
文件: Game.cs 项目: jlkalberer/Space
        /// <summary>
        /// Creates a SolarSystemConstants in a Galaxy.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <returns>
        /// A new SolarSystemConstants stored in a datastore.
        /// </returns>
        public SolarSystem CreateSolarSystem(GalaxySettings settings)
        {
            var solarSystem = this.solarSystemRepository.Create();

            // get the type of solar system -- what type of central mass it has
            var r = new Random();
            var ssc = settings.SolarSystemConstants;

            var numberOfEntities = r.Next(ssc.MinimumEntities, ssc.MaximumEntities);

            // Create this array so we can use it to decide which entity is to be created
            var probabilityArray = (from e in Enum.GetValues(typeof(SpatialEntityType)).Cast<SpatialEntityType>()
                                    from o in ssc.SpatialEntityProbabilities
                                    where o.Type == e
                                    select new KeyValuePair<double, SpatialEntityType>(
                                        o.SpawningProbability, e)).ToList();

            // Get the sum of the probability array
            var sum = probabilityArray.Select(o => o.Key).Sum();

            for (var i = 0; i < numberOfEntities; i += 1)
            {
                SpatialEntityType itemType = SpatialEntityType.Planet;
                var value = r.NextDouble() * sum;
                var count = 0.0;

                // Using the randomly generated value, get the item type from the array
                for (var j = 0; j < probabilityArray.Count; j += 1)
                {
                    count += probabilityArray[j].Key;
                    if (value < count)
                    {
                        itemType = probabilityArray[j].Value;
                        break;
                    }
                }

                SpatialEntity entity;

                // now create the entity!!!
                // This may be refactored to just use entity type and get rid of the Planet class.
                if (itemType == SpatialEntityType.Planet)
                {
                    entity = this.planetRepository.Create();
                    solarSystem.Planets.Add((Planet)entity);
                    var planet = entity as Planet;

                    // TODO: figure out the planet building capacity and bonuses here....
                    if (planet != null)
                    {
                        planet.BuildingCapacity = r.Next(150, 350);
                    }
                }
                else
                {
                    entity = this.spatialEntityRepository.Create();
                }

                if (entity == null)
                {
                    continue;
                }

                solarSystem.SpatialEntities.Add(entity);

                entity.Type = itemType;

                var entitySettings = ssc.SpatialEntityProbabilities.FirstOrDefault(o => o.Type == itemType);

                if (entitySettings == null)
                {
                    throw new Exception("foobar");
                }

                // make the radius
                var max = entitySettings.MaximumRadius;
                var min = entitySettings.MinimumRadius;

                entity.Radius = (r.NextDouble() * (max - min)) + min;

                // make the mass
                max = entitySettings.MaximumMass;
                min = entitySettings.MinimumMass;

                // Random mass * the area of the planet (could use volume but it doesn't really matter)
                entity.Mass = (r.NextDouble() * (max - min)) + min;
                entity.Mass *= entity.Radius * entity.Radius * Math.PI;
            }

            if (solarSystem.SpatialEntities.Count < 1)
            {
                return solarSystem;
            }

            // find the largest entity to use as the center of the solar system
            // TODO: to make this more awesome we might allow multiple centers of gravity
            var largestEntity = solarSystem.SpatialEntities.MaxBy(e => e.Mass);

            solarSystem.SpatialEntities.Remove(largestEntity);
            solarSystem.SpatialEntities.Add(largestEntity);
            var entities = solarSystem.SpatialEntities.Reverse().ToList();

            // give all the spatial entities properties for placement and movement
            for (var i = 1; i < entities.Count; i++)
            {
                var entity = entities[i];

                entity.OrbitRadius = Math.Pow(16 * i, 2.2) * settings.SolarSystemScalar;

                var randomRadians = r.NextDouble() * CircleCoefficient;
                entity.Latitude = entity.OrbitRadius * Math.Cos(randomRadians);
                entity.Longitude = entity.OrbitRadius * Math.Sin(randomRadians);

                entity.OrbitSpeed = ((r.NextDouble() * settings.OrbitSpeedDifference) + settings.OrbitSpeedMinimum) * settings.SolarSystemScalar;
            }

            solarSystem.SpatialEntities = entities;

            return solarSystem;
        }
示例#12
0
文件: Game.cs 项目: jlkalberer/Space
        /// <summary>
        /// Creates a SolarSystemConstants in a Galaxy.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <returns>
        /// A new SolarSystemConstants stored in a datastore.
        /// </returns>
        public SolarSystem CreateSolarSystem(GalaxySettings settings)
        {
            var solarSystem = this.solarSystemRepository.Create();

            // get the type of solar system -- what type of central mass it has
            var r   = new Random();
            var ssc = settings.SolarSystemConstants;

            var numberOfEntities = r.Next(ssc.MinimumEntities, ssc.MaximumEntities);

            // Create this array so we can use it to decide which entity is to be created
            var probabilityArray = (from e in Enum.GetValues(typeof(SpatialEntityType)).Cast <SpatialEntityType>()
                                    from o in ssc.SpatialEntityProbabilities
                                    where o.Type == e
                                    select new KeyValuePair <double, SpatialEntityType>(
                                        o.SpawningProbability, e)).ToList();

            // Get the sum of the probability array
            var sum = probabilityArray.Select(o => o.Key).Sum();

            for (var i = 0; i < numberOfEntities; i += 1)
            {
                SpatialEntityType itemType = SpatialEntityType.Planet;
                var value = r.NextDouble() * sum;
                var count = 0.0;

                // Using the randomly generated value, get the item type from the array
                for (var j = 0; j < probabilityArray.Count; j += 1)
                {
                    count += probabilityArray[j].Key;
                    if (value < count)
                    {
                        itemType = probabilityArray[j].Value;
                        break;
                    }
                }

                SpatialEntity entity;

                // now create the entity!!!
                // This may be refactored to just use entity type and get rid of the Planet class.
                if (itemType == SpatialEntityType.Planet)
                {
                    entity = this.planetRepository.Create();
                    solarSystem.Planets.Add((Planet)entity);
                    var planet = entity as Planet;

                    // TODO: figure out the planet building capacity and bonuses here....
                    if (planet != null)
                    {
                        planet.BuildingCapacity = r.Next(150, 350);
                    }
                }
                else
                {
                    entity = this.spatialEntityRepository.Create();
                }

                if (entity == null)
                {
                    continue;
                }

                solarSystem.SpatialEntities.Add(entity);

                entity.Type = itemType;

                var entitySettings = ssc.SpatialEntityProbabilities.FirstOrDefault(o => o.Type == itemType);

                if (entitySettings == null)
                {
                    throw new Exception("foobar");
                }

                // make the radius
                var max = entitySettings.MaximumRadius;
                var min = entitySettings.MinimumRadius;

                entity.Radius = (r.NextDouble() * (max - min)) + min;

                // make the mass
                max = entitySettings.MaximumMass;
                min = entitySettings.MinimumMass;

                // Random mass * the area of the planet (could use volume but it doesn't really matter)
                entity.Mass  = (r.NextDouble() * (max - min)) + min;
                entity.Mass *= entity.Radius * entity.Radius * Math.PI;
            }

            if (solarSystem.SpatialEntities.Count < 1)
            {
                return(solarSystem);
            }

            // find the largest entity to use as the center of the solar system
            // TODO: to make this more awesome we might allow multiple centers of gravity
            var largestEntity = solarSystem.SpatialEntities.MaxBy(e => e.Mass);

            solarSystem.SpatialEntities.Remove(largestEntity);
            solarSystem.SpatialEntities.Add(largestEntity);
            var entities = solarSystem.SpatialEntities.Reverse().ToList();

            // give all the spatial entities properties for placement and movement
            for (var i = 1; i < entities.Count; i++)
            {
                var entity = entities[i];

                entity.OrbitRadius = Math.Pow(16 * i, 2.2) * settings.SolarSystemScalar;

                var randomRadians = r.NextDouble() * CircleCoefficient;
                entity.Latitude  = entity.OrbitRadius * Math.Cos(randomRadians);
                entity.Longitude = entity.OrbitRadius * Math.Sin(randomRadians);

                entity.OrbitSpeed = ((r.NextDouble() * settings.OrbitSpeedDifference) + settings.OrbitSpeedMinimum) * settings.SolarSystemScalar;
            }

            solarSystem.SpatialEntities = entities;

            return(solarSystem);
        }