示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PrototypeCivilizationFactory" /> class.
 /// </summary>
 public PrototypeCivilizationFactory()
 {
     this.protoCity             = new BasicCity(new Point(0, 0), null, null);
     XmlDepartDirectorPrototype = new XmlAnything <IDepartDirector>(new BasicDepartDirector());
     XmlStudentPrototype        = new XmlAnything <IStudent>(new BasicStudent(0, 0, 0, 0));
     XmlTeacherPrototype        = new XmlAnything <ITeacher>(new BasicTeacher(0, 0, 0, 0));
 }
 private void OnCityClicked(ICity city)
 {
     if (!IsAdding)
     {
         city.Destroy();
     }
 }
        public IBuilding BuildBuilding(IBuildingTemplate template, ICity city)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }
            else if (city == null)
            {
                throw new ArgumentNullException("city");
            }

            var newBuilding = new Building(template);

            var slots = new List <IWorkerSlot>();

            for (int i = 0; i < template.SpecialistCount; i++)
            {
                slots.Add(WorkerSlotFactory.BuildSlot(newBuilding));
            }

            newBuilding.Slots = slots.AsReadOnly();

            if (!PossessionCanon.CanChangeOwnerOfPossession(newBuilding, city))
            {
                throw new BuildingCreationException("The building produced from this template cannot be placed into this city");
            }
            PossessionCanon.ChangeOwnerOfPossession(newBuilding, city);

            allBuildings.Add(newBuilding);

            return(newBuilding);
        }
 private void OnCityBeingDestroyed(ICity city)
 {
     foreach (var building in PossessionCanon.GetPossessionsOfOwner(city).ToArray())
     {
         DestroyBuilding(building);
     }
 }
        private YieldSummary GetMultiplier(ICity city)
        {
            var owningCivilization = CityPossessionCanon.GetOwnerOfPossession(city);

            return(YieldSummary.Ones + IncomeModifierLogic.GetYieldMultipliersForCity(city)
                   + IncomeModifierLogic.GetYieldMultipliersForCivilization(owningCivilization));
        }
        public YieldSummary GetTotalYieldForCity(ICity city, YieldSummary additionalBonuses)
        {
            if (city == null)
            {
                throw new ArgumentNullException("city");
            }

            var retval = CityCenterYieldLogic.GetYieldOfCityCenter(city);

            foreach (var cell in CellPossessionCanon.GetPossessionsOfOwner(city))
            {
                if (!cell.SuppressSlot && cell.WorkerSlot.IsOccupied)
                {
                    retval += GetYieldOfCellForCity(cell, city);
                }
            }

            foreach (var building in BuildingPossessionCanon.GetPossessionsOfOwner(city))
            {
                retval += GetYieldOfBuildingForCity(building, city);
            }

            retval += GetYieldOfUnemployedPersonForCity(city) * UnemploymentLogic.GetUnemployedPeopleInCity(city);

            return(retval * (YieldSummary.Ones + additionalBonuses));
        }
示例#7
0
        public Game(IAgeStrategy ageStrategy, IWinningStrategy winningStrategy, IActionStrategy actionStrategy = null)
        {
            _ageStrategy     = ageStrategy;
            _winningStrategy = winningStrategy;
            _actionStrategy  = actionStrategy;

            PlayerInTurn = Player.RED;
            Age          = -4000;

            // Add Standard Cities
            _cities.Add(new Position(1, 1), new City(Player.RED, new Position(1, 1)));
            _cities.Add(new Position(4, 1), new City(Player.BLUE, new Position(4, 1)));

            // Add standard units
            _units.Add(new Position(2, 0), new Unit(Player.RED, GameConstants.Archer));
            _units.Add(new Position(3, 2), new Unit(Player.BLUE, GameConstants.Legion));
            _units.Add(new Position(4, 3), new Unit(Player.RED, GameConstants.Settler));

            // Decorate the board with tiles
            _tiles.Add(new Position(1, 0), new Tile(GameConstants.Ocean));
            _tiles.Add(new Position(0, 1), new Tile(GameConstants.Hills));
            _tiles.Add(new Position(2, 2), new Tile(GameConstants.Mountains));

            _redCity  = GetCityAt(new Position(1, 1));
            _blueCity = GetCityAt(new Position(4, 1));
        }
        public bool IsCityConnectedToCapital(ICity city)
        {
            var cityOwner = CityPossessionCanon.GetOwnerOfPossession(city);

            var capitalOfOwner = CapitalCityCanon.GetCapitalOfCiv(cityOwner);

            if (capitalOfOwner == city)
            {
                return(true);
            }

            if (capitalOfOwner == null)
            {
                return(false);
            }

            var cityLocation    = CityLocationCanon.GetOwnerOfPossession(city);
            var capitalLocation = CityLocationCanon.GetOwnerOfPossession(capitalOfOwner);

            var pathTo = HexPathfinder.GetShortestPathBetween(
                cityLocation, capitalLocation, ConnectionPathCostLogic.BuildCapitalConnectionPathCostFunction(cityOwner)
                );

            return(pathTo != null);
        }
示例#9
0
        /// <summary>
        /// Handles the 1 event of the createCityButton_Click control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void createCityButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (selectedUnit is ITeacher)
            {
                bool hasCity = false;
                foreach (IPlayer player in players)
                {
                    foreach (ICity city in player.Cities)
                    {
                        if (city.IsAtPosition(selectedUnit.Position))
                        {
                            hasCity = true;
                        }
                    }
                }

                if (!hasCity)
                {
                    ITeacher selectedTeacher = selectedUnit as ITeacher;
                    ICity    City            = selectedTeacher.CreateCity(selectedTeacher.Position, mapViewer.Map, players[currentPlayerIndex]);
                    players[currentPlayerIndex].Cities.Add(City);
                    selectedTeacher.HP       = 0;
                    selectedTeacher.Movement = 0;
                    players[currentPlayerIndex].Units.Remove(selectedUnit);
                }
                else
                {
                    Log.Instance.Write("Une ville possède déjà cette case.");
                }
            }
            mapViewer.Redraw();
        }
示例#10
0
        public virtual Error CanStrongholdBeAttacked(ICity city, IStronghold stronghold, bool forceAttack)
        {
            if (stronghold.StrongholdState == StrongholdState.Inactive)
            {
                return(Error.StrongholdStillInactive);
            }

            if (!city.Owner.IsInTribe)
            {
                return(Error.TribesmanNotPartOfTribe);
            }

            if (!forceAttack)
            {
                if (city.Owner.Tribesman.Tribe == stronghold.Tribe)
                {
                    return(Error.StrongholdCantAttackSelf);
                }

                if (stronghold.GateOpenTo != null && stronghold.GateOpenTo != city.Owner.Tribesman.Tribe)
                {
                    return(Error.StrongholdGateNotOpenToTribe);
                }
            }

            return(Error.Ok);
        }
示例#11
0
        public override void Execute(params string[] commandParams)
        {
            string attackerName = commandParams[0];
            string defenderName = commandParams[1];

            ICity attacker = this.Engine.Continent.GetCityByName(attackerName);
            ICity defender = this.Engine.Continent.GetCityByName(defenderName);

            this.Engine.Continent.VerifyTroopMovement(attacker, defender);

            if (attacker.ControllingHouse == defender.ControllingHouse)
            {
                throw new InvalidOperationException("House cannot attack one of its own cities");
            }

            attacker.FoodStorage -= this.Engine.Continent.CityNeighborsAndDistances[attacker][defender];

            var attackPower  = attacker.AvailableMilitaryUnits.Sum(u => u.Damage);
            var defensePower = defender.Defense + defender.AvailableMilitaryUnits.Sum(u => u.Armor);

            if (attackPower > defensePower)
            {
                this.ProcessSuccessfulAttack(defender, attacker);
            }
            else
            {
                this.ProcessFailedAttack(defender, attacker);
            }
        }
示例#12
0
        /// <summary>
        /// Handles the Click event of the nextTurnButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void nextTurnButton_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < players.Count; ++i)
            {
                if (players[i].IsDead())
                {
                    players.RemoveAt(i);
                }
            }

            if (players.Count == 1)
            {
                MessageBox.Show("Félicitations [" + players[0].Name + "]  vous avez gagné");
            }

            Log.Instance.Write("Fin du tour du joueur [" + players[currentPlayerIndex].Name + "]");
            players[currentPlayerIndex].NextTurn();

            currentPlayerIndex = (++currentPlayerIndex % players.Count);

            mapViewer.Redraw();
            selectedUnit = null;
            selectedCity = null;
            pickContentControl.DataContext = null;
            Log.Instance.Write("Debut du tour du joueur [" + players[currentPlayerIndex].Name + "]");
        }
示例#13
0
        public async Task SaveAsync(ICity city)
        {
            using (var databaseContext = _databaseContextFactory.Create())
            {
                var cityEntity = await databaseContext
                                 .City
                                 .SingleOrDefaultAsync(entity => entity.Code == city.Code);

                if (cityEntity == null)
                {
                    cityEntity = new CityEntity
                    {
                        Code = city.Code
                    };

                    databaseContext.City.Add(cityEntity);
                }

                if (cityEntity.Name == city.Name)
                {
                    return;
                }

                cityEntity.Name = city.Name;

                await databaseContext.SaveChangesAsync();
            }
        }
示例#14
0
        protected ICity Roulette(IAnt ant)
        {
            if (ant.Visited.Count - 1 == ant.CitiesToVisit)
            {
                return(ant.Colony.Destination);
            }

            if (TraverseLevel == 3)
            {
                ICountry country = GetCountryRouletteForAnt(ant).GetNext();

                IRegion region = country.Regions.FirstOrDefault().Value;

                ICity city = region.Cities.FirstOrDefault().Value;

                return(city);
            }
            if (TraverseLevel == 2)
            {
                IRegion region = GetRegionRouletteForAnt(ant).GetNext();

                ICity city = region.Cities.FirstOrDefault().Value;

                return(city);
            }

            return(GetCityRouletteForAnt(ant).GetNext());
        }
示例#15
0
        public void MoveToNextCity(IAnt ant)
        {
            ICity city = Roulette(ant);

            ant.Visited.Add(city);
            ant.Current = city;
        }
示例#16
0
        public IMultiObjectLock Lock(uint cityId, out ICity city, out ITribe tribe)
        {
            tribe = null;

            if (!locator.TryGetObjects(cityId, out city))
            {
                return(Lock());
            }

            var lck = callbackLockFactory().Lock(custom =>
            {
                ICity cityParam = (ICity)custom[0];

                return(!cityParam.Owner.IsInTribe
                               ? new ILockable[] {}
                               : new ILockable[] { cityParam.Owner.Tribesman.Tribe });
            }, new object[] { city }, city);

            if (city.Owner.IsInTribe)
            {
                tribe = city.Owner.Tribesman.Tribe;
            }

            return(lck);
        }
 internal SpsrExpressStreet(object id, ICity city, IReadOnlyDictionary <CultureInfo, string> names,
                            double latitude, double longitude)
 {
     _names = names;
     Id     = id;
     City   = city;
 }
示例#18
0
 public Train(string name, ICompany company, ICity city)
 {
     Name       = name;
     Company    = company;
     Assignment = null;
     City       = city;
 }
示例#19
0
 public virtual void RecalculateCityResourceRates(ICity city)
 {
     city.Resource.Crop.Rate = formula.GetCropRate(city);
     city.Resource.Iron.Rate = formula.GetIronRate(city);
     city.Resource.Wood.Rate = formula.GetWoodRate(city);
     city.Resource.Gold.Rate = formula.GetGoldRate(city);
 }
示例#20
0
 public CityBuilder(ICity city, IRenderer renderer, IWriter writer)
 {
     this.City = city;
     this.Renderer = renderer;
     this.Writer = writer;
     this.IsRunning = false;
 }
        public override void Execute(params string[] commandParams)
        {
            string startingCityName = commandParams[0];
            string destinationName  = commandParams[1];

            ICity startingCity    = this.Engine.Continent.GetCityByName(startingCityName);
            ICity destinationCity = this.Engine.Continent.GetCityByName(destinationName);

            this.Engine.Continent.VerifyTroopMovement(startingCity, destinationCity);

            if (startingCity.ControllingHouse != destinationCity.ControllingHouse)
            {
                throw new InvalidOperationException("Cannot move troops between cities controlled by different Houses");
            }

            var canArmyMove = VerifyDestinationHousingSpaces(destinationCity, startingCity);

            if (!canArmyMove)
            {
                throw new InsufficientHousingSpacesException("Destination city has insufficient housing spaces");
            }

            startingCity.FoodStorage -= this.Engine.Continent.CityNeighborsAndDistances[startingCity][destinationCity];
            var unitsToMove = startingCity.RemoveUnits();

            destinationCity.AddUnits(unitsToMove);

            this.Engine.Render("Successfully moved all units from {0} to {1}", startingCity.Name, destinationCity.Name);
        }
        /// <inheritdoc/>
        public void DistributeWorkersIntoSlots(
            int workerCount, IEnumerable <IWorkerSlot> slots, ICity sourceCity,
            YieldFocusType focus
            )
        {
            foreach (var slot in slots)
            {
                slot.IsOccupied = false;
            }

            switch (focus)
            {
            case YieldFocusType.Food:       PerformFocusedDistribution(workerCount, slots, sourceCity, YieldType.Food);       break;

            case YieldFocusType.Gold:       PerformFocusedDistribution(workerCount, slots, sourceCity, YieldType.Gold);       break;

            case YieldFocusType.Production: PerformFocusedDistribution(workerCount, slots, sourceCity, YieldType.Production); break;

            case YieldFocusType.Culture:    PerformFocusedDistribution(workerCount, slots, sourceCity, YieldType.Culture);    break;

            case YieldFocusType.Science:    PerformFocusedDistribution(workerCount, slots, sourceCity, YieldType.Science);    break;

            case YieldFocusType.TotalYield: PerformUnfocusedDistribution(workerCount, slots, sourceCity); break;

            default: break;
            }
        }
示例#23
0
 public void SetCity(ICity city)
 {
     if (_city == null || !_city.Equals(city))
     {
         _city = city;
     }
 }
示例#24
0
        public override void Execute(params string[] commandParams)
        {
            ICity city = this.Engine.Continent.GetCityByName(commandParams[0]);

            if (city == null)
            {
                throw new ArgumentNullException("city");
            }

            for (int i = 1; i < commandParams.Length; i += 2)
            {
                ICity neighbor = this.Engine.Continent.GetCityByName(commandParams[i]);

                try
                {
                    this.AddNeighborInfo(commandParams, neighbor, i, city);
                }
                catch (ArgumentNullException ex)
                {
                    this.Engine.Render(ex.Message);
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    this.Engine.Render(ex.Message);
                }
            }

            this.Engine.Render(String.Format("All valid neighbor records added for city {0}", city.Name));
        }
        private void MaximizeYield(int workerCount, IEnumerable <IWorkerSlot> slots, ICity sourceCity,
                                   Comparison <IWorkerSlot> yieldMaximizationComparer)
        {
            var maximizedSlotsAscending = new List <IWorkerSlot>(slots);

            maximizedSlotsAscending.Sort(yieldMaximizationComparer);

            var occupiedSlots = new List <IWorkerSlot>();

            int employedWorkers = 0;

            for (; employedWorkers < workerCount; ++employedWorkers)
            {
                var nextBestSlot = maximizedSlotsAscending.LastOrDefault();
                if (nextBestSlot != null)
                {
                    nextBestSlot.IsOccupied = true;
                    maximizedSlotsAscending.Remove(nextBestSlot);
                    occupiedSlots.Add(nextBestSlot);
                }
                else
                {
                    return;
                }
            }
        }
 private void pDraw_Click(object sender, EventArgs e)
 {
     ClickCount++;
     if (drawMode == "city")//!isChoosen(posX, posY)
     {
         storage.Add(new City(posX, posY));
     }
     else if (tmpCity == null && isChoosen(posX, posY))
     {
         for (int i = 0; i < storage.Count; i++)
         {
             if (storage[i].IsSelected() == true)
             {
                 tmpCity = storage[i];
                 break;
             }
         }
     }
     else if (txtWeight.Text != "" && isChoosen(posX, posY))
     {
         for (int i = 0; i < storage.Count; i++)
         {
             ICity current = storage[i];
             if (current.IsSelected() == true && current.Id != tmpCity.Id)
             {
                 tmpCity.SetRoadTo(current, Int32.Parse(txtWeight.Text));
                 tmpCity.ResetSelect();
                 tmpCity = null;
                 current.ResetSelect();
                 break;
             }
         }
     }
     Refresh();
 }
示例#27
0
        private async Task AskJudgedPerson(ICity city, Role role, IReadOnlyCollection <IPerson> choosers)
        {
            if (choosers.Count < 2)
            {
                return;
            }

            var chatId = cityToChat[city];

            await AddCityVoting(city.Name);

            var names = choosers.Select(p => p.Name).ToArray();

            var messageText = CreateMessageText("<b>Who will you blame?</b>\n\n", city.Name, names);

            var cityVotingPool = cityVotingPools[city.Name];

            cityVotingPool.AddChatId(chatId);
            foreach (var userId in choosers.Select(c => personToChat[c]))
            {
                cityVotingPool.AddRole(userId, role);
            }

            var roleVoting = new RoleVotingPool(names);

            cityVotingPool.AddRoleVoting(role, roleVoting);

            await bot.SendTextMessageAsync(chatId, messageText, ParseMode.Html);
        }
 private void OnDistributionPerformed(ICity city)
 {
     if (city == ObjectToDisplay)
     {
         Refresh();
     }
 }
示例#29
0
        private async Task AskRoleForInteractionTarget(ICity city, Role role, IReadOnlyCollection <IPerson> choosers)
        {
            var names = city.Population
                        .Where(p => p.IsAlive && !choosers.Contains(p))
                        .Select(p => p.Name).ToArray();

            await AddCityVoting(city.Name);

            var messageText = CreateMessageText("<b>Who will be your target?</b>\n\n", city.Name, names);

            var cityVotingPool = cityVotingPools[city.Name];

            foreach (var userId in choosers.Select(person => personToChat[person]))
            {
                cityVotingPool.AddChatId(userId);
                cityVotingPool.AddRole(userId, role);
            }

            var roleVoting = new RoleVotingPool(names);

            cityVotingPool.AddRoleVoting(role, roleVoting);

            if (names.Length == 1)
            {
                // bot.SendTextMessageAsync(chatId, $"{role.Name} automatically chosen {targets[0]}").Wait();
                roleVoting.Vote(0, 0); // illegal move
                return;
            }

            await Task.WhenAll(choosers.Select(person => bot.SendTextMessageAsync(personToChat[person], messageText, ParseMode.Html)));
        }
示例#30
0
        public void VerifyTroopMovement(ICity startingCity, ICity destinationCity)
        {
            if (startingCity == null)
            {
                throw new ArgumentNullException("startingCity");
            }

            if (destinationCity == null)
            {
                throw new ArgumentNullException("destinationCity");
            }

            if (startingCity == destinationCity)
            {
                throw new InvalidOperationException(DestinationAndStartAreSameErrorMessage);
            }

            if (!this.CityNeighborsAndDistances[startingCity].ContainsKey(destinationCity))
            {
                throw new LocationOutOfRangeException(CitiesAreNotNeighborsErrorMessage);
            }

            if (!startingCity.AvailableMilitaryUnits.Any())
            {
                throw new ArgumentException("No troops to move");
            }

            if (startingCity.FoodStorage < this.CityNeighborsAndDistances[startingCity][destinationCity])
            {
                throw new NotEnoughProvisionsException(string.Format(
                                                           NotEnoughProvisionsErrorMessage,
                                                           startingCity.Name,
                                                           destinationCity.Name));
            }
        }
示例#31
0
        public void UpdateFromServer(ICity city, IPlayer player)
        {
            var caption = transform.Find("Caption");
            var oldCity = City;

            City = city;

            if (oldCity == null || City.Name != oldCity.Name)
            {
                caption.gameObject.GetComponent <TextMesh>().text = City.Name;
            }

            var visible = player.VisibleCities.Contains(city.Guid);

            if (oldCity == null || Visible != visible)
            {
                Visible = visible;
                gameObject.SetActive(Visible);
            }

            if (oldCity == null || Math.Abs(City.X - oldCity.X) > SharedValues.Tolerance || Math.Abs(City.Y - oldCity.Y) > SharedValues.Tolerance || Math.Abs(City.Size - oldCity.Size) > SharedValues.Tolerance)
            {
                ChangeSize();
            }
        }
示例#32
0
 //
 // GET: /Account/
 public AccountController(IUnitOfWork uow, IAccount accountService, ICountry countryService, IProvince provinceService, ICity cityService, IComment commentService)
 {
     _accountService = accountService;
     _countryService = countryService;
     _provinceService = provinceService;
     _cityService = cityService;
     _commentService = commentService;
     _uow = uow;
 }
示例#33
0
        public override void UpgradeCity(ICity city)
        {
            if (city == null)
            {
                throw new ArgumentNullException(nameof(city));
            }

            this.TreasuryAmount -= city.UpgradeCost;
            city.Upgrade();
        }
示例#34
0
        public void Property_ReturnsTheValueForTheSpecificCityType(ICity city,
                                                                   Expression<Func<ICity, int>> property,
                                                                   int expectedValue)
        {
            // :::: ACT ::::
            var actualValue = property.Compile().Invoke(city);

            // :::: ASSERT ::::
            actualValue.Should().Be(expectedValue);
        }
示例#35
0
        public override void UpgradeCity(ICity city)
        {
            if (city == null)
            {
                throw new ArgumentNullException("city", "Specified city does not exist or is not controlled by house {0}");
            }

            city.Upgrade();
            this.TreasuryAmount -= city.UpgradeCost;
        }
示例#36
0
        public override void UpgradeCity(ICity city)
        {
            if (city == null)
            {
                throw new ArgumentNullException("city", CityNotFoundErrorMessage);
            }

            city.Upgrade();
            this.TreasuryAmount -= city.UpgradeCost;
        }
        public void Equals_ReturnsFalse_BecauseTheCitiesAreNotEqual(ICity first, ICity second)
        {
            // :::: ARRANGE ::::
            var comparer = new CityEqualityComparer();

            // :::: ACT ::::
            var actualEquality = comparer.Equals(first, second);

            // :::: ASSERT ::::
            actualEquality.Should().BeFalse();
        }
示例#38
0
        public void Winner_IsNobody(ICity[] cities)
        {
            // :::: ARRANGE ::::
            var stubCities = StubWorld.Cities(cities);
            var cityConquerorWins = new CityConquerorWins(stubCities);

            // :::: ACT ::::
            var actualWinner = cityConquerorWins.Winner;

            // :::: ASSERT ::::
            actualWinner.Should().Be(Player.Nobody);
        }
        public void GetHashCode_ReturnsTheSameHashCodeForBothCities_BecauseTheCitiesAreEqual(ICity first, ICity second)
        {
            // :::: ARRANGE ::::
            var comparer = new CityEqualityComparer();

            // :::: ACT ::::
            var firstHashCode = comparer.GetHashCode(first);
            var secondHashCode = comparer.GetHashCode(second);

            // :::: ASSERT ::::
            firstHashCode.Should().Be(secondHashCode);
        }
示例#40
0
        public void Winner_IsThePlayerWhoOwnsAllCities(ICity[] cities)
        {
            // :::: ARRANGE ::::
            var stubCities = StubWorld.Cities(cities);
            var cityConquerorWins = new CityConquerorWins(stubCities);

            // :::: ACT ::::
            var actualWinner = cityConquerorWins.Winner;

            // :::: ASSERT ::::
            var expectedWinner = cities[0].Owner;
            actualWinner.Should().Be(expectedWinner);
        }
示例#41
0
        public void MoveTo_ConquersOpponentCities(IUnit<Archer> unit, ICity city)
        {
            // :::: ARRANGE ::::
            var stubCities = StubWorld.Cities(new[] { city });
            var cityConquestUnit = new CityConquest<Archer>(unit, stubCities);

            // :::: ACT ::::
            var destination = city.Location;
            cityConquestUnit.MoveTo(destination);

            // :::: ASSERT ::::
            city.Owner.Should().Be(unit.Owner);
        }
示例#42
0
        private void ProcessSuccessfulAttack(ICity defender, ICity attacker)
        {
            defender.RemoveUnits();
            var previousController = defender.ControllingHouse.Name;

            defender.ControllingHouse.RemoveCityFromHouse(defender.Name);
            attacker.ControllingHouse.AddCityToHouse(defender);

            this.Engine.Render(
                "House {0} conquered {1} from House {2}",
                attacker.ControllingHouse.Name,
                defender.Name,
                previousController);
        }
示例#43
0
文件: Link.cs 项目: nlehtola/ict
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name">Name of the route</param>
        /// <param name="startCity">Start city</param>
        /// <param name="finalCity">Final city</param>
        /// <param name="distance">Distance</param>
        public Link(string name, ICity startCity, ICity finalCity, int distance)
        {
            // Precondition
            Contract.Requires(!string.IsNullOrEmpty(name), "Link name is valid");
            Contract.Requires(startCity != null, "Start city is valid");
            Contract.Requires(finalCity != null, "Final city is valid");
            Contract.Requires(distance > 0, "Distance is valid");

            // Initialize instance variables
            Name = name;
            StartCity = startCity;
            FinalCity = finalCity;
            Distance = distance;
        }
        public void TheCostOfTheUnit_IsDeductedFromTheProductionTreasury(ICity<City> city, int rounds)
        {
            // :::: ARRANGE ::::
            var stubUnits = StubWorld.NoUnits;
            var stubNotifier = A.Fake<INotifyBeginningNextRound>();
            var accumulatingCity = new ProductionAccumulation<City>(city, stubUnits, stubNotifier);

            // :::: ACT ::::
            rounds.Times(() => stubNotifier.BeginningNextRound += Raise.With(DummyEventArgs));

            // :::: ASSERT ::::
            var expectedTreasury = rounds * city.GeneratedProduction - city.ProductionProject.Cost;
            accumulatingCity.ProductionTreasury.Should().Be(expectedTreasury);
        }
示例#45
0
        public void AddCity(ICity city)
        {
            if (city == null)
            {
                throw new ArgumentNullException("city");
            }

            if (this.Cities.Any(c => c.Name == city.Name))
            {
                throw new DuplicateCityException(string.Format(DuplicateCityErrorMessage, city.Name));
            }

            this.Cities.Add(city);
        }
示例#46
0
        public void PerformAction_DoesNotBuildACity_BecauseTheTileIsNotVacant(ICity<City> city, IUnit<Settler> unit)
        {
            // :::: ARRANGE ::::
            var stubCities = StubWorld.Cities(new[] { city });
            var stubUnits = StubWorld.Units(new[] { unit });
            var stubCityFactory = StubFactories.SimpleCityFactory;
            var cityBuildingUnit = new CityBuildingAction<Settler>(unit, stubUnits, stubCities, stubCityFactory);

            // :::: ACT ::::
            cityBuildingUnit.PerformAction();

            // :::: ASSERT ::::
            var existingCity = stubCities.Single();
            existingCity.Should().BeSameAs(city);
        }
示例#47
0
        private static bool VerifyDestinationHousingSpaces(ICity destinationCity, ICity startingCity)
        {
            bool infantryCanMove = destinationCity.AvailableUnitCapacity(UnitType.Infantry)
                                   >= startingCity.AvailableMilitaryUnits.Where(u => u.Type == UnitType.Infantry).Sum(u => u.HousingSpacesRequired);

            bool cavalryCanMove = destinationCity.AvailableUnitCapacity(UnitType.Cavalry)
                                  >= startingCity.AvailableMilitaryUnits.Where(u => u.Type == UnitType.Cavalry).Sum(u => u.HousingSpacesRequired);

            bool airforceCanMove = destinationCity.AvailableUnitCapacity(UnitType.AirForce)
                                   >= startingCity.AvailableMilitaryUnits.Where(u => u.Type == UnitType.AirForce).Sum(u => u.HousingSpacesRequired);

            bool canArmyMove = infantryCanMove && cavalryCanMove && airforceCanMove;

            return canArmyMove;
        }
        public void Execute(ICity city, IList<AlienInvader> invaders, StringBuilder outputText)
        {
            _outputText = outputText;

            if (city != City)
            {
                LogAction(string.Format("Unable to fire - this asset is in {0}, but the enemy is in {1}!", City.Name, city.Name));
                return;
            }

            if (_turnsUntilLoaded > 0)
            {
                LogAction("Unable to fire - not loaded");
                return;
            }

            DoExecute(invaders);
        }
示例#49
0
        private void AddNeighborInfo(string[] commandParams, ICity neighbor, int i, ICity city)
        {
            if (neighbor == null)
            {
                throw new ArgumentNullException(nameof(neighbor), "Specified neighbor does not exist");
            }

            double distance = double.Parse(commandParams[i + 1]);

            if (distance < 0)
            {
                throw new ArgumentOutOfRangeException(
                    nameof(distance),
                    "The distance between cities cannot be negative");
            }

            this.Engine.Continent.CityNeighborsAndDistances[city].Add(neighbor, distance);
            this.Engine.Continent.CityNeighborsAndDistances[neighbor].Add(city, distance);
        }
示例#50
0
        private void ProcessFailedAttack(ICity defender, ICity attacker)
        {
            this.Engine.Render(
                "House {0} defended {1} from House {2}",
                defender.ControllingHouse.Name,
                defender.Name,
                attacker.ControllingHouse.Name);

            var counterAttackStrength = defender.AvailableMilitaryUnits.Sum(u => u.Damage);
            var attackerDefence = attacker.AvailableMilitaryUnits.Sum(u => u.Armor);

            if (counterAttackStrength > attackerDefence)
            {
                attacker.RemoveUnits();

                this.Engine.Render(
                    "House {0} lost all attacking forces dispatched from {1}",
                    attacker.ControllingHouse.Name,
                    attacker.Name);
            }
        }
示例#51
0
        public void PerformAction_DoesNotRemoveTheCityBuildingUnit_BecauseTheTileIsNotVacant(ICity city,
                                                                                             IUnit<Settler> unit,
                                                                                             IUnit[] otherUnits)
        {
            // :::: ARRANGE ::::
            var stubCities = StubWorld.Cities(new[] { city });
            var stubUnits = StubWorld.Units(new[] { unit }.Concat(otherUnits));
            var stubCityFactory = StubFactories.SimpleCityFactory;
            var cityBuildingUnit = new CityBuildingAction<Settler>(unit, stubUnits, stubCities, stubCityFactory);

            // :::: ACT ::::
            cityBuildingUnit.PerformAction();

            // :::: ASSERT ::::
            stubUnits.Should().Contain(unit).And.Contain(otherUnits);
        }
示例#52
0
 public LocationManager(IUnitOfWork uow)
 {
     this.countryrepo = uow.GetCountryRepository();
        this.staterepo = uow.GetStateRepository();
        this.cityrepo = uow.GetCityRepository();
 }
 public Peashooter500Blaster(ICity city)
     : base(city)
 {
 }
示例#54
0
 /// <summary>
 /// Removes the city.
 /// </summary>
 /// <param name="city">The city.</param>
 public void RemoveCity(ICity city)
 {
     cities.Remove(city);
 }
        public void Units_DoNotSpawnOnTheCityTile(ICity<City> city, IUnit existingUnit)
        {
            // :::: ARRANGE ::::
            var stubUnits = StubWorld.Units(new[] { existingUnit });
            var stubNotifier = A.Fake<INotifyBeginningNextRound>();
            var accumulatingCity = new ProductionAccumulation<City>(city, stubUnits, stubNotifier);

            // :::: ACT ::::
            stubNotifier.BeginningNextRound += Raise.With(DummyEventArgs);

            // :::: ASSERT ::::
            stubUnits.Should().HaveCount(1);
        }
示例#56
0
        public void CityAt_ReturnsTheCityOnTheTile(ICity city)
        {
            // :::: ARRANGE ::::
            var stubCityLayer = StubWorld.CityLayer(new[] { city });
            var game = new ExtenCivGame(stubCityLayer, DummyTerrainLayer, DummyUnitLayer,
                                        DummyTurnTaking, DummyWorldAge, DummyWinnerStrategy,
                                        DummyProjects);

            // :::: ACT ::::
            var location = city.Location;
            var actualCityViewModel = game.CityAt(location);

            // :::: ASSERT ::::
            actualCityViewModel.Owner.Should().Be(city.Owner);
            actualCityViewModel.Population.Should().Be(city.Population);
        }
示例#57
0
 public virtual void produceUnits(ICity city, IUnit unit)
 {
     throw new System.NotImplementedException();
 }
        public void ProductionCost_IsNotDeductedFromTheProductionTreasury(ICity<City> city, IUnit existingUnit)
        {
            // :::: ARRANGE ::::
            var stubUnits = StubWorld.Units(new[] { existingUnit });
            var stubNotifier = A.Fake<INotifyBeginningNextRound>();
            var accumulatingCity = new ProductionAccumulation<City>(city, stubUnits, stubNotifier);

            // :::: ACT ::::
            stubNotifier.BeginningNextRound += Raise.With(DummyEventArgs);

            // :::: ASSERT ::::
            accumulatingCity.ProductionTreasury.Should().BeGreaterOrEqualTo(accumulatingCity.ProductionProject.Cost);
        }
示例#59
0
 /// <summary>
 /// Adds the city.
 /// </summary>
 /// <param name="city">The city.</param>
 public void AddCity(ICity city)
 {
     cities.Add(city);
 }
        public void TheUnit_IsPlacedOnTheCityTile_AndBelongsToTheCityOwner(ICity<City> city, Type expectedType)
        {
            // :::: ARRANGE ::::
            var stubUnits = StubWorld.NoUnits;
            var stubNotifier = A.Fake<INotifyBeginningNextRound>();
            var accumulatingCity = new ProductionAccumulation<City>(city, stubUnits, stubNotifier);

            // :::: ACT ::::
            stubNotifier.BeginningNextRound += Raise.With(DummyEventArgs);

            // :::: ASSERT ::::
            var newlyProducedUnit = stubUnits.Single();

            newlyProducedUnit.Should().BeOfType(expectedType);
            newlyProducedUnit.Owner.Should().Be(accumulatingCity.Owner);
            newlyProducedUnit.Location.Should().Be(accumulatingCity.Location);
        }