public override void Callback(object custom) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!city.TryGetStructure(structureId, out structure)) { StateChange(ActionState.Failed); return; } structure.City.BeginUpdate(); structure.BeginUpdate(); structureCsvFactory.GetUpgradedStructure(structure, structure.Type, (byte)(structure.Lvl + 1)); procedure.OnStructureUpgradeDowngrade(structure); structure.EndUpdate(); structure.City.EndUpdate(); callbackProcedure.OnStructureUpgrade(structure); StateChange(ActionState.Completed); }); }
private void InterruptCatchAll(bool wasKilled) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!city.TryGetStructure(structureId, out structure)) { StateChange(ActionState.Failed); return; } if (!wasKilled) { city.BeginUpdate(); city.Resource.Add(formula.GetActionCancelResource(BeginTime, resource)); city.EndUpdate(); } StateChange(ActionState.Failed); }); }
private void InterruptCatchAll(bool wasKilled) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!city.TryGetStructure(structureId, out structure)) { StateChange(ActionState.Failed); return; } if (!wasKilled) { RefundResource(city); } StateChange(ActionState.Failed); }); }
private void ApplyThemeToAll(Session session, Packet packet) { uint cityId; string itemId; bool applyWall; try { cityId = packet.GetUInt32(); itemId = packet.GetString(); applyWall = packet.GetBoolean(); } catch (Exception) { ReplyError(session, packet, Error.Unexpected); return; } locker.Lock(session.Player).Do(() => { var city = session.Player.GetCity(cityId); if (city == null) { ReplyError(session, packet, Error.CityNotFound); return; } var result = themeManager.ApplyToAll(city, itemId, applyWall); ReplyWithResult(session, packet, result); }); }
private void StoreThemePurchased(dynamic payload) { uint playerId; string themeId; try { playerId = (uint)payload.player_id; themeId = (string)payload.theme_id; } catch (Exception e) { logger.Error(e, "Failed to process AddCoins"); return; } IPlayer player; locker.Lock(playerId, out player).Do(() => { if (player == null) { return; } player.AddTheme(themeId); }); }
private void MarketBuy(Session session, Packet packet) { uint cityId; uint objectId; ResourceType type; ushort quantity; ushort price; try { cityId = packet.GetUInt32(); objectId = packet.GetUInt32(); type = (ResourceType)packet.GetByte(); quantity = packet.GetUInt16(); price = packet.GetUInt16(); } catch (Exception) { ReplyError(session, packet, Error.Unexpected); return; } locker.Lock(session.Player).Do(() => { ICity city = session.Player.GetCity(cityId); if (city == null) { ReplyError(session, packet, Error.Unexpected); return; } IStructure obj; if (!city.TryGetStructure(objectId, out obj)) { ReplyError(session, packet, Error.Unexpected); return; } if (obj != null) { var rba = actionFactory.CreateResourceBuyActiveAction(cityId, objectId, price, quantity, type); Error ret = city.Worker.DoActive(structureCsvFactory.GetActionWorkerType(obj), obj, rba, obj.Technologies); if (ret == 0) { ReplySuccess(session, packet); } else { ReplyError(session, packet, ret); } return; } ReplyError(session, packet, Error.Unexpected); }); }
public string CreateCity(Session session, String[] parms) { bool help = false; string cityName = string.Empty; string playerName = string.Empty; uint x = 0; uint y = 0; try { var p = new OptionSet { { "?|help|h", v => help = true }, { "newcity=", v => cityName = v.TrimMatchingQuotes() }, { "player=", v => playerName = v.TrimMatchingQuotes() }, { "x=", v => x = uint.Parse(v.TrimMatchingQuotes()) }, { "y=", v => y = uint.Parse(v.TrimMatchingQuotes()) }, }; p.Parse(parms); } catch (Exception) { help = true; } if (help || cityName == string.Empty) { return("createcity --player=### --newcity=### --x=#### --y=####"); } uint playerId; if (!world.FindPlayerId(playerName, out playerId)) { return("Player not found"); } IPlayer player; return(locker.Lock(playerId, out player).Do(() => { { if (player == null) { return "Player not found"; } ICity city = player.GetCityList().First(); var cityCreateAction = actionFactory.CreateCityCreatePassiveAction(city.Id, x, y, cityName); Error ret = city.Worker.DoPassive(city[1], cityCreateAction, true); if (ret != Error.Ok) { return string.Format("Error: {0}", ret); } } return "OK!"; })); }
private void ProfileByType(Session session, Packet packet) { var reply = new Packet(packet); string type; uint id; try { type = packet.GetString().ToLowerInvariant(); id = packet.GetUInt32(); } catch (Exception) { ReplyError(session, packet, Error.Unexpected); return; } if (type == "city") { ICity city; locker.Lock(id, out city).Do(() => { if (city == null) { ReplyError(session, reply, Error.PlayerNotFound); return; } PacketHelper.AddPlayerProfileToPacket(city.Owner, reply); session.Write(reply); }); return; } if (type == "stronghold") { IStronghold stronghold; locker.Lock(id, out stronghold).Do(() => { if (stronghold == null || stronghold.StrongholdState == StrongholdState.Inactive) { ReplyError(session, reply, Error.ObjectNotFound); return; } PacketHelper.AddStrongholdProfileToPacket(session, stronghold, reply); session.Write(reply); }); return; } ReplyError(session, packet, Error.Unexpected); }
private string RankUpdate(Session session, string[] parms) { bool help = false; string tribeName = string.Empty; string rank = string.Empty; string name = string.Empty; string permission = string.Empty; try { var p = new OptionSet { { "?|help|h", v => help = true }, { "tribe=", v => tribeName = v.TrimMatchingQuotes() }, { "rank=", v => rank = v.TrimMatchingQuotes() }, { "name=", v => name = v.TrimMatchingQuotes() }, { "permission=", v => permission = v.TrimMatchingQuotes() }, }; p.Parse(parms); } catch (Exception) { help = true; } if (help || string.IsNullOrEmpty(tribeName) || string.IsNullOrEmpty(rank)) { var str = Enum.GetNames(typeof(TribePermission)).Aggregate((s, s1) => s + "," + s1); return("TribeRankUpdate --rank=rank_id --tribe=tribe_name [--name=rank_name] [--Permission=Permission(" + str + ")]"); } uint tribeId; if (!tribeManager.FindTribeId(tribeName, out tribeId)) { return("Tribe not found"); } ITribe tribe; return(locker.Lock(tribeId, out tribe).Do(() => { ITribeRank tribeRank = tribe.Ranks.First(x => x.Id == byte.Parse(rank)); if (tribeRank == null) { return "Rank not found"; } tribe.UpdateRank(tribeRank.Id, name == string.Empty ? tribeRank.Name : name, permission == string.Empty ? tribeRank.Permission : (TribePermission)Enum.Parse(typeof(TribePermission), permission, true)); return "OK"; })); }
public override void WorkerRemoved(bool wasKilled) { ICity city; locker.Lock(newCityId, out city).Do(() => { CityRemover remover = cityRemoverFactory.CreateCityRemover(newCityId); remover.Start(); StateChange(ActionState.Failed); }); }
public string SendResources(Session session, string[] parms) { var resource = new Resource(); string cityName = string.Empty; bool help = false; try { var p = new OptionSet { { "?|help|h", v => help = true }, { "city=", v => cityName = v.TrimMatchingQuotes() }, { "crop=", v => resource.Crop = int.Parse(v) }, { "wood=", v => resource.Wood = int.Parse(v) }, { "labor=", v => resource.Labor = int.Parse(v) }, { "iron=", v => resource.Iron = int.Parse(v) }, { "gold=", v => resource.Gold = int.Parse(v) }, }; p.Parse(parms); } catch (Exception) { help = true; } if (help || string.IsNullOrEmpty(cityName)) { return("sendresources --city=city [--crop=###] [--wood=###] [--iron=###] [--labor=###] [--gold=###]"); } uint cityId; if (!world.Cities.FindCityId(cityName, out cityId)) { return("City not found"); } ICity city; return(locker.Lock(cityId, out city).Do(() => { if (city == null) { return "City not found"; } city.BeginUpdate(); city.Resource.Add(resource); city.EndUpdate(); return "OK!"; })); }
public override void Callback(object custom) { ICity city; IStructure structure; // Block structure var isOk = locker.Lock(cityId, objectId, out city, out structure).Do(() => { if (!IsValid()) { return(false); } if (structure.CheckBlocked(ActionId)) { StateChange(ActionState.Failed); return(false); } structure.BeginUpdate(); structure.IsBlocked = ActionId; structure.EndUpdate(); return(true); }); if (!isOk) { return; } structure.City.Worker.Remove(structure, new GameAction[] { this }); locker.Lock(cityId, objectId, out city, out structure).Do(() => { if (!IsValid()) { return; } if (structure == null) { logger.Warn("StructureChange did not find structure"); StateChange(ActionState.Completed); return; } procedure.StructureChange(structure, type, lvl, callbackProcedure, structureCsvFactory); StateChange(ActionState.Completed); }); }
public override void Callback(object custom) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!city.TryGetStructure(structureId, out structure)) { StateChange(ActionState.Failed); return; } if (unitFactory.GetName(type, 1) == null) { StateChange(ActionState.Failed); return; } structure.City.DefaultTroop.BeginUpdate(); structure.City.DefaultTroop.AddUnit(city.HideNewUnits ? FormationType.Garrison : FormationType.Normal, type, 1); structure.City.DefaultTroop.EndUpdate(); --ActionCount; if (ActionCount == 0) { StateChange(ActionState.Completed); return; } var template = structure.City.Template[type]; if (template == null) { StateChange(ActionState.Completed); return; } var unitStats = unitFactory.GetUnitStats(type, template.Lvl); var timePerUnit = CalculateTime(formula.TrainTime(structure.Lvl, 1, unitStats)); var timeUntilComplete = CalculateTime(formula.TrainTime(structure.Lvl, ActionCount, unitStats)); nextTime = SystemClock.Now.AddSeconds(timePerUnit); endTime = SystemClock.Now.AddSeconds(timeUntilComplete); StateChange(ActionState.Rescheduled); }); }
public override void WorkerRemoved(bool wasKilled) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } StateChange(ActionState.Failed); }); }
public override void Callback(object custom) { ICity city; IStructure structure; locker.Lock(cityId, objectId, out city, out structure).Do(() => { if (!IsValid()) { return; } StateChange(ActionState.Completed); }); }
public void Callback(object custom) { locker.Lock(forestManager.CallbackLockHandler, new object[] { Forest.ObjectId }) .Do(() => { logger.Debug(string.Format("Destroying forest[{0}]", Forest.ObjectId)); var camps = new List <IStructure>(Forest); if (!Forest.InWorld) { logger.Warn("Trying to remove forest that isnt even in the world"); } foreach (var obj in camps) { Forest.BeginUpdate(); Forest.RemoveLumberjack(obj); Forest.EndUpdate(); obj.City.Owner.SendSystemMessage(null, string.Format("{0}: Forest depleted", obj.City.Name), string.Format("{0}: One of your lumbermill outposts have finished gathering wood from a forest. All laborers have returned to your city and are now idle.", obj.City.Name)); // Remove structure from city obj.BeginUpdate(); regionManager.Remove(obj); obj.City.ScheduleRemove(obj, false, true); obj.EndUpdate(); } forestManager.RemoveForest(Forest); }); }
public LockerWrapper(ILocker locker, Action onBeginLock, Action onEndLock) { _locker = locker; _onEndLock = onEndLock; _locker.Lock(); onBeginLock(); }
public void Callback(object custom) { foreach (IStronghold stronghold in strongholdManager.Where(s => s.StrongholdState == StrongholdState.Inactive && strongholdActivationCondition.ShouldActivate(s))) { locker.Lock(stronghold).Do(() => strongholdManager.Activate(stronghold)); } // Activate stronghold with highest score if there are no neutral strongholds var lastNeutralActivationTimeVar = systemVariableManager["Stronghold.neutral_check"]; var lastNeutralActivationTime = (DateTime)lastNeutralActivationTimeVar.Value; if (SystemClock.Now.Subtract(lastNeutralActivationTime).TotalHours >= 8) { if (strongholdManager.All(s => s.StrongholdState != StrongholdState.Neutral)) { var mapCenter = new Position(Config.map_width / 2, Config.map_height / 2); var stronghold = strongholdManager.Where(s => s.StrongholdState == StrongholdState.Inactive && s.NearbyCitiesCount > 0) .OrderByDescending(s => strongholdActivationCondition.Score(s)) .ThenBy(s => tileLocator.TileDistance(s.PrimaryPosition, 1, mapCenter, 1)) .FirstOrDefault(); // Do the same check for a SH but w/o nearby cities restriction if (stronghold == null) { stronghold = strongholdManager.Where(s => s.StrongholdState == StrongholdState.Inactive) .OrderByDescending(s => strongholdActivationCondition.Score(s)) .ThenBy(s => tileLocator.TileDistance(s.PrimaryPosition, 1, mapCenter, 1)) .FirstOrDefault(); } if (stronghold != null) { locker.Lock(stronghold).Do(() => strongholdManager.Activate(stronghold)); } } using (dbManager.GetThreadTransaction()) { lastNeutralActivationTimeVar.Value = SystemClock.Now; dbManager.Save(lastNeutralActivationTimeVar); } } Time = DateTime.UtcNow.Add(TimeSpan); scheduler.Put(this); }
private void InterruptCatchAll(bool wasKilled) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!city.TryGetStructure(structureId, out structure)) { StateChange(ActionState.Failed); return; } if (!wasKilled) { city.BeginUpdate(); Resource resource = new Resource(); switch (resourceType) { case ResourceType.Crop: resource = new Resource(quantity, 0, 0, 0, 0); Market.Crop.Consume(quantity); break; case ResourceType.Wood: resource = new Resource(0, 0, 0, quantity, 0); Market.Wood.Consume(quantity); break; case ResourceType.Iron: resource = new Resource(0, 0, quantity, 0, 0); Market.Iron.Consume(quantity); break; } city.Resource.Add(formula.GetActionCancelResource(BeginTime, resource)); city.EndUpdate(); } StateChange(ActionState.Failed); }); }
private void AfterTroopMoved(ActionState state) { if (state == ActionState.Completed) { ICity city; ICity targetCity; ITroopObject troopObject; if (!gameObjectLocator.TryGetObjects(cityId, troopObjectId, out city, out troopObject)) { throw new Exception("City or troop object is missing"); } if (!gameObjectLocator.TryGetObjects(targetCityId, out targetCity)) { //If the target is missing, walk back locker.Lock(city).Do(() => { TroopMovePassiveAction tma = actionFactory.CreateTroopMovePassiveAction(city.Id, troopObject.ObjectId, city.PrimaryPosition.X, city.PrimaryPosition.Y, true, true); ExecuteChainAndWait(tma, AfterTroopMovedHome); }); return; } // Get all of the stationed city id's from the target city since they will be used by the engage attack action CallbackLock.CallbackLockHandler lockAllStationed = delegate { return(targetCity.Troops.StationedHere() .Select(stationedStub => stationedStub.City) .Cast <ILockable>() .ToArray()); }; locker.Lock(lockAllStationed, null, city, targetCity).Do(() => { var bea = actionFactory.CreateCityEngageAttackPassiveAction(cityId, troopObject.ObjectId, targetCityId); ExecuteChainAndWait(bea, AfterBattle); }); } }
private void AfterTroopMoved(ActionState state) { if (state == ActionState.Completed) { ICity city; locker.Lock(cityId, out city).Do(() => { ITroopObject troopObject; if (!city.TryGetTroop(troopObjectId, out troopObject)) { throw new Exception(); } city.Notifications.Remove(this); if (city.Battle == null) { city.References.Remove(troopObject, this); procedure.TroopObjectDelete(troopObject, true); StateChange(ActionState.Completed); } else { var eda = actionFactory.CreateCityEngageDefensePassiveAction(cityId, troopObjectId, FormationType.Defense); ExecuteChainAndWait(eda, AfterEngageDefense); } }); return; } if (state == ActionState.Failed) { ICity city; locker.Lock(cityId, out city).Do(() => { ITroopObject troopObject; if (!city.TryGetTroop(troopObjectId, out troopObject)) { throw new Exception(); } procedure.TroopObjectStation(troopObject, city); }); } }
private string CmdStrongholdFindNearbyCities(Session session, string[] parms) { var list = new List <Position>(mapFactory.Locations.Take(mapFactory.Index)); foreach (var stronghold in strongholdManager.Where(s => s.StrongholdState == StrongholdState.Inactive)) { locker.Lock(stronghold).Do(() => { stronghold.BeginUpdate(); int count = list.Count(pt => tileLocator.TileDistance(stronghold.PrimaryPosition, 3, pt, 1) <= Config.stronghold_radius_base + Config.stronghold_radius_per_level * stronghold.Lvl); stronghold.NearbyCitiesCount = (ushort)count; stronghold.EndUpdate(); }); } return("OK"); }
public void NewMessage(PlayerUnreadCount playerUnreadCount) { IPlayer player; locker.Lock((uint)playerUnreadCount.Id, out player).Do(() => { if (player.Session == null) { return; } try { protocolFactory.CreateProtocol(player.Session).MessageSendUnreadCount(playerUnreadCount.UnreadCount); } catch { } }); }
public void Remove(IGameObject workerObject, params GameAction[] ignoreActions) { var ignoreActionList = new List <GameAction>(ignoreActions); // Cancel Active actions IList <ActiveAction> activeList = null; locker.Lock(LockDelegate()).Do(() => { // Very important to keep the ToList() here since we will be modifying the collection in the loop below and an IEnumerable will crash! activeList = active.Values.Where(actionStub => actionStub.WorkerObject == workerObject).ToList(); }); foreach (var stub in activeList) { if (ignoreActionList.Contains(stub)) { continue; } stub.WorkerRemoved(false); } // Cancel Passive actions IList <PassiveAction> passiveList = null; locker.Lock(LockDelegate()).Do(() => { // Very important to keep the ToList() here since we will be modifying the collection in the loop below and an IEnumerable will crash! passiveList = passive.Values.Where(action => action.WorkerObject == workerObject).ToList(); }); foreach (var stub in passiveList) { if (ignoreActionList.Contains(stub)) { continue; } stub.WorkerRemoved(false); } ActionsRemovedFromWorker(workerObject); }
private void InterruptCatchAll(bool wasKilled) { ICity city; locker.Lock(cityId, out city).Do(() => { if (!IsValid()) { return; } IStructure structure; if (!world.TryGetObjects(cityId, structureId, out city, out structure)) { return; } Technology tech; TechnologyBase techBase; if (structure.Technologies.TryGetTechnology(techId, out tech)) { techBase = technologyFactory.GetTechnologyBase(tech.Type, (byte)(tech.Level + 1)); } else { techBase = technologyFactory.GetTechnologyBase(techId, 1); } if (techBase == null) { StateChange(ActionState.Failed); return; } if (!wasKilled) { city.BeginUpdate(); city.Resource.Add(formula.GetActionCancelResource(BeginTime, techBase.Resources)); city.EndUpdate(); } StateChange(ActionState.Failed); }); }
private void CreateCity(Session session, Packet packet) { uint cityId; uint x; uint y; string cityName; try { cityId = packet.GetUInt32(); x = packet.GetUInt32(); y = packet.GetUInt32(); cityName = packet.GetString(); } catch (Exception) { ReplyError(session, packet, Error.Unexpected); return; } locker.Lock(session.Player).Do(() => { ICity city = session.Player.GetCity(cityId); if (city == null) { ReplyError(session, packet, Error.Unexpected); return; } var cityCreateAction = actionFactory.CreateCityCreatePassiveAction(cityId, x, y, cityName); Error ret = city.Worker.DoPassive(city[1], cityCreateAction, true); if (ret != 0) { ReplyError(session, packet, ret); } else { ReplySuccess(session, packet); } }); }
public override void Callback(object custom) { ICity city; if (!world.TryGetObjects(cityId, out city)) { throw new Exception("City is missing"); } locker.Lock(forestManager.CallbackLockHandler, new object[] { forestId }, city).Do(() => { if (!IsValid()) { return; } endTime = DateTime.UtcNow.AddSeconds(30); StateChange(ActionState.Rescheduled); }); }
public override void WorkerRemoved(bool wasKilled) { locker.Lock(structure.City).Do(() => { if (!IsValid()) { return; } StateChange(ActionState.Failed); }); }
public override void Callback(object custom) { IBarbarianTribe barbarianTribe; if (!gameObjectLocator.TryGetObjects(barbarianTribeId, out barbarianTribe)) { throw new Exception("Barb tribe is missing"); } CallbackLock.CallbackLockHandler lockHandler = delegate { var toBeLocked = new List <ILockable>(); toBeLocked.AddRange(barbarianTribe.Battle.LockList); toBeLocked.Add(barbarianTribe); return(toBeLocked.ToArray()); }; locker.Lock(lockHandler, null, barbarianTribe).Do(() => { if (barbarianTribe.Battle.ExecuteTurn()) { // Battle continues, just save it and reschedule dbManager.Save(barbarianTribe.Battle); endTime = SystemClock.Now.AddSeconds(formula.GetBattleInterval(barbarianTribe.Battle.Defenders, barbarianTribe.Battle.Attackers)); StateChange(ActionState.Fired); return; } // Battle has ended // Delete the battle world.Remove(barbarianTribe.Battle); dbManager.Delete(barbarianTribe.Battle); barbarianTribe.BeginUpdate(); barbarianTribe.Battle = null; barbarianTribe.State = GameObjectStateFactory.NormalState(); var initialBarbResources = formula.BarbarianTribeResources(barbarianTribe); if (!initialBarbResources.Equals(barbarianTribe.Resource)) { // Lower camps remaining barbarianTribe.CampRemains--; // Reset resources barbarianTribe.Resource.Clear(); barbarianTribe.Resource.Add(formula.BarbarianTribeResources(barbarianTribe)); } barbarianTribe.EndUpdate(); StateChange(ActionState.Completed); }); }
private void ListAll(Session session, Packet packet) { locker.Lock(session.Player).Do(() => { if (!session.Player.IsInTribe) { ReplyError(session, packet, Error.TribesmanNotPartOfTribe); return; } var reply = new Packet(packet); var strongholds = strongholdManager.StrongholdsForTribe(session.Player.Tribesman.Tribe).ToList(); reply.AddInt16((short)strongholds.Count); foreach (var stronghold in strongholds) { reply.AddUInt32(stronghold.ObjectId); reply.AddString(stronghold.Name); reply.AddByte(stronghold.Lvl); reply.AddUInt32(stronghold.PrimaryPosition.X); reply.AddUInt32(stronghold.PrimaryPosition.Y); } session.Write(reply); }); }