Esempio n. 1
0
 private ResourceQuantity ComputeSYAbilityRate()
 {
     if (Container.HasAbility("Space Yard"))
     {
         var rate = new ResourceQuantity();
         // TODO - moddable resources?
         for (int i = 1; i <= 3; i++)
         {
             var      amount = Container.GetAbilityValue("Space Yard", 2, true, true, a => a.Value1 == i.ToString()).ToInt();
             Resource res    = null;
             if (i == 1)
             {
                 res = Resource.Minerals;
             }
             else if (i == 2)
             {
                 res = Resource.Organics;
             }
             else if (i == 3)
             {
                 res = Resource.Radioactives;
             }
             rate[res] = amount;
         }
         return(rate);
     }
     else
     {
         return(null);
     }
 }
Esempio n. 2
0
File: Hull.cs Progetto: ekolis/FrEee
 public Hull()
 {
     PictureNames       = new List <string>();
     UnlockRequirements = new List <Requirement <Empire> >();
     Abilities          = new List <Ability>();
     Cost = new ResourceQuantity();
 }
        public void PreferVolumeNameMappingForVolume()
        {
            var config           = new KubernetesConfig("image", CreatePodParameters.Create(hostConfig: VolumeMountHostConfig1), Option.None <AuthConfig>());
            var docker           = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVarsDict);
            var module           = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var mapper           = new KubernetesPvcMapper("a-volume", "storageclass", 1);
            var resourceQuantity = new ResourceQuantity("1Mi");

            var pvcs = mapper.CreatePersistentVolumeClaims(module, DefaultLabels);

            Assert.True(pvcs.HasValue);
            var pvcList = pvcs.OrDefault();

            Assert.True(pvcList.Any());
            Assert.Single(pvcList);

            var aVolumeClaim = pvcList.Single(pvc => pvc.Metadata.Name == "module1-a-volume");

            Assert.True(aVolumeClaim.Metadata.Labels.SequenceEqual(DefaultLabels));
            Assert.Equal("ReadOnlyMany", aVolumeClaim.Spec.AccessModes[0]);
            Assert.Equal("storageclass", aVolumeClaim.Spec.StorageClassName);
            Assert.Equal("a-volume", aVolumeClaim.Spec.VolumeName);
            Assert.Equal(resourceQuantity, aVolumeClaim.Spec.Resources.Requests["storage"]);
            Assert.Equal(1, aVolumeClaim.Metadata.OwnerReferences.Count);
            Assert.Equal(V1Deployment.KubeKind, aVolumeClaim.Metadata.OwnerReferences[0].Kind);
            Assert.Equal(EdgeletModuleOwner.Name, aVolumeClaim.Metadata.OwnerReferences[0].Name);
        }
        public void VolumeNameMappingForVolume()
        {
            var config           = new KubernetesConfig("image", CreatePodParameters.Create(hostConfig: VolumeMountHostConfig), Option.None <AuthConfig>());
            var docker           = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVarsDict);
            var module           = new KubernetesModule(docker, config);
            var mapper           = new KubernetesPvcMapper("a-pvc-name", null, 37);
            var resourceQuantity = new ResourceQuantity("37Mi");

            var pvcs = mapper.CreatePersistentVolumeClaims(module, DefaultLabels);

            Assert.True(pvcs.HasValue);
            var pvcList = pvcs.OrDefault();

            Assert.True(pvcList.Any());
            Assert.Equal(2, pvcList.Count);

            var aVolumeClaim = pvcList.Single(pvc => pvc.Metadata.Name == "a-volume");

            Assert.True(aVolumeClaim.Metadata.Labels.SequenceEqual(DefaultLabels));
            Assert.Equal("ReadOnlyMany", aVolumeClaim.Spec.AccessModes[0]);
            Assert.Null(aVolumeClaim.Spec.StorageClassName);
            Assert.Equal("a-pvc-name", aVolumeClaim.Spec.VolumeName);
            Assert.Equal(resourceQuantity, aVolumeClaim.Spec.Resources.Requests["storage"]);

            var bVolumeClaim = pvcList.Single(pvc => pvc.Metadata.Name == "b-volume");

            Assert.True(bVolumeClaim.Metadata.Labels.SequenceEqual(DefaultLabels));
            Assert.Equal("ReadWriteMany", bVolumeClaim.Spec.AccessModes[0]);
            Assert.Null(bVolumeClaim.Spec.StorageClassName);
            Assert.Equal("a-pvc-name", bVolumeClaim.Spec.VolumeName);
            Assert.Equal(resourceQuantity, bVolumeClaim.Spec.Resources.Requests["storage"]);
        }
Esempio n. 5
0
        public static void InitialiseBluePrints()
        {
            // pull these in from XML eventually
            ResourceQuantity prod = new ResourceQuantity();

            prod.Type     = ResourceTypeEnum.Platinum;
            prod.Quantity = 1;
            ResourceQuantity cons = new ResourceQuantity();

            cons.Type     = ResourceTypeEnum.Spice;
            cons.Quantity = 9;
            types_Var[(int)BluePrintEnum.SpiceToPlatinum] = createBluePrint(BluePrintEnum.SpiceToPlatinum, "Spice To Platinum", new List <ResourceQuantity> {
                prod
            }, new List <ResourceQuantity> {
                cons
            }, 10);


            prod          = new ResourceQuantity();
            prod.Type     = ResourceTypeEnum.Spice;
            prod.Quantity = 10;
            cons          = new ResourceQuantity();
            cons.Type     = ResourceTypeEnum.Platinum;
            cons.Quantity = 1;
            types_Var[(int)BluePrintEnum.PlatinumToSpice] = createBluePrint(BluePrintEnum.PlatinumToSpice, "Platinum to Spice", new List <ResourceQuantity> {
                prod
            }, new List <ResourceQuantity> {
                cons
            }, 50);
        }
Esempio n. 6
0
 public GoapLoadShipAction(Int64 dockScId, ResourceQuantity resQ)
 {
     addPrecondition("isDocked", true);
     addPrecondition("DockedAt", dockScId);
     addResource((Int64)resQ.Type, (Int64)resQ.Quantity);
     _resourceQ = resQ;
 }
Esempio n. 7
0
        public ResourceQuantity Evaluate(object host)
        {
            var q = new ResourceQuantity();

            foreach (var kvp in this)
            {
                q.Add(kvp.Key, kvp.Value.Evaluate(host));
            }
            return(q);
        }
        public void InvalidPreferVolumeNameMappingForVolume()
        {
            var config           = new KubernetesConfig("image", CreatePodParameters.Create(hostConfig: VolumeMountHostConfig), Option.None <AuthConfig>());
            var docker           = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVarsDict);
            var module           = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var mapper           = new KubernetesPvcMapper("a-volume", "storageclass", 1);
            var resourceQuantity = new ResourceQuantity("1Mi");

            Assert.Throws <InvalidModuleException>(() => mapper.CreatePersistentVolumeClaims(module, DefaultLabels));
        }
 /// <summary>
 /// Check how much money is needed to build a given building.
 /// </summary>
 /// <param name="building">The building to build.</param>
 /// <returns>The amount of coins needed.</returns>
 public int IsMoneyRequired(Card building)
 {
     if (building.CardBuildCondition.Resources.Length == 1)
     {
         ResourceQuantity firstRes = building.CardBuildCondition.Resources.ElementAt(0);
         if (firstRes.Type == ResourceType.GOLD)
         {
             return(firstRes.Quantity);
         }
     }
     return(0);
 }
Esempio n. 10
0
 public Package(Empire owner, Empire recipient)
 {
     Owner                 = owner;
     Recipient             = recipient;
     TreatyClauses         = new HashSet <Clause>();
     Planets               = new GalaxyReferenceSet <Planet>();
     Vehicles              = new GalaxyReferenceSet <IVehicle>();
     Resources             = new ResourceQuantity();
     Technology            = new ModReferenceKeyedDictionary <Tech, int>();
     StarCharts            = new GalaxyReferenceSet <StarSystem>();
     CommunicationChannels = new GalaxyReferenceSet <Empire>();
 }
Esempio n. 11
0
        /// <summary>
        /// Does 1 turn's worth of building.
        /// </summary>
        public void Execute(IOrderable q)
        {
            var queue  = (ConstructionQueue)q;
            var errors = GetErrors(queue);

            foreach (var error in errors)
            {
                queue.Owner.Log.Add(error);
            }

            if (!errors.Any())
            {
                // create item if needed
                if (Item == null)
                {
                    Item = Template.Instantiate();
                    if (!(Item is Facility))
                    {
                        Item.Owner = queue.Owner;
                    }
                    if (Item is SpaceVehicle)
                    {
                        // space vehicles need their supplies filled up
                        var sv = (SpaceVehicle)(IConstructable)Item;
                        sv.SupplyRemaining = sv.SupplyStorage;
                    }
                }

                // apply build rate
                var costLeft = Item.Cost - Item.ConstructionProgress;
                var spending = ResourceQuantity.Min(costLeft, queue.UnspentRate);
                if (!(spending <= queue.Owner.StoredResources))
                {
                    spending = ResourceQuantity.Min(spending, queue.Owner.StoredResources);
                    if (spending.IsEmpty)
                    {
                        if (!queue.IsConstructionDelayed)                         // don't spam messages!
                        {
                            Owner.Log.Add(queue.Container.CreateLogMessage("Construction of " + Template + " at " + queue.Container + " was paused due to lack of resources."));
                        }
                    }
                    else
                    {
                        Owner.Log.Add(queue.Container.CreateLogMessage("Construction of " + Template + " at " + queue.Container + " was slowed due to lack of resources."));
                    }
                    queue.IsConstructionDelayed = true;
                }
                queue.Owner.StoredResources -= spending;
                queue.UnspentRate           -= spending;
                Item.ConstructionProgress   += spending;
            }
        }
Esempio n. 12
0
    public PlayedCardV2(Member performer, Target[] targets, Card card, ResourceQuantity spent, ResourceQuantity gained)
    {
        if (targets.Length < card.ActionSequences.Length)
        {
            throw new InvalidDataException($"Cannot play {card.Name} with only {targets.Length}");
        }

        _performer = performer;
        _targets   = targets;
        _card      = card;
        _spent     = spent;
        _gained    = gained;
    }
Esempio n. 13
0
        public static List <ResourceQuantity> addResource(ResourceQuantity resource, List <ResourceQuantity> list)
        {
            var item = list.FirstOrDefault(x => x.Resource == resource.Resource);

            if (item == null)
            {
                list.Add(resource);
            }
            else
            {
                item.Quantity += resource.Quantity;
            }
            return(list);
        }
Esempio n. 14
0
        /// <summary>
        /// Computes the max of each resource in a group of resource quantities.
        /// </summary>
        /// <param name="qs"></param>
        /// <returns></returns>
        public static ResourceQuantity MaxOfAllResources(this IEnumerable <ResourceQuantity> qs)
        {
            var result = new ResourceQuantity();

            foreach (var q in qs)
            {
                foreach (var kvp in q)
                {
                    if (kvp.Value > result[kvp.Key])
                    {
                        result[kvp.Key] = kvp.Value;
                    }
                }
            }
            return(result);
        }
Esempio n. 15
0
        public void IsGoalAchievedFail2Ressources()
        {
            var initPos = new CoordinateInt2D()
            {
                X = 4, Y = 4
            };
            var rq = new ResourceQuantity()
            {
                Resource = ResourceType.Gold, Quantity = 10
            };
            var goal = new List <ResourceQuantity>()
            {
                new ResourceQuantity()
                {
                    Resource = ResourceType.Gold, Quantity = 10
                },
                new ResourceQuantity()
                {
                    Resource = ResourceType.Silver, Quantity = 10
                }
            };
            var cntx = new PlayerContext()
            {
                Level = 1
            };
            var mockedDrone = new Mock <IDrone>();

            mockedDrone
            .Setup(dr => dr.GetValidInstructions())
            .Returns(new List <IInstruction>()
            {
                new Unload(cntx, new Drone(initPos), new DateTime(2018, 1, 1, 0, 0, 0))
                {
                    Resource = rq
                }
            });

            cntx.Drones = new List <IDrone>()
            {
                mockedDrone.Object
            };

            cntx.IsResourceGoalAchieved(goal).Should().BeFalse();
        }
Esempio n. 16
0
 public ResourceTreeNode(ResourceQuantity rq, bool buyable)
 {
     this.Resources = new Dictionary <ResourceType, int>()
     {
         [rq.Type] = rq.Quantity
     };
     if (buyable)
     {
         this.BuyableResources = new Dictionary <ResourceType, int>()
         {
             [rq.Type] = rq.Quantity
         }
     }
     ;
     else
     {
         this.BuyableResources = new Dictionary <ResourceType, int>();
     }
     this.Children = new List <ResourceTreeNode>();
 }
Esempio n. 17
0
        /// <summary>
        /// Does 1 turn's worth of building.
        /// </summary>
        public void Execute(IOrderable ord)
        {
            if (ord is ConstructionQueue queue)
            {
                var errors = GetErrors(queue);
                foreach (var error in errors)
                {
                    queue.Owner.Log.Add(error);
                }

                if (!errors.Any())
                {
                    // create item if needed
                    if (NewFacility == null)
                    {
                        NewFacility = Upgrade.New.Instantiate();
                    }

                    // apply build rate
                    var costLeft = Cost - NewFacility.ConstructionProgress;
                    var spending = ResourceQuantity.Min(costLeft, queue.UnspentRate);
                    if (spending < queue.Owner.StoredResources)
                    {
                        spending = ResourceQuantity.Min(spending, queue.Owner.StoredResources);
                        queue.Container.CreateLogMessage("Construction of " + Upgrade.New + " at " + queue.Container + " was delayed due to lack of resources.");
                    }
                    queue.Owner.StoredResources      -= spending;
                    queue.UnspentRate                -= spending;
                    NewFacility.ConstructionProgress += spending;

                    // if we're done, delete the old facility and replace it with this one
                    if (CheckCompletion(queue))
                    {
                        var planet = (Planet)queue.Container;
                        planet.Colony.Facilities.Where(f => f.Template == Upgrade.Old).First().Dispose();
                        planet.Colony.Facilities.Add(NewFacility);
                    }
                }
            }
        }
Esempio n. 18
0
        public void GetStoredResourcesAtTest()
        {
            var initPos = new CoordinateInt2D()
            {
                X = 4, Y = 4
            };
            var rq = new ResourceQuantity()
            {
                Resource = ResourceType.Gold, Quantity = 42
            };
            var cntx = new PlayerContext()
            {
                Level = 1
            };
            var mockedDrone = new Mock <IDrone>();

            mockedDrone
            .Setup(dr => dr.GetValidInstructions())
            .Returns(new List <IInstruction>()
            {
                new Unload(cntx, new Drone(initPos), new DateTime(2018, 1, 1, 0, 0, 0))
                {
                    Resource = rq
                }
            });

            cntx.Drones = new List <IDrone>()
            {
                mockedDrone.Object
            };
            IEnumerable <ResourceQuantity> expected = new List <ResourceQuantity>()
            {
                rq
            };

            var actual = cntx.Resources;

            actual.Should().BeEquivalentTo(expected);
        }
Esempio n. 19
0
    /// <summary>
    /// Distribute randomly a wonder to all players.
    /// </summary>
    /// <param name="side">Choose A/B side of wonders (both if not mentionned)</param>
    public void LoadWonders(char side = '\0')
    {
        List <Wonder> wonders = WondersDAO.GetWonders(side);

        Random rand = new Random();

        foreach (Player player in this.Players)
        {
            Wonder        wonder          = wonders.ElementAt(rand.Next(wonders.Count));
            List <Wonder> wondersToRemove = wonders.Where(w => w.Name.Contains(wonder.Name)).ToList();
            foreach (Wonder wonderToRemove in wondersToRemove)
            {
                wonders.Remove(wonderToRemove); // Remove A & B side.
            }
            player.WonderManager.Wonder = wonder;
            ResourceQuantity baseResource = new ResourceQuantity
            {
                Type     = wonder.BaseResource,
                Quantity = 1
            };
            player.City.AddToResourceTree(new ResourceQuantity[] { baseResource }, false, false);
        }
    }
Esempio n. 20
0
 // Resource Commands
 public void Gain(ResourceQuantity qty) => GainResource(qty.ResourceType, qty.Amount);
Esempio n. 21
0
 public Planet()
 {
     ResourceValue = new ResourceQuantity();
     Orders        = new List <IOrder>();
 }
Esempio n. 22
0
        // TODO - status messages for the GUI
        private void PlaceEmpire(Galaxy gal, Empire emp, PRNG dice)
        {
            if (AllSystemsExplored)
            {
                // set all systems explored
                foreach (var sys in gal.StarSystemLocations.Select(ssl => ssl.Item))
                {
                    sys.ExploredByEmpires.Add(emp);
                }
            }

            // give empire starting techs
            Galaxy.Current.CleanGameState();             // need to know what the techs in the game are!
            foreach (var tech in Mod.Current.Technologies.Where(t => !t.IsRacial || emp.Abilities().Any(a => a.Rule.Matches("Tech Area") && a.Value1 == t.RacialTechID)))
            {
                switch (StartingTechnologyLevel)
                {
                case StartingTechnologyLevel.Low:
                    emp.ResearchedTechnologies[tech] = tech.StartLevel;
                    break;

                case StartingTechnologyLevel.Medium:
                    emp.ResearchedTechnologies[tech] = Math.Max(tech.StartLevel, tech.RaiseLevel);
                    break;

                case StartingTechnologyLevel.High:
                    emp.ResearchedTechnologies[tech] = tech.MaximumLevel;
                    break;
                }
            }

            // give empire starting resources and storage capacity
            foreach (var r in Resource.All.Where(r => r.IsGlobal))
            {
                emp.StoredResources.Add(r, StartingResources);
                emp.IntrinsicResourceStorage.Add(r, ResourceStorage);
            }

            // give empire starting research
            emp.BonusResearch = StartingResearch + (int)(ResearchPointsPerUnspentEmpirePoint * (EmpirePoints - emp.PrimaryRace.Traits.Sum(q => q.Cost)));

            // TODO - moddable colony techs?
            string colonyTechName = null;

            if ((emp.PrimaryRace.NativeSurface) == "Rock")
            {
                colonyTechName = "Rock Planet Colonization";
            }
            else if ((emp.PrimaryRace.NativeSurface) == "Ice")
            {
                colonyTechName = "Ice Planet Colonization";
            }
            else if ((emp.PrimaryRace.NativeSurface) == "Gas Giant")
            {
                colonyTechName = "Gas Giant Colonization";
            }
            var colonyTech = Mod.Current.Technologies.SingleOrDefault(t => t.Name == colonyTechName);

            if (colonyTech != null && emp.ResearchedTechnologies[colonyTech] < 1)
            {
                emp.ResearchedTechnologies[colonyTech] = 1;
            }

            // find facilities to place on homeworlds
            var facils = emp.UnlockedItems.OfType <FacilityTemplate>();
            var sy     = facils.WithMax(facil => facil.GetAbilityValue("Space Yard", 2).ToInt()).LastOrDefault();
            var sp     = facils.LastOrDefault(facil => facil.HasAbility("Spaceport"));
            var rd     = facils.LastOrDefault(facil => facil.HasAbility("Supply Generation"));
            var min    = facils.WithMax(facil => facil.GetAbilityValue("Resource Generation - Minerals").ToInt()).LastOrDefault();
            var org    = facils.WithMax(facil => facil.GetAbilityValue("Resource Generation - Organics").ToInt()).LastOrDefault();
            var rad    = facils.WithMax(facil => facil.GetAbilityValue("Resource Generation - Radioactives").ToInt()).LastOrDefault();
            var res    = facils.WithMax(facil => facil.GetAbilityValue("Point Generation - Research").ToInt()).LastOrDefault();
            // TODO - game setup option for intel facilities on homeworlds? HomeworldStartingFacilities.txt ala se5?

            // SY rate, for colonies
            var rate = new ResourceQuantity();

            if (sy != null)
            {
                // TODO - define mappings between SY ability numbers and resource names in a mod file
                rate.Add(Resource.Minerals, sy.GetAbilityValue("Space Yard", 2, true, true, a => a.Value1 == "1").ToInt());
                rate.Add(Resource.Organics, sy.GetAbilityValue("Space Yard", 2, true, true, a => a.Value1 == "2").ToInt());
                rate.Add(Resource.Radioactives, sy.GetAbilityValue("Space Yard", 2, true, true, a => a.Value1 == "3").ToInt());
            }

            // build connectivity graph for computing warp distance
            var graph = new ConnectivityGraph <StarSystem>();

            foreach (var s in Galaxy.Current.StarSystemLocations.Select(ssl => ssl.Item))
            {
                graph.Add(s);
            }
            foreach (var s in Galaxy.Current.StarSystemLocations.Select(ssl => ssl.Item))
            {
                foreach (var wp in s.FindSpaceObjects <WarpPoint>())
                {
                    graph.Connect(s, wp.TargetStarSystemLocation.Item, true);
                }
            }

            for (int i = 0; i < HomeworldsPerEmpire; i++)
            {
                // TODO - respect Empire Placement and Max Homeworld Dispersion settings
                var planets   = gal.StarSystemLocations.SelectMany(ssl => ssl.Item.FindSpaceObjects <Planet>(p => p.Owner == null && p.MoonOf == null));
                var okSystems = gal.StarSystemLocations.Select(ssl => ssl.Item).Where(sys => sys.EmpiresCanStartIn);
                if (i > 0)
                {
                    // make sure subsequent homeworlds are placed within a limited number of warps from the first homeworld
                    okSystems = okSystems.Where(sys => graph.ComputeDistance(sys, emp.OwnedSpaceObjects.OfType <Planet>().First().FindStarSystem()) <= MaxHomeworldDispersion);
                }
                switch (EmpirePlacement)
                {
                case EmpirePlacement.CanStartInSameSystem:
                    // no further filtering
                    break;

                case EmpirePlacement.DifferentSystems:
                    // filter to systems containing no other empires' homeworlds
                    okSystems = okSystems.Where(sys => !sys.FindSpaceObjects <Planet>(p => p.Owner != null && p.Owner != emp).Any());
                    break;

                case EmpirePlacement.Equidistant:
                    // filter to systems containing no other empires' homeworlds
                    okSystems = okSystems.Where(sys => !sys.FindSpaceObjects <Planet>(p => p.Owner != null && p.Owner != emp).Any());
                    // filter to systems that are the maximum distance away from any other empire's homeworlds
                    var otherEmpireHomeSystems = gal.StarSystemLocations.SelectMany(ssl => ssl.Item.FindSpaceObjects <Planet>(p => p.Owner != null && p.Owner != emp).Select(p => p.FindStarSystem()).Distinct()).ToArray();
                    okSystems = okSystems.WithMax(sys => otherEmpireHomeSystems.Min(o => graph.ComputeDistance(sys, o)));
                    break;
                }
                okSystems = okSystems.ToArray();
                if (!okSystems.Any())
                {
                    // replace an inhospitable system with a hospitable one
                    var convertSys = gal.StarSystemLocations.Select(ssl => ssl.Item).Where(sys => !sys.EmpiresCanStartIn).PickRandom(dice);
                    if (convertSys == null)
                    {
                        throw new Exception("No suitable system found to place " + emp + "'s homeworld #" + (i + 1) + ". (Try increasing the number of star systems.)");
                    }
                    var newSys = Mod.Current.StarSystemTemplates.Where(q => q.EmpiresCanStartIn).PickRandom(dice).Instantiate();
                    var sid    = convertSys.ID;
                    newSys.CopyTo(convertSys);
                    convertSys.ID   = sid;
                    convertSys.Name = Mod.Current.StarSystemNames.Except(gal.StarSystemLocations.Select(q => q.Item.Name)).PickRandom(dice);
                    foreach (var l in Galaxy.Current.StarSystemLocations)
                    {
                        foreach (var wp in l.Item.FindSpaceObjects <WarpPoint>().Where(q => q.Target.StarSystem == convertSys).ToArray())
                        {
                            wp.Dispose();
                            WarpPointPlacementStrategy.PlaceWarpPoints(Galaxy.Current.StarSystemLocations.Single(q => q.Item == convertSys), l);
                        }
                    }
                    GalaxyTemplate.NameStellarObjects(convertSys);
                    okSystems = new[] { convertSys };
                }
                Planet hw;
                planets = planets.Where(p => okSystems.Contains(p.FindStarSystem()));
                if (!planets.Any())
                {
                    // make sure we're placing the homeworld in a system with at least one empty sector
                    okSystems = okSystems.Where(sys2 => sys2.Sectors.Any(sec => !sec.SpaceObjects.Any()));

                    if (!okSystems.Any())
                    {
                        throw new Exception("No suitable system found to place " + emp + "'s homeworld #" + (i + 1) + ". (Try regenerating the map or increasing the number of star systems.)");
                    }

                    // make brand new planet in an OK system
                    var sys     = okSystems.PickRandom(dice);
                    var nextNum = sys.FindSpaceObjects <Planet>(p => p.MoonOf == null).Count() + 1;
                    hw = MakeHomeworld(emp, sys.Name + " " + nextNum.ToRomanNumeral(), dice);
                    var okSectors = sys.Sectors.Where(sector => !sector.SpaceObjects.Any());
                    okSectors.PickRandom(dice).Place(hw);
                }
                else
                {
                    hw = planets.PickRandom(dice);
                }
                if (hw.Surface != emp.PrimaryRace.NativeSurface || hw.Atmosphere != emp.PrimaryRace.NativeAtmosphere || hw.Size != HomeworldSize)
                {
                    var replacementHomeworld = MakeHomeworld(emp, hw.Name, dice);
                    replacementHomeworld.CopyTo(hw);
                }
                hw.ResourceValue[Resource.Minerals] = hw.ResourceValue[Resource.Organics] = hw.ResourceValue[Resource.Radioactives] = HomeworldValue;
                hw.Colony = new Colony
                {
                    Owner             = emp,
                    ConstructionQueue = new ConstructionQueue(hw),
                    IsHomeworld       = true,
                };
                hw.AddPopulation(emp.PrimaryRace, hw.Size.MaxPopulation);
                if (sy != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                {
                    hw.Colony.Facilities.Add(sy.Instantiate());
                }
                if (sp != null && hw.Colony.Facilities.Count < hw.MaxFacilities && (!emp.HasAbility("No Spaceports") || sp.Abilities.Count > 1))
                {
                    // natural merchants get spaceports only if spaceports have more than one ability
                    // of course, if the other abilities are *penalties*... oh well, they can scrap them!
                    hw.Colony.Facilities.Add(sp.Instantiate());
                }
                if (rd != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                {
                    hw.Colony.Facilities.Add(rd.Instantiate());
                }
                var lastCount = 0;
                while (hw.Colony.Facilities.Count < hw.MaxFacilities && hw.Colony.Facilities.Count > lastCount)
                {
                    lastCount = hw.Colony.Facilities.Count;

                    if (min != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                    {
                        hw.Colony.Facilities.Add(min.Instantiate());
                    }
                    if (org != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                    {
                        hw.Colony.Facilities.Add(org.Instantiate());
                    }
                    if (rad != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                    {
                        hw.Colony.Facilities.Add(rad.Instantiate());
                    }

                    // no research facilities needed at max tech!
                    if (StartingTechnologyLevel != StartingTechnologyLevel.High)
                    {
                        if (res != null && hw.Colony.Facilities.Count < hw.MaxFacilities)
                        {
                            hw.Colony.Facilities.Add(res.Instantiate());
                        }
                    }
                }
                foreach (var f in hw.Colony.Facilities)
                {
                    f.ConstructionProgress = f.Cost;
                }
            }

            // mark home systems explored
            foreach (var sys in gal.StarSystemLocations.Select(ssl => ssl.Item))
            {
                if (!sys.ExploredByEmpires.Contains(emp) && sys.FindSpaceObjects <Planet>().Any(planet => planet.Owner == emp))
                {
                    sys.ExploredByEmpires.Add(emp);
                }
            }

            // in case two empires started in the same system
            foreach (var x in gal.FindSpaceObjects <ISpaceObject>().Owned().ToArray())
            {
                x.UpdateEmpireMemories();
            }
        }
Esempio n. 23
0
 public StellarObject()
 {
     IntrinsicAbilities = new List <Ability>();
     StoredResources    = new ResourceQuantity();
 }
Esempio n. 24
0
        private void BindEmpire(Empire emp, TabPage tab = null)
        {
            empire = emp;
            if (tab != null)
            {
                tabs.SelectedTab = tab;
            }
            else if (emp == Empire.Current && tabs.SelectedTab == tabDiplomacy)
            {
                tabs.SelectedTab = tabBudget;
            }
            else if (emp != Empire.Current && tabs.SelectedTab == tabBudget)
            {
                tabs.SelectedTab = tabDiplomacy;
            }

            report.Empire = emp;

            if (emp == null)
            {
                txtTreaty.Text      = "N/A";
                txtTreaty.ForeColor = Color.White;
                toolTip.SetToolTip(txtTreaty, "Select an empire to view its treaty status.");
            }
            else
            {
                if (emp == Empire.Current)
                {
                    txtTreaty.Text      = "Self";
                    txtTreaty.ForeColor = Color.CornflowerBlue;
                    toolTip.SetToolTip(txtTreaty, "You can't have a treaty with your own empire. Nice try, though...");
                }
                else
                {
                    var treaty         = Empire.Current.GetTreaty(emp);
                    var giving         = treaty.Where(c => c.Giver == Empire.Current);
                    var receiving      = treaty.Where(c => c.Receiver == Empire.Current);
                    var givingTexts    = giving.Select(c => c.ToString());
                    var receivingTexts = receiving.Select(c => c.ToString());
                    var helptext       = "";
                    if (!treaty.Any())
                    {
                        txtTreaty.Text      = "None";
                        txtTreaty.ForeColor = Color.Yellow;
                        helptext            = "You don't have any treaty with this empire.";
                    }
                    else if (!giving.Any())
                    {
                        txtTreaty.Text      = "Receiving " + string.Join(", ", receivingTexts.ToArray());
                        txtTreaty.ForeColor = Color.Green;
                        helptext            = string.Join("\n", receiving.Select(x => x.FullDescription));
                    }
                    else if (!receiving.Any())
                    {
                        txtTreaty.Text      = "Giving " + string.Join(", ", givingTexts.ToArray());
                        txtTreaty.ForeColor = Color.LightGray;
                        helptext            = string.Join("\n", giving.Select(x => x.FullDescription));
                    }
                    else
                    {
                        var mutualTexts        = givingTexts.Join(receivingTexts, s => s, s => s, (g, r) => g);
                        var givingOnlyTexts    = givingTexts.Except(mutualTexts);
                        var receivingOnlyTexts = receivingTexts.Except(mutualTexts);
                        if (givingOnlyTexts.Any() && receivingTexts.Any())
                        {
                            txtTreaty.Text = "Trading " + string.Join(", ", givingOnlyTexts.ToArray()) + " for " + string.Join(", ", receivingOnlyTexts.ToArray());
                        }
                        else if (givingOnlyTexts.Any())
                        {
                            txtTreaty.Text = "Giving " + string.Join(", ", givingOnlyTexts.ToArray());
                        }
                        else if (receivingOnlyTexts.Any())
                        {
                            txtTreaty.Text = "Receiving " + string.Join(", ", receivingOnlyTexts.ToArray());
                        }
                        if (mutualTexts.Any())
                        {
                            if (givingOnlyTexts.Any() || receivingOnlyTexts.Any())
                            {
                                txtTreaty.Text = "Mutual " + string.Join(", ", mutualTexts.ToArray()) + "; " + txtTreaty.Text;
                            }
                            else
                            {
                                txtTreaty.Text = "Mutual " + string.Join(", ", mutualTexts.ToArray());
                            }
                        }
                        txtTreaty.ForeColor = Color.White;

                        helptext = string.Join("\n", giving.Union(receiving).Select(x => x.FullDescription));
                    }
                    toolTip.SetToolTip(txtTreaty, helptext);
                }

                // budget
                if (emp == Empire.Current)
                {
                    rqdConstruction.ResourceQuantity = emp.ConstructionSpending;
                }
                else
                {
                    // assume other empires' construction queues are running at full capacity
                    rqdConstruction.ResourceQuantity = emp.ConstructionQueues.Sum(rq => rq.Rate);
                }
                rqdExtraction.ResourceQuantity  = emp.ColonyIncome + emp.RemoteMiningIncome + emp.RawResourceIncome;
                rqdIncome.ResourceQuantity      = emp.GrossDomesticIncome;
                rqdMaintenance.ResourceQuantity = emp.Maintenance;
                rqdNet.ResourceQuantity         = emp.NetIncomeLessConstruction;
                rqdStorage.ResourceQuantity     = emp.ResourceStorage;
                var spoilageOrDeficit = new ResourceQuantity();
                var newResources      = emp.StoredResources + emp.NetIncomeLessConstruction;
                foreach (var r in Resource.All)
                {
                    if (newResources[r] > emp.ResourceStorage[r])
                    {
                        spoilageOrDeficit[r] = newResources[r] - emp.ResourceStorage[r];
                    }
                    else if (newResources[r] < 0)
                    {
                        spoilageOrDeficit[r] = newResources[r];
                    }
                    else
                    {
                        spoilageOrDeficit[r] = 0;
                    }
                }
                rqdSpoiledDeficit.ResourceQuantity = spoilageOrDeficit;
                rqdStored.ResourceQuantity         = emp.StoredResources;
                rqdTrade.ResourceQuantity          = emp.TradeIncome;
                rqdTributesIn.ResourceQuantity     = new ResourceQuantity();             // TODO - show tributes
                rqdTributesOut.ResourceQuantity    = new ResourceQuantity();             // TODO - show tributes
                rqExpenses.ResourceQuantity        = rqdConstruction.ResourceQuantity + rqdMaintenance.ResourceQuantity + rqdTributesOut.ResourceQuantity;
                lblBudgetWarning.Visible           = emp != Empire.Current;

                // message log
                var msgs = Empire.Current.IncomingMessages.Where(m => m.Owner == emp).Union(Empire.Current.SentMessages.Where(m => m.Recipient == emp)).Union(Empire.Current.Commands.OfType <SendMessageCommand>().Select(cmd => cmd.Message));
                lstMessages.Initialize(64, 64);
                foreach (var msg in msgs.OrderByDescending(m => m.TurnNumber))
                {
                    lstMessages.AddItemWithImage(msg.TurnNumber.ToStardate(), "", msg, msg.Owner.Portrait, null, msg.Owner == Empire.Current ? "Us" : msg.Owner.Name, msg.Recipient == Empire.Current ? "Us" : msg.Recipient.Name, msg.Text);
                }

                // player info
                txtName.Text    = emp.PlayerInfo?.Name;
                lnkPbw.Text     = emp.PlayerInfo?.Pbw;
                lnkEmail.Text   = emp.PlayerInfo?.Email;
                txtIrc.Text     = emp.PlayerInfo?.Irc;
                txtDiscord.Text = emp.PlayerInfo?.Discord;
                lnkWebsite.Text = emp.PlayerInfo?.Website;
                txtNotes.Text   = emp.PlayerInfo?.Notes;
            }
        }
Esempio n. 25
0
 public ResourceQuantityViewModel(ResourceQuantity x)
 {
     Model = x;
 }
Esempio n. 26
0
 public ConstructionQueue(IConstructor c)
 {
     Orders      = new List <IConstructionOrder>();
     Container   = c;
     UnspentRate = new ResourceQuantity();
 }
Esempio n. 27
0
 public void Lose(ResourceQuantity qty) => LoseResource(qty.ResourceType, qty.Amount);
Esempio n. 28
0
        private ResourceQuantity ComputeRate()
        {
            var rate = ComputeSYAbilityRate();

            if (Colony != null)
            {
                if (rate == null)
                {
                    rate = Mod.Current.Settings.DefaultColonyConstructionRate;
                }

                // apply population modifier
                var pop = Colony.Population.Sum(p => p.Value);
                if (pop == 0)
                {
                    return(new ResourceQuantity());
                }
                rate *= Mod.Current.Settings.GetPopulationConstructionFactor(pop);

                // apply mood modifier
                // TODO - load mood modifier from mod
                var moodModifier = Colony.Mood == Mood.Rioting ? 0 : 100;
                rate *= moodModifier / 100d;

                var ratios = Colony.Population.Select(p => new { Race = p.Key, Ratio = (double)p.Value / (double)pop });

                // apply racial trait planetary SY modifier
                // TODO - should Planetary SY Rate apply only to planets that have space yards, or to all planetary construction queues?
                double traitmod = 1d;
                foreach (var ratio in ratios)
                {
                    traitmod += (ratio.Race.GetAbilityValue("Planetary SY Rate").ToDouble() / 100d) * ratio.Ratio;
                }
                rate *= traitmod;

                // apply aptitude modifier
                if (IsSpaceYardQueue)
                {
                    double aptmod = 0d;
                    foreach (var ratio in ratios)
                    {
                        aptmod += ((ratio.Race.Aptitudes[Aptitude.Construction.Name] / 100d)) * ratio.Ratio;
                    }
                    rate *= aptmod;

                    // apply culture modifier
                    rate *= (100d + (Owner?.Culture?.Construction ?? 0)) / 100d;
                }
            }
            if (rate == null)
            {
                rate = new ResourceQuantity();
            }
            if (Container is IVehicle)
            {
                // apply aptitude modifier for empire's primary race
                rate *= Owner.PrimaryRace.Aptitudes[Aptitude.Construction.Name] / 100d;
            }

            return(rate);
        }
Esempio n. 29
0
        /// <summary>
        /// Executes orders for a turn.
        /// </summary>
        public bool ExecuteOrders()
        {
            bool didStuff = false;

            if (AreOrdersOnHold)
            {
                return(didStuff);
            }

            UnspentRate = Rate;
            var  empty         = new ResourceQuantity();
            var  builtThisTurn = new HashSet <IConstructable>();
            bool done          = false;

            while (!done && Orders.Any() && (Owner.StoredResources > empty || UpcomingSpending.IsEmpty))
            {
                var numOrders      = Orders.Count;
                var spentThisRound = new ResourceQuantity();

                foreach (var order in Orders.Cast <IConstructionOrder>().ToArray())
                {
                    if (order == null)
                    {
                        // WTF
                        Orders.Remove(order);
                        continue;
                    }
                    var reasonForNotBuilding = GetReasonForBeingUnableToConstruct(order.Template);
                    if (reasonForNotBuilding != null)
                    {
                        // can't build that here!
                        Orders.RemoveAt(0);
                        Owner.Log.Add(Container.CreateLogMessage(order.Template + " cannot be built at " + this + " because " + reasonForNotBuilding));
                    }
                    else
                    {
                        var oldProgress = new ResourceQuantity(order.Item?.ConstructionProgress);
                        order.Execute(this);
                        var newProgress = new ResourceQuantity(order.Item?.ConstructionProgress);
                        if (newProgress < (order.Item?.Cost ?? new ResourceQuantity()) && newProgress == oldProgress && order == Orders.Last())
                        {
                            done = true;                             // made no progress and nothing else to try and build
                        }
                        if (order.CheckCompletion(this))
                        {
                            // upgrade facility orders place their own facilities
                            if (!(order is UpgradeFacilityOrder))
                            {
                                order.Item.Place(Container);
                            }
                            Orders.Remove(order);
                            if (AreRepeatOrdersEnabled)
                            {
                                var copy = order.Copy <IConstructionOrder>();
                                copy.Reset();
                                Orders.Add(copy);
                            }
                            builtThisTurn.Add(order.Item);
                            if (order.Item is Ship || order.Item is Base)
                            {
                                // trigger ship built happiness changes
                                Owner.TriggerHappinessChange(hm => hm.AnyShipConstructed);
                                if (Container is Planet p)
                                {
                                    p.Colony.TriggerHappinessChange(hm => hm.ShipConstructed);
                                }
                            }
                            if (order.Item is Facility)
                            {
                                // trigger facility built happiness changes
                                if (Container is Planet p)
                                {
                                    p.Colony.TriggerHappinessChange(hm => hm.FacilityConstructed);
                                }
                            }
                        }
                    }
                }

                didStuff = true;

                if (!AreRepeatOrdersEnabled)
                {
                    done = true;
                }
            }
            foreach (var g in builtThisTurn.GroupBy(i => i.Template))
            {
                if (g.Count() == 1)
                {
                    Owner.Log.Add(g.First().CreateLogMessage(g.First() + " has been constructed at " + Name + "."));
                }
                else
                {
                    Owner.Log.Add(g.First().CreateLogMessage(g.Count() + "x " + g.Key + " have been constructed at " + Name + "."));
                }
            }
            return(didStuff);
        }
Esempio n. 30
0
 public SpaceVehicle()
 {
     Orders          = new List <IOrder>();
     StoredResources = new ResourceQuantity();
 }