public static void Prefix(Rect rect, List <ListableOption> optList) { //File.WriteAllText(Loger.PathLog + @"optList.txt", DevelopTest.TextObj(optList), Encoding.UTF8); if (optList.Count > 0 && optList[0].GetType() == typeof(ListableOption)) { if (Current.ProgramState == ProgramState.Entry) { var item = new ListableOption("OCity_LAN_btn".Translate(), delegate { MainMenu.OnMainMenuNetClick(); }, null); optList.Insert(0, item); } else { if (SessionClient.Get.IsLogined) { for (int i = 0; i < optList.Count; i++) { if (optList[i].label == "Save".Translate() || optList[i].label == "LoadGame".Translate() || optList[i].label == "ReviewScenario".Translate() || optList[i].label == "SaveAndQuitToMainMenu".Translate() || optList[i].label == "SaveAndQuitToOS".Translate() || optList[i].label == "ConfirmQuit".Translate() || optList[i].label == "QuitToMainMenu".Translate() || optList[i].label == "QuitToOS".Translate()) { optList.RemoveAt(i--); } } var item = new ListableOption("QuitToMainMenu".Translate(), delegate { if (GameExit.BeforeExit != null) { GameExit.BeforeExit(); } GenScene.GoToMainMenu(); }, null); optList.Add(item); item = new ListableOption("QuitToOS".Translate(), delegate { if (GameExit.BeforeExit != null) { GameExit.BeforeExit(); } Root.Shutdown(); }, null); optList.Add(item); } } } if (Inited) { return; } Inited = true; SessionClientController.Init(); }
public void Load() { var connect = SessionClient.Get; var serverInfo = connect.GetInfo(ServerInfoType.Full); SessionClientController.SetFullInfo(serverInfo); Init(); }
public static void MailProcessAttackCancel(ModelMailTrade mail) { Loger.Log("Client MailProcessAttackCancel"); GameAttackTrigger_Patch.ForceSpeed = -1f; //на всякий случай if (SessionClientController.Data.AttackModule != null) { SessionClientController.Data.AttackModule.Clear(); } if (SessionClientController.Data.AttackUsModule != null) { SessionClientController.Data.AttackUsModule.Clear(); } SessionClientController.Disconnected("OCity_GameAttacker_Dialog_ErrorMessage".Translate()); }
private void CannalAdd() { var form = new Dialog_Input("OCity_Dialog_ChennelCreating".Translate(), "OCity_Dialog_ChennelCreateName".Translate(), ""); form.PostCloseAction = () => { if (form.ResultOK && !string.IsNullOrEmpty(form.InputText) && form.InputText.Replace(" ", "") != "") { var mainCannal = SessionClientController.Data.Chats[0]; SessionClientController.Command((connect) => { connect.PostingChat(mainCannal.Id, "/createChat '" + form.InputText.Replace("'", "''") + "'"); }); //to do Сделать старт крутяшки до обновления чата } }; Find.WindowStack.Add(form); }
private void CannalDelete() { var form = new Dialog_Input("OCity_Dialog_ChennelQuit".Translate(), "OCity_Dialog_ChennelQuitCheck".Translate()); form.PostCloseAction = () => { if (form.ResultOK) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; SessionClientController.Command((connect) => { connect.PostingChat(selectCannal.Id, "/exitChat"); }); //to do Сделать старт крутяшки до обновления чата } }; Find.WindowStack.Add(form); }
private void CannalRename() { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; var form = new Dialog_Input("OCity_Dialog_ChennelRenLabel".Translate(), "OCity_Dialog_ChennelNewName".Translate() + selectCannal.Name, ""); form.PostCloseAction = () => { if (form.ResultOK && form.InputText != null) { SessionClientController.Command((connect) => { connect.PostingChat(selectCannal.Id, "/renameChat '" + form.InputText.Replace("'", "''") + "'"); }); //to do Сделать старт крутяшки до обновления чата } }; Find.WindowStack.Add(form); }
public static void MailProcessDeleteByServerId(ModelMailTrade mail) { Loger.Log("Client MailProcessDeleteByServerId " + mail.PlaceServerId); if (mail.PlaceServerId <= 0) { Loger.Log("Mail fail: no data"); return; } var place = GetPlace(mail, false, true); if (place != null) { Find.WorldObjects.Remove(place); //автосейв с единым сохранением SessionClientController.SaveGameNow(true); } }
public static void MailProcessStartIncident(ModelMail incoming) { Loger.Log("IncidentLod MailController.MailProcessStartIncident 1"); var mail = (ModelMailStartIncident)incoming; Find.TickManager.Pause(); var incident = new Incidents().GetIncident(mail.IncidentType); incident.mult = mail.IncidentMult; incident.arrivalMode = mail.IncidentArrivalMode; incident.strategy = mail.IncidentStrategy; incident.faction = mail.IncidentFaction; incident.attacker = mail.From.Login; incident.place = GetPlace(mail); incident.TryExecuteEvent(); if (!SessionClientController.Data.BackgroundSaveGameOff) { SessionClientController.SaveGameNow(true); } Loger.Log("IncidentLod MailController.MailProcessStartIncident 2"); }
public void DoTab0Contents(Rect inRect) { var iconWidth = 25f; var iconWidthSpase = 30f; //StatusTemp = Text.CalcSize("VersionLabel").y.ToString(); //Widgets.Label(new Rect(inRect.width - 100f, inRect.height - 30f, inRect.width, inRect.height), StatusTemp + " " + lbCannalsLastSelectedIndex.ToString()); /// ----------------------------------------------------------------------------------------- /// Список каналов /// if (SessionClientController.Data.Chats != null) { //Loger.Log("Client " + SessionClientController.Data.Chats.Count); if (lbCannalsHeight == 0) { var textHeight = new DialogControlBase().TextHeight; lbCannalsHeight = (float)Math.Round((decimal)(inRect.height / 2f / textHeight)) * textHeight; } Widgets.Label(new Rect(inRect.x, inRect.y + iconWidthSpase + lbCannalsHeight, 100f, 22f), "OCity_Dialog_Players".Translate()); if (lbCannals == null) { //первый запуск lbCannals = new ListBox <string>(); lbCannals.Area = new Rect(inRect.x , inRect.y + iconWidthSpase , 100f , lbCannalsHeight); //lbCannals.OnClick += (index, text) => StatusTemp = text; lbCannals.SelectedIndex = 0; } if (lbPlayers == null) { //первый запуск lbPlayers = new ListBox <ListBoxPlayerItem>(); lbPlayers.Area = new Rect(inRect.x , inRect.y + iconWidthSpase + lbCannalsHeight + 22f , 100f , inRect.height - (iconWidthSpase + lbCannalsHeight + 22f)); lbPlayers.OnClick += (index, item) => { //убираем выделение lbPlayers.SelectedIndex = -1; //вызываем контекстное меню PlayerItemMenu(item); }; lbPlayers.Tooltip = (item) => item.Tooltip; } if (DataLastChatsTime != SessionClientController.Data.ChatsTime) { //пишем в лог var updateLogHash = SessionClientController.Data.Chats.Count * 1000000 + SessionClientController.Data.Chats.Sum(c => c.Posts.Count); if (updateLogHash != UpdateLogHash) { UpdateLogHash = updateLogHash; Loger.Log("Client UpdateChats count=" + SessionClientController.Data.Chats.Count.ToString() + " posts=" + (updateLogHash % 1000000).ToString() + " - " + SessionClientController.Data.ChatsTime.ToString(Loger.Culture)); } //устанавливаем данные lbCannals.DataSource = SessionClientController.Data.Chats //.OrderBy(c => (c.OwnerMaker ? "2" : "1") + c.Name) нелья просто отсортировать, т.к. потом находим по индексу .Select(c => c.Name) .ToList(); if (lbCannalsGoToChat != null) { var lbCannalsGoToChatIndex = lbCannals.DataSource.IndexOf(lbCannalsGoToChat); if (lbCannalsGoToChatIndex >= 0) { lbCannals.SelectedIndex = lbCannalsGoToChatIndex; lbCannalsGoToChat = null; } } var listPlayersInChat = new List <string>(); if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; listPlayersInChat = selectCannal.PartyLogin; lbPlayers.DataSource = listPlayersInChat .Where(p => p != "system") .OrderBy(p => (selectCannal.OwnerLogin == p ? "1" : "2") + p) .Select(p => new ListBoxPlayerItem() { Login = p, Text = (selectCannal.OwnerLogin == p ? "<b>★ " + p + "</b>" : "<b>" + p + "</b>"), Tooltip = p + (selectCannal.OwnerLogin == p ? "OCity_Dialog_ChennelOwn".Translate() : "OCity_Dialog_ChennelUser".Translate()), InChat = true }) .ToList(); } else { lbPlayers.DataSource = new List <ListBoxPlayerItem>(); } var mainCannal = SessionClientController.Data.Chats[0]; lbPlayers.DataSource.AddRange(mainCannal.PartyLogin .Where(p => !listPlayersInChat.Any(sp => sp == p)) .OrderBy(p => p) .Select(p => new ListBoxPlayerItem() { Login = p, Text = "<color=#888888ff>" + p + "</color>", Tooltip = p, InChat = false }) ); DataLastChatsTime = SessionClientController.Data.ChatsTime; lbCannalsLastSelectedIndex = -1; //сброс для обновления содержимого окна } lbCannals.Drow(); lbPlayers.Drow(); var iconRect = new Rect(inRect.x, inRect.y, iconWidth, iconWidth); TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelCreate".Translate()); if (Widgets.ButtonImage(iconRect, IconAddTex)) { CannalAdd(); } if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { //Если что-то выделено, и это не общий чат (строка 0) iconRect.x += iconWidthSpase; TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelClose".Translate()); if (Widgets.ButtonImage(iconRect, IconDelTex)) { CannalDelete(); } } if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { iconRect.x += iconWidthSpase; TooltipHandler.TipRegion(iconRect, "OCity_Dialog_OthersFunctions".Translate()); if (Widgets.ButtonImage(iconRect, IconSubMenuTex)) { CannalsMenuShow(); } } /// ----------------------------------------------------------------------------------------- /// Чат /// if (lbCannalsLastSelectedIndex != lbCannals.SelectedIndex) { lbCannalsLastSelectedIndex = lbCannals.SelectedIndex; if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { Func <ChatPost, string> getPost = (cp) => "[" + cp.OwnerLogin + "]: " + cp.Message; var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; ChatText = selectCannal.Posts .Aggregate("", (r, i) => (r == "" ? "" : r + Environment.NewLine) + getPost(i)); } else { ChatText = ""; } } if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; //var chatTextSize = Text.CalcSize(ChatText); var chatAreaOuter = new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 30f); var chatAreaInner = new Rect(0, 0 , /*inRect.width - (inRect.x + 110f) */ chatAreaOuter.width - ListBox <string> .WidthScrollLine , 0 /*chatTextSize.y*/); chatAreaInner.height = Text.CalcHeight(ChatText, chatAreaInner.width); ChatScrollPosition = GUI.BeginScrollView(chatAreaOuter, ChatScrollPosition, chatAreaInner); GUILayout.BeginArea(chatAreaInner); GUILayout.TextField(ChatText, "Label"); GUILayout.EndArea(); GUI.EndScrollView(); /// if (ChatInputText != "") { var ev = Event.current; if (ev.isKey && ev.type == EventType.keyDown && ev.keyCode == KeyCode.Return) { SessionClientController.Command((connect) => { connect.PostingChat(selectCannal.Id, ChatInputText); }); ChatInputText = ""; } } GUI.SetNextControlName("StartTextField"); ChatInputText = GUI.TextField(new Rect(inRect.x + 110f, inRect.y + inRect.height - 25f, inRect.width - 110f, 25f) , ChatInputText, 10000); if (NeedFockus) { NeedFockus = false; GUI.FocusControl("StartTextField"); } } } }
private void exchangeOfGoods(Caravan caravan) { //Pawn bestNegotiator = CaravanVisitUtility.BestNegotiator(caravan); ThingOwner <Thing> сontainer = new ThingOwner <Thing>(); Dialog_TradeOnline form = null; if (сaravanOnline.OnlineWObject == null) { Log.Error("OCity_Caravan_LOGNoData".Translate()); return; } var goods = GameUtils.GetAllThings(caravan); form = new Dialog_TradeOnline(goods , сaravanOnline.OnlinePlayerLogin , сaravanOnline.OnlineWObject.FreeWeight , () => { if (!SessionClientController.Data.BackgroundSaveGameOff) { var select = form.GetSelect(); bool selectAllCaravan = caravan.PawnsListForReading.Count == select.Count(s => s.Key is Pawn); if (selectAllCaravan) { Log.Message("OCity_Caravan_LOGSwap".Translate()); select = new Dictionary <Thing, int>(); foreach (var pawn in caravan.PawnsListForReading) { foreach (var item in pawn.inventory.innerContainer.ToDictionary(t => t, t => t.stackCount)) { select.Add(item.Key, item.Value); } select.Add(pawn, 1); pawn.inventory.innerContainer.Clear(); } } //передаем выбранные товары из caravan к другому игроку в сaravanOnline var sendThings = new List <ThingEntry>(); foreach (var pair in select) { var thing = pair.Key; var numToTake = pair.Value; if (thing is Pawn) { var pawn = thing as Pawn; //если отдали пешку, то выкладываем все другим и удаляемся из каравана var things = pawn.inventory.innerContainer.ToList(); pawn.inventory.innerContainer.Clear(); GameUtils.DeSpawnSetupOnCaravan(caravan, pawn); foreach (var thin in things) { var p = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thin, caravan.PawnsListForReading, null); if (p != null) { p.inventory.innerContainer.TryAdd(thin, true); } } } sendThings.Add(ThingEntry.CreateEntry(thing, numToTake)); } if (selectAllCaravan) { //удаляем пешку из игры foreach (var pawn in caravan.PawnsListForReading) { GameUtils.PawnDestroy(pawn); } Find.WorldObjects.Remove(caravan); } else { foreach (var pair in select) { var thing = pair.Key; var numToTake = pair.Value; if (thing is Pawn) { var pawn = thing as Pawn; //удаляем пешку из игры GameUtils.PawnDestroy(pawn); } else { //если отдали вешь, то находим кто её тащит и убираем с него Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(caravan, thing); ownerOf.inventory.innerContainer.TryTransferToContainer(thing, сontainer, numToTake); } } } //После передачи сохраняем, чтобы нельзя было обузить, после чего передаем вещи SessionClientController.SaveGameNowSingleAndCommandSafely( (connect) => { return(connect.SendThings(sendThings , SessionClientController.My.Login , сaravanOnline.OnlinePlayerLogin , сaravanOnline.OnlineWObject.ServerId , сaravanOnline.Tile )); }, null, null); //если не удалось отправить письмо, то жопа так как сейв уже прошел } }); Find.WindowStack.Add(form); }
public override void Arrived(Caravan caravan) { if (mode == "exchangeOfGoods") { //Pawn bestNegotiator = CaravanVisitUtility.BestNegotiator(caravan); ThingOwner <Thing> сontainer = new ThingOwner <Thing>(); Dialog_TradeOnline form = null; if (сaravanOnline.OnlineWObject == null) { Log.Error("OCity_Caravan_LOGNoData".Translate()); return; } var goods = CaravanInventoryUtility.AllInventoryItems(caravan).ToList().Concat( caravan.PawnsListForReading .Cast <Thing>() ).ToList(); form = new Dialog_TradeOnline(goods , сaravanOnline.OnlinePlayerLogin , сaravanOnline.OnlineWObject.FreeWeight , () => { var select = form.GetSelect(); bool selectAllCaravan = caravan.PawnsListForReading.Count == select.Count(s => s.Key is Pawn); if (selectAllCaravan) { Log.Message("OCity_Caravan_LOGSwap".Translate()); select = new Dictionary <Thing, int>(); foreach (var pawn in caravan.PawnsListForReading) { foreach (var item in pawn.inventory.innerContainer.ToDictionary(t => t, t => t.stackCount)) { select.Add(item.Key, item.Value); } select.Add(pawn, 1); pawn.inventory.innerContainer.Clear(); } } //передаем выбранные товары из caravan к другому игроку в сaravanOnline var sendThings = new List <ThingEntry>(); foreach (var pair in select) { var thing = pair.Key; var numToTake = pair.Value; if (thing is Pawn) { var pawn = thing as Pawn; //если отдали пешку, то выкладываем все другим и удаляемся из каравана var things = pawn.inventory.innerContainer.ToList(); pawn.inventory.innerContainer.Clear(); GameUtils.DeSpawnSetupOnCaravan(caravan, pawn); foreach (var thin in things) { var p = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thin, caravan.PawnsListForReading, null); if (p != null) { p.inventory.innerContainer.TryAdd(thin, true); } } } sendThings.Add(new ThingEntry(thing, numToTake)); } SessionClientController.Command((connect) => { connect.SendThings(sendThings , SessionClientController.My.Login , сaravanOnline.OnlinePlayerLogin , сaravanOnline.OnlineWObject.ServerId , сaravanOnline.Tile ); }); if (selectAllCaravan) { //удаляем пешку из игры foreach (var pawn in caravan.PawnsListForReading) { pawn.Destroy(DestroyMode.Vanish); } Find.WorldObjects.Remove(caravan); } else { foreach (var pair in select) { var thing = pair.Key; var numToTake = pair.Value; if (thing is Pawn) { var pawn = thing as Pawn; //удаляем пешку из игры pawn.Destroy(DestroyMode.Vanish); //Find.WorldPawns.RemovePawn(pawn); не проверенное не полное удаление, если её вернут назад } else { //если отдали вешь, то находим кто её тащит и убираем с него Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(caravan, thing); ownerOf.inventory.innerContainer.TryTransferToContainer(thing, сontainer, numToTake); } } } }); Find.WindowStack.Add(form); } }
public void DoTab3Contents(Rect inRect) { Text.Font = GameFont.Medium; Widgets.Label(inRect, "OCity_Dialog_AboutMode".Translate()); Text.Font = GameFont.Small; var chatAreaOuter = new Rect(inRect.x + 150f, inRect.y + 40f, inRect.width - 150f, inRect.height - 30f - 40f); AboutBox.Drow(chatAreaOuter); var rect2 = new Rect(inRect.x, inRect.y + inRect.height / 2f, 150f, inRect.height - 30f - 40f); Text.Font = GameFont.Small; List <ListableOption> list2 = new List <ListableOption>(); ListableOption item2 = new ListableOption_WebLink("OCity_Dialog_AutorPage".Translate(), "https://steamcommunity.com/sharedfiles/filedetails/?id=1908437382", GeneralTexture.IconForums); list2.Add(item2); rect2 = new Rect(inRect.x, inRect.y + 30f, 150f, 40f); Text.Font = GameFont.Small; list2 = new List <ListableOption>(); item2 = new ListableOption_WebLink("OCity_Dialog_Regame".Translate(), () => { var form = new Dialog_Input("OCity_Dialog_DeleteData".Translate(), "OCity_Dialog_DeleteDataCheck".Translate()); form.PostCloseAction = () => { if (form.ResultOK) { var mainCannal = SessionClientController.Data.Chats[0]; SessionClientController.Command((connect) => { var res = connect.PostingChat(mainCannal.Id, "/killmyallplease"); if (res != null && res.Status == 0) { SessionClientController.Disconnected("OCity_Dialog_DeletedData".Translate()); } }); } }; Find.WindowStack.Add(form); }, GeneralTexture.IconDelTex); list2.Add(item2); float num = OptionListingUtility.DrawOptionListing(rect2, list2); GUI.BeginGroup(rect2); if (Current.ProgramState == ProgramState.Entry && Widgets.ButtonImage(new Rect(0f, num + 10f, 64f, 32f), LanguageDatabase.activeLanguage.icon)) { List <FloatMenuOption> list3 = new List <FloatMenuOption>(); foreach (LoadedLanguage current in LanguageDatabase.AllLoadedLanguages) { LoadedLanguage localLang = current; list3.Add(new FloatMenuOption(localLang.FriendlyNameNative, delegate { LanguageDatabase.SelectLanguage(localLang); Prefs.Save(); }, MenuOptionPriority.Default, null, null, 0f, null, null)); } Find.WindowStack.Add(new FloatMenu(list3)); } GUI.EndGroup(); /* * var rectCannals = new Rect(inRect.x, inRect.y, 100f, (float)Math.Round((decimal)(inRect.height / 2f * 10f)) / 10f); * Widgets.DrawBoxSolid(inRect, new Color(0.2f, 0.2f, 0)); * Widgets.DrawBoxSolid(rectCannals, new Color(0.4f, 0.4f, 0)); * * * Widgets.DrawBoxSolid(new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 40f) * , new Color(0.4f, 0, 0)); * * Widgets.DrawBoxSolid(new Rect(inRect.x + 110f, inRect.y + inRect.height - 35f, inRect.width - 110f, 25f) * , new Color(0, 0, 0.4f)); * * Widgets.Label(inRect, "Вкладка 3"); */ }
/// <summary> /// Расчитывает стоимость инциндента, и изымает её. /// </summary> /// <param name="command">Текстовая команда для чата</param> /// <param name="onliCheck">Только рассчитать, не изымая.</param> /// <error>Ошибка, или результат при onliCheck</error> /// <returns>Строка с количество требуемой стоимости</returns> public static string GetCostOnGameByCommand(string command, bool onliCheck, out string error) { Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 1 command:" + command); //разбираем аргументы в кавычках '. Удвоенная кавычка указывает на её символ. string cmd; List <string> args; ChatUtils.ParceCommand(command, out cmd, out args); if (args.Count < 3) { error = "OC_Incidents_OCIncident_WrongArg".Translate().ToString(); Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error); return(null); } // /call raid '111' 1 10 air tribe //проверка, что денег хватает int cost = OCIncident.CalculateRaidCost(args[0].ToLower(), Int64.Parse(args[2]) , args.Count > 3 ? Int32.Parse(args[3]) : 1 , args.Count > 4 ? args[4].ToLower() : null , args.Count > 5 ? args[5].ToLower() : null); int gold = -1; Map map = null; if (cost > 0) { gold = GameUtils.FindThings(ThingDefOf.Gold, 0, false); } if (cost < 0 || gold < 0 || gold < cost) { error = cost < 0 || gold < 0 ? "OC_Incidents_OCIncident_WealthErr".Translate().ToString() + $" cost={cost} gold={gold}" : "OC_Incidents_OCIncident_GoldErr".Translate(gold, cost, cost - gold).ToString(); Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error); return(null); } if (onliCheck) { error = null; return("OC_Incidents_OCIncident_NotEnoughGold".Translate(cost)); } Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 2"); //отнимаем нужное кол-во денег(золото или серебро... или что-нибудь ещё) GameUtils.FindThings(ThingDefOf.Gold, cost, false); Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 3"); //принудительное сохранение if (!SessionClientController.Data.BackgroundSaveGameOff) { SessionClientController.SaveGameNow(true); } Loger.Log("IncidentLod ChatController.AfterStartIncident 4"); error = null; return("OC_Incidents_OCIncident_GoldPay".Translate(cost)); }
private void PlayerItemMenu(ListBoxPlayerItem item) { if (item.GroupTitle) { return; } var listMenu = new List <FloatMenuOption>(); var myLogin = SessionClientController.My.Login; ///Личное сообщение if (item.Login != myLogin) { listMenu.Add(new FloatMenuOption("OCity_Dialog_PrivateMessage".Translate(), () => { var privateChat = String.Compare(myLogin, item.Login) < 0 ? myLogin + " · " + item.Login : item.Login + " · " + myLogin; var index = lbCannals.DataSource.IndexOf(privateChat); if (index >= 0) { lbCannals.SelectedIndex = index; return; } //создаем канал var mainCannal = SessionClientController.Data.Chats[0]; SessionClientController.Command((connect) => { connect.PostingChat(mainCannal.Id, "/createChat '" + privateChat.Replace("'", "''") + "' '" + item.Login.Replace("'", "''") + "'"); }); lbCannalsGoToChat = privateChat; })); } ///Добавить участника if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; if (!item.InChat) { listMenu.Add(new FloatMenuOption("OCity_Dialog_ChennelAddUser".Translate(), () => { SessionClientController.Command((connect) => { connect.PostingChat(selectCannal.Id, "/addPlayer '" + item.Login.Replace("'", "''") + "'"); }); })); } } if (SessionClientController.Data.Players.ContainsKey(item.Login)) { listMenu.Add(new FloatMenuOption("OCity_Dialog_ChennelPlayerInfo".Translate(), () => { var pl = SessionClientController.Data.Players[item.Login]; InfoTabTitle = "OCity_Dialog_ChennelPlayerInfoTitle".Translate() + item.Login; InfoBox.Text = pl.GetTextInfo(); TabIndex = 1; })); } if (listMenu.Count == 0) { return; } var menu = new FloatMenu(listMenu); Find.WindowStack.Add(menu); }
public void Start(Caravan caravan, BaseOnline attackedBase) { SessionClientController.Command((connect) => { connect.ErrorMessage = null; Loger.Log("Client GameAttack State 0"); var res = connect.AttackOnlineInitiator(new AttackInitiatorToSrv() { State = 0, StartHostPlayer = attackedBase.Player.Public.Login, HostPlaceServerId = attackedBase.OnlineWObject.ServerId, InitiatorPlaceServerId = UpdateWorldController.GetServerInfo(caravan).ServerId }); if (!string.IsNullOrEmpty(connect.ErrorMessage)) { ErrorBreak(connect.ErrorMessage); return; } // ждем положительного ответа с статусом больше 2 и отправляем своих колонистов Loger.Log("Client GameAttack State 1"); var s1Time = DateTime.UtcNow; while (true) { var res1 = connect.AttackOnlineInitiator(new AttackInitiatorToSrv() { State = 1 }); if (!string.IsNullOrEmpty(connect.ErrorMessage)) { ErrorBreak(connect.ErrorMessage); return; } if (res1.State == 2) { break; } if ((DateTime.UtcNow - s1Time).TotalSeconds > 20) { ErrorBreak("Timeout"); return; } } var pawnsToSend = GetPawnsAndDeleteCaravan(caravan); var response = connect.AttackOnlineInitiator(new AttackInitiatorToSrv() { State = 2, Pawns = pawnsToSend }); if (!string.IsNullOrEmpty(connect.ErrorMessage)) { ErrorBreak(connect.ErrorMessage); return; } // принимаем карту и создаем Loger.Log("Client GameAttack CreateMap State=" + response.State); Loger.Log("Client GameAttack WaitTo3"); s1Time = DateTime.UtcNow; while (true) { response = connect.AttackOnlineInitiator(new AttackInitiatorToSrv() { State = 3 }); if (!string.IsNullOrEmpty(connect.ErrorMessage)) { ErrorBreak(connect.ErrorMessage); return; } if (response.State >= 4) { break; } if ((DateTime.UtcNow - s1Time).TotalSeconds > 60) { ErrorBreak("Timeout"); return; } } Find.TickManager.Pause(); CreateClearMap(attackedBase.Tile, response.MapSize.Get(), (map, mapParent) => { GameMap = map; Loger.Log("Client StartCreateClearMap 1"); CellRect cellRect = CellRect.WholeMap(map); cellRect.ClipInsideMap(map); Loger.Log("Client StartCreateClearMap 2"); //почва for (int i = 0; i < response.TerrainDefNameCell.Count; i++) { var current = response.TerrainDefNameCell[i].Get(); var terrName = response.TerrainDefName[i]; //Log.Message(terr.defName); map.terrainGrid.SetTerrain(current, DefDatabase <TerrainDef> .GetNamed(terrName)); } Loger.Log("Client StartCreateClearMap 3"); //скалы, преграды и строения без пешек и без растений не деревьев ThingsIDDicRev = new Dictionary <int, int>(); ThingsIDDic = new Dictionary <int, int>(); ThingsObjDic = new Dictionary <int, Thing>(); AttackerPawns = new Dictionary <Pawn, int>(); ToSendCommand = new Dictionary <int, AttackPawnCommand>(); for (int i = 0; i < response.ThingCell.Count; i++) { var current = response.ThingCell[i].Get(); var tt = response.Thing[i]; var th = tt.CreateThing(); GenSpawn.Spawn(th, current, map, new Rot4(tt.Rotation), WipeMode.Vanish); //словарь сопоставления ID их и сейчас созданный (их из OriginalID, наш ID) if (tt.OriginalID != 0 && th.thingIDNumber != 0) { ThingsIDDicRev[tt.OriginalID] = th.thingIDNumber; ThingsIDDic[th.thingIDNumber] = tt.OriginalID; ThingsObjDic[th.thingIDNumber] = th; } } Loger.Log("Client StartCreateClearMap 4 CountThings=" + ThingsIDDic.Count.ToString() + " CountThingsRev=" + ThingsIDDicRev.Count.ToString() + " CountThingsObj=" + ThingsObjDic.Count.ToString()); //режим вечной паузы //todo Loger.Log("Client StartCreateClearMap 5"); AttackUpdateTick = 0; AttackUpdate(); TimerObj = SessionClientController.Timers.Add(200, AttackUpdate); //включаем обработку событий выдачи команд Loger.Log("Client StartCreateClearMap 6"); }); }); }
private void AttackUpdate() { bool inTimerEvent = false; try { //Scribe.ForceStop(); Find.TickManager.Pause(); if (InTimer) { return; } InTimer = true; AttackUpdateTick++; Loger.Log("Client AttackUpdate #" + AttackUpdateTick.ToString()); inTimerEvent = true; SessionClientController.Command((connect) => { try { Loger.Log("Client AttackUpdate 2"); var toSendCommand = ToSendCommand; ToSendCommand = new Dictionary <int, AttackPawnCommand>(); var toClient = connect.AttackOnlineInitiator(new AttackInitiatorToSrv() { State = 10, UpdateCommand = toSendCommand.Values.ToList(), }); Action actUpdateState = () => { Loger.Log("Client AttackUpdate 4. UpdateState=" + toClient.UpdateState.Count); //Применение изменения местоположения и пр. по ID хоста for (int i = 0; i < toClient.UpdateState.Count; i++) { int id; if (!ThingsIDDicRev.TryGetValue(toClient.UpdateState[i].HostThingID, out id)) { Loger.Log("Client AttackUpdate 4 Err1 " + toClient.UpdateState[i].ToString()); continue; } Thing thing; if (!ThingsObjDic.TryGetValue(id, out thing)) { Loger.Log("Client AttackUpdate 4 Err2 " + toClient.UpdateState[i].ToString() + " id=" + id.ToString()); continue; } if (thing == null) { Loger.Log("Client AttackUpdate 4 Err3 " + toClient.UpdateState[i].ToString() + " id=" + id.ToString()); continue; } if (!(thing is Pawn)) { Loger.Log("Client AttackUpdate 4 Apply " + toClient.UpdateState[i].ToString() + " thing=" + thing.Label + " ID=" + thing.thingIDNumber); } if (thing is Pawn && toClient.UpdateState[i].DownState == AttackThingState.PawnHealthState.Dead) { DelayDestroyPawn.Remove(thing); } GameUtils.ApplyState(thing, toClient.UpdateState[i]); } for (int i = 0; i < DelayDestroyPawn.Count; i++) { Thing thing = DelayDestroyPawn[i]; Loger.Log("Client AttackUpdate 4 DelayDestroyPawn " + toClient.Delete[i].ToString() + " thing=" + thing.Label + " ID=" + thing.thingIDNumber); DestroyThing(thing); } DelayDestroyPawn.Clear(); for (int i = 0; i < toClient.Delete.Count; i++) { int id; if (!ThingsIDDicRev.TryGetValue(toClient.Delete[i], out id)) { Loger.Log("Client AttackUpdate 4 Err4 " + toClient.Delete[i].ToString()); continue; } Thing thing; if (!ThingsObjDic.TryGetValue(id, out thing)) { Loger.Log("Client AttackUpdate 4 Err5 " + toClient.Delete[i].ToString() + " id=" + id.ToString()); continue; } if (thing == null) { Loger.Log("Client AttackUpdate 4 Err6 " + toClient.Delete[i].ToString() + " id=" + id.ToString()); continue; } if (thing is Pawn) { Loger.Log("Client AttackUpdate 4 ToDelayDestroy " + toClient.Delete[i].ToString() + " thing=" + thing.Label + " ID=" + thing.thingIDNumber); DelayDestroyPawn.Add(thing); } else { Loger.Log("Client AttackUpdate 4 Destroy " + toClient.Delete[i].ToString() + " thing=" + thing.Label + " ID=" + thing.thingIDNumber); DestroyThing(thing, toClient.Delete[i]); } } }; if (toClient.NewPawns.Count > 0 || toClient.NewThings.Count > 0) { LongEventHandler.QueueLongEvent(delegate { try { Loger.Log("Client AttackUpdate 3. NewPawn=" + toClient.NewPawns.Count); if (toClient.NewPawns.Count > 0) { //удаляем пешки NewPawnsId (здесь список thingIDNumber от хоста), которые сейчас обновим for (int i = 0; i < toClient.NewPawnsId.Count; i++) { var hostid = toClient.NewPawnsId[i]; int id; if (!ThingsIDDicRev.TryGetValue(hostid, out id)) { continue; } Thing thing; if (!ThingsObjDic.TryGetValue(id, out thing)) { continue; } if (thing == null) { continue; } Loger.Log("Client AttackUpdate 3 DestroyPawnForUpdate " + hostid.ToString() + " pawn=" + thing.Label + " ID=" + thing.thingIDNumber); DestroyThing(thing, hostid); } //создаем список пешек toClient.NewPawns GameUtils.SpawnList(GameMap, toClient.NewPawns, false , (p) => p.TransportID == 0 //если без нашего ID, то у нас как пират , (th, te) => { var p = th as Pawn; //Loger.Log("Client AttackUpdate 3. NewPawn " + (p.IsColonist ? "IsColonist" : "NotColonist")); //Дополнить словарь сопоставления ID (их из OriginalID, наш ID, а TransportID уже никому не нужен, т.к. пешки дропнуты и переозданы) if (te.OriginalID != 0 && th.thingIDNumber != 0) { ThingsIDDicRev[te.OriginalID] = th.thingIDNumber; ThingsIDDic[th.thingIDNumber] = te.OriginalID; ThingsObjDic[th.thingIDNumber] = th; //Наши пешки сохраняем отдельно if (te.TransportID != 0) { AttackerPawns[p] = te.OriginalID; p.playerSettings.hostilityResponse = HostilityResponseMode.Ignore; p.jobs.StartJob(new Job(JobDefOf.Wait_Combat) { playerForced = true, expiryInterval = int.MaxValue, checkOverrideOnExpire = false, } , JobCondition.InterruptForced); } } else { Loger.Log("Client AttackUpdate SpawnListPawn NotOrigID! " + " thing=" + th.Label + " ID=" + th.thingIDNumber); } }); } Loger.Log("Client AttackUpdate 3. NewThings=" + toClient.NewThings.Count); if (toClient.NewThings.Count > 0) { GameUtils.SpawnList(GameMap, toClient.NewThings, false, (p) => false , (th, te) => { var p = th as Pawn; //Loger.Log("Client AttackUpdate 3. NewPawn " + (p.IsColonist ? "IsColonist" : "NotColonist")); //Дополнить словарь сопоставления ID (их из OriginalID, наш ID, а TransportID уже никому не нужен, т.к. пешки дропнуты и переозданы) if (te.OriginalID != 0 && th.thingIDNumber != 0) { ThingsIDDicRev[te.OriginalID] = th.thingIDNumber; ThingsIDDic[th.thingIDNumber] = te.OriginalID; ThingsObjDic[th.thingIDNumber] = th; } else { Loger.Log("Client AttackUpdate SpawnListThings NotOrigID! " + " thing=" + th.Label + " ID=" + th.thingIDNumber); } }); } actUpdateState(); Loger.Log("Client AttackUpdate 5"); //после первого массового спавна всех пешек if (AttackUpdateTick == 1) { //проверка обзора и переключение на карту FloodFillerFog.DebugRefogMap(GameMap); CameraJumper.TryJump(GameMap.Center, GameMap); GameAttackTrigger_Patch.ActiveAttacker.Add(GameMap, this); } } catch (Exception ext) { Loger.Log("Client AttackUpdate SpawnListEvent Exception " + ext.ToString()); } InTimer = false; }, "", false, null); //".." } else { actUpdateState(); InTimer = false; } } catch (Exception ext) { InTimer = false; Loger.Log("Client AttackUpdate SpawnList Exception " + ext.ToString()); } }); } catch (Exception ext) { Loger.Log("AttackUpdate Exception " + ext.ToString()); } if (!inTimerEvent) { InTimer = false; } }
public static void Prefix(Rect rect, List <ListableOption> optList) { if (optList.Count > 0 && optList[0].GetType() == typeof(ListableOption)) { if (Current.ProgramState == ProgramState.Entry) { var item = new ListableOption("OCity_LAN_btn".Translate(), delegate { MainMenu.OnMainMenuNetClick(); }, null); optList.Insert(0, item); } else { if (SessionClient.Get.IsLogined) { for (int i = 0; i < optList.Count; i++) { if (optList[i].label == "Save".Translate() || optList[i].label == "LoadGame".Translate() || optList[i].label == "ReviewScenario".Translate() || optList[i].label == "SaveAndQuitToMainMenu".Translate() || optList[i].label == "SaveAndQuitToOS".Translate() || optList[i].label == "ConfirmQuit".Translate() || optList[i].label == "QuitToMainMenu".Translate() || optList[i].label == "QuitToOS".Translate()) { optList.RemoveAt(i--); } } var item = new ListableOption("OCity_MainMenu_Online".Translate(), delegate { Dialog_MainOnlineCity.ShowHide(); }, null); optList.Add(item); if (SessionClientController.Data.AttackModule != null) { item = new ListableOption("OCity_MainMenu_Withdraw".Translate(), delegate { Loger.Log("Client MainMenu VictoryHost"); SessionClientController.Data.AttackModule.VictoryHostToHost = true; }, null); optList.Add(item); } if (SessionClientController.Data.AttackUsModule != null) { item = new ListableOption("OCity_MainMenu_Surrender".Translate(), delegate { Loger.Log("Client MainMenu VictoryAttacker"); SessionClientController.Data.AttackUsModule.ConfirmedVictoryAttacker = true; }, null); optList.Add(item); } item = new ListableOption("QuitToMainMenu".Translate(), delegate { if (GameExit.BeforeExit != null) { GameExit.BeforeExit(); } GenScene.GoToMainMenu(); }, null); optList.Add(item); item = new ListableOption("QuitToOS".Translate(), delegate { if (GameExit.BeforeExit != null) { GameExit.BeforeExit(); } Root.Shutdown(); }, null); optList.Add(item); } } } if (Inited) { return; } Inited = true; SessionClientController.Init(); }
public void DoTab0Contents(Rect inRect) { var iconWidth = 25f; var iconWidthSpase = 30f; //StatusTemp = Text.CalcSize("VersionLabel").y.ToString(); //Widgets.Label(new Rect(inRect.width - 100f, inRect.height - 30f, inRect.width, inRect.height), StatusTemp + " " + lbCannalsLastSelectedIndex.ToString()); /// ----------------------------------------------------------------------------------------- /// Список каналов /// if (SessionClientController.Data.Chats != null) { if (SessionClientController.Data.ChatNotReadPost > 0) { SessionClientController.Data.ChatNotReadPost = 0; } //Loger.Log("Client " + SessionClientController.Data.Chats.Count); if (lbCannalsHeight == 0) { var textHeight = new DialogControlBase().TextHeight; lbCannalsHeight = (float)Math.Round((decimal)(inRect.height / 2f / textHeight)) * textHeight; } Widgets.Label(new Rect(inRect.x, inRect.y + iconWidthSpase + lbCannalsHeight, 100f, 22f), "OCity_Dialog_Players".Translate()); if (lbCannals == null) { //первый запуск lbCannals = new ListBox <string>(); lbCannals.Area = new Rect(inRect.x , inRect.y + iconWidthSpase , 100f , lbCannalsHeight); lbCannals.OnClick += (index, text) => DataLastChatsTime = DateTime.MinValue; /*StatusTemp = text;*/ lbCannals.SelectedIndex = 0; } if (lbPlayers == null) { //первый запуск lbPlayers = new ListBox <ListBoxPlayerItem>(); /* * lbPlayers.Area = new Rect(inRect.x * , inRect.y + iconWidthSpase + lbCannalsHeight + 22f * , 100f * , inRect.height - (iconWidthSpase + lbCannalsHeight + 22f)); */ lbPlayers.OnClick += (index, item) => { //убираем выделение lbPlayers.SelectedIndex = -1; //вызываем контекстное меню PlayerItemMenu(item); }; lbPlayers.Tooltip = (item) => item.Tooltip; } if (DoTab0LastHeight != inRect.height) { DoTab0LastHeight = inRect.height; lbPlayers.Area = new Rect(inRect.x , inRect.y + iconWidthSpase + lbCannalsHeight + 22f , 100f , inRect.height - (iconWidthSpase + lbCannalsHeight + 22f)); } if (DataLastChatsTime != SessionClientController.Data.ChatsTime || DataLastChatsTimeUpdateTime < DateTime.UtcNow.AddSeconds(-5)) { DataLastChatsTimeUpdateTime = DateTime.UtcNow; //пишем в лог var updateLogHash = SessionClientController.Data.Chats.Count * 1000000 + SessionClientController.Data.Chats.Sum(c => c.Posts.Count); if (updateLogHash != UpdateLogHash) { UpdateLogHash = updateLogHash; Loger.Log("Client UpdateChats count=" + SessionClientController.Data.Chats.Count.ToString() + " posts=" + (updateLogHash % 1000000).ToString() + " - " + SessionClientController.Data.ChatsTime.ToString(Loger.Culture)); } //устанавливаем данные lbCannals.DataSource = SessionClientController.Data.Chats //.OrderBy(c => (c.OwnerMaker ? "2" : "1") + c.Name) нелья просто отсортировать, т.к. потом находим по индексу .Select(c => c.Name) .ToList(); if (lbCannalsGoToChat != null) { var lbCannalsGoToChatIndex = lbCannals.DataSource.IndexOf(lbCannalsGoToChat); if (lbCannalsGoToChatIndex >= 0) { lbCannals.SelectedIndex = lbCannalsGoToChatIndex; lbCannalsGoToChat = null; } } //Заполняем список игроков по группами { lbPlayers.DataSource = new List <ListBoxPlayerItem>(); var allreadyLogin = new List <string>(); Func <string, string, ListBoxPlayerItem> addPl = (login, text) => { allreadyLogin.Add(login); var n = new ListBoxPlayerItem() { Login = login, Text = text, Tooltip = login }; lbPlayers.DataSource.Add(n); return(n); }; Action <string> addTit = (text) => { if (lbPlayers.DataSource.Count > 0) { addPl(null, " ").GroupTitle = true; } addPl(null, " <i>– " + text + " –</i> ").GroupTitle = true; }; Func <string, bool> isOnline = (login) => login == SessionClientController.My.Login || SessionClientController.Data.Players[login].Online; Func <bool, string, string> frameOnline = (online, txt) => online ? "<b>" + txt + "</b>" : "<color=#888888ff>" + txt + "</color>"; if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; // в чате создатель addTit("в чате".NeedTranslate()); var n = addPl(selectCannal.OwnerLogin , frameOnline(isOnline(selectCannal.OwnerLogin), "★ " + selectCannal.OwnerLogin)); n.Tooltip += "OCity_Dialog_ChennelOwn".Translate(); n.InChat = true; // в чате var offlinePartyLogin = new List <string>(); for (int i = 0; i < selectCannal.PartyLogin.Count; i++) { var lo = selectCannal.PartyLogin[i]; if (lo != "system" && lo != selectCannal.OwnerLogin) { if (isOnline(lo)) { n = addPl(lo, frameOnline(true, lo)); n.Tooltip += "OCity_Dialog_ChennelUser".Translate(); n.InChat = true; } else { offlinePartyLogin.Add(lo); } } } // в чате оффлайн //addTit("оффлайн".NeedTranslate()); for (int i = 0; i < offlinePartyLogin.Count; i++) { var lo = offlinePartyLogin[i]; n = addPl(lo, frameOnline(false, lo)); n.Tooltip += "OCity_Dialog_ChennelUser".Translate(); n.InChat = true; } } var other = SessionClientController.Data.Chats[0].PartyLogin .Where(p => p != "" && p != "system" && !allreadyLogin.Any(al => al == p)) .ToList(); if (other.Count > 0) { // игроки addTit("игроки".NeedTranslate()); var offlinePartyLogin = new List <string>(); for (int i = 0; i < other.Count; i++) { var lo = other[i]; if (isOnline(lo)) { var n = addPl(lo, frameOnline(true, lo)); //n.Tooltip += "OCity_Dialog_ChennelUser".Translate(); } else { offlinePartyLogin.Add(lo); } } // игроки оффлайн //addTit("оффлайн".NeedTranslate()); for (int i = 0; i < offlinePartyLogin.Count; i++) { var lo = offlinePartyLogin[i]; var n = addPl(lo, frameOnline(false, lo)); //n.Tooltip += "OCity_Dialog_ChennelUser".Translate(); } } DataLastChatsTime = SessionClientController.Data.ChatsTime; lbCannalsLastSelectedIndex = -1; //сброс для обновления содержимого окна } // } lbCannals.Drow(); lbPlayers.Drow(); var iconRect = new Rect(inRect.x, inRect.y, iconWidth, iconWidth); TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelCreate".Translate()); if (Widgets.ButtonImage(iconRect, IconAddTex)) { CannalAdd(); } if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { //Если что-то выделено, и это не общий чат (строка 0) iconRect.x += iconWidthSpase; TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelClose".Translate()); if (Widgets.ButtonImage(iconRect, IconDelTex)) { CannalDelete(); } } if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { iconRect.x += iconWidthSpase; TooltipHandler.TipRegion(iconRect, "OCity_Dialog_OthersFunctions".Translate()); if (Widgets.ButtonImage(iconRect, IconSubMenuTex)) { CannalsMenuShow(); } } /// ----------------------------------------------------------------------------------------- /// Чат /// if (lbCannalsLastSelectedIndex != lbCannals.SelectedIndex) { lbCannalsLastSelectedIndex = lbCannals.SelectedIndex; if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; var chatLastPostTime = selectCannal.Posts.Max(p => p.Time); if (ChatLastPostTime != chatLastPostTime) { ChatLastPostTime = chatLastPostTime; Func <ChatPost, string> getPost = (cp) => "[" + cp.Time.ToGoodUtcString("dd HH:mm ") + cp.OwnerLogin + "]: " + cp.Message; var totalLength = 0; ChatBox.Text = selectCannal.Posts .Reverse <ChatPost>() .Where(i => (totalLength += i.Message.Length) < 5000) .Aggregate("", (r, i) => getPost(i) + (r == "" ? "" : Environment.NewLine + r)); ChatScrollToDown = true; } } else { ChatBox.Text = ""; } } if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex) { var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex]; var chatAreaOuter = new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 30f); ChatBox.Drow(chatAreaOuter, ChatScrollToDown); ChatScrollToDown = false; var rrect = new Rect(inRect.x + inRect.width - 25f, inRect.y + inRect.height - 25f, 25f, 25f); Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rrect, "▶"); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.MiddleLeft; bool rrcklick = Widgets.ButtonInvisible(rrect); if (ChatInputText != "") { if (Mouse.IsOver(rrect)) { Widgets.DrawHighlight(rrect); } var ev = Event.current; if (ev.isKey && ev.type == EventType.keyDown && ev.keyCode == KeyCode.Return || rrcklick) { SoundDefOf.RadioButtonClicked.PlayOneShotOnCamera(); SessionClientController.Command((connect) => { connect.PostingChat(selectCannal.Id, ChatInputText); }); ChatInputText = ""; } } GUI.SetNextControlName("StartTextField"); ChatInputText = GUI.TextField(new Rect(inRect.x + 110f, inRect.y + inRect.height - 25f, inRect.width - 110f - 30f, 25f) , ChatInputText, 10000); if (NeedFockus) { NeedFockus = false; GUI.FocusControl("StartTextField"); } } } }
private void AttackUpdate() { bool inTimerEvent = false; try { if (InTimer) { return; } InTimer = true; AttackUpdateTick++; // Loger.Log("Client HostAttackUpdate #" + AttackUpdateTick.ToString()); SessionClientController.Command((connect) => { try { List <Pawn> mapPawns; AttackHostFromSrv toClient; lock (ToSendListsSync) { // Loger.Log("Client HostAttackUpdate 1"); //обновляем списки mapPawns = GameMap.mapPawns.AllPawnsSpawned; var mapPawnsId = new HashSet <int>(mapPawns.Select(p => p.thingIDNumber)); mapPawnsId.SymmetricExceptWith(SendedPawnsId); //новые пешки + те что на сервере, но их уже нет на карте if (mapPawnsId.Count > 0) { var toSendAddId = new HashSet <int>(mapPawnsId); toSendAddId.ExceptWith(SendedPawnsId); //только новые пешки if (toSendAddId.Count > 0) { toSendAddId.ExceptWith(ToSendAddId); //исключаем те, которые уже есть в списке ToSendAddId.AddRange(toSendAddId); } var toSendDeleteId = new HashSet <int>(mapPawnsId); toSendDeleteId.IntersectWith(SendedPawnsId); //только те, что на сервере но их уже нет на карте if (toSendDeleteId.Count > 0) { toSendDeleteId.ExceptWith(ToSendDeleteId); //исключаем те, которые уже есть в списке ToSendDeleteId.AddRange(toSendDeleteId); } } //посылаем пакеты с данными // Loger.Log("Client HostAttackUpdate 2"); var newPawns = new List <ThingEntry>(); var newPawnsId = new List <int>(); int cnt = ToSendAddId.Count < 3 || ToSendAddId.Count > 6 || AttackUpdateTick == 0 ? ToSendAddId.Count : 3; int i = 0; int[] added = new int[cnt]; foreach (int id in ToSendAddId) { if (i >= cnt) { break; } added[i++] = id; var thing = mapPawns.Where(p => p.thingIDNumber == id).FirstOrDefault(); var tt = ThingEntry.CreateEntry(thing, 1); //передаем те, что были исходные у атакуемого (хотя там используется только как признак TransportID != 0 - значит те кто атакует) if (AttackingPawnDic.ContainsKey(tt.OriginalID)) { tt.TransportID = AttackingPawnDic[tt.OriginalID]; } newPawns.Add(tt); newPawnsId.Add(id); } for (i = 0; i < cnt; i++) { ToSendAddId.Remove(added[i]); SendedPawnsId.Add(added[i]); } foreach (int id in ToSendDeleteId) { SendedPawnsId.Remove(id); } //вещи var newThings = ToSendThingAdd .Where(thing => !ToSendDeleteId.Any(d => thing.thingIDNumber == d)) .Select(thing => ThingEntry.CreateEntry(thing, thing.stackCount)) .ToList(); //передаем изменение местоположения и пр. по ID хоста var toSendState = new List <AttackThingState>(); var toSendStateId = new List <int>(); for (int imp = 0; imp < mapPawns.Count; imp++) { var mp = mapPawns[imp]; var mpID = mp.thingIDNumber; if (ToUpdateStateId.Contains(mpID)) { continue; } var mpHash = AttackThingState.GetHash(mp); int mpHS; if (!SendedState.TryGetValue(mpID, out mpHS) || mpHS != mpHash) { SendedState[mpID] = mpHash; toSendState.Add(new AttackThingState(mp)); } } for (int imp = 0; imp < ToUpdateState.Count; imp++) { var mp = ToUpdateState[imp]; var mpID = mp.thingIDNumber; if (ToSendDeleteId.Contains(mpID)) { continue; } if (mp is Pawn) { var mpHash = AttackThingState.GetHash(mp); SendedState[mpID] = mpHash; //заносим только для проверки выше } toSendState.Add(new AttackThingState(mp)); } //обновляем поколения вещей учавствующих в Job и отправляем нужные foreach (var mp in ThingPrepareChange0) { var mpID = mp.thingIDNumber; if (ToSendDeleteId.Contains(mpID)) { continue; } toSendState.Add(new AttackThingState(mp)); } Loger.Log("HostAttackUpdate UpdateCommand FromJob Count=" + ThingPrepareChange0.Count.ToString()); ThingPrepareChange0 = ThingPrepareChange1; ThingPrepareChange1 = new HashSet <Thing>(); //Loger.Log("Client HostAttackUpdate 3"); toClient = connect.AttackOnlineHost(new AttackHostToSrv() { State = 10, NewPawns = newPawns, NewPawnsId = newPawnsId, NewThings = newThings, NewThingsId = newThings.Select(th => th.OriginalID).ToList(), Delete = ToSendDeleteId.ToList(), UpdateState = toSendState }); ToSendThingAdd.Clear(); ToSendDeleteId.Clear(); ToUpdateStateId.Clear(); ToUpdateState.Clear(); } //принимаем обновление команд атакующих if (toClient.UpdateCommand.Count > 0) { Loger.Log("HostAttackUpdate UpdateCommand Count=" + toClient.UpdateCommand.Count.ToString()); UIEventNewJobDisable = true; for (int ii = 0; ii < toClient.UpdateCommand.Count; ii++) { var comm = toClient.UpdateCommand[ii]; var pawn = mapPawns.Where(p => p.thingIDNumber == comm.HostPawnID).FirstOrDefault() as Pawn; if (pawn == null) { Loger.Log("HostAttackUpdate UpdateCommand pawn == null " + comm.HostPawnID.ToString()); continue; } AttackingPawnJobDic[comm.HostPawnID] = comm; ApplyAttackingPawnJob(pawn); } UIEventNewJobDisable = false; } // Loger.Log("Client HostAttackUpdate 4"); } catch (Exception ext) { InTimer = false; Loger.Log("HostAttackUpdate Event Exception " + ext.ToString()); } finally { InTimer = false; } }); } catch (Exception ext) { Loger.Log("HostAttackUpdate Exception " + ext.ToString()); } if (!inTimerEvent) { InTimer = false; } }
/// <summary> /// Начинаем процесс, первые запросы информации /// </summary> /// <param name="connect"></param> public void Start(SessionClient connect) { Loger.Log("Client GameAttackHost Start 1"); var tolient = connect.AttackOnlineHost(new AttackHostToSrv() { State = 2 }); if (!string.IsNullOrEmpty(connect.ErrorMessage)) { ErrorBreak(connect.ErrorMessage); return; } AttackerLogin = tolient.StartInitiatorPlayer; InitiatorPlaceServerId = tolient.InitiatorPlaceServerId; HostPlaceServerId = tolient.HostPlaceServerId; Loger.Log("Client GameAttackHost Start 2 " + tolient.HostPlaceServerId); LongEventHandler.QueueLongEvent(delegate { try { Loger.Log("Client GameAttackHost Start 3"); var hostPlace = UpdateWorldController.GetWOByServerId(HostPlaceServerId) as MapParent; var cloneMap = hostPlace.Map; var toSrvMap = new AttackHostToSrv() { State = 4, TerrainDefNameCell = new List <IntVec3S>(), TerrainDefName = new List <string>(), Thing = new List <ThingTrade>(), ThingCell = new List <IntVec3S>() }; toSrvMap.MapSize = new IntVec3S(cloneMap.Size); CellRect cellRect = CellRect.WholeMap(cloneMap); cellRect.ClipInsideMap(cloneMap); //почва Loger.Log("Client GameAttackHost Start 4"); foreach (IntVec3 current in cellRect) { var terr = cloneMap.terrainGrid.TerrainAt(current); toSrvMap.TerrainDefNameCell.Add(new IntVec3S(current)); toSrvMap.TerrainDefName.Add(terr.defName); } //скалы, преграды и строения без пешек и без растений не деревьев, вывести кол-во Loger.Log("Client GameAttackHost Start 5"); foreach (IntVec3 current in cellRect) { foreach (Thing thc in Find.CurrentMap.thingGrid.ThingsAt(current).ToList <Thing>()) { if (thc is Pawn) { continue; } //из растений оставляем только деревья if (thc.def.category == ThingCategory.Plant && !thc.def.plant.IsTree) { continue; } if (thc.Position != current) { continue; } var tt = ThingTrade.CreateTrade(thc, thc.stackCount, false); toSrvMap.ThingCell.Add(new IntVec3S(current)); toSrvMap.Thing.Add(tt); } } Loger.Log("Client GameAttackHost Start 6"); SessionClientController.Command((connect0) => { Loger.Log("Client GameAttackHost Start 7"); connect0.AttackOnlineHost(toSrvMap); if (!string.IsNullOrEmpty(connect0.ErrorMessage)) { ErrorBreak(connect0.ErrorMessage); return; } //Ждем и получаем пешки атакующего и добавляем их Loger.Log("Client GameAttackHost Start 8"); List <ThingEntry> pawnsA = null; var s1Time = DateTime.UtcNow; while (true) { var toClient5 = connect0.AttackOnlineHost(new AttackHostToSrv() { State = 5 }); if (!string.IsNullOrEmpty(connect0.ErrorMessage)) { ErrorBreak(connect0.ErrorMessage); return; } pawnsA = toClient5.Pawns; if (pawnsA != null && pawnsA.Count > 0) { break; } if ((DateTime.UtcNow - s1Time).TotalSeconds > 20) { ErrorBreak("Timeout"); return; } } if (!string.IsNullOrEmpty(connect0.ErrorMessage)) { ErrorBreak(connect0.ErrorMessage); return; } Loger.Log("Client GameAttackHost Start 9"); //Потом добавляем список к отправке SendedPawnsId = new HashSet <int>(); SendedState = new Dictionary <int, int>(); ToUpdateStateId = new List <int>(); ToUpdateState = new List <Thing>(); ToSendDeleteId = new HashSet <int>(); ToSendAddId = new HashSet <int>(); ToSendThingAdd = new HashSet <Thing>(); AttackingPawns = new List <Pawn>(); AttackingPawnDic = new Dictionary <int, int>(); AttackingPawnJobDic = new Dictionary <int, AttackPawnCommand>(); AttackUpdateTick = 0; GameMap = cloneMap; UIEventNewJobDisable = true; var cellPawns = GameUtils.SpawnCaravanPirate(cloneMap, pawnsA, (th, te) => { var p = th as Pawn; if (p == null) { return; } AttackingPawns.Add(p); AttackingPawnDic.Add(p.thingIDNumber, te.OriginalID); //задаем команду стоять и не двигаться (но стрелять если кто в радиусе) Loger.Log("Client GameAttackHost Start 9 StartJob Wait_Combat "); p.playerSettings.hostilityResponse = HostilityResponseMode.Ignore; p.jobs.StartJob(new Job(JobDefOf.Wait_Combat) { playerForced = true, expiryInterval = int.MaxValue, checkOverrideOnExpire = false, } , JobCondition.InterruptForced); /* * if (p.Label == "Douglas, Клерк") * { * //todo для теста не забыть удалить! * var pp = p; * var th = new Thread(() => * { * Thread.Sleep(5000); * while (true) * { * Thread.Sleep(1000); * try * { * var jj = pp.jobs.curJob; * Loger.Log("Host ThreadTestJob " + pp.Label + " job=" + (jj == null ? "null" : jj.def.defName.ToString())); * } * catch * { } * } * }); * th.IsBackground = true; * th.Start(); * } */ }); UIEventNewJobDisable = false; Loger.Log("Client GameAttackHost Start 10"); CameraJumper.TryJump(cellPawns, cloneMap); TimerObj = SessionClientController.Timers.Add(200, AttackUpdate); //включаем обработку событий урона и уничтожения объектов GameAttackTrigger_Patch.ActiveAttackHost.Add(GameMap, this); Loger.Log("Client GameAttackHost Start 11"); }); } catch (Exception ext) { Loger.Log("GameAttackHost Start() Exception " + ext.ToString()); } }, "...", false, null); }
public override void DoWindowContents(Rect inRect) { const float categoryPadding = 10f; const float categoryInset = 30f; const float radioLabelInset = 40f; const float mainListingSpacing = 6f; const float subListingSpacing = 6f; const float subListingLabelWidth = 100f; const float subListingRowHeight = 30f; const float checkboxListingWidth = 280f; const float listingColumnSpacing = 17f; var btnSize = new Vector2(140f, 40f); var buttonYStart = inRect.height - btnSize.y; if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x, buttonYStart, btnSize.x, btnSize.y), "OCity_Dialog_Registration_Close".Translate())) { Close(); } var ev = Event.current; if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x * 2, buttonYStart, btnSize.x, btnSize.y), "OCity_Dialog_Registration_BtnReg".Translate()) || ev.isKey && ev.type == EventType.keyDown && ev.keyCode == KeyCode.Return) { var msgError = SessionClientController.Registration(InputAddr, InputLogin, InputPassword); if (msgError == null) { StorageData.GlobalData.LastIP.Value = InputAddr; StorageData.GlobalData.LastLoginName.Value = InputLogin; HugsLibController.SettingsManager.SaveChanges(); Close(); } } var mainListing = new Listing_Standard(); mainListing.verticalSpacing = mainListingSpacing; mainListing.Begin(inRect); Text.Font = GameFont.Medium; mainListing.Label("OCity_Dialog_Registration_LabelReg".Translate()); Text.Font = GameFont.Small; mainListing.GapLine(); mainListing.Gap(); var textEditSize = new Vector2(150f, 25f); TextInput(mainListing, "OCity_Dialog_Registration_Server".Translate(), (sub, rect) => { GUI.SetNextControlName("StartTextField"); InputAddr = GUI.TextField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputAddr, 100); }); TextInput(mainListing, "OCity_Dialog_Registration_Login".Translate(), (sub, rect) => { InputLogin = GUI.TextField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputLogin, 100); }); TextInput(mainListing, "OCity_Dialog_Registration_Pass".Translate(), (sub, rect) => { InputPassword = GUI.PasswordField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputPassword, "*"[0], 100); }); TextInput(mainListing, "OCity_Dialog_Registration_Check".Translate(), (sub, rect) => { InputPassword2 = GUI.PasswordField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputPassword2, "*"[0], 100); }); if (NeedFockus) { NeedFockus = false; GUI.FocusControl("StartTextField"); } //mainListing.Label("Регистрация3."); mainListing.End(); //Text.Anchor = TextAnchor.UpperLeft; }
public override void DoWindowContents(Rect inRect) { const float categoryPadding = 10f; const float categoryInset = 30f; const float radioLabelInset = 40f; const float mainListingSpacing = 6f; const float subListingSpacing = 6f; const float subListingLabelWidth = 100f; const float subListingRowHeight = 30f; const float checkboxListingWidth = 280f; const float listingColumnSpacing = 17f; var btnSize = new Vector2(140f, 40f); var buttonYStart = inRect.height - btnSize.y; //кнопки var ev = Event.current; if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x * 3, buttonYStart, btnSize.x, btnSize.y), "OCity_LoginForm_BtnEnter".Translate()) || ev.isKey && ev.type == EventType.keyDown && ev.keyCode == KeyCode.Return) { var msgError = SessionClientController.Login(InputAddr, InputLogin, InputPassword); if (msgError == null) { StorageData.GlobalData.LastIP.Value = InputAddr; StorageData.GlobalData.LastLoginName.Value = InputLogin; HugsLibController.SettingsManager.SaveChanges(); //Loger.Log("login " + StorageData.GlobalData.LastIP.Value); Close(); } } if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x * 2, buttonYStart, btnSize.x, btnSize.y), "OCity_LoginForm_Register".Translate())) { Close(); Find.WindowStack.Add(new Dialog_Registration()); } if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x, buttonYStart, btnSize.x, btnSize.y), "OCity_LoginForm_Close".Translate())) { Close(); } //заголовок var mainListing = new Listing_Standard(); mainListing.verticalSpacing = mainListingSpacing; mainListing.Begin(inRect); Text.Font = GameFont.Medium; mainListing.Label("OCity_LoginForm_LabelEnter".Translate()); Text.Font = GameFont.Small; mainListing.GapLine(); mainListing.Gap(); var iresct = mainListing.GetRect(20f); //что к чему ListableOption item = new ListableOption_WebLink("Что к чему".NeedTranslate(), () => { var textForm = new Dialog_TextOut(Dialog_MainOnlineCity.AboutGeneralText); Find.WindowStack.Add(textForm); }, Dialog_MainOnlineCity.IconForums); item.DrawOption(new Vector2(iresct.x, iresct.y), iresct.width); //поля ввода var textEditSize = new Vector2(150f, 25f); TextInput(mainListing, "OCity_LoginForm_Server".Translate(), (sub, rect) => { InputAddr = GUI.TextField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputAddr, 100); }); TextInput(mainListing, "OCity_LoginForm_Login".Translate(), (sub, rect) => { InputLogin = GUI.TextField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputLogin, 100); }); TextInput(mainListing, "OCity_LoginForm_Pass".Translate(), (sub, rect) => { GUI.SetNextControlName("StartTextField"); InputPassword = GUI.PasswordField(new Rect(rect.x, rect.y, textEditSize.x, textEditSize.y), InputPassword, "*"[0], 100); }); if (NeedFockus) { NeedFockus = false; GUI.FocusControl("StartTextField"); } mainListing.End(); //Text.Anchor = TextAnchor.UpperLeft; }
public void DoTab2Contents(Rect inRect) { Text.Font = GameFont.Medium; Widgets.Label(inRect, "OCity_Dialog_AboutMode".Translate()); Text.Font = GameFont.Small; //var chatTextSize = Text.CalcSize(InfoTabText); var chatAreaOuter = new Rect(inRect.x + 150f, inRect.y + 40f, inRect.width - 150f, inRect.height - 30f - 40f); var chatAreaInner = new Rect(0, 0 , /*inRect.width - (inRect.x + 50f)*/ chatAreaOuter.width - ListBox <string> .WidthScrollLine , 0 /*chatTextSize.y*/); chatAreaInner.height = Text.CalcHeight(AboutTabText, chatAreaInner.width); InfoScrollPosition = GUI.BeginScrollView(chatAreaOuter, InfoScrollPosition, chatAreaInner); GUILayout.BeginArea(chatAreaInner); GUILayout.TextField(AboutTabText, "Label"); GUILayout.EndArea(); GUI.EndScrollView(); var rect2 = new Rect(inRect.x, inRect.y + inRect.height / 2f, 150f, inRect.height - 30f - 40f); Text.Font = GameFont.Small; List <ListableOption> list2 = new List <ListableOption>(); ListableOption item2 = new ListableOption_WebLink("OCity_Dialog_AutorPage".Translate(), "https://vk.com/rimworldonline", IconForums); list2.Add(item2); float num = OptionListingUtility.DrawOptionListing(rect2, list2); rect2 = new Rect(inRect.x, inRect.y + 30f, 150f, 40f); Text.Font = GameFont.Small; list2 = new List <ListableOption>(); item2 = new ListableOption_WebLink("OCity_Dialog_Regame".Translate(), () => { var form = new Dialog_Input("OCity_Dialog_DeleteData".Translate(), "OCity_Dialog_DeleteDataCheck".Translate()); form.PostCloseAction = () => { if (form.ResultOK) { var mainCannal = SessionClientController.Data.Chats[0]; SessionClientController.Command((connect) => { if (connect.PostingChat(mainCannal.Id, "/killmyallpleace")) { SessionClientController.Disconnected("OCity_Dialog_DeletedData".Translate()); } }); } }; Find.WindowStack.Add(form); }, IconDelTex); list2.Add(item2); num = OptionListingUtility.DrawOptionListing(rect2, list2); /* * GUI.BeginGroup(rect2); * if (Current.ProgramState == ProgramState.Entry && Widgets.ButtonImage(new Rect(0f, num + 10f, 64f, 32f), LanguageDatabase.activeLanguage.icon)) * { * List<FloatMenuOption> list3 = new List<FloatMenuOption>(); * foreach (LoadedLanguage current in LanguageDatabase.AllLoadedLanguages) * { * LoadedLanguage localLang = current; * list3.Add(new FloatMenuOption(localLang.FriendlyNameNative, delegate * { * LanguageDatabase.SelectLanguage(localLang); * Prefs.Save(); * }, MenuOptionPriority.Default, null, null, 0f, null, null)); * } * Find.WindowStack.Add(new FloatMenu(list3)); * } * GUI.EndGroup(); */ /* * var rectCannals = new Rect(inRect.x, inRect.y, 100f, (float)Math.Round((decimal)(inRect.height / 2f * 10f)) / 10f); * Widgets.DrawBoxSolid(inRect, new Color(0.2f, 0.2f, 0)); * Widgets.DrawBoxSolid(rectCannals, new Color(0.4f, 0.4f, 0)); * * * Widgets.DrawBoxSolid(new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 40f) * , new Color(0.4f, 0, 0)); * * Widgets.DrawBoxSolid(new Rect(inRect.x + 110f, inRect.y + inRect.height - 35f, inRect.width - 110f, 25f) * , new Color(0, 0, 0.4f)); * * Widgets.Label(inRect, "Вкладка 3"); */ }
/// <summary> /// Первая инициализация проекта. Остальная после входа в игру (после логина или регистрации). /// </summary> public MainButtonWorker_OC() { SessionClientController.Init(); }
private static void UpdateWorld(bool firstRun = false) { lock (UpdatingWorld) { Command((connect) => { //собираем пакет на сервер var toServ = new ModelPlayToServer() { UpdateTime = Data.UpdateTime, //время прошлого запроса }; //данные сохранения игры if (Data.SaveFileData != null) { toServ.SaveFileData = Data.SaveFileData; toServ.SingleSave = Data.SingleSave; Data.SaveFileData = null; } //собираем данные с планеты if (!firstRun) { UpdateWorldController.SendToServer(toServ); } if (firstRun) { GetPlayersInfoCountRequest = 0; } //запрос на информацию об игроках. Можно будет ограничить редкое получение для тех кто оффлайн if (Data.Chats != null && Data.Chats[0].PartyLogin != null) { if (Data.Players == null || Data.Players.Count == 0 || GetPlayersInfoCountRequest % 5 == 0) { //в начале и раз в пол минуты (5 сек между UpdateWorld * 5) получаем инфу обо всех toServ.GetPlayersInfo = Data.Chats[0].PartyLogin; } else { //в промежутках о тех кто онлайн toServ.GetPlayersInfo = Data.Players.Values.Where(p => p.Online).Select(p => p.Public.Login).ToList(); } GetPlayersInfoCountRequest++; //Loger.Log("Client " + My.Login + " UpdateWorld* " + (toServ.GetPlayersInfo.Count.ToString()) // + " " + (toServ.GetPlayersInfo.Any(p => p == SessionClientController.My.Login) ? "1" : "0")); } //отправляем на сервер, получаем ответ ModelPlayToClient fromServ = connect.PlayInfo(toServ); //Loger.Log("Client UpdateWorld 5 "); Loger.Log("Client " + My.Login + " UpdateWorld " + string.Format("Отпр. свои {0}, своиDel {1}{5}. Пришло {2}, del {3}, игроков {8}, посылок {4}{6}{7}" , toServ.WObjects == null ? 0 : toServ.WObjects.Count , toServ.WObjectsToDelete == null ? 0 : toServ.WObjectsToDelete.Count , fromServ.WObjects == null ? 0 : fromServ.WObjects.Count , fromServ.WObjectsToDelete == null ? 0 : fromServ.WObjectsToDelete.Count , fromServ.Mails == null ? 0 : fromServ.Mails.Count , toServ.SaveFileData == null || toServ.SaveFileData.Length == 0 ? "" : ", сейв" , fromServ.AreAttacking ? " Атакуют!" : "" , fromServ.NeedSaveAndExit ? " Команда на отключение" : "" , fromServ.PlayersInfo == null ? "null" : fromServ.PlayersInfo.Count.ToString() )); //сохраняем время актуальности данных Data.UpdateTime = fromServ.UpdateTime; if (!string.IsNullOrEmpty(fromServ.KeyReconnect)) { Data.KeyReconnect = fromServ.KeyReconnect; } //обновляем информацию по игрокам if (fromServ.PlayersInfo != null && fromServ.PlayersInfo.Count > 0) { foreach (var pi in fromServ.PlayersInfo) { if (pi.Login == null) { continue; } Data.Players[pi.Login] = new PlayerClient() { Public = pi }; if (pi.Login == My.Login) { My = pi; Data.MyEx = Data.Players[pi.Login]; //Loger.Log("Client " + My.Login + " UpdateWorld* " + My.LastOnlineTime.ToString("o") + " " + DateTime.UtcNow.ToString("o") // + " " + (toServ.GetPlayersInfo.Any(p => p == My.Login) ? "1" : "0")); } } } //обновляем планету UpdateWorldController.LoadFromServer(fromServ, firstRun); //обновляем инфу по поселениям var allWObjects = Find.WorldObjects.AllWorldObjects .Select(o => o as CaravanOnline) .Where(o => o != null) .ToList(); foreach (var pi in Data.Players) { if (pi.Value.Public.Login == My.Login) { continue; } pi.Value.WObjects = allWObjects.Where(wo => wo.OnlinePlayerLogin == pi.Key).ToList(); } //Сохраняем и выходим if (fromServ.NeedSaveAndExit) { if (!SessionClientController.Data.BackgroundSaveGameOff) { SessionClientController.SaveGameNow(false, () => { SessionClientController.Disconnected("OCity_SessionCC_Shutdown_Command_ProgressSaved".Translate()); }); } else { SessionClientController.Disconnected("OCity_SessionCC_Shutdown_Command".Translate()); } } //если на нас напали запускаем процесс if (fromServ.AreAttacking && GameAttackHost.AttackMessage()) { GameAttackHost.Get.Start(connect); } }); } }