示例#1
0
 public SoldiersIterator(Army army)
 {
   _army = army;
   _heroIsIterated = false;
   _currentGroup = 0;
   _currentGroupSoldier = 0;
 }
示例#2
0
    public SupplyNetwork(Army army, LevelV0 level, GamePlayState gamePlayState)
    {
        this.gamePlayState = gamePlayState;
        NetworkNodes = new SortedDictionary<int, SupplyNode>();
        NetworkConnections = new Dictionary<int, List<int>>();

        // add nodes for all the entry points in our level.
        // caution is needed when changing, since we are calling a static method
        // that does a lot of writing to various locations.  If this constructor
        // is ever called twice in one succession, disaster might arise.
        level.AddBuildingEntryPointsToNetwork(this);

        int startingPointId = level.Buildings.Single(building => building.isStartingPosition == true).nodeIdsForEntryPoints.First();
        this.NetworkNodes[startingPointId].SquadsInNode = army.Squads;

        // instead of adding new functions to 'initialize' the units in there initial starting building,
        // we'll reuse the Event Queue, adding 'unit arrived' events.
        army.Squads.ForEach( squad =>
            {
                UnityEngine.Object unitResource = Resources.Load(@"Unit");
                GameObject unitTest = UnityEngine.Object.Instantiate( unitResource, Vector3.zero, Quaternion.identity) as GameObject;
                Unit unit = unitTest.GetComponent(typeof(Unit)) as Unit;
                unit.InitializeOnGameSetup(startingPointId, squad.id,this.gamePlayState);
                unit.gameObject.SetActive(false);
                GameObject.Destroy(unitTest);
                GameObject.Destroy(unit);
            });
    }
示例#3
0
 public static List<Country> ArmiesReturnHome(List<Country> countries)
 {
     using (var context = new ApplicationDbContext())
     {
         foreach (var c in countries)
         {
             foreach (var a in c.Assaults)
             {
                 foreach (var f in a.Forces)
                 {
                     if (c.StandingForce.FirstOrDefault(m => m.Type.Id == f.Type.Id) != null)
                     {
                         c.StandingForce.First(m => m.Type.Id == f.Type.Id).Size += f.Size;
                     }
                     else
                     {
                         Army army = new Army();
                         army.Size = f.Size;
                         army.Type = f.Type;
                         c.StandingForce.Add(army);
                     }
                 }
                 a.Forces.Clear();
             }
             c.Assaults.Clear();
         }
         return countries;
     }
 }
 void Start()
 {
     pathfind = GetComponent<AStar2D>();
     humanSpawnPoint = GameObject.Find ("HumanSpawnPoint");
     armyScript = humanSpawnPoint.GetComponent<HumanSpawnPoint> ().monsterCore.GetComponent<MonsterCore> ().armyScript;
     nearbyPawns = new List<GameObject> ();
     InvokeRepeating("healNearby", 0, 1);
 }
示例#5
0
文件: Army.cs 项目: LeSphax/Famine
    /**
     * Each army inflict his damages on the other, the attackers hit first
     * Return -1 if the defenders lost
     * Return 1 if the attackers lost
     * Return 0 if the battle isn't over yet
     **/
    public static int Fight(Army defenders, Army attackers)
    {
        if (!defenders.TakeDamage(attackers.InflictDamages()))
        {
            return -1;
        }

        if (!attackers.TakeDamage(defenders.InflictDamages()))
        {
            return 1;
        }
        return 0;
    }
示例#6
0
 void FixedUpdate()
 {
     if (labelEnnemies == IDLE) { }
     else if (labelEnnemies == COMING)
     {
         UpdateTimer();
         if (timer == 0)
         {
             timer = TIMER_START;
             labelEnnemies = FIGHTING;
             defendersArmy = new Army(jobs, jobs.GetNumberOf(Data.SOLDIERS), jobs.GetNumberOf(Data.RECRUITS));
             InvokeRepeating("Fight", 0, 1);
         }
     }
 }
        public static XmlElement army(XmlDocument doc, Army a, String org)
        {
            XmlElement e = doc.CreateElement("Army");

            e.SetAttribute("money", a.Money.ToString());

            e.SetAttribute("org", org);
            e.AppendChild(standbyChar(doc, a.Standby));

            foreach (Unit u in a.Units)
                e.AppendChild(unit(doc, u));

            e.AppendChild(inventory(doc, a.Inventory));

            return e;
        }
示例#8
0
 public GamePlayer(string playerID, Army.ArmyTypeEnum armyType)
 {
     PlayerID = playerID;
     switch (armyType)
     {
         case Army.ArmyTypeEnum.Undead:
             Factory = new UndeadUnitFactory();
             break;
         case Army.ArmyTypeEnum.Alliance:
             Factory = new AllianceUnitFactory();
             break;
         case Army.ArmyTypeEnum.Beast:
             Factory = new BeastUnitFactory();
             break;
         default:
             break;
     }
 }
示例#9
0
        public GameState()
        {
            turn = 0;
            alignment = 0;
            att = 0;
            saved = false;

            mainArmy = new Army();
            mainChar = null;
            mainCharPos = new Point(-1, -1);
            gen = null;

            citymap = new Dictionary<String, CityMap>();

            citymap.Add("gen", Content.Instance.gen.CityMap.clone());

            foreach (String s in Tilemap.reflist("map\\gen.map"))
                citymap.Add(s, new Tilemap(s).CityMap.clone());
        }
示例#10
0
        public static Army army(XmlElement e)
        {
            Army a = new Army();

            a.Standby = standbyChar(e["StandbyChar"]);

            List<Unit> uls = new List<Unit>();

            foreach (XmlElement te in e.ChildNodes)
                if (te.Name == "Unit")
                    uls.Add(unit(te));

            a.Units = uls;

            a.Money = int.Parse(e.GetAttribute("money"));

            a.Inventory = inventory(e["Inventory"]);

            return a;
        }
示例#11
0
    public override void Execute(Army army, global::PlayerController playerController, out Ticket ticket, EventHandler <TicketRaisedEventArgs> ticketRaisedEventHandler, params object[] parameters)
    {
        ticket = null;
        IGameEntity gameEntity = null;

        ArmyAction.FailureFlags.Clear();
        for (int i = 0; i < parameters.Length; i++)
        {
            if (parameters[i] is IGameEntity)
            {
                gameEntity = (parameters[i] as IGameEntity);
                break;
            }
            if (parameters[i] is List <IGameEntity> )
            {
                List <IGameEntity> list = parameters[i] as List <IGameEntity>;
                bool flag = false;
                for (int j = 0; j < list.Count; j++)
                {
                    if (this.CanAttackGameEntity(army, list[j], ref flag, ref ArmyAction.FailureFlags))
                    {
                        gameEntity = list[j];
                        break;
                    }
                }
                break;
            }
        }
        if (gameEntity != null)
        {
            DepartmentOfForeignAffairs agency = army.Empire.GetAgency <DepartmentOfForeignAffairs>();
            Diagnostics.Assert(agency != null);
            if (agency.CanAttack(gameEntity) || army.IsPrivateers)
            {
                OrderAttack orderAttack = new OrderAttack(army.Empire.Index, army.GUID, gameEntity.GUID);
                orderAttack.NumberOfActionPointsToSpend = base.GetCostInActionPoints();
                Diagnostics.Assert(playerController != null);
                playerController.PostOrder(orderAttack, out ticket, ticketRaisedEventHandler);
            }
        }
    }
    public int ListNearbyPointsOfInterest(Army army)
    {
        if (army == null)
        {
            throw new ArgumentNullException("army");
        }
        this.PointsOfInterest.Clear();
        IGameService service = Services.GetService <IGameService>();

        if (service == null)
        {
            return(0);
        }
        global::Game game = service.Game as global::Game;

        if (game == null)
        {
            return(0);
        }
        IPathfindingService       service2 = service.Game.Services.GetService <IPathfindingService>();
        IWorldPositionningService service3 = service.Game.Services.GetService <IWorldPositionningService>();

        Diagnostics.Assert(service3 != null);
        PointOfInterest pointOfInterest = service3.GetPointOfInterest(army.WorldPosition);

        if (pointOfInterest != null)
        {
            this.AddPOIifPossible(pointOfInterest, service2, army);
        }
        List <WorldPosition> neighbours = army.WorldPosition.GetNeighbours(game.World.WorldParameters);

        for (int i = 0; i < neighbours.Count; i++)
        {
            PointOfInterest pointOfInterest2 = service3.GetPointOfInterest(neighbours[i]);
            if (pointOfInterest2 != null)
            {
                this.AddPOIifPossible(pointOfInterest2, service2, army);
            }
        }
        return(this.PointsOfInterest.Count);
    }
示例#13
0
    public static void Main(string[] args)
    {
        int[] soldiers = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
        int   n        = int.Parse(Console.ReadLine());
        Army  army;

        try
        {
            army = new Army(soldiers, n);
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e.Message);
            return;
        }

        foreach (int number in army)
        {
            Console.WriteLine(number);
        }
    }
    private void ComputeScoreWithDistance(IWorldPositionable target, Army army, ref float score)
    {
        float propertyValue  = army.GetPropertyValue(SimulationProperties.MaximumMovement);
        float propertyValue2 = army.GetPropertyValue(SimulationProperties.Movement);
        float num            = (float)this.worldPositionningService.GetDistance(army.WorldPosition, target.WorldPosition);
        float num2           = num / propertyValue;

        if (num > propertyValue2)
        {
            num2 += 1f;
        }
        if (num2 > this.MaximumTurnDistance)
        {
            score = -1f;
            return;
        }
        float num3 = 1f;
        float num4 = 1f + num3 * num2;

        score /= num4;
    }
示例#15
0
        public CreateSoldierEvent GetCreateSoldierEvent(Guid gameId, Army army, string troopType, string ownerUserId, bool immediately = false)
        {
            var    snap           = _domain.GetGameSnapshot(gameId);
            var    game           = snap?.Payload as GameAggregate;
            double productionTime = 0;

            if (!immediately)
            {
                productionTime = _gameSettings.ProductionTime;
                if (game != null)
                {
                    productionTime = productionTime * GameSpeedHelper.GetSpeedValue(game.Speed);
                }
            }
            var @event = new CreateSoldierEvent(army,
                                                troopType, DateTime.UtcNow,
                                                TimeSpan.FromMinutes(productionTime),
                                                ownerUserId);

            return(@event);
        }
示例#16
0
    public float GetCooldownDurationReduction(Army army)
    {
        float num = 0f;
        SimulationProperty property = army.SimulationObject.GetProperty(SimulationProperties.CooldownReduction);

        if (property == null)
        {
            foreach (Unit unit in army.Units)
            {
                property = unit.SimulationObject.GetProperty(SimulationProperties.CooldownReduction);
                if (property == null)
                {
                    return(0f);
                }
                num = Math.Min(num, property.Value);
            }
            return(num);
        }
        num = Math.Min(num, property.Value);
        return(num);
    }
示例#17
0
        public Army GenerateTeamB()
        {
            Army         team     = new Army("US");
            List <IUnit> allUnits = new List <IUnit>
            {
                new Crusader(300, 30, "Jeremy", team),
                new Assassin(150, 50, "Kevin", team),
                new Cerberus(70, 25, "Henry", team),

                /* new Crusader(300, 30, "Lex", team),
                 * new Assassin(150, 50, "Danny", team),
                 * new Cerberus (70, 25, "Juliya", team),*/
                new WizardWarrior(120, 25, "David", team, 100, 35, 150),
                new WizardHealer(150, 0, "Gordon", team, 100, 35),
                new Elf(110, 45, "Jenny", team),
                new Tree("Kile", team, 0, 20),
            };

            team.AllUnits = allUnits;
            return(team);
        }
示例#18
0
        public Army GenerateTeamA()
        {
            Army         team     = new Army("GB");
            List <IUnit> allUnits = new List <IUnit>
            {
                new Crusader(300, 30, "Bernard", team),
                new Assassin(150, 50, "Menny", team),
                new Cerberus(70, 25, "Robert", team),

                /*new Crusader(300, 30, "Andrew", team),
                 * new Assassin(150, 50, "Pall", team),
                 * new Cerberus (70, 25, "Lili", team),*/
                new WizardWarrior(120, 25, "Richard", team, 100, 35, 150),
                new WizardHealer(150, 0, "Gektor", team, 100, 35),
                new Elf(110, 45, "Miriam", team),
                new Tree("William", team, 0, 15),
            };

            team.AllUnits = allUnits;
            return(team);
        }
示例#19
0
        public async Task <IActionResult> Create([Bind("Id,Name")] Army army)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    await _armyService.Create(army);

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (Exception)
            {
                throw;
            }

            var castleList = _castleService.GetAll().OrderBy(x => x.Name);

            ViewData["CastleId"] = new SelectList(castleList, "Id", "Id");
            return(View(army));
        }
示例#20
0
        public void Tick_MakesArmyHungryWhenOwnerHasNotEnoughResources()
        {
            // arrange
            var army = new Army
            {
                Owner = new Player {
                    Resources = new DefaultResources(3)
                },
                Consumption       = new DefaultResources(4),
                ConsumptionPeriod = TimeSpan.FromDays(1),
                Constants         = new GameConstants {
                    ZeroResources = new DefaultResources()
                },
            };

            // act
            army.Tick(TimeSpan.FromDays(1));

            // assert
            Assert.IsTrue(army.IsHungry);
        }
示例#21
0
        public void Construction_GivenSoldiersWhenEnrollSoldiersTheSoldiersGetAnId()
        {
            var soldiers = new[]
            {
                new Soldier("soldier1", Weapon.BareFist),
                new Soldier("soldier2", Weapon.BareFist)
            };

            hqMock.Setup(x => x.ReportEnlistment(soldiers[0].Name)).Returns(1);
            hqMock.Setup(x => x.ReportEnlistment(soldiers[1].Name)).Returns(2);

            var army = new Army(hqMock.Object);

            foreach (var soldier in soldiers)
            {
                army.Enroll(soldier);
            }

            army.Soldiers[0].Id.Should().Be(1);
            army.Soldiers[1].Id.Should().Be(2);
        }
示例#22
0
        public int?FindRandomUnitInRange(Army army, int sourceIndex, int range, Func <Unit, bool> selector)
        {
            int start = Math.Max(0, sourceIndex - range * 3),
                end   = Math.Min(army.Count - 1, sourceIndex + range * 3);

            if (start > end)
            {
                return(null);
            }

            var possible = (from ind in Enumerable.Range(start, end - start + 1)
                            let diff = Math.Abs(ind - sourceIndex)
                                       where diff % 3 + diff / 3 <= range && selector(army[ind])
                                       select ind).ToList();

            if (possible.Count == 0)
            {
                return(null);
            }
            return(possible[Random.Next(possible.Count)]);
        }
示例#23
0
        public int GetArmyPoints(Army army)
        {
            var armyPoints    = 0;
            var squadUnits    = army.Squads.SelectMany(s => s.SquadUnits).ToList();
            var unitGroupList = squadUnits.GroupBy(su => su.Unit.Type).ToList();

            foreach (var unitGroup in unitGroupList)
            {
                var squadUnit = unitGroup.FirstOrDefault();
                if (squadUnit.Unit.Type == UnitTypes.Shark)
                {
                    armyPoints += unitGroup.Sum(ug => ug.NumberOfUnits) * SHARK_POINTS;
                }
                else
                {
                    armyPoints += unitGroup.Sum(ug => ug.NumberOfUnits) * UNIT_POINTS;
                }
            }

            return(armyPoints);
        }
示例#24
0
    private void saveArmy()
    {
        //相同直接关闭窗口不保存
        if (ArmyManager.Instance.compareArmy(savingArmy, oldArmy))
        {
            saveArmyCallBack();
            return;
        }
        List <string> oldCards  = ArmyManager.Instance.getAllArmyCardsExceptMining(); //改变队伍前的卡片上阵情况
        List <string> oldBeasts = ArmyManager.Instance.getFightBeasts();              //改变队伍前的召唤兽情况

        Army[] arr = new Army[1] {
            savingArmy
        };
        ArmyUpdateFPort port = FPortManager.Instance.getFPort("ArmyUpdateFPort") as ArmyUpdateFPort;

        port.access(arr, () => {
            saveArmyCallBack();
            ArmyManager.Instance.updateBackChangeState(oldCards, oldBeasts, 1);
        });
    }
示例#25
0
 public Facility(int pBuildingId,
                 string pName,
                 string pDisplayStringActivated,
                 string pDisplayStringInactivated,
                 Resources pPrice,
                 Resources pProduct,
                 Resources pCost,
                 Army pMaterial,
                 Army pRollouted,
                 LambdaFuncInt onClickEvent) : base(pBuildingId,
                                                    pName,
                                                    pDisplayStringActivated,
                                                    pDisplayStringInactivated,
                                                    pPrice,
                                                    pProduct,
                                                    pCost,
                                                    pMaterial,
                                                    pRollouted)
 {
     this.onClickEvent = onClickEvent;
 }
    public void Test()
    {
        var army              = new Army();
        var af                = new AmmunitionFactory();
        var wareHouse         = new WareHouse(af);
        var soldierFactory    = new SoldierFactory();
        var missionFactory    = new MissionFactory();
        var missionController = new MissionController(army, wareHouse);
        var writer            = new ConsoleWriter();
        var gamecontroller    = new GameController(army, wareHouse, missionController, soldierFactory, missionFactory, writer);

        var    mission = new Easy(1);
        string result  = string.Empty;

        for (int i = 0; i < 4; i++)
        {
            result = missionController.PerformMission(mission).Trim();
        }

        Assert.IsTrue(result.StartsWith("Mission declined - Suppression of civil rebellion"));
    }
        /// <summary>
        /// Checks whether a character can see an army
        /// </summary>
        /// <param name="pc">Head of family attempting to view army</param>
        /// <param name="o">Army</param>
        /// <returns>Whetehr or not army can be seen</returns>
        public static bool canSeeArmy(PlayerCharacter pc, object o)
        {
            // Can see army if owns army or a character can see fief army is in
            Army army = o as Army;

            if (OwnsArmy(pc, o))
            {
                return(true);
            }
            else
            {
                if (canSeeFief(pc, army.GetLocation()))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
示例#28
0
    public override void CreateArmy()
    {
        GameObject a = Instantiate(Resources.Load("GameObjects/Army", typeof(Object))) as GameObject;

        a.name = "New Army " + Random.Range(1, 1000);
        a.transform.position = armedForcePosition;

        Army ar = a.GetComponent <Army> ();

        ar.SetInitialData(a.name, this, GlobalData.currentPlayer);
        ar.GetComponent <Renderer>().materials [0].color = GlobalData.currentPlayer.playerColor;

        ar.units.Add(new Unit("unit1", "", 1, 200, 30, 40));
        ar.units.Add(new Unit("unit2", "", 2, 500, 60, 80));
        ar.units.Add(new Unit("unit3", "", 3, 1000, 120, 260));

        GameObject armies = GameObject.Find("Armies");

        armies.GetComponent <Armies> ().AddArmy(a);
        armedForce = ar;
    }
示例#29
0
        /// <summary>
        /// Initiates a battle between two Armies.
        /// </summary>
        /// <param name="attacker">The Army that initiated the attack.</param>
        /// <param name="defender">The Army that is being attacked.</param>
        private void InitBattle(Army attacker, Army defender, bool split = false)
        {
            // Save the square on which the battle is occuring (the defender's square)
            battlePosition = defender.PositionInGrid;

            // Remove BOTH armies from the grid; one will be replaced by what is remaining, the other will be annihilated
            Tile attackingTile = this[attacker.PositionInGrid] as Tile;
            Tile defendingTile = this[defender.PositionInGrid] as Tile;

            if (!split)
            {
                (this[attacker.PositionInGrid] as Tile).SetUnit(null);
            }
            (this[defender.PositionInGrid] as Tile).SetUnit(null);

            // Unselect the current tile as we move to another state
            SelectTile(InvalidTile);

            // Tell the battle state that we want to initiate a battle
            GameStateManager.OnInitiateBattle(attacker, defender, attackingTile, defendingTile);
        }
示例#30
0
    private void InitBattle()
    {
        enemyArmiesList = new List <Army>(3);
        enemyArmiesList.Add(new Army("敌人前锋", 50, 50, 10000));
        enemyArmiesList.Add(new Army("敌人中军", 50, 50, 10000));
        enemyArmiesList.Add(new Army("敌人大营", 50, 50, 10000));


        ourArmiesList = new List <Army>();

        Army me = new Army("主角", 50, 50, 10000);

        me.AddSkill(ChooseSkill(me, "火烧连营"));//给部队增加一个技能

        me.color = GameConst.Color.greenColor;
        enemyArmiesList[0].color = GameConst.Color.redColor;
        enemyArmiesList[1].color = GameConst.Color.redColor;
        enemyArmiesList[2].color = GameConst.Color.redColor;

        ourArmiesList.Add(me);
    }
示例#31
0
    public static void Main()
    {
        IReader            reader            = new ConsoleReader();
        IWriter            writer            = new ConsoleWriter();
        ISoldierFactory    soldierFactory    = new SoldierFactory();
        IAmmunitionFactory ammunitionFactory = new AmmunitionFactory();
        IMissionFactory    missionFactory    = new MissionFactory();
        IArmy              army              = new Army();
        IWareHouse         wareHouse         = new WareHouse(ammunitionFactory);
        IMissionController missionController = new MissionController(army, wareHouse);
        IGameController    gameController    = new GameController(
            army,
            writer,
            wareHouse,
            soldierFactory,
            missionFactory,
            missionController);
        IEngine engine = new Engine(reader, writer, gameController);

        engine.Run();
    }
示例#32
0
        public override void Process(Entity entity)
        {
            ArmyAi armyAi = entity.GetComponent <ArmyAi>();
            Army   army   = entity.GetComponent <Army>();

            _eventBus.Register(armyAi.DefaultDecisionThinker);
            armyAi.DefaultDecisionThinker.Think(entity, _eventBus);

            float lastMovementPoints = 0; //protection against standing in place

            while (army.MovementPoints > 0 && army.MovementPoints != lastMovementPoints)
            {
                lastMovementPoints = army.MovementPoints;
                IDecisionThinker decisionThinker = armyAi.DecisionThinkers[armyAi.ArmyStateMachine.State];
                decisionThinker.Think(entity, _eventBus);
            }


            _eventBus.Unregister(armyAi.DefaultDecisionThinker);
            // Debug.WriteLine("Update AI");
        }
示例#33
0
 public override State CheckCondition(QuestBehaviour questBehaviour, GameEvent gameEvent, params object[] parameters)
 {
     this.Initialize(questBehaviour);
     this.RefreshVar(questBehaviour);
     if (this.CityGUID != GameEntityGUID.Zero)
     {
         IGameService service = Services.GetService <IGameService>();
         Diagnostics.Assert(service != null);
         if (service.Game as global::Game == null)
         {
             return(State.Failure);
         }
         IWorldPositionningService service2 = service.Game.Services.GetService <IWorldPositionningService>();
         global::Empire            empire;
         if (gameEvent != null)
         {
             empire = (gameEvent.Empire as global::Empire);
         }
         else
         {
             empire = questBehaviour.Initiator;
         }
         Diagnostics.Assert(empire.GetAgency <DepartmentOfForeignAffairs>() != null);
         Army army = empire.GetAgency <DepartmentOfDefense>().GetArmy(this.ArmyGuid);
         if (army == null)
         {
             return(State.Failure);
         }
         District district = service2.GetDistrict(army.WorldPosition);
         if (district == null)
         {
             return(State.Failure);
         }
         if (district.City.GUID == this.CityGUID)
         {
             return(State.Success);
         }
     }
     return(State.Failure);
 }
示例#34
0
        public bool AddDataToArmy(SaveLua.Army ArmyData)
        {
            for (int c = 0; c < Data.Configurations.Length; c++)
            {
                for (int t = 0; t < Data.Configurations[c].Teams.Length; t++)
                {
                    for (int a = 0; a < Data.Configurations[c].Teams[t].Armys.Count; a++)
                    {
                        if (Data.Configurations[c].Teams[t].Armys[a].Name == ArmyData.Name)
                        {
                            Data.Configurations[c].Teams[t].Armys[a].Data = ArmyData;
                            return(true);
                        }
                    }
                }

                for (int a = 0; a < Data.Configurations[c].ExtraArmys.Count; a++)
                {
                    if (Data.Configurations[c].ExtraArmys[a].Name == ArmyData.Name)
                    {
                        Data.Configurations[c].ExtraArmys[a].Data = ArmyData;
                        return(true);
                    }
                }
            }

            //No army found - Force new army
            if (Data.Configurations.Length > 0 && Data.Configurations[0].Teams.Length > 0)
            {
                Army NewArmy = new Army();
                NewArmy.Name   = ArmyData.Name;
                NewArmy.NoRush = new NoRusnOffset();
                NewArmy.Data   = ArmyData;

                Data.Configurations[0].Teams[0].Armys.Add(NewArmy);
                return(true);
            }

            return(false);            // Unable to add new army
        }
示例#35
0
        public void Battle_GetStacks()
        {
            Unit angel    = new UnitAngel();
            Unit skeleton = new UnitSkeleton();

            UnitsStack stack1 = new UnitsStack(angel, 10);
            UnitsStack stack2 = new UnitsStack(skeleton, 42);
            UnitsStack stack3 = new UnitsStack(angel, 2);

            List <UnitsStack> stacks1 = new List <UnitsStack> {
                stack1, stack2
            };
            List <UnitsStack> stacks2 = new List <UnitsStack> {
                stack3
            };

            Army army1 = new Army(stacks1);
            Army army2 = new Army(stacks2);

            Battle battle = new Battle(army1, army2);

            battle.Start();

            IList <BattleUnitsStack> stacks = battle.GetStacks();

            Assert.AreEqual(stack1, stacks[0].GetBaseStack());
            Assert.AreEqual(stack2, stacks[1].GetBaseStack());
            Assert.AreEqual(stack3, stacks[2].GetBaseStack());

            stacks[0].SetHitPoints(0);

            IList <BattleUnitsStack> aliveStacks = battle.GetAliveStacks();
            IList <BattleUnitsStack> deadStacks  = battle.GetDeadStacks();

            Assert.AreEqual(2, aliveStacks.Count);
            Assert.AreEqual(stacks[1], aliveStacks[0]);
            Assert.AreEqual(stacks[2], aliveStacks[1]);
            Assert.AreEqual(1, deadStacks.Count);
            Assert.AreEqual(stacks[0], deadStacks[0]);
        }
示例#36
0
        protected void TrySpawnUnit(string soldierType)
        {
            // Check if the player can afford this soldier
            int cost = SoldierRegistry.GetSoldierCost(soldierType);

            if (!owner.CanAfford(cost) || owner.Population <= 0)
            {
                return;
            }

            // Set this soldier in the world if possible
            Tile currentTile = ((GameWorld as Grid)[positionInGrid] as Tile);

            if (!currentTile.Occupied)
            {
                // Nothing here, just place it in this square
                Army army = new Army(positionInGrid.X, positionInGrid.Y, owner);
                army.AddSoldier(SoldierRegistry.GetSoldier(soldierType, owner));
                currentTile.SetUnit(army);
            }
            else if (currentTile.Unit.Owner == owner && currentTile.Unit is Army)
            {
                // Our own army is here, just place it in there :)
                Army a = currentTile.Unit as Army;
                if (a.GetTotalUnitCount() >= 20)
                {
                    return;
                }
                a.AddSoldier(SoldierRegistry.GetSoldier(soldierType, owner));
            }
            else
            {
                // We can't place it, just stop this whole function
                return;
            }

            // Buy the soldier, as we placed it.
            owner.Buy(cost);
            owner.CalculatePopulation();
        }
示例#37
0
        /// <summary>
        /// Test stub for spy character
        /// </summary>
        /// <param name="testClient"></param>
        /// <param name="charID"></param>
        /// <param name="targetID"></param>
        /// <param name="DoSpy"></param>

        public void SpyArmyTest(TestClient testClient, string charID, string targetID)
        {
            testClient.SpyOnArmy(charID, targetID);
            Task <ProtoMessage> responseTask = testClient.GetReply();

            responseTask.Wait();
            ProtoMessage response = responseTask.Result;

            if (string.IsNullOrWhiteSpace(charID) || string.IsNullOrWhiteSpace(targetID))
            {
                Assert.AreEqual(DisplayMessages.ErrorGenericMessageInvalid, response.ResponseType);
                return;
            }
            Character spy    = Globals_Game.getCharFromID(charID);
            Army      target = null;

            Globals_Game.armyMasterList.TryGetValue(targetID, out target);
            if (spy == null || target == null)
            {
                Assert.AreEqual(DisplayMessages.ErrorGenericCharacterUnidentified, response.ResponseType);
                return;
            }
            Client client = Globals_Server.Clients[testClient.playerID];

            if (spy.GetPlayerCharacter() != client.myPlayerCharacter)
            {
                Assert.AreEqual(DisplayMessages.ErrorGenericUnauthorised, response.ResponseType);
                return;
            }
            if (spy.location != target.GetLocation())
            {
                Assert.AreEqual(DisplayMessages.ErrorGenericNotInSameFief, response.ResponseType);
                return;
            }
            if (!(spy.days >= 10))
            {
                Assert.AreEqual(DisplayMessages.ErrorGenericNotEnoughDays, response.ResponseType);
                return;
            }
        }
示例#38
0
        /// <summary>
        /// <para>
        ///     Random-based Targeting Policy targets units randomly based on a uniform distribution.
        ///     It is the fastest targeting policy in exchange of maximizing rewards to destroy opposing
        ///     army. If the current unit can target the given random enemy unit, it will be the set target
        ///     regardless of health, damage/energy, worth, and distance. It also disregards that multiple
        ///     units could target the same unit. In the case that the current enemy unit cannot be targeted,
        ///     an offset is added until it reaches the same enemy unit, resulting to having no target at all.
        /// </para>
        /// <para>
        ///     This method only affects '<paramref name="focused_army"/>', which means that this is
        ///     the only one to have targets at the end of the policy.
        /// </para>
        /// </summary>
        /// <remarks>
        /// <para>
        ///     While it can be said it is the fastest, it can be slow as the other policy when the current
        ///     enemy unit cannot be targeted by the current unit. It's running time is probably O(n^2).
        /// </para>
        /// </remarks>
        /// <param name="focused_army"></param>
        /// <param name="opposed_army"></param>
        private void RandomBasedTargetPolicy(ref Army focused_army, Army opposed_army)
        {
            try
            {
                var random             = Services.ModelRepositoryService.ModelService.GetModelService().RandomEngine;
                var array_opposed_army = opposed_army.ToArray();
                for (var focused_enumerator = focused_army.GetEnumerator(); focused_enumerator.MoveNext();)
                {
                    int selected_enemy = random.Next(0, array_opposed_army.Length), offset = 0;

                    //Continue to increase the offset if the current selected enemy cannot be targeted
                    //Stop if we return back to the original enemy unit
                    for (bool started = true; true; offset++, started = false)
                    {
                        int offsetted_index = ((offset + selected_enemy) % array_opposed_army.Length);

                        //Check if offsetted index is the same as the original enemy unit
                        //and that this is the second time, not when it started
                        if (!started && (offsetted_index == selected_enemy))
                        {
                            break;
                        }

                        //Check if the current unit can target the given enemy unit
                        if (focused_enumerator.Current.CanTarget(array_opposed_army[offsetted_index]))
                        {
                            //Set the target since it can be targeted
                            focused_enumerator.Current.SetTarget(array_opposed_army[offsetted_index]);
                            break;
                        }
                    }
                }
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine($@"RandomBasedTargetPolicy() [{focused_army.ToString()}\n{opposed_army.ToString()}] -> {ex.Message}");
                System.Diagnostics.Debugger.Break();
                throw new Exception("");
            }
        }
 private bool CanToggleOverCreepingNode(Army army, CreepingNode creepingNode, ref List <StaticString> failureFlags)
 {
     if (army == null || creepingNode == null || creepingNode.Empire == army.Empire)
     {
         failureFlags.Add(ArmyAction.NoCanDoWhileHidden);
         return(false);
     }
     if (creepingNode.DismantlingArmy != null)
     {
         if (creepingNode.DismantlingArmy == army)
         {
             return(true);
         }
         failureFlags.Add(ArmyAction.NoCanDoWhileHidden);
         return(false);
     }
     else
     {
         IGameService service = Services.GetService <IGameService>();
         Diagnostics.Assert(service != null);
         IWorldPositionningService service2 = service.Game.Services.GetService <IWorldPositionningService>();
         Diagnostics.Assert(service2 != null);
         Army armyAtPosition = service2.GetArmyAtPosition(creepingNode.WorldPosition);
         if (creepingNode != null && creepingNode.DismantlingArmy == null && armyAtPosition != null && creepingNode.Empire.Index != army.Empire.Index)
         {
             failureFlags.Add(ArmyAction.NoCanDoWhileHidden);
             return(false);
         }
         if (creepingNode.Empire != army.Empire && army.Empire is MajorEmpire)
         {
             DiplomaticRelation diplomaticRelation = army.Empire.GetAgency <DepartmentOfForeignAffairs>().DiplomaticRelations[creepingNode.Empire.Index];
             if (diplomaticRelation != null && diplomaticRelation.State != null && (diplomaticRelation.State.Name == DiplomaticRelationState.Names.Alliance || diplomaticRelation.State.Name == DiplomaticRelationState.Names.Peace || diplomaticRelation.State.Name == DiplomaticRelationState.Names.Truce))
             {
                 failureFlags.Add(ArmyAction.NoCanDoWhileHidden);
                 return(false);
             }
         }
         return(true);
     }
 }
示例#40
0
    protected override State Execute(AIBehaviorTree aiBehaviorTree, params object[] parameters)
    {
        Army army;

        if (base.GetArmyUnlessLocked(aiBehaviorTree, "$Army", out army) > AIArmyMission.AIArmyMissionErrorCode.None)
        {
            return(State.Failure);
        }
        bool flag = false;

        foreach (AICommanderMission aicommanderMission in aiBehaviorTree.AICommander.Missions)
        {
            IGameEntity gameEntity = null;
            if (aicommanderMission.AIDataArmyGUID.IsValid && aicommanderMission.AIDataArmyGUID != army.GUID && this.gameEntityRepositoryService.TryGetValue(aicommanderMission.AIDataArmyGUID, out gameEntity) && gameEntity is Army)
            {
                Army army2 = gameEntity as Army;
                if (army2.GUID.IsValid && this.worldPositionningService.GetDistance(army.WorldPosition, army2.WorldPosition) > this.Range)
                {
                    flag = true;
                    break;
                }
            }
        }
        if (this.Inverted)
        {
            if (flag)
            {
                return(State.Success);
            }
            return(State.Failure);
        }
        else
        {
            if (!flag)
            {
                return(State.Success);
            }
            return(State.Failure);
        }
    }
示例#41
0
        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            var game = (FantasyWars) ScreenManager.Game;

            bindings.Add(new KeyBinding(inputEvents, Keys.Escape, this.HandlePause, KeyState.Down));

            if (_content == null)
                _content = new ContentManager(ScreenManager.Game.Services, "Content");

            _gameFont = _content.Load<SpriteFont>("gamefont");

            _map = new Map(this);
            _map.LoadContent(_content);

            army1 = new Army(this);
            army1.LoadContent(_content);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();

            base.LoadContent();
        }
示例#42
0
 public void ThenItShouldBeTurn(Army army)
 {
     ChessScenario.Game.CurrentTurn
            .Should()
            .Be(army);
 }
示例#43
0
        public void load(String path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            alignment = int.Parse(doc.DocumentElement.GetAttribute("ali"));
            turn = int.Parse(doc.DocumentElement.GetAttribute("turn"));
            att = int.Parse(doc.DocumentElement.GetAttribute("att"));

            /*foreach (XmlElement e in doc.DocumentElement.ChildNodes)
                if (e.Name=="Character" && e.GetAttribute("org") == "main")
                    mainChar = XmlTransaltor.xmlToChar(e);*/

            foreach (XmlElement e in doc.DocumentElement.ChildNodes)
                if (e.Name=="Army" && e.GetAttribute("org") == "main")
                    mainArmy = XmlTransaltor.army(e);

            //mainChar = mainArmy.MainCharUnit.Leader;

            mainCharPos = XmlTransaltor.pos(doc.DocumentElement["MainCharPos"]);

            gen = XmlTransaltor.fog(doc.DocumentElement["Fog"]);

            citymap.Clear();

            foreach (XmlElement e in doc.DocumentElement["CityMapList"].ChildNodes)
                citymap.Add(e.GetAttribute("region"), XmlTransaltor.citymap(e));

            foreach (XmlElement e in doc.DocumentElement["RecruitmentList"].ChildNodes)
                Content.Instance.recruitedLs.Add(e.GetAttribute("name"));

            Content.Instance.cleanRecruitLs();

            saved = true;
        }
示例#44
0
 private void AddHero(Selection selection, Army army)
 {
     var hero = selection.MapTo<Character>();
     army.Heroes.Add(hero);
 }
示例#45
0
 protected override Army NewArmy()
 {
     Heroes.Core.Army army = new Army();
     army.CopyFrom((Heroes.Core.Army)Heroes.Core.Setting._armies[(int)Heroes.Core.ArmyIdEnum.Monk]);
     return army;
 }
示例#46
0
 private void AddRare(Selection selection, Army army)
 {
     var unit = CreateUnit(selection);
     army.Rare.Add(unit);
 }
示例#47
0
 private void AddLord(Selection selection, Army army)
 {
     var lord = selection.MapTo<Character>();
     army.Lords.Add(lord);
 }
示例#48
0
    void Start()
    {
        constitution = level;
        agility = level;
        strength = level;

        for(int i = 0; i < level - 1; i++) {
            int skill = UnityEngine.Random.Range (1, 5);

            switch(skill) {
            case 1:
                constitution ++;
                break;
            case 2:
                agility ++;
                break;
            case 3:
                strength ++;
                break;
            }
        }

        health = 50.0f + constitution * 10;
        speed = 1.0f + agility * 0.33f;
        hitDamage = 4.0f + strength;

        pathfind = GetComponent<AStar2D>();
        if(pathfind == null) {
            Debug.Log ("Pathfind not found!");
        }

        grid = spawnpoint.GetComponent<HumanSpawnPoint>().grid;
        map = spawnpoint.GetComponent<HumanSpawnPoint>().map;
        resourcesScript = Camera.main.gameObject.GetComponent<ResourcesControl>();
        armyScript = spawnpoint.GetComponent<HumanSpawnPoint>().monsterCore.GetComponent<MonsterCore>().armyScript;
        pathfind.speed = speed;
        pathfind.seeker.StartPath(transform.position, spawnpoint.GetComponent<HumanSpawnPoint>().monsterCore.transform.position, pathfind.OnPathComplete);
    }
示例#49
0
 public override bool IsMoveable(Army.ArmyBase army)
 {
     return true;
 }
示例#50
0
        internal IEnumerable<Square> GetThretenedSquares(Army threatenedBy)
        {
            var pieces = from square in Squares
                         let piece = square.Piece
                         where piece != null && piece.Color == threatenedBy
                         select piece;

            var threatenedSquares = pieces
                .SelectMany(square => square.GetThreatenedSquares())
                .Distinct();

            return threatenedSquares;
        }
示例#51
0
 internal bool IsInCheck(Army color)
 {
     var otherColor = color == Army.White ? Army.Black : Army.White;
     return GetThretenedSquares(otherColor)
         .Contains(GetKingSquare(color));
 }
示例#52
0
 internal Square GetKingSquare(Army color)
 {
     return Squares.First(s => s.Piece is King && s.Piece.Color == color);
 }
示例#53
0
 void Start()
 {
     armyScript = Camera.main.gameObject.GetComponent<Army>();
 }
示例#54
0
        public override bool mouseClick(Territory target, uint Button)
        {
            Unit nu;
            Player me = Game.GetInstance().State.CurrentPlayer;

            if (target.MapTerritory.isLand)
            {
            if ((target.Owner != me) || (target.OriginalOwner != me.CountryID))
                return false;
            nu = new Army(me, target);
            } else {
            if (Game.GetInstance().GUI.Map.distanceFromClosestHomeTerritory(target, me) > 1)
                return false;
            if (!target.occupiable(me))
                return false;
            nu = new Navy(me, target);
            }

            /* Can't use Contains since hash values are different ... search stupidly */
            foreach(Unit u in unitsToBuild)
            {
            if (u.Name == nu.Name)
            {
                unitsToBuild.Remove(u);
                Game.GetInstance().GUI.writeToLog("Building " + nu.Name);
                Orig_BuildUnit cmd = new Orig_BuildUnit(nu, target, me);
                Game.GetInstance().State.Execute(cmd);
                break; // must break, because another iteration will fault
            }
            }

            displayUnitsLeftToBuild();
            return true;
        }
示例#55
0
    void Start()
    {
        state = Army.MinionState.Rallying;

        pathfind.seeker.StartPath(transform.position, messHall.transform.position, pathfind.OnPathComplete);

        humanSpawnPoint = GameObject.Find("HumanSpawnPoint");
        armyScript = humanSpawnPoint.GetComponent<HumanSpawnPoint>().monsterCore.GetComponent<MonsterCore>().armyScript;
        nearbyPawns = new List<GameObject>();
    }
示例#56
0
 private void AddSpecial(Selection selection, Army army)
 {
     var unit = CreateUnit(selection);
     army.Special.Add(unit);
 }
示例#57
0
 public void RaidLaunched(int numberAttackers)
 {
     display.SetActive(true);
     labelEnnemies = COMING;
     timer = TIMER_START;
     enemiesData.AddNumberOf(Data.SOLDIERS, numberAttackers);
     //
     attackersArmy = new Army(enemiesData, enemiesData.GetNumberOf(Data.SOLDIERS));
     //
     logger.PutLine(numberAttackers + " ennemies are coming to loot us !");
 }
示例#58
0
 public bool IsThreatenedBy(Army army)
 {
     return Board
         .GetThretenedSquares(army)
         .Contains(this);
 }
示例#59
0
        public UnitCreation(Army a)
        {
            MainWindow.BackgroundImage = Content.Graphics.Instance.Images.background.bg_bigMenu;

            sel = 0;

            choosing = false;

            army = a;

            lbl_unitCre = new Label("Unit Creation");
            lbl_unitCre.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.TITLE;
            lbl_unitCre.Position = new Vector2(50, 30);
            MainWindow.add(lbl_unitCre);

            lbl_chooseLdr = new Label("Available Characters");
            lbl_chooseLdr.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.BOLD;
            lbl_chooseLdr.Position = new Vector2(400, 90);
            MainWindow.add(lbl_chooseLdr);

            txt_unitName = new TextBox(10);
            txt_unitName.Position = new Vector2(130, 150);
            MainWindow.add(txt_unitName);

            lnk_choose = new Link("Choose Leader");
            lnk_choose.Position = new Vector2(130, 210);
            lnk_choose.selected = choose;
            MainWindow.add(lnk_choose);

            lnk_create = new Link("Create Unit");
            lnk_create.Position = new Vector2(130, 270);
            lnk_create.selected = create;
            MainWindow.add(lnk_create);

            menu_leader = new Menu(10);
            menu_leader.Position = new Vector2(400, 90);
            foreach(Character c in army.Standby)
            {
                menu_leader.add(new Link(c.Name));
            }
            menu_leader.TabStop = false;
            MainWindow.add(menu_leader);

            lbl_err = new Label("You must name your new unit!");
            lbl_err.Position = new Vector2(90, 330);
            lbl_err.Color = Color.Red;
            lbl_err.Visible = false;
            MainWindow.add(lbl_err);

            lbl_v = new Label("V");
            lbl_v.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.CONTROL;
            lbl_v.Position = new Vector2(50, 440);
            lbl_v.Visible = false;
            MainWindow.add(lbl_v);

            lbl_vAction = new Label("View Character");
            lbl_vAction.Position = new Vector2(80, 440);
            lbl_vAction.Visible = false;
            MainWindow.add(lbl_vAction);

            lbl_enter = new Label("ENTER");
            lbl_enter.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.CONTROL;
            lbl_enter.Position = new Vector2(50, 470);
            lbl_enter.Visible = false;
            MainWindow.add(lbl_enter);

            lbl_enterAction = new Label("");
            lbl_enterAction.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.NORM;
            lbl_enterAction.Position = new Vector2(120, 470);
            lbl_enterAction.Visible = false;
            MainWindow.add(lbl_enterAction);

            lbl_esc = new Label("ESC");
            lbl_esc.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.CONTROL;
            lbl_esc.Position = new Vector2(50, 500);
            MainWindow.add(lbl_esc);

            lbl_escAction = new Label("Go Back");
            lbl_escAction.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.NORM;
            lbl_escAction.Position = new Vector2(100, 500);
            MainWindow.add(lbl_escAction);
        }
示例#60
0
        /// <summary>
        /// Generates Main Army
        /// </summary>
        private void genArmy()
        {
            if (sel_class.SelectedValue == "Fighter")
                GameState.CurrentState.mainChar = new Fighter(txt_name.Text);
            else if (sel_class.SelectedValue == "Archer")
                GameState.CurrentState.mainChar = new Archer(txt_name.Text);
            else if (sel_class.SelectedValue == "Healer")
                GameState.CurrentState.mainChar = new Healer(txt_name.Text);
            else if (sel_class.SelectedValue == "Caster")
                GameState.CurrentState.mainChar = new Caster(txt_name.Text);
            else if (sel_class.SelectedValue == "Scout")
                GameState.CurrentState.mainChar = new Scout(txt_name.Text);
            else
                GameState.CurrentState.mainChar = new Fighter(txt_name.Text);

            GameState.CurrentState.mainChar.toLvl(5);

            Army a = new Army();

            Unit u = new Unit(GameState.CurrentState.mainChar);

            Fighter f1 = new Fighter("Patrick");
            f1.toLvl(3);

            Archer a1 = new Archer("Violaine");
            a1.toLvl(4);

            Character.Stats.Traits gat=new Character.Stats.Traits();
            gat.norm();
            gat.dex=10;

            Item ga=new Item("Art Bow", Item.Item_Type.WEAPON, 20, gat);
            a1.equipWeapon(ga);

            Caster cc = new Caster("Brendan");
            cc.levelUp();

            Healer h1 = new Healer("Sophie");

            Scout s1 = new Scout("Steven");

            u.set(3, 2, f1);
            u.set(3, 3, a1);
            u.set(0, 3, cc);
            u.set(1, 1, h1);
            a.Standby.Add(s1);

            a.Units.Add(u);

            a.setOrgAll("main");

            Item i = new Item("Heal Potion", Item.Item_Type.CONSUMABLE, 100, new Character.Stats.Traits(), new Item.OtherEffect(10, 0));

            a.Inventory.Items.Add(i);

            GameState.CurrentState.mainArmy = a;
        }