コード例 #1
0
        public async Task FightBattles(Player player)
        {
            var defendingSquad = player.Army.Squads
                                 .Where(s => s.CityId == player.City.Id)
                                 .SingleOrDefault();

            if (defendingSquad == null)
            {
                defendingSquad = new Squad {
                    ArmyId = player.Army.Id
                };
                await _squadService.InsertSquad(defendingSquad, player.Army, player.City.Id);
            }

            var attackingSquads = await _dbContext.Squads
                                  .Include(s => s.SquadUnits)
                                  .ThenInclude(su => su.Unit)
                                  .Include(s => s.Army)
                                  .ThenInclude(a => a.Player)
                                  .ThenInclude(p => p.Stock)
                                  .Include(s => s.Army) //Is it OK to include game as well this way?
                                  .ThenInclude(a => a.Player)
                                  .ThenInclude(p => p.Game)
                                  .Where(s => s.CityId == player.City.Id && s.ArmyId != player.Army.Id).ToListAsync();

            Random random = new Random();

            attackingSquads = attackingSquads.OrderBy(_ => random.NextDouble()).ToList(); // shuffle attacker squads randomly
            foreach (var squad in attackingSquads)
            {
                //FIGHTING
                var victory = await _squadService.FightBattle(defendingSquad, squad);

                if (victory)
                {
                    await _squadService.WeakenDefeatedSquad(squad, true);

                    int xPBonus = (int)await _squadService.GetSumAttackStrength(squad) + FIGHT_XP_REWARD_BASE;
                    await AddAttackXP(squad.Army, xPBonus / FIGHT_LOSER_REWARD_DIVIDER);
                    await AddDefenseXP(defendingSquad.Army, xPBonus);
                }
                else
                {
                    await _squadService.WeakenDefeatedSquad(defendingSquad, false);

                    await _stockService.SackCity(squad.Army.Player.Stock, player.Stock);

                    int xPBonus = (int)await _squadService.GetSumDefenseStrength(defendingSquad) + FIGHT_XP_REWARD_BASE;
                    await AddAttackXP(squad.Army, xPBonus);
                    await AddDefenseXP(defendingSquad.Army, xPBonus / FIGHT_LOSER_REWARD_DIVIDER);
                }
                // SCOUTING
                if (_squadService.GetScoutNumber(squad) > 0)
                {
                    await Scouting(defendingSquad, squad);
                }
            }
        }