Exemple #1
0
        public void RetreatUnits_RetreatsStationedUnitsThatAreNotInTribeThatOwnsStronghold(
            IStronghold stronghold, 
            [FrozenMock] IActionFactory actionFactory,
            [FrozenMock] ITroopObjectInitializerFactory troopInitializerFactory,
            ITroopObjectInitializer troopInitializer,
            ITroopStub stub,
            ITribe tribe,
            ITribe shTribe,
            RetreatChainAction retreatAction,
            StrongholdManager strongholdManager)
        {
            stub.State.Returns(TroopState.Stationed);
            stub.City.Owner.IsInTribe.Returns(true);
            stub.City.Id.Returns<uint>(1234);
            stub.TroopId.Returns<ushort>(2);
            stub.City.Owner.Tribesman.Tribe.Returns(tribe);

            stronghold.MainBattle.Returns((IBattleManager)null);
            stronghold.Tribe.Returns(shTribe);
            stronghold.Troops.StationedHere().Returns(new[] { stub });

            troopInitializerFactory.CreateStationedTroopObjectInitializer(stub).Returns(troopInitializer);
            actionFactory.CreateRetreatChainAction(stub.City.Id, troopInitializer).Returns(retreatAction);

            strongholdManager.RetreatUnits(stronghold);
            
            stub.City.Worker.Received(1).DoPassive(stub.City, retreatAction, true);
        }
Exemple #2
0
 private void UnsubscribeEvents(ITribe tribe)
 {
     tribe.TribesmanRemoved -= TribeOnTribesmanRemoved;
     tribe.Updated          -= TribeOnUpdated;
     tribe.RanksUpdated     += TribeOnRanksUpdated;
     tribeLogger.Unlisten(tribe);
 }
Exemple #3
0
        private void Delete(Session session, Packet packet)
        {
            if (!session.Player.IsInTribe)
            {
                ReplyError(session, packet, Error.TribeIsNull);
                return;
            }

            ITribe tribe = session.Player.Tribesman.Tribe;

            CallbackLock.CallbackLockHandler lockHandler = delegate
            {
                var locks =
                    strongholdManager.StrongholdsForTribe(tribe)
                    .SelectMany(stronghold => stronghold.LockList())
                    .ToList();

                locks.AddRange(tribe.Tribesmen);

                return(locks.ToArray());
            };

            locker.Lock(lockHandler, new object[] {}, tribe).Do(() =>
            {
                if (!session.Player.Tribesman.Tribe.IsOwner(session.Player))
                {
                    ReplyError(session, packet, Error.TribesmanNotAuthorized);
                    return;
                }

                var result = tribeManager.Remove(tribe);
                ReplyWithResult(session, packet, result);
            });
        }
Exemple #4
0
        public IEnumerable <Tribe.IncomingListItem> GetIncomingList(ITribe tribe)
        {
            var incomingTroops = (from tribesmen in tribe.Tribesmen
                                  from city in tribesmen.Player.GetCityList()
                                  from notification in city.Notifications
                                  where
                                  notification.Action is IActionTime &&
                                  notification.Action.Category == ActionCategory.Attack &&
                                  notification.GameObject.City != city && notification.Subscriptions.Count > 0
                                  select
                                  new Tribe.IncomingListItem
            {
                Source = notification.GameObject.City,
                Target = city,
                EndTime = ((IActionTime)notification.Action).EndTime
            }).ToList();

            incomingTroops.AddRange(from stronghold in strongholdManager.StrongholdsForTribe(tribe)
                                    from notification in stronghold.Notifications
                                    where
                                    notification.Action is IActionTime &&
                                    notification.Action.Category == ActionCategory.Attack &&
                                    notification.Subscriptions.Count > 0 &&
                                    (!notification.GameObject.City.Owner.IsInTribe ||
                                     notification.GameObject.City.Owner.Tribesman.Tribe != tribe)
                                    select
                                    new Tribe.IncomingListItem
            {
                Source  = notification.GameObject.City,
                Target  = stronghold,
                EndTime = ((IActionTime)notification.Action).EndTime
            });

            return(incomingTroops.OrderBy(i => i.EndTime));
        }
Exemple #5
0
        public IMultiObjectLock Lock(uint cityId, out ICity city, out ITribe tribe)
        {
            tribe = null;

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

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

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

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

            return(lck);
        }
Exemple #6
0
        private void Edit(Session session, Packet packet)
        {
            int    assignmentId;
            string description;

            try
            {
                assignmentId = packet.GetInt32();
                description  = packet.GetString();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (!session.Player.IsInTribe)
            {
                ReplyError(session, packet, Error.TribesmanNotPartOfTribe);
                return;
            }

            ITribe tribe = session.Player.Tribesman.Tribe;

            locker.Lock(session.Player, tribe).Do(() =>
            {
                Error result = tribe.EditAssignment(session.Player, assignmentId, description);
                ReplyWithResult(session, packet, result);
            });
        }
Exemple #7
0
 public Tribesman(ITribe tribe, IPlayer player, ITribeRank rank)
 {
     Tribe        = tribe;
     Player       = player;
     JoinDate     = DateTime.UtcNow;
     Rank         = rank;
     Contribution = new Resource();
 }
Exemple #8
0
 public Tribesman(ITribe tribe, IPlayer player, DateTime joinDate, Resource contribution, ITribeRank rank)
 {
     Tribe        = tribe;
     Player       = player;
     JoinDate     = joinDate;
     Contribution = contribution;
     Rank         = rank;
 }
Exemple #9
0
 void Save(ITribe tribe, TribeLogType type, params object[] objs)
 {
     dbManager.Query(string.Format(@"INSERT INTO `{0}` VALUES (NULL,@tribe_id,UTC_TIMESTAMP(),@type,@parameters)", TRIBE_LOG_DB),
                     new[]
     {
         new DbColumn("tribe_id", tribe.Id, DbType.UInt32), new DbColumn("type", type, DbType.Int32),
         new DbColumn("parameters", JsonConvert.SerializeObject(objs), DbType.String),
     });
 }
Exemple #10
0
 public static void AddTribeRanksToPacket(ITribe tribe, Packet packet)
 {
     packet.AddByte((byte)tribe.Ranks.Count());
     foreach (var rank in tribe.Ranks)
     {
         packet.AddString(rank.Name);
         packet.AddInt32((int)rank.Permission);
     }
 }
Exemple #11
0
        public IEnumerable <IStronghold> OpenStrongholdsForTribe(ITribe tribe)
        {
            lock (indexLock)
            {
                ReindexIfNeeded();

                return(!gateOpenToIndex.Contains(tribe) ? new IStronghold[] {} : gateOpenToIndex[tribe]);
            }
        }
Exemple #12
0
 public void Unlisten(ITribe tribe)
 {
     tribe.Upgraded             -= Tribe_Upgraded;
     tribe.TribesmanContributed -= Tribe_TribesmanContributed;
     tribe.TribesmanJoined      -= Tribe_TribesmanJoined;
     tribe.TribesmanKicked      -= Tribe_TribesmanKicked;
     tribe.TribesmanLeft        -= Tribe_TribesmanLeft;
     tribe.TribesmanRankChanged -= Tribe_TribesmanRankChanged;
 }
Exemple #13
0
        private void Join(Session session, Packet packet)
        {
            uint        cityId;
            int         assignmentId;
            ISimpleStub stub;

            try
            {
                cityId       = packet.GetUInt32();
                assignmentId = packet.GetInt32();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (!session.Player.IsInTribe)
            {
                ReplyError(session, packet, Error.TribesmanNotPartOfTribe);
                return;
            }

            ITribe tribe = session.Player.Tribesman.Tribe;

            locker.Lock(session.Player, tribe).Do(() =>
            {
                ICity city = session.Player.GetCity(cityId);
                if (city == null)
                {
                    ReplyError(session, packet, Error.CityNotFound);
                    return;
                }

                // TODO: Clean this up
                Assignment assignment = tribe.Assignments.FirstOrDefault(x => x.Id == assignmentId);
                if (assignment == null)
                {
                    ReplyError(session, packet, Error.AssignmentDone);
                    return;
                }

                try
                {
                    stub = PacketHelper.ReadStub(packet, assignment.IsAttack ? FormationType.Attack : FormationType.Defense);
                }
                catch (Exception)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                Error result = tribe.JoinAssignment(assignmentId, city, stub);

                ReplyWithResult(session, packet, result);
            });
        }
Exemple #14
0
        private string TribesmanRemove(Session session, string[] parms)
        {
            bool   help       = false;
            string playerName = string.Empty;
            string tribeName  = string.Empty;

            try
            {
                var p = new OptionSet
                {
                    { "?|help|h", v => help = true },
                    { "tribe=", v => tribeName = v.TrimMatchingQuotes() },
                    { "player=", v => playerName = v.TrimMatchingQuotes() },
                };
                p.Parse(parms);
            }
            catch (Exception)
            {
                help = true;
            }

            if (help || string.IsNullOrEmpty(playerName) || string.IsNullOrEmpty(tribeName))
            {
                return("TribesmanRemove --tribe=tribe_name --player=player_name");
            }

            uint playerId;

            if (!world.FindPlayerId(playerName, out playerId))
            {
                return("Player not found");
            }

            uint tribeId;

            if (!tribeManager.FindTribeId(tribeName, out tribeId))
            {
                return("Tribe not found");
            }

            Dictionary <uint, IPlayer> players;

            return(locker.Lock(out players, playerId, tribeId).Do(() =>
            {
                ITribe tribe = players[tribeId].Tribesman.Tribe;
                Error ret = tribe.RemoveTribesman(playerId, true);
                if (ret != Error.Ok)
                {
                    return Enum.GetName(typeof(Error), ret);
                }

                return "OK";
            }));
        }
Exemple #15
0
        public void Request(Session session, Packet packet)
        {
            string playerName;

            try
            {
                playerName = packet.GetString();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (session.Player.Tribesman == null)
            {
                ReplyError(session, packet, Error.TribeIsNull);
                return;
            }

            uint playerId;

            if (!world.FindPlayerId(playerName, out playerId))
            {
                ReplyError(session, packet, Error.PlayerNotFound);
                return;
            }

            Dictionary <uint, IPlayer> players;
            ITribe tribe = session.Player.Tribesman.Tribe;

            locker.Lock(out players, playerId, tribe.Owner.PlayerId).Do(() =>
            {
                if (!tribe.HasRight(session.Player.PlayerId, TribePermission.Invite))
                {
                    ReplyError(session, packet, Error.TribesmanNotAuthorized);
                    return;
                }
                if (players[playerId].Tribesman != null)
                {
                    ReplyError(session, packet, Error.TribesmanAlreadyInTribe);
                    return;
                }
                if (players[playerId].TribeRequest != 0)
                {
                    ReplyError(session, packet, Error.TribesmanPendingRequest);
                    return;
                }

                players[playerId].TribeRequest = tribe.Id;
                dbManager.Save(players[playerId]);
                ReplySuccess(session, packet);
            });
        }
Exemple #16
0
        public void DbLoaderAdd(ITribe tribe)
        {
            tribeIdGen.Set(tribe.Id);

            if (!Tribes.TryAdd(tribe.Id, tribe))
            {
                return;
            }

            SubscribeEvents(tribe);
        }
Exemple #17
0
        public void Add(ITribe tribe)
        {
            tribe.Id = tribeIdGen.GetNext();
            if (!Tribes.TryAdd(tribe.Id, tribe))
            {
                return;
            }

            dbManager.Save(tribe);

            SubscribeEvents(tribe);
        }
Exemple #18
0
        public void TribeFailedToTakeStronghold(IStronghold stronghold, ITribe attackingTribe)
        {
            switch (stronghold.StrongholdState)
            {
            case StrongholdState.Neutral:
                chat.SendSystemChat("STRONGHOLD_FAILED_NEUTRAL_TAKEOVER", stronghold.Name, attackingTribe.Name);
                break;

            case StrongholdState.Occupied:
                chat.SendSystemChat("STRONGHOLD_FAILED_OCCUPIED_TAKEOVER", stronghold.Name, attackingTribe.Name, stronghold.Tribe.Name);
                break;
            }
        }
Exemple #19
0
        private string Add(Session session, string[] parms)
        {
            bool   help       = false;
            string playerName = string.Empty;
            string tribeName  = string.Empty;

            try
            {
                var p = new OptionSet
                {
                    { "?|help|h", v => help = true },
                    { "tribe=", v => tribeName = v.TrimMatchingQuotes() },
                    { "player=", v => playerName = v.TrimMatchingQuotes() },
                };
                p.Parse(parms);
            }
            catch (Exception)
            {
                help = true;
            }

            if (help || string.IsNullOrEmpty(playerName) || string.IsNullOrEmpty(tribeName))
            {
                return("TribesmanAdd --tribe=tribe_name --player=player_name");
            }

            uint playerId;

            if (!world.FindPlayerId(playerName, out playerId))
            {
                return("Player not found");
            }

            uint tribeId;

            if (!tribeManager.FindTribeId(tribeName, out tribeId))
            {
                return("Tribe not found");
            }

            Dictionary <uint, IPlayer> players;

            locker.Lock(out players, playerId, tribeId).Do(() =>
            {
                ITribe tribe  = players[tribeId].Tribesman.Tribe;
                var tribesman = new Tribesman(tribe, players[playerId], tribe.DefaultRank);
                tribe.AddTribesman(tribesman, true);
            });

            return("OK");
        }
Exemple #20
0
        public void RemoveStrongholdsFromTribe(ITribe tribe)
        {
            foreach (var stronghold in StrongholdsForTribe(tribe))
            {
                stronghold.BeginUpdate();
                stronghold.StrongholdState = StrongholdState.Neutral;
                stronghold.Tribe           = null;
                stronghold.DateOccupied    = DateTime.MinValue;
                stronghold.BonusDays       = 0;
                stronghold.EndUpdate();
            }

            MarkIndexDirty();
        }
Exemple #21
0
        private void OnTribeChanged(object sender, SelectionChangedEventArgs e)
        {
            ITribe tribe = this.TribeComboBox.SelectedItem as ITribe;

            if (tribe == null || this.Tribe == tribe)
            {
                return;
            }

            this.Tribe            = tribe;
            this.Appearance.Tribe = this.Tribe.Tribe;

            this.UpdateRaceAndTribe();
        }
Exemple #22
0
        public void Transfer(Session session, Packet packet)
        {
            string newOwnerName;

            try
            {
                newOwnerName = packet.GetString();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (session.Player.Tribesman == null)
            {
                ReplyError(session, packet, Error.TribeIsNull);
                return;
            }

            uint newOwnerPlayerId;

            if (!world.FindPlayerId(newOwnerName, out newOwnerPlayerId))
            {
                ReplyError(session, packet, Error.PlayerNotFound);
                return;
            }

            Dictionary <uint, IPlayer> players;

            locker.Lock(out players, newOwnerPlayerId, session.Player.Tribesman.Tribe.Owner.PlayerId).Do(() =>
            {
                if (players == null)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                ITribe tribe = session.Player.Tribesman.Tribe;
                if (!tribe.IsOwner(session.Player))
                {
                    ReplyError(session, packet, Error.TribesmanNotAuthorized);
                    return;
                }

                var result = tribe.Transfer(newOwnerPlayerId);

                ReplyWithResult(session, packet, result);
            });
        }
Exemple #23
0
        public void Lock_TribeId_WhenTribeIsNotFound_ShouldReturnEmptyLockObject(
            [Frozen] IGameObjectLocator locator,
            ITribe tribe,
            DefaultLocker locker)
        {
            ITribe outTribe;

            locator.TryGetObjects(1, out outTribe).Returns(false);

            ITribe lockedTribe;
            var    multiObjLock = locker.Lock(1, out lockedTribe);

            lockedTribe.Should().BeNull();
            multiObjLock.Received(1)
            .Lock(Arg.Is <ILockable[]>(itemsLocked => !itemsLocked.Any()));
        }
Exemple #24
0
        private void Upgrade(Session session, Packet packet)
        {
            if (!session.Player.Tribesman.Tribe.HasRight(session.Player.PlayerId, TribePermission.Upgrade))
            {
                ReplyError(session, packet, Error.TribesmanNotAuthorized);
                return;
            }

            ITribe tribe = session.Player.Tribesman.Tribe;

            locker.Lock(tribe).Do(() =>
            {
                var result = tribe.Upgrade();
                ReplyWithResult(session, packet, result);
            });
        }
Exemple #25
0
        public void Add(params object[] objects)
        {
            foreach (var o in objects)
            {
                ICity city = o as ICity;
                if (city != null)
                {
                    cities.Add(city.Id, city);
                }

                IPlayer player = o as IPlayer;
                if (player != null)
                {
                    players.Add(player.PlayerId, player);
                }

                ITribe tribe = o as ITribe;
                if (tribe != null)
                {
                    tribes.Add(tribe.Id, tribe);
                }

                IBattleManager battle = o as IBattleManager;
                if (battle != null)
                {
                    battles.Add(battle.BattleId, battle);
                }

                IStronghold stronghold = o as IStronghold;
                if (stronghold != null)
                {
                    strongholds.Add(stronghold.ObjectId, stronghold);
                }

                IBarbarianTribe barbarianTribe = o as IBarbarianTribe;
                if (barbarianTribe != null)
                {
                    barbarianTribes.Add(barbarianTribe.ObjectId, barbarianTribe);
                }

                IGameObject gameObject = o as IGameObject;
                if (gameObject != null)
                {
                    gameObjects.Add(new Tuple <uint, uint>(gameObject.GroupId, gameObject.ObjectId), gameObject);
                }
            }
        }
Exemple #26
0
        private void RemoveTroop(Session session, Packet packet)
        {
            int    assignmentId;
            uint   cityId;
            ushort stubId;

            try
            {
                assignmentId = packet.GetInt32();
                cityId       = packet.GetUInt32();
                stubId       = packet.GetUInt16();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (!session.Player.IsInTribe)
            {
                ReplyError(session, packet, Error.TribesmanNotPartOfTribe);
                return;
            }

            ITribe tribe = session.Player.Tribesman.Tribe;

            locker.Lock(session.Player, tribe).Do(() =>
            {
                var city = session.Player.GetCity(cityId);
                if (city == null)
                {
                    ReplyError(session, packet, Error.CityNotFound);
                    return;
                }

                ITroopStub stub;
                if (!city.Troops.TryGetStub(stubId, out stub))
                {
                    ReplyError(session, packet, Error.ObjectNotFound);
                    return;
                }

                Error result = tribe.RemoveFromAssignment(assignmentId, session.Player, stub);
                ReplyWithResult(session, packet, result);
            });
        }
Exemple #27
0
        public void TransferTo(IStronghold stronghold, ITribe tribe)
        {
            if (tribe == null)
            {
                return;
            }

            ITribe oldTribe = stronghold.Tribe;

            stronghold.BeginUpdate();
            if (stronghold.StrongholdState == StrongholdState.Occupied)
            {
                stronghold.BonusDays = ((decimal)SystemClock.Now.Subtract(stronghold.DateOccupied).TotalDays + stronghold.BonusDays) * .75m;
            }

            stronghold.StrongholdState = StrongholdState.Occupied;
            stronghold.Tribe           = tribe;
            stronghold.GateOpenTo      = null;
            stronghold.GateMax         = (int)formula.StrongholdGateLimit(stronghold.Lvl);
            stronghold.Gate            = stronghold.GateMax;
            stronghold.DateOccupied    = DateTime.UtcNow;
            stronghold.EndUpdate();
            MarkIndexDirty();

            RetreatUnits(stronghold);

            if (oldTribe != null)
            {
                chat.SendSystemChat("STRONGHOLD_TAKEN_OVER", stronghold.Name, tribe.Name, oldTribe.Name);
                StrongholdGained.Raise(this, new StrongholdGainedEventArgs {
                    Tribe = tribe, OwnBy = oldTribe, Stronghold = stronghold
                });
                StrongholdLost.Raise(this, new StrongholdLostEventArgs {
                    Tribe = oldTribe, AttackedBy = tribe, Stronghold = stronghold
                });
                oldTribe.SendUpdate();
            }
            else
            {
                chat.SendSystemChat("STRONGHOLD_NEUTRAL_TAKEN_OVER", stronghold.Name, tribe.Name);
                StrongholdGained.Raise(this, new StrongholdGainedEventArgs {
                    Tribe = tribe, Stronghold = stronghold
                });
            }
        }
Exemple #28
0
        public void SetRank(Session session, Packet packet)
        {
            uint playerId;
            byte rank;

            try
            {
                playerId = packet.GetUInt32();
                rank     = packet.GetByte();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            if (session.Player.Tribesman == null)
            {
                ReplyError(session, packet, Error.TribeIsNull);
                return;
            }

            Dictionary <uint, IPlayer> players;

            locker.Lock(out players, playerId, session.Player.Tribesman.Tribe.Owner.PlayerId).Do(() =>
            {
                ITribe tribe = session.Player.Tribesman.Tribe;
                if (!tribe.HasRight(session.Player.PlayerId, TribePermission.SetRank))
                {
                    ReplyError(session, packet, Error.TribesmanNotAuthorized);
                    return;
                }

                var error = tribe.SetRank(playerId, rank);
                if (error == Error.Ok)
                {
                    ReplySuccess(session, packet);
                }
                else
                {
                    ReplyError(session, packet, error);
                }
            });
        }
Exemple #29
0
        /// <summary>
        ///     Creates a new assignment.
        ///     NOTE: This constructor is used by the db loader. Use the other constructor when creating a new assignment from scratch.
        /// </summary>
        public Assignment(int id,
                          ITribe tribe,
                          uint x,
                          uint y,
                          ILocation target,
                          AttackMode mode,
                          DateTime targetTime,
                          uint dispatchCount,
                          string description,
                          bool isAttack,
                          Formula formula,
                          IDbManager dbManager,
                          IGameObjectLocator gameObjectLocator,
                          IScheduler scheduler,
                          Procedure procedure,
                          ITileLocator tileLocator,
                          IActionFactory actionFactory,
                          ILocker locker,
                          ITroopObjectInitializerFactory troopObjectInitializerFactory)
        {
            this.formula                       = formula;
            this.dbManager                     = dbManager;
            this.gameObjectLocator             = gameObjectLocator;
            this.scheduler                     = scheduler;
            this.procedure                     = procedure;
            this.tileLocator                   = tileLocator;
            this.actionFactory                 = actionFactory;
            this.locker                        = locker;
            this.troopObjectInitializerFactory = troopObjectInitializerFactory;

            Id            = id;
            Tribe         = tribe;
            TargetTime    = targetTime;
            Target        = target;
            X             = x;
            Y             = y;
            AttackMode    = mode;
            DispatchCount = dispatchCount;
            Description   = description;
            IsAttack      = isAttack;

            IdGen.Set((uint)id);
        }
Exemple #30
0
        public void Lock_TribeId_WhenTribeIsFound_ShouldReturnLockedTribe(
            [Frozen] IGameObjectLocator locator,
            ITribe tribe,
            DefaultLocker locker)
        {
            ITribe outTribe;

            locator.TryGetObjects(1, out outTribe).Returns(call =>
            {
                call[1] = tribe;
                return(true);
            });

            ITribe lockedTribe;
            var    multiObjLock = locker.Lock(1, out lockedTribe);

            lockedTribe.Should().Be(tribe);
            multiObjLock.Received(1)
            .Lock(Arg.Is <ILockable[]>(itemsLocked => itemsLocked.SequenceEqual(new[] { tribe })));
        }