Exemplo n.º 1
0
        public static Scaffold.CurrentVillageSupport ToModel(
            long sourceVillageId,
            short worldId,
            int accessGroupId,
            JSON.PlayerOutwardSupport.SupportedVillage villageData,
            DateTime currentTime,
            Scaffold.CurrentVillageSupport existingSupport = null,
            Scaffold.VaultContext context = null
            )
        {
            if (existingSupport == null)
            {
                existingSupport               = new Scaffold.CurrentVillageSupport();
                existingSupport.WorldId       = worldId;
                existingSupport.AccessGroupId = accessGroupId;
                if (context != null)
                {
                    context.CurrentVillageSupport.Add(existingSupport);
                }
            }

            existingSupport.SourceVillageId = sourceVillageId;
            existingSupport.TargetVillageId = villageData.Id;

            existingSupport.LastUpdatedAt  = currentTime;
            existingSupport.SupportingArmy = ArmyConvert.JsonToArmy(villageData.TroopCounts, worldId, existingSupport.SupportingArmy, context);

            return(existingSupport);
        }
Exemplo n.º 2
0
        public TranslationContext(Scaffold.VaultContext context, Scaffold.TranslationRegistry currentRegistry, params short[] fallbackIds)
        {
            this.context         = context;
            this.CurrentRegistry = currentRegistry;
            this.fallbackIds     = fallbackIds.Distinct().ToList();

            this.loadedFallbacks = new Dictionary <short, Scaffold.TranslationRegistry>();
        }
Exemplo n.º 3
0
        private List <FetchingJob> GetFetchingJobs(Scaffold.VaultContext context, DateTime now, bool forceReApply)
        {
            var maxAge      = TimeSpan.FromHours(1);
            var cachingPath = FileCachingPath;
            var worlds      = context.World.Where(w => !w.IsPendingDeletion).ToList();

            return(worlds.Select(w => new FetchingJob(w, cachingPath)).Where(j => forceReApply || j.NeedsRefresh).ToList());
        }
Exemplo n.º 4
0
        public static async Task StoreData(Scaffold.VaultContext context, bool force = false, bool rollover = true)
        {
            DateTime now = DateTime.UtcNow;

            if (force || now - LastPersistedAt > PersistProfilingInterval)
            {
                var records = Interlocked.Exchange(ref PerformanceRecords, new ConcurrentDictionary <String, ConcurrentBag <TimeSpan> >());
                if (records.IsEmpty)
                {
                    return;
                }

                var newRecords = new List <Scaffold.PerformanceRecord>();

                foreach (var kvp in records)
                {
                    var operation = kvp.Key;
                    var samples   = kvp.Value;

                    if (samples.Count < 10 && rollover)
                    {
                        foreach (var time in kvp.Value)
                        {
                            AddRecord(kvp.Key, time);
                        }
                        continue;
                    }

                    var newRecord = new Scaffold.PerformanceRecord();
                    newRecord.GeneratedAt    = now;
                    newRecord.NumSamples     = samples.Count;
                    newRecord.OperationLabel = operation;

                    newRecord.AverageTime = TimeSpan.FromSeconds(samples.Average(s => s.TotalSeconds));
                    newRecord.MinTime     = TimeSpan.FromSeconds(samples.Min(s => s.TotalSeconds));
                    newRecord.MaxTime     = TimeSpan.FromSeconds(samples.Max(s => s.TotalSeconds));

                    newRecords.Add(newRecord);
                }

                context.AddRange(newRecords);
                await context.SaveChangesAsync();

                LastPersistedAt = now;
            }
        }
Exemplo n.º 5
0
        public static Scaffold.ReportBuilding JsonToReportBuilding(JSON.BuildingLevels buildingLevels, short worldId, Scaffold.ReportBuilding existingBuildings = null, Scaffold.VaultContext context = null)
        {
            if (buildingLevels == null || buildingLevels.Count == 0)
            {
                if (existingBuildings != null && context != null)
                {
                    context.Remove(existingBuildings);
                }

                return(null);
            }

            Scaffold.ReportBuilding result;
            if (existingBuildings != null)
            {
                result = existingBuildings;
            }
            else
            {
                result         = new Scaffold.ReportBuilding();
                result.WorldId = worldId;
                context.Add(result);
            }

            result.Barracks   = GetOrNull(buildingLevels, "barracks");
            result.Church     = GetOrNull(buildingLevels, "church");
            result.Farm       = GetOrNull(buildingLevels, "farm");
            result.Garage     = GetOrNull(buildingLevels, "garage");
            result.Hide       = GetOrNull(buildingLevels, "hide");
            result.Iron       = GetOrNull(buildingLevels, "iron");
            result.Main       = GetOrNull(buildingLevels, "main");
            result.Market     = GetOrNull(buildingLevels, "market");
            result.Place      = GetOrNull(buildingLevels, "place");
            result.Smith      = GetOrNull(buildingLevels, "smith");
            result.Snob       = GetOrNull(buildingLevels, "snob");
            result.Stable     = GetOrNull(buildingLevels, "stable");
            result.Statue     = GetOrNull(buildingLevels, "statue");
            result.Stone      = GetOrNull(buildingLevels, "stone");
            result.Storage    = GetOrNull(buildingLevels, "storage");
            result.Wall       = GetOrNull(buildingLevels, "wall");
            result.Watchtower = GetOrNull(buildingLevels, "watchtower");
            result.Wood       = GetOrNull(buildingLevels, "wood");

            // ?
            //result.FirstChurch = GetOrNull(buildingLevels, "First church");

            return(result);
        }
Exemplo n.º 6
0
 public static Scaffold.ReportBuilding ToModel(this JSON.BuildingLevels jsonBuildings, short worldId, Scaffold.ReportBuilding existingBuildings = null, Scaffold.VaultContext context = null)
 => JsonToReportBuilding(jsonBuildings, worldId, existingBuildings, context);
Exemplo n.º 7
0
        public static void JsonToModel(JSON.Report report, short worldId, Scaffold.Report target, Scaffold.VaultContext context = null)
        {
            target.WorldId   = worldId;
            target.ReportId  = report.ReportId.Value;
            target.OccuredAt = report.OccurredAt.Value;
            target.Morale    = report.Morale.Value;
            target.Luck      = report.Luck.Value;
            target.Loyalty   = report.Loyalty;

            target.AttackerPlayerId  = report.AttackingPlayerId;
            target.AttackerVillageId = report.AttackingVillageId.Value;

            target.AttackerArmy       = ArmyConvert.JsonToArmy(report.AttackingArmy, worldId, target.AttackerArmy, context);
            target.AttackerLossesArmy = ArmyConvert.JsonToArmy(report.AttackingArmyLosses, worldId, target.AttackerLossesArmy, context, emptyIfNull: true);

            target.DefenderPlayerId  = report.DefendingPlayerId;
            target.DefenderVillageId = report.DefendingVillageId.Value;

            target.DefenderArmy          = ArmyConvert.JsonToArmy(report.DefendingArmy, worldId, target.DefenderArmy, context);
            target.DefenderLossesArmy    = ArmyConvert.JsonToArmy(report.DefendingArmyLosses, worldId, target.DefenderLossesArmy, context);
            target.DefenderTravelingArmy = ArmyConvert.JsonToArmy(report.TravelingTroops, worldId, target.DefenderTravelingArmy, context);

            target.Building = BuildingConvert.JsonToReportBuilding(report.BuildingLevels, worldId, target.Building, context);
        }
Exemplo n.º 8
0
 public static void ToModel(this JSON.Report report, short worldId, Scaffold.Report target, Scaffold.VaultContext context = null) => JsonToModel(report, worldId, target, context);
Exemplo n.º 9
0
        public static async Task <String> ListCoords(Scaffold.VaultContext context, Query query, bool randomize = true)
        {
            var players    = new List <String>(query.PlayerNames);
            var tribes     = query.TribeNamesOrTags;
            var worldId    = query.WorldId;
            var continents = query.Continents;

            players.AddRange(await(
                                 from tribe in context.Ally.FromWorld(worldId)
                                 join player in context.Player.FromWorld(worldId) on tribe.TribeId equals player.TribeId
                                 where tribes.Contains(tribe.TribeName) || tribes.Contains(tribe.Tag)
                                 select player.PlayerName
                                 ).ToListAsync());

            var playerIds = await context.Player.FromWorld(worldId)
                            .Where(p => players.Contains(p.PlayerName))
                            .Select(p => p.PlayerId)
                            .ToListAsync();

            var villageCoords = await context.Village.FromWorld(worldId)
                                .Where(v => playerIds.Contains(v.PlayerId.Value))
                                .Select(v => new { X = v.X.Value, Y = v.Y.Value, v.VillageId })
                                .OrderBy(v => v.VillageId)
                                .ToListAsync();

            if (continents.Count > 0)
            {
                villageCoords = villageCoords.Where(coord => continents.Any(k =>
                {
                    var xmin = int.Parse(k[1].ToString()) * 100;
                    var ymin = int.Parse(k[0].ToString()) * 100;

                    return
                    (coord.X >= xmin && coord.X < xmin + 100 &&
                     coord.Y >= ymin && coord.Y < ymin + 100);
                })).ToList();
            }

            if (query.MinCoord != null)
            {
                var minCoord = query.MinCoord.Value;
                villageCoords = villageCoords.Where(coord => coord.X >= minCoord.X && coord.Y >= minCoord.Y).ToList();
            }

            if (query.MaxCoord != null)
            {
                var maxCoord = query.MaxCoord.Value;
                villageCoords = villageCoords.Where(coord => coord.X <= maxCoord.X && coord.Y <= maxCoord.Y).ToList();
            }

            if (query.CenterCoord != null && query.MaxDistance != null)
            {
                var centerCoord = query.CenterCoord.Value;
                var maxDistance = query.MaxDistance.Value;

                villageCoords = villageCoords.Where(coord => centerCoord.DistanceTo(coord.X, coord.Y) <= maxDistance).ToList();
            }

            if (randomize)
            {
                var random = new System.Random(0);
                var ranked = villageCoords.Select(c => new { Rank = random.Next(), Coord = c }).OrderBy(r => r.Rank).Select(r => r.Coord);
                villageCoords = ranked.ToList();
            }

            var coordString = String.Join(' ', villageCoords.Select(c => $"{c.X}|{c.Y}"));

            return(coordString);
        }
Exemplo n.º 10
0
 public TranslationController(Scaffold.VaultContext vaultContext)
 {
     this.context = vaultContext;
 }
Exemplo n.º 11
0
 public static Scaffold.Command ToModel(this JSON.Command command, short worldId, int accessGroupId, Scaffold.Command existingCommand, DateTime currentTime, Scaffold.VaultContext context = null) =>
 JsonToModel(command, worldId, accessGroupId, existingCommand, currentTime, context);
Exemplo n.º 12
0
        private static T JsonToArmy <T>(JSON.Army armyCounts, short worldId, T existingArmy = null, Scaffold.VaultContext context = null, bool emptyIfNull = false) where T : class, new()
        {
            if (Object.ReferenceEquals(armyCounts, null))
            {
                if (emptyIfNull)
                {
                    armyCounts = JSON.Army.Empty;
                }
                else
                {
                    if (existingArmy != null && context != null)
                    {
                        context.Remove(existingArmy);
                    }

                    return(null);
                }
            }

            T result;

            if (existingArmy != null)
            {
                result = existingArmy;
            }
            else
            {
                result = new T();
            }

            var scaffoldArmyType = typeof(T);

            foreach (var troopType in Enum.GetValues(typeof(JSON.TroopType)).Cast <JSON.TroopType>())
            {
                var troopCount    = GetOrNull(armyCounts, troopType);
                var troopProperty = scaffoldArmyType.GetProperty(troopType.ToString(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                var currentCount  = (int?)troopProperty.GetValue(result);

                if (currentCount == troopCount)
                {
                    continue;
                }

                if (typeof(short?).IsAssignableFrom(troopProperty.PropertyType))
                {
                    troopProperty.SetValue(result, troopCount?.ToShort());
                }
                else
                {
                    troopProperty.SetValue(result, troopCount);
                }
            }

            var worldIdProperty = scaffoldArmyType.GetProperty("WorldId", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            if (worldIdProperty != null)
            {
                worldIdProperty.SetValue(result, worldId);
            }

            if (existingArmy == null && context != null)
            {
                context.Add(result);
            }

            return(result);
        }
Exemplo n.º 13
0
 public static Scaffold.CurrentArmy JsonToArmy(JSON.Army armyCounts, short worldId, Scaffold.CurrentArmy existingArmy = null, Scaffold.VaultContext context = null, bool emptyIfNull = false) =>
 JsonToArmy <Scaffold.CurrentArmy>(armyCounts, worldId, existingArmy, context, emptyIfNull);
Exemplo n.º 14
0
 public ManageController(Scaffold.VaultContext context, ILoggerFactory factory)
 {
     this.context = context;
     logger       = factory.CreateLogger <ManageController>();
 }
Exemplo n.º 15
0
        public static Task <Scaffold.Command> FindCommandForReport(Scaffold.Report report, Scaffold.VaultContext context)
        {
            return((
                       from command in context.Command.FromWorld(report.WorldId).FromAccessGroup(report.AccessGroupId)
                       where
                       command.TargetVillageId == report.DefenderVillageId &&
                       command.SourceVillageId == report.AttackerVillageId &&
                       command.LandsAt == report.OccuredAt &&
                       command.IsAttack

                       select command
                       ).FirstOrDefaultAsync());
        }
 public PerformanceController(Scaffold.VaultContext context, ILoggerFactory loggerFactory)
 {
     this.context = context;
     this.logger  = loggerFactory.CreateLogger <PerformanceController>();
 }
Exemplo n.º 17
0
        public async Task <Dictionary <String, UserStats> > GenerateHighScores(Scaffold.VaultContext context, int worldId, int accessGroupId, CancellationToken ct)
        {
            context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

            logger.LogDebug("Generating high scores for world {0}", worldId);

            var CurrentSets = new
            {
                ActiveUser            = context.User.Active().FromWorld(worldId).FromAccessGroup(accessGroupId),
                Player                = context.Player.FromWorld(worldId),
                Village               = context.Village.FromWorld(worldId),
                CurrentVillage        = context.CurrentVillage.FromWorld(worldId).FromAccessGroup(accessGroupId),
                Ally                  = context.Ally.FromWorld(worldId),
                CurrentVillageSupport = context.CurrentVillageSupport.FromWorld(worldId).FromAccessGroup(accessGroupId),
                Command               = context.Command.FromWorld(worldId).FromAccessGroup(accessGroupId),
                Report                = context.Report.FromWorld(worldId).FromAccessGroup(accessGroupId),
                EnemyTribe            = context.EnemyTribe.FromWorld(worldId).FromAccessGroup(accessGroupId)
            };

            var serverSettings = await context.WorldSettings.Where(s => s.WorldId == worldId).FirstOrDefaultAsync();

            var lastWeek = serverSettings.ServerTime - TimeSpan.FromDays(7);

            logger.LogDebug("Running data queries...");

            var tribePlayers = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                select new { player.PlayerName, player.PlayerId }
                ).ToListAsync(ct);

            var tribeVillas = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join village in CurrentSets.Village on player.PlayerId equals village.PlayerId
                join currentVillage in CurrentSets.CurrentVillage
                on village.VillageId equals currentVillage.VillageId
                where currentVillage.ArmyAtHomeId != null && currentVillage.ArmyTravelingId != null
                select new { X = village.X.Value, Y = village.Y.Value, player.PlayerId, village.VillageId, currentVillage.ArmyAtHome, currentVillage.ArmyTraveling }
                ).ToListAsync(ct);

            var tribeSupport = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join village in CurrentSets.Village on player.PlayerId equals village.PlayerId
                join support in CurrentSets.CurrentVillageSupport
                on village.VillageId equals support.SourceVillageId
                select new { player.PlayerId, support.TargetVillageId, support.SupportingArmy }
                ).ToListAsync(ct);

            var tribeAttackCommands = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join command in CurrentSets.Command on player.PlayerId equals command.SourcePlayerId
                where command.ArmyId != null
                where command.LandsAt > lastWeek
                where command.IsAttack
                where command.TargetPlayerId != null
                select new { command.CommandId, command.SourcePlayerId, command.LandsAt, command.TargetVillageId, command.Army }
                ).ToListAsync(ct);

            var tribeSupportCommands = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join command in CurrentSets.Command on player.PlayerId equals command.SourcePlayerId
                where command.ArmyId != null
                where command.LandsAt > lastWeek
                where !command.IsAttack
                where command.TargetPlayerId != null
                select new SlimSupportCommand {
                SourcePlayerId = command.SourcePlayerId, TargetPlayerId = command.TargetPlayerId.Value, TargetVillageId = command.TargetVillageId, LandsAt = command.LandsAt
            }
                ).ToListAsync(ct);

            var tribeAttackingReports = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join report in CurrentSets.Report on player.PlayerId equals report.AttackerPlayerId
                where report.OccuredAt > lastWeek
                where report.AttackerArmy != null
                where report.DefenderPlayerId != null
                select new SlimReport {
                AttackerArmy = report.AttackerArmy, ReportId = report.ReportId, OccuredAt = report.OccuredAt, AttackerPlayerId = report.AttackerPlayerId.Value, DefenderVillageId = report.DefenderVillageId
            }
                ).ToListAsync(ct);

            var tribeDefendingReports = await(
                from user in CurrentSets.ActiveUser
                join player in CurrentSets.Player on user.PlayerId equals player.PlayerId
                join report in CurrentSets.Report on player.PlayerId equals report.DefenderPlayerId
                where report.OccuredAt > lastWeek
                where report.AttackerArmy != null
                select new SlimReport {
                AttackerArmy = report.AttackerArmy, DefenderVillageId = report.DefenderVillageId, ReportId = report.ReportId, OccuredAt = report.OccuredAt
            }
                ).ToListAsync(ct);

            var enemyVillas = await(
                from enemy in CurrentSets.EnemyTribe
                join player in CurrentSets.Player on enemy.EnemyTribeId equals player.TribeId
                join village in CurrentSets.Village on player.PlayerId equals village.PlayerId
                select new { X = village.X.Value, Y = village.Y.Value }
                ).ToListAsync(ct);

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            logger.LogDebug("Finished data queries");

            var tribeVillageIds = tribeVillas.Select(v => v.VillageId).ToList();

            var supportedVillageIds = tribeSupport.Select(s => s.TargetVillageId).Distinct().ToList();
            var villageTribeIds     = await(
                from village in CurrentSets.Village
                join player in CurrentSets.Player on village.PlayerId equals player.PlayerId
                join tribe in CurrentSets.Ally on player.TribeId equals tribe.TribeId
                where supportedVillageIds.Contains(village.VillageId)
                select new { village.VillageId, tribe.TribeId }
                ).ToDictionaryAsync(d => d.VillageId, d => d.TribeId, ct);

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            var supportedTribeIds = villageTribeIds.Values.Distinct().ToList();
            var tribeInfo         = await(
                from tribe in CurrentSets.Ally
                where supportedTribeIds.Contains(tribe.TribeId)
                select new { tribe.TribeId, tribe.TribeName, tribe.Tag }
                ).ToDictionaryAsync(d => d.TribeId, d => new { Name = d.TribeName, d.Tag }, ct);

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            logger.LogDebug("Finished supplemental queries");

            var defenseReportsWithNobles           = tribeDefendingReports.Where(r => r.AttackerArmy.Snob > 0).OrderBy(r => r.OccuredAt).ToList();
            var defenseNobleReportsByTargetVillage = defenseReportsWithNobles.GroupBy(r => r.DefenderVillageId).ToDictionary(g => g.Key, g => g.ToList());
            var possibleSnipesByTargetVillage      = tribeSupportCommands
                                                     .Where(c => defenseNobleReportsByTargetVillage.Keys.Contains(c.TargetVillageId))
                                                     .GroupBy(c => c.TargetVillageId, c => c)
                                                     .ToDictionary(g => g.Key, g => g.ToList());

            var numSnipesByPlayer = tribePlayers.ToDictionary(p => p.PlayerId, p => 0);

            foreach ((var villageId, var possibleSnipes) in possibleSnipesByTargetVillage.Tupled())
            {
                var attacksToVillage = defenseNobleReportsByTargetVillage[villageId];

                foreach (var snipe in possibleSnipes)
                {
                    var earlierReport = attacksToVillage.LastOrDefault(r => r.OccuredAt <= snipe.LandsAt);
                    var laterReport   = attacksToVillage.FirstOrDefault(r => r.OccuredAt > snipe.LandsAt);

                    if (laterReport == null)
                    {
                        continue;
                    }

                    if (earlierReport != null)
                    {
                        //  Check if between two nobles that landed at around the same time
                        if (laterReport.OccuredAt - earlierReport.OccuredAt < TimeSpan.FromMilliseconds(500))
                        {
                            numSnipesByPlayer[snipe.SourcePlayerId]++;
                        }
                    }
                    else if (laterReport.OccuredAt - snipe.LandsAt < TimeSpan.FromMilliseconds(1000))
                    {
                        // Landed before
                        numSnipesByPlayer[snipe.SourcePlayerId]++;
                    }
                }
            }



            var supportByTargetTribe = tribePlayers.ToDictionary(p => p.PlayerId, p => supportedTribeIds.ToDictionary(t => t, t => new List <Scaffold.CurrentArmy>()));

            foreach (var support in tribeSupport.Where(s => villageTribeIds.ContainsKey(s.TargetVillageId) && !tribeVillageIds.Contains(s.TargetVillageId)))
            {
                supportByTargetTribe[support.PlayerId][villageTribeIds[support.TargetVillageId]].Add(support.SupportingArmy);
            }

            logger.LogDebug("Sorted support by tribe");


            var reportsBySourcePlayer = tribePlayers.ToDictionary(p => p.PlayerId, _ => new Dictionary <long, List <SlimReport> >());

            foreach (var report in tribeAttackingReports)
            {
                var playerReports = reportsBySourcePlayer[report.AttackerPlayerId];
                if (!playerReports.ContainsKey(report.OccuredAt.Ticks))
                {
                    playerReports.Add(report.OccuredAt.Ticks, new List <SlimReport>());
                }
                playerReports[report.OccuredAt.Ticks].Add(report);
            }

            logger.LogDebug("Sorted reports by source player");

            var commandArmiesWithReports = new Dictionary <Scaffold.CommandArmy, SlimReport>();

            foreach (var command in tribeAttackCommands.Where(cmd => reportsBySourcePlayer.ContainsKey(cmd.SourcePlayerId)))
            {
                var matchingReport = reportsBySourcePlayer[command.SourcePlayerId].GetValueOrDefault(command.LandsAt.Ticks)?.FirstOrDefault(c => c.DefenderVillageId == command.TargetVillageId);
                if (matchingReport != null)
                {
                    commandArmiesWithReports.Add(command.Army, matchingReport);
                }
            }

            logger.LogDebug("Gathered commands with associated reports");

            var reportsWithoutCommands = tribeAttackingReports.Except(commandArmiesWithReports.Values).ToList();

            var usedAttackArmies = tribeAttackCommands
                                   .Select(c => new { c.SourcePlayerId, Army = (Army)c.Army })
                                   .Concat(reportsWithoutCommands.Select(r => new { SourcePlayerId = r.AttackerPlayerId, Army = (Army)r.AttackerArmy }))
                                   .ToList();

            logger.LogDebug("Gathered used attack armies");

            var usedAttackArmiesByPlayer = tribePlayers.ToDictionary(p => p.PlayerId, p => new List <Army>());

            foreach (var army in usedAttackArmies)
            {
                usedAttackArmiesByPlayer[army.SourcePlayerId].Add(army.Army);
            }

            logger.LogDebug("Sorted attack armies by player");

            var villagesByPlayer = tribeVillas.GroupBy(v => v.PlayerId).ToDictionary(g => g.Key, g => g.ToList());

            var armiesNearEnemy = new HashSet <long>();
            var enemyMap        = new Spatial.Quadtree(enemyVillas.Select(v => new Coordinate {
                X = v.X, Y = v.Y
            }));

            foreach (var village in tribeVillas.Where(v => enemyMap.ContainsInRange(new Coordinate {
                X = v.X, Y = v.Y
            }, 10)))
            {
                armiesNearEnemy.Add(village.ArmyAtHome.ArmyId);
            }

            logger.LogDebug("Collected armies near enemies");

            var result = new Dictionary <String, UserStats>();

            foreach (var player in tribePlayers)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                var playerVillages = villagesByPlayer.GetValueOrDefault(player.PlayerId);
                var playerArmies   = usedAttackArmiesByPlayer[player.PlayerId];

                int numFangs = 0, numNukes = 0, numFakes = 0;
                foreach (var army in playerArmies)
                {
                    if (ArmyStats.IsFake(army))
                    {
                        numFakes++;
                    }
                    if (ArmyStats.IsNuke(army))
                    {
                        numNukes++;
                    }
                    if (ArmyStats.IsFang(army))
                    {
                        numFangs++;
                    }
                }

                var playerResult = new UserStats
                {
                    FangsInPastWeek   = numFangs,
                    NukesInPastWeek   = numNukes,
                    FakesInPastWeek   = numFakes,
                    SnipesInPastWeek  = numSnipesByPlayer[player.PlayerId],
                    BacklineDVsAtHome = playerVillages?.Where(v => !armiesNearEnemy.Contains(v.ArmyAtHome.ArmyId)).Sum(v => BattleSimulator.TotalDefensePower(v.ArmyAtHome) / (float)ArmyStats.FullDVDefensivePower) ?? 0,
                    DVsAtHome         = playerVillages?.Sum(v => BattleSimulator.TotalDefensePower(v.ArmyAtHome) / (float)ArmyStats.FullDVDefensivePower) ?? 0,
                    DVsTraveling      = playerVillages?.Sum(v => BattleSimulator.TotalDefensePower(v.ArmyTraveling) / (float)ArmyStats.FullDVDefensivePower) ?? 0,
                    PopPerTribe       = supportByTargetTribe[player.PlayerId].Where(kvp => kvp.Value.Count > 0).ToDictionary(
                        kvp => tribeInfo[kvp.Key].Tag.UrlDecode(),
                        kvp => kvp.Value.Sum(a => BattleSimulator.TotalDefensePower(a) / (float)ArmyStats.FullDVDefensivePower)
                        )
                };

                result.Add(player.PlayerName.UrlDecode(), playerResult);
            }

            logger.LogDebug("Generated result data");

            return(result);
        }
Exemplo n.º 18
0
        public static Scaffold.Command JsonToModel(JSON.Command command, short worldId, int accessGroupId, Scaffold.Command existingCommand, DateTime currentTime, Scaffold.VaultContext context = null)
        {
            if (command == null)
            {
                if (existingCommand != null && context != null)
                {
                    context.Remove(existingCommand);
                }

                return(null);
            }

            Scaffold.Command result;
            if (existingCommand != null)
            {
                result = existingCommand;
            }
            else
            {
                result               = new Scaffold.Command();
                result.CommandId     = command.CommandId.Value;
                result.WorldId       = worldId;
                result.AccessGroupId = accessGroupId;
                if (context != null)
                {
                    context.Add(result);
                }
            }

            result.CommandId       = command.CommandId.Value;
            result.UserLabel       = result.UserLabel ?? command.UserLabel;  // Don't overwrite existing labels
            result.SourcePlayerId  = command.SourcePlayerId.Value;
            result.SourceVillageId = command.SourceVillageId.Value;
            result.TargetPlayerId  = command.TargetPlayerId;
            result.TargetVillageId = command.TargetVillageId.Value;
            result.LandsAt         = command.LandsAt.Value;
            result.FirstSeenAt     = result.FirstSeenAt == DateTime.MinValue ? currentTime : result.FirstSeenAt;
            result.IsAttack        = command.CommandType == JSON.CommandType.Attack;
            result.IsReturning     = command.IsReturning.Value;

            result.Army = ArmyConvert.JsonToArmy(command.Troops, worldId, result.Army, context);

            if (result.TroopType == null)
            {
                result.TroopType = TroopTypeConvert.TroopTypeToString(command.TroopType);
            }
            else if (command.TroopType != null)
            {
                var currentType = result.TroopType.ToTroopType();
                var updatedType = command.TroopType.Value;

                if (Native.ArmyStats.TravelSpeed[currentType] < Native.ArmyStats.TravelSpeed[updatedType])
                {
                    result.TroopType = updatedType.ToTroopString();
                }
            }

            return(result);
        }
Exemplo n.º 19
0
 public RequireAuthAttribute(Scaffold.VaultContext dbContext, ILoggerFactory loggerFactory)
 {
     this.dbContext = dbContext;
     this.logger    = loggerFactory.CreateLogger <RequireAuthAttribute>();
 }