public bool Handle(DomainEventHandlerData <MoveSoldierEvent> @event)
        {
            GameAggregate snapshot = @event.Snapshot as GameAggregate;

            if (snapshot == null)
            {
                return(false);
            }
            if (@event.EventObject.Soldiers == null)
            {
                return(true);
            }
            var army         = snapshot.UserId == @event.EventObject.CreatedBy ? Army.Blue : Army.Red;
            var soldiers     = army == Army.Blue ? snapshot.UserSoldiers : snapshot.OpponentSoldiers ?? new List <SoldierAggregate>();
            var moveSoldiers = soldiers.Where(e => @event.EventObject.Soldiers.Contains(e.Id.ToString()));
            var moveToCastle = snapshot.Castles.FirstOrDefault(e => e.Id == @event.EventObject.CastleId);

            if (moveToCastle == null)
            {
                return(false);
            }
            if (moveToCastle.Soldiers == null)
            {
                moveToCastle.Soldiers = new List <SoldierAggregate>();
            }
            moveToCastle.Soldiers.AddRange(moveSoldiers);
            soldiers.RemoveAll(e => @event.EventObject.Soldiers.Contains(e.Id.ToString()));
            snapshot.UpdateSoldierAmount();
            return(true);
        }
Ejemplo n.º 2
0
        private GameStateModel GetGameStateBySnapshot(GameAggregate gameSnapshot)
        {
            GameStateModel result = new GameStateModel
            {
                Id                     = gameSnapshot.Id,
                Status                 = gameSnapshot.Status,
                UserId                 = gameSnapshot.UserId,
                UserHeroId             = gameSnapshot.UserHeroId,
                OpponentId             = gameSnapshot.OpponentId,
                OpponentHeroId         = gameSnapshot.OpponentHeroId,
                SelfPlaying            = gameSnapshot.SelfPlaying,
                Speed                  = gameSnapshot.Speed,
                Difficulty             = gameSnapshot.Difficulty,
                UserCoins              = gameSnapshot.UserCoins,
                OpponentCoins          = gameSnapshot.OpponentCoins,
                Castles                = new List <CastleStateModel>(),
                UserProducedTroopTypes = gameSnapshot.UserProducedTroopTypes,
                UserSoldiers           = Mapper.Map <List <SoldierModel> >(gameSnapshot.UserSoldiers),
                OpponentSoldiers       = Mapper.Map <List <SoldierModel> >(gameSnapshot.OpponentSoldiers)
            };

            foreach (var castle in gameSnapshot.Castles)
            {
                CastleStateModel castleModel = Mapper.Map <CastleStateModel>(castle);
                result.Castles.Add(castleModel);
            }
            return(result);
        }
Ejemplo n.º 3
0
        public async Task <bool> RestartCastleProduction(Guid id, Guid castleId)
        {
            var state = await Build(id, string.Empty, -1);

            if (state.HasError)
            {
                return(false);
            }
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;
            var           castle         = gameSnapshot?.Castles?.FirstOrDefault(e => e.Id == castleId);

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

            //if (gameSnapshot.CanProduce(castle,
            //    _gameDomainService.GetUpkeepCoinBySoldierType(castle, gameSnapshot.GetDefaultTroopType())))
            //{
            //    _domain.AddEvent(id, new RestartCastleProductionEvent(castleId, castle.OwnerUserId));
            //    return true;
            //}
            return(false);
        }
Ejemplo n.º 4
0
        public async Task Handle(CreateGame message)
        {
            var item = new GameAggregate(message.Id, message.Name);
            await _session.Add(item);

            await _session.Commit();
        }
Ejemplo n.º 5
0
        public CreateSoldierEvent GetCreateSoldierIfNeedCreate(GameAggregate game, Army army)
        {
            if (!game.IsProductionState(army))
            {
                return(null);
            }
            var productEvent       = _domain.GetNotExecuteEvents <CreateSoldierEvent>(game.Id) ?? new List <CreateSoldierEvent>();
            var hasInProgressEvent = productEvent.Any(e => e.Army == army);

            if (hasInProgressEvent)
            {
                return(null);
            }
            var troopType = game.GetDefaultTroopType(army);

            //var needCoin = GetUpkeepCoinBySoldierType(game, army, troopType);
            //bool canProduction;
            //if (army == Army.Blue)
            //    canProduction = game.UserCoins > needCoin;
            //else
            //    canProduction = game.OpponentCoins > needCoin;
            //if (canProduction)
            return(GetCreateSoldierEvent(game.Id, army,
                                         troopType,
                                         game.GetUserId(army)));

            return(null);
        }
Ejemplo n.º 6
0
#pragma warning disable 1998
        public async Task <GameStateModel> GetState(Guid id, int streamVersion)
#pragma warning restore 1998
        {
            GameStateModel result = new GameStateModel
            {
                Id       = id,
                HasError = false
            };
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, streamVersion);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;

            if (gameSnapshot == null)
            {
                return(null);
            }
            result.Status         = gameSnapshot.Status;
            result.UserId         = gameSnapshot.UserId;
            result.UserHeroId     = gameSnapshot.UserHeroId;
            result.OpponentId     = gameSnapshot.OpponentId;
            result.OpponentHeroId = gameSnapshot.OpponentHeroId;
            result.StreamRevision = latestSnapshot.StreamRevision;
            result.SelfPlaying    = gameSnapshot.SelfPlaying;
            result.Castles        = new List <CastleStateModel>();
            foreach (var castle in gameSnapshot.Castles)
            {
                CastleStateModel castleModel = Mapper.Map <CastleStateModel>(castle);
                //var events = _domain.GetNotExecuteEvents<CreateSoldierEvent>(id);
                //var latestEvent = events.FirstOrDefault(e => e.CastleId == castle.Id);
                //if (latestEvent != null)
                //    castleModel.ProduceExecuteAt = latestEvent.ExecuteAt;
                result.Castles.Add(castleModel);
            }
            return(result);
        }
Ejemplo n.º 7
0
        public double GetUpkeepCoinBySoldierType(GameAggregate game, Army army, string troopType)
        {
            var troopTypeData = (army == Army.Blue ? game.UserTroopTypes : game.OpponentTroopTypes)?.FirstOrDefault(e => e.ResourceType == troopType);

            if (troopTypeData != null)
            {
                return(troopTypeData.UpkeepCoins);
            }
            return(0);
        }
Ejemplo n.º 8
0
        public bool CreateSoldierIfNeed(GameAggregate game, Army army)
        {
            var @event = GetCreateSoldierIfNeedCreate(game, army);

            if (@event != null)
            {
                _domain.AddEvent(game.Id, @event);
                return(true);
            }
            return(false);
        }
Ejemplo n.º 9
0
        private GameAggregate InitGameSnapshot(Guid id)
        {
            GameAggregate gameAggregate = new GameAggregate
            {
                Id      = id,
                Castles = new List <CastleAggregate>(),
                Status  = GameStatus.Requesting
            };

            return(gameAggregate);
        }
Ejemplo n.º 10
0
        public async Task <UpgradeCastleResult> UpgradeCastleAsync(Guid id, Guid castleId)
        {
            var state = await Build(id, string.Empty, -1);

            if (state.HasError)
            {
                return new UpgradeCastleResult()
                       {
                           Errors = new List <string>()
                           {
                               "Failed when building game state"
                           }
                       }
            }
            ;
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;
            var           castle         = gameSnapshot?.Castles?.FirstOrDefault(e => e.Id == castleId);

            if (castle == null)
            {
                return new UpgradeCastleResult()
                       {
                           Errors = new List <string>()
                           {
                               "Castle not found"
                           }
                       }
            }
            ;

            var maxStrength = await GetMaximunStrength();

            if (castle.Strength < maxStrength)
            {
                _domain.AddEvent(id, new UpgradeCastleEvent(castleId, castle.OwnerUserId));

                return(new UpgradeCastleResult()
                {
                    Strength = castle.Strength + 1
                });
            }

            return(new UpgradeCastleResult()
            {
                Errors = new List <string>()
                {
                    "Your Castle is got max strength"
                }
            });
        }
Ejemplo n.º 11
0
        public void AddSiegeEvent(GameAggregate game, CastleAggregate castle, CastleAggregate destinationCastle, List <SoldierAggregate> soldiers)
        {
            var battleAt = GetBattleTime(game.Speed);

            destinationCastle.Siege = new SiegeAggregate
            {
                Id          = Guid.NewGuid(),
                OwnerUserId = castle.OwnerUserId,
                Soldiers    = soldiers,
                BattleAt    = battleAt,
                SiegeAt     = DateTime.UtcNow
            };
            // create siege event
            AddSiegeEvent(game, destinationCastle, soldiers);
        }
Ejemplo n.º 12
0
        public bool Handle(DomainEventHandlerData <ChangeGameStatusEvent> @event)
        {
            GameAggregate snapshot = @event.Snapshot as GameAggregate;

            if (snapshot == null)
            {
                return(false);
            }
            GameAggregate         gameAggregate = snapshot;
            ChangeGameStatusEvent eventObject   = @event.EventObject;
            int num = eventObject != null ? (int)eventObject.Status : 0;

            gameAggregate.Status = (GameStatus)num;
            return(true);
        }
Ejemplo n.º 13
0
        public void AddSiegeEvent(GameAggregate game, CastleAggregate destinationCastle, List <SoldierAggregate> soldiers)
        {
            if (destinationCastle.Siege == null)
            {
                return;
            }
            var battleAt = GetBattleTime(game.Speed);

            _domain.AddEvent(game.Id,
                             new SiegeCastleEvent(destinationCastle.Siege.OwnerUserId,
                                                  destinationCastle.Id,
                                                  soldiers,
                                                  DateTime.UtcNow,
                                                  battleAt));
        }
Ejemplo n.º 14
0
        public bool Handle(DomainEventHandlerData <AddCastleEvent> @event)
        {
            GameAggregate snapshot = @event.Snapshot as GameAggregate;

            if (snapshot == null)
            {
                return(false);
            }
            if (snapshot.Castles == null)
            {
                snapshot.Castles = new List <CastleAggregate>();
            }
            snapshot.Castles.Add(new CastleAggregate()
            {
                Id = @event.EventObject.Id
            });
            return(true);
        }
Ejemplo n.º 15
0
        public bool Handle(DomainEventHandlerData <CreateSoldierEvent> data)
        {
            GameAggregate snapshot = data.Snapshot as GameAggregate;

            if (snapshot == null)
            {
                return(false);
            }
            if (data.EventObject.Army == Army.Blue)
            {
                if (snapshot.UserSoldiers == null)
                {
                    snapshot.UserSoldiers = new List <SoldierAggregate>();
                }
                ++snapshot.UserSoldiersAmount;
            }
            else
            {
                if (snapshot.OpponentSoldiers == null)
                {
                    snapshot.OpponentSoldiers = new List <SoldierAggregate>();
                }
                ++snapshot.OpponentSoldierAmount;
            }
            SoldierAggregate soldierAggregate = new SoldierAggregate {
                Id = Guid.NewGuid()
            };
            var castleTroopType = snapshot.GetTroopTypeData(data.EventObject.Army, data.EventObject.TroopType);

            if (castleTroopType != null)
            {
                soldierAggregate.CastleTroopType = castleTroopType;
                if (data.EventObject.Army == Army.Blue)
                {
                    snapshot.UserSoldiers.Add(soldierAggregate);
                }
                else
                {
                    snapshot.OpponentSoldiers.Add(soldierAggregate);
                }
            }
            _gameDomainService.CreateSoldierIfNeed(snapshot, data.EventObject.Army);
            return(true);
        }
Ejemplo n.º 16
0
        public bool Handle(DomainEventHandlerData <InitCastleEvent> @event)
        {
            GameAggregate snapshot = @event.Snapshot as GameAggregate;
            var           castle   = snapshot?.Castles?.FirstOrDefault(e => e.Id == @event.EventObject.Id);

            if (castle == null)
            {
                return(false);
            }
            castle.Name             = @event.EventObject.Name;
            castle.Army             = @event.EventObject.Army;
            castle.Position         = @event.EventObject.Position;
            castle.MaxResourceLimit = @event.EventObject.MaxResourceLimit;
            castle.OwnerUserId      = @event.EventObject.OwnerUserId;
            castle.OwnerId          = @event.EventObject.OwnerId;
            castle.Soldiers         = new List <SoldierAggregate>();
            castle.Strength         = @event.EventObject.Strength;
            return(true);
        }
Ejemplo n.º 17
0
        public async Task <bool> SuspendCastleProduction(Guid id, Guid castleId)
        {
            var state = await Build(id, string.Empty, -1);

            if (state.HasError)
            {
                return(false);
            }
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;
            var           castle         = gameSnapshot?.Castles?.FirstOrDefault(e => e.Id == castleId);

            if (castle == null)
            {
                return(false);
            }
            _domain.AddEvent(id, new SuspendCastleProductionEvent(castleId, castle.OwnerUserId));
            return(true);
        }
Ejemplo n.º 18
0
        public GameStateModel GetLatestSnapshot(Guid id)
        {
            GameStateModel result = new GameStateModel()
            {
                Id = id
            };

            _domain.Build(id, InitGameSnapshot);
            result.HasError = false;
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;

            if (gameSnapshot == null)
            {
                result.HasError = true;
                return(result);
            }
            result = GetGameStateBySnapshot(gameSnapshot);
            result.StreamRevision = latestSnapshot.StreamRevision;
            return(result);
        }
Ejemplo n.º 19
0
        public async Task <GameStateModel> Build(Guid id, string userId, int streamVersion)
        {
            GameStateModel result = new GameStateModel()
            {
                Id = id,
            };
            var gameData = await _gameRepository.GetByIdAsync(id.ToString());

            if (gameData == null)
            {
                result.HasError = true;
                return(result);
            }

            _domain.Build(id, InitGameSnapshot);
            result.HasError = false;
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;

            if (gameSnapshot == null)
            {
                result.HasError = true;
                return(result);
            }
            result = GetGameStateBySnapshot(gameSnapshot);

            result.StreamRevision = latestSnapshot.StreamRevision;
            if (streamVersion >= 0)
            {
                result.Events = GetUsedEvents(id, userId, streamVersion);
            }
            result.BattalionMovements =
                Mapper.Map <List <BattalionMovementEventModel> >(_domain.GetNotExecuteEvents <BattalionMovementEvent>(id));
            await UpdateGameStateForReadData(id.ToString(), result);

            return(result);
        }
Ejemplo n.º 20
0
        public double CalculateCoin(GameAggregate game, CastleAggregate castle)
        {
            var revenueCoins = _gameSettings.RevenueCoins * GameSpeedHelper.GetSpeedValue(game.Speed);

            return(revenueCoins);
        }
Ejemplo n.º 21
0
        public async Task <DetailCastleStateModel> DetailCastle(Guid id, Guid castleId, string userId, int streamVersion)
        {
            var state = await Build(id, userId, streamVersion);

            if (state.HasError)
            {
                return(null);
            }
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, int.MaxValue);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;
            var           castle         = gameSnapshot?.Castles?.FirstOrDefault(e => e.Id == castleId);

            if (castle == null)
            {
                return(null);
            }
            DetailCastleStateModel result = Mapper.Map <DetailCastleStateModel>(castle);

            result.StreamRevision  = latestSnapshot.StreamRevision;
            result.CurrentUserArmy = state.UserId == userId ? Army.Blue : Army.Red;
            if (streamVersion >= 0)
            {
                result.Events = Mapper.Map <List <EventBaseModel> >(_domain.GetEvents(id, userId, streamVersion));
            }
            result.Soldiers = GetSoldiersOfCastle(castle);
            bool isOwner = result.OwnerUserId == userId;

            result.CanChangeTroopType = isOwner;
            result.CanUpgrade         = isOwner && result.Strength < await GetMaximunStrength();
            await UpdateGameStateForReadData(id.ToString(), state);

            result.Revenue              = _gameDomainService.CalculateCoin(gameSnapshot, castle);
            result.RevenueTime          = _gameDomainService.GetRevenueTimeBySpeed(gameSnapshot.Speed);
            result.UpkeepTime           = _gameDomainService.GetUpkeepTimeBySpeed(gameSnapshot.Speed);
            result.CanProductionSoldier = castle.IsProductionState() && result.ProduceExecuteAt.CompareTo(DateTime.UtcNow) > 0;
            if (!result.CanProductionSoldier)
            {
                var ownerCoins = castle.OwnerUserId == state.UserId ? state.UserCoins : state.OpponentCoins;
                result.IsNotEnoughCoinForProduction = ownerCoins < 0;
            }
            var ownerTask = _userRepository.GetByIdAsync(castle.OwnerUserId).ContinueWith(r =>
            {
                if (r.Result == null)
                {
                    return;
                }
                result.OwnerUser   = Mapper.Map <UserModel>(r.Result);
                List <Hero> heroes = r.Result.Heroes;
                if (heroes == null || heroes.All(e => e.Id != castle.OwnerId))
                {
                    return;
                }
                result.Owner = Mapper.Map <HeroModel>(r.Result.Heroes.First(e => e.Id == castle.OwnerId));
            });
            var siegeOwnerTask = castle.Siege == null?Task.FromResult(true) : _userRepository.GetByIdAsync(castle.Siege.OwnerUserId).ContinueWith(r =>
            {
                if (r.Result == null)
                {
                    return;
                }
                result.Siege.OwnerUser = Mapper.Map <UserModel>(r.Result);
            });

            await Task.WhenAll(ownerTask, siegeOwnerTask);

            return(result);
        }
Ejemplo n.º 22
0
 public void CreateSoldierIfNeed(GameAggregate snap)
 {
     CreateSoldierIfNeed(snap, Army.Blue);
     CreateSoldierIfNeed(snap, Army.Red);
 }