void InitUPnP() { server.UPnP.ForwardPort(config.Port, "barotrauma"); upnpBox = new GUIMessageBox("Please wait...", "Attempting UPnP port forwarding", new string[] { "Cancel" }); upnpBox.Buttons[0].OnClicked = upnpBox.Close; }
private void ShowError(string header, string message) { GUIFrame dummyFrame = new GUIFrame(new Rectangle(0, 0, graphicsWidth, graphicsHeight)); GUIMessageBox errorBox = new GUIMessageBox(header, message, new string[] { "OK" }, 400, 250, Alignment.TopLeft, dummyFrame); errorBox.Buttons[0].OnClicked = errorBox.Close; }
public void CreateKickReasonPrompt(string clientName, bool ban, bool rangeBan = false) { var banReasonPrompt = new GUIMessageBox(ban ? "Reason for the ban?" : "Reason for kicking?", "", new string[] { "OK", "Cancel" }, 400, 300); var banReasonBox = new GUITextBox(new Rectangle(0, 30, 0, 50), Alignment.TopCenter, "", banReasonPrompt.children[0]); banReasonBox.Wrap = true; banReasonBox.MaxTextLength = 100; GUINumberInput durationInputDays = null, durationInputHours = null; GUITickBox permaBanTickBox = null; if (ban) { new GUITextBlock(new Rectangle(0, 80, 0, 0), "Duration:", "", banReasonPrompt.children[0]); permaBanTickBox = new GUITickBox(new Rectangle(0, 110, 15, 15), "Permanent", Alignment.TopLeft, banReasonPrompt.children[0]); permaBanTickBox.Selected = true; var durationContainer = new GUIFrame(new Rectangle(0, 130, 0, 40), null, banReasonPrompt.children[0]); durationContainer.Visible = false; permaBanTickBox.OnSelected += (tickBox) => { durationContainer.Visible = !tickBox.Selected; return(true); }; new GUITextBlock(new Rectangle(0, 0, 30, 20), "Days:", "", Alignment.TopLeft, Alignment.CenterLeft, durationContainer); durationInputDays = new GUINumberInput(new Rectangle(40, 0, 50, 20), "", 0, 1000, durationContainer); new GUITextBlock(new Rectangle(100, 0, 30, 20), "Hours:", "", Alignment.TopLeft, Alignment.CenterLeft, durationContainer); durationInputHours = new GUINumberInput(new Rectangle(150, 0, 50, 20), "", 0, 24, durationContainer); } banReasonPrompt.Buttons[0].OnClicked += (btn, userData) => { if (ban) { if (!permaBanTickBox.Selected) { TimeSpan banDuration = new TimeSpan(durationInputDays.Value, durationInputHours.Value, 0, 0); BanPlayer(clientName, banReasonBox.Text, ban, banDuration); } else { BanPlayer(clientName, banReasonBox.Text, ban); } } else { KickPlayer(clientName, banReasonBox.Text); } return(true); }; banReasonPrompt.Buttons[0].OnClicked += banReasonPrompt.Close; banReasonPrompt.Buttons[1].OnClicked += banReasonPrompt.Close; }
void InitUPnP() { server.UPnP.ForwardPort(NetPeerConfiguration.Port, "barotrauma"); if (Steam.SteamManager.USE_STEAM) { server.UPnP.ForwardPort(QueryPort, "barotrauma"); } upnpBox = new GUIMessageBox(TextManager.Get("PleaseWaitUPnP"), TextManager.Get("AttemptingUPnP"), new string[] { TextManager.Get("Cancel") }); upnpBox.Buttons[0].OnClicked = upnpBox.Close; }
private void ShowError(string header, string message) { GUIMessageBox errorBox = new GUIMessageBox(header, message, new string[] { "OK" }, 400, 250, Alignment.Center); errorBox.Buttons[0].OnClicked = errorBox.Close; /*errorBox.InnerFrame.Rect = new Rectangle( * (graphicsWidth - errorBox.InnerFrame.Rect.Width) / 2, * (graphicsHeight - errorBox.InnerFrame.Rect.Height) / 2, * errorBox.InnerFrame.Rect.Width, * errorBox.InnerFrame.Rect.Height);*/ }
public override void MsgBox() { if (mission == null) { return; } var missionMsg = new GUIMessageBox(mission.Name, mission.Description, 400, 400); missionMsg.UserData = "missionstartmessage"; Networking.GameServer.Log("Mission: " + mission.Name, Networking.ServerLog.MessageType.ServerMessage); Networking.GameServer.Log(mission.Description, Networking.ServerLog.MessageType.ServerMessage); }
private void ShowError(string header, string message) { GUIFrame dummyFrame = new GUIFrame(new Rectangle(0, 0, graphicsWidth, graphicsHeight)); dummyFrame.Padding = Vector4.Zero; GUIMessageBox errorBox = new GUIMessageBox(header, message, new string[] { "OK" }, 400, 250, Alignment.Center, dummyFrame); errorBox.Buttons[0].OnClicked = errorBox.Close; errorBox.InnerFrame.Rect = new Rectangle( (graphicsWidth - errorBox.InnerFrame.Rect.Width) / 2, (graphicsHeight - errorBox.InnerFrame.Rect.Height) / 2, errorBox.InnerFrame.Rect.Width, errorBox.InnerFrame.Rect.Height); }
private IEnumerable <object> Dead() { yield return(new WaitForSeconds(3.0f)); var messageBox = new GUIMessageBox("You have died", "Do you want to try again?", new string[] { "Yes", "No" }); messageBox.Buttons[0].OnClicked += Restart; messageBox.Buttons[0].OnClicked += messageBox.Close; messageBox.Buttons[1].OnClicked = GameMain.MainMenuScreen.SelectTab; messageBox.Buttons[1].OnClicked += messageBox.Close; yield return(CoroutineStatus.Success); }
// Выход из программы. private void TB_Exit_Click(object sender, EventArgs e) { // Запрашивать подтверждение, но только если программа запущена без ошибок в базе данных. if (isCorrectLaunch) { DialogResult result = GUIMessageBox.ShowDlg(GUIMessageBox.Type.CONFIRMATION, "Вы действительно хотите закрыть программу управления?"); if (result == DialogResult.Yes) { Dispose(); } } else { Dispose(); } }
public override void Update(float deltaTime) { if (!isActive) { return; } if (ChildServerRelay.HasShutDown || (ChildServerRelay.Process?.HasExited ?? true)) { Close(); var msgBox = new GUIMessageBox(TextManager.Get("ConnectionLost"), TextManager.Get("ServerProcessClosed")); msgBox.Buttons[0].OnClicked += (btn, obj) => { GameMain.MainMenuScreen.Select(); return(false); }; return; } for (int i = remotePeers.Count - 1; i >= 0; i--) { if (remotePeers[i].DisconnectTime != null && remotePeers[i].DisconnectTime < Timing.TotalTime) { ClosePeerSession(remotePeers[i]); } } for (int i = 0; i < 100; i++) { if (!Steamworks.SteamNetworking.IsP2PPacketAvailable()) { break; } var packet = Steamworks.SteamNetworking.ReadP2PPacket(); if (packet.HasValue) { OnP2PData(packet?.SteamId ?? 0, packet?.Data, packet?.Data.Length ?? 0, 0); receivedBytes += packet?.Data.Length ?? 0; } } GameMain.Client?.NetStats?.AddValue(NetStats.NetStatType.ReceivedBytes, receivedBytes); GameMain.Client?.NetStats?.AddValue(NetStats.NetStatType.SentBytes, sentBytes); while (ChildServerRelay.Read(out byte[] incBuf)) { ChildServerRelay.DisposeLocalHandles(); IReadMessage inc = new ReadOnlyMessage(incBuf, false, 0, incBuf.Length, ServerConnection); HandleDataMessage(inc); } }
private IEnumerable <object> Dead() { GUI.PreventPauseMenuToggle = true; Character.Controlled = character = null; Stop(); yield return(new WaitForSeconds(3.0f)); var messageBox = new GUIMessageBox(TextManager.Get("Tutorial.TryAgainHeader"), TextManager.Get("Tutorial.TryAgain"), new string[] { TextManager.Get("Yes"), TextManager.Get("No") }); messageBox.Buttons[0].OnClicked += Restart; messageBox.Buttons[0].OnClicked += messageBox.Close; messageBox.Buttons[1].OnClicked = GameMain.MainMenuScreen.ReturnToMainMenu; messageBox.Buttons[1].OnClicked += messageBox.Close; yield return(CoroutineStatus.Success); }
/// <summary> /// Возвращает тип повреждения, исходя из имени. /// </summary> public static Type GetTypeByName(string tgName) { switch (tgName) { case "Ожог": return(Type.BURN); case "Открытая рана": return(Type.OPEN); case "Перелом": return(Type.BREAK); case "Разорваный сосуд": return(Type.VEIL); case "Разорваный нерв": return(Type.NERV); default: { // Такого происходить не должно, поэтому сообщаем об ошибке. GUIMessageBox.ShowDlg("Попытка получить несуществующий тип повреждения \"" + tgName + "\"."); return(Type.BURN); } } }
public override void Update(float deltaTime) { if (!isActive) { return; } if (ownerKey != 0 && (ChildServerRelay.Process?.HasExited ?? true)) { Close(); var msgBox = new GUIMessageBox(TextManager.Get("ConnectionLost"), TextManager.Get("ServerProcessClosed")); msgBox.Buttons[0].OnClicked += (btn, obj) => { GameMain.MainMenuScreen.Select(); return(false); }; return; } incomingLidgrenMessages.Clear(); netClient.ReadMessages(incomingLidgrenMessages); GameMain.Client?.NetStats?.AddValue(NetStats.NetStatType.ReceivedBytes, netClient.Statistics.ReceivedBytes); GameMain.Client?.NetStats?.AddValue(NetStats.NetStatType.SentBytes, netClient.Statistics.SentBytes); foreach (NetIncomingMessage inc in incomingLidgrenMessages) { if (inc.SenderConnection != (ServerConnection as LidgrenConnection).NetConnection) { continue; } switch (inc.MessageType) { case NetIncomingMessageType.Data: HandleDataMessage(inc); break; case NetIncomingMessageType.StatusChanged: HandleStatusChanged(inc); break; } } }
private void Completed(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { string errorMsg = "Error while downloading: " + e.Error; GUITextBlock textBlock = new GUITextBlock( new Rectangle(0, 0, 0, 0), errorMsg, "", Alignment.TopLeft, Alignment.TopLeft, updateInfoBox, true, GUI.SmallFont); textBlock.TextColor = Color.Red; GUIFrame dummyFrame = new GUIFrame(new Rectangle(0, 0, graphicsWidth, graphicsHeight)); dummyFrame.Padding = Vector4.Zero; GUIMessageBox errorBox = new GUIMessageBox("Error while updating", "Downloading the update failed.", new string[] { "Retry", "Cancel" }, 400, 200, Alignment.Center, dummyFrame); errorBox.InnerFrame.Rect = new Rectangle( (graphicsWidth - errorBox.InnerFrame.Rect.Width) / 2, (graphicsHeight - errorBox.InnerFrame.Rect.Height) / 2, errorBox.InnerFrame.Rect.Width, errorBox.InnerFrame.Rect.Height); errorBox.Buttons[0].OnClicked += DownloadButtonClicked; errorBox.Buttons[0].OnClicked += errorBox.Close; errorBox.Buttons[1].OnClicked = CancelUpdate; errorBox.Buttons[1].OnClicked += errorBox.Close; return; } filesDownloaded++; progressBar.BarSize = ((float)filesDownloaded / (float)filesToDownloadCount);//e.ProgressPercentage; DownloadNextFile(); }
protected override void CreateGUI() { controlContainer = new GUIFrame(new RectTransform(new Vector2(Sonar.controlBoxSize.X, 1 - Sonar.controlBoxSize.Y * 2), GuiFrame.RectTransform, Anchor.CenterRight), "ItemUI"); var paddedControlContainer = new GUIFrame(new RectTransform(controlContainer.Rect.Size - GUIStyle.ItemFrameMargin, controlContainer.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset }, style: null); var steeringModeArea = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), paddedControlContainer.RectTransform, Anchor.TopLeft), style: null); steeringModeSwitch = new GUIButton(new RectTransform(new Vector2(0.2f, 1), steeringModeArea.RectTransform), string.Empty, style: "SwitchVertical") { Selected = autoPilot, Enabled = true, ClickSound = GUISoundType.UISwitch, OnClicked = (button, data) => { button.Selected = !button.Selected; AutoPilot = button.Selected; if (GameMain.Client != null) { unsentChanges = true; user = Character.Controlled; } return(true); } }; var steeringModeRightSide = new GUIFrame(new RectTransform(new Vector2(1.0f - steeringModeSwitch.RectTransform.RelativeSize.X, 0.8f), steeringModeArea.RectTransform, Anchor.CenterLeft) { RelativeOffset = new Vector2(steeringModeSwitch.RectTransform.RelativeSize.X, 0) }, style: null); manualPilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.TopLeft), TextManager.Get("SteeringManual"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall") { Selected = !autoPilot, Enabled = false }; autopilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.BottomLeft), TextManager.Get("SteeringAutoPilot"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall") { Selected = autoPilot, Enabled = false }; manualPilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor); autopilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor); GUITextBlock.AutoScaleAndNormalize(manualPilotIndicator.TextBlock, autopilotIndicator.TextBlock); var autoPilotControls = new GUIFrame(new RectTransform(new Vector2(0.75f, 0.62f), paddedControlContainer.RectTransform, Anchor.BottomCenter), "OutlineFrame"); var paddedAutoPilotControls = new GUIFrame(new RectTransform(new Vector2(0.92f, 0.88f), autoPilotControls.RectTransform, Anchor.Center), style: null); maintainPosTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.TopCenter), TextManager.Get("SteeringMaintainPos"), font: GUI.SmallFont, style: "GUIRadioButton") { Enabled = autoPilot, Selected = maintainPos, OnSelected = tickBox => { if (maintainPos != tickBox.Selected) { unsentChanges = true; user = Character.Controlled; maintainPos = tickBox.Selected; if (maintainPos) { if (controlledSub == null) { posToMaintain = null; } else { posToMaintain = controlledSub.WorldPosition; } } else if (!LevelEndSelected && !LevelStartSelected) { AutoPilot = false; } if (!maintainPos) { posToMaintain = null; } } return(true); } }; int textLimit = (int)(MathHelper.Clamp(25 * GUI.xScale, 15, 35)); levelStartTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.Center), GameMain.GameSession?.StartLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.StartLocation.Name, textLimit), font: GUI.SmallFont, style: "GUIRadioButton") { Enabled = autoPilot, Selected = levelStartSelected, OnSelected = tickBox => { if (levelStartSelected != tickBox.Selected) { unsentChanges = true; user = Character.Controlled; levelStartSelected = tickBox.Selected; levelEndSelected = !levelStartSelected; if (levelStartSelected) { UpdatePath(); } else if (!MaintainPos && !LevelEndSelected) { AutoPilot = false; } } return(true); } }; levelEndTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.BottomCenter), (GameMain.GameSession?.EndLocation == null || Level.IsLoadedOutpost) ? "" : ToolBox.LimitString(GameMain.GameSession.EndLocation.Name, textLimit), font: GUI.SmallFont, style: "GUIRadioButton") { Enabled = autoPilot, Selected = levelEndSelected, Visible = GameMain.GameSession?.EndLocation != null, OnSelected = tickBox => { if (levelEndSelected != tickBox.Selected) { unsentChanges = true; user = Character.Controlled; levelEndSelected = tickBox.Selected; levelStartSelected = !levelEndSelected; if (levelEndSelected) { UpdatePath(); } else if (!MaintainPos && !LevelStartSelected) { AutoPilot = false; } } return(true); } }; maintainPosTickBox.RectTransform.IsFixedSize = levelStartTickBox.RectTransform.IsFixedSize = levelEndTickBox.RectTransform.IsFixedSize = false; maintainPosTickBox.RectTransform.MaxSize = levelStartTickBox.RectTransform.MaxSize = levelEndTickBox.RectTransform.MaxSize = new Point(int.MaxValue, paddedAutoPilotControls.Rect.Height / 3); maintainPosTickBox.RectTransform.MinSize = levelStartTickBox.RectTransform.MinSize = levelEndTickBox.RectTransform.MinSize = Point.Zero; GUITextBlock.AutoScaleAndNormalize(scaleHorizontal: false, scaleVertical: true, maintainPosTickBox.TextBlock, levelStartTickBox.TextBlock, levelEndTickBox.TextBlock); GUIRadioButtonGroup destinations = new GUIRadioButtonGroup(); destinations.AddRadioButton((int)Destination.MaintainPos, maintainPosTickBox); destinations.AddRadioButton((int)Destination.LevelStart, levelStartTickBox); destinations.AddRadioButton((int)Destination.LevelEnd, levelEndTickBox); destinations.Selected = (int)(maintainPos ? Destination.MaintainPos : levelStartSelected ? Destination.LevelStart : Destination.LevelEnd); // Status -> statusContainer = new GUIFrame(new RectTransform(Sonar.controlBoxSize, GuiFrame.RectTransform, Anchor.BottomRight) { RelativeOffset = Sonar.controlBoxOffset }, "ItemUI"); var paddedStatusContainer = new GUIFrame(new RectTransform(statusContainer.Rect.Size - GUIStyle.ItemFrameMargin, statusContainer.RectTransform, Anchor.Center, isFixedSize: false) { AbsoluteOffset = GUIStyle.ItemFrameOffset }, style: null); var elements = GUI.CreateElements(3, new Vector2(1f, 0.333f), paddedStatusContainer.RectTransform, rt => new GUIFrame(rt, style: null), Anchor.TopCenter, relativeSpacing: 0.01f); List <GUIComponent> leftElements = new List <GUIComponent>(), centerElements = new List <GUIComponent>(), rightElements = new List <GUIComponent>(); for (int i = 0; i < elements.Count; i++) { var e = elements[i]; var group = new GUILayoutGroup(new RectTransform(Vector2.One, e.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft) { RelativeSpacing = 0.01f, Stretch = true }; var left = new GUIFrame(new RectTransform(new Vector2(0.45f, 1), group.RectTransform), style: null); var center = new GUIFrame(new RectTransform(new Vector2(0.15f, 1), group.RectTransform), style: null); var right = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.8f), group.RectTransform), style: null); leftElements.Add(left); centerElements.Add(center); rightElements.Add(right); string leftText = string.Empty, centerText = string.Empty; GUITextBlock.TextGetterHandler rightTextGetter = null; switch (i) { case 0: leftText = TextManager.Get("DescentVelocity"); centerText = $"({TextManager.Get("KilometersPerHour")})"; rightTextGetter = () => { Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity; var realWorldVel = ConvertUnits.ToDisplayUnits(vel.Y * Physics.DisplayToRealWorldRatio) * 3.6f; return(((int)(-realWorldVel)).ToString()); }; break; case 1: leftText = TextManager.Get("Velocity"); centerText = $"({TextManager.Get("KilometersPerHour")})"; rightTextGetter = () => { Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity; var realWorldVel = ConvertUnits.ToDisplayUnits(vel.X * Physics.DisplayToRealWorldRatio) * 3.6f; return(((int)realWorldVel).ToString()); }; break; case 2: leftText = TextManager.Get("Depth"); centerText = $"({TextManager.Get("Meter")})"; rightTextGetter = () => { float realWorldDepth = controlledSub == null ? -1000.0f : controlledSub.RealWorldDepth; return(((int)realWorldDepth).ToString()); }; break; } new GUITextBlock(new RectTransform(Vector2.One, left.RectTransform), leftText, font: GUI.SubHeadingFont, wrap: leftText.Contains(' '), textAlignment: Alignment.CenterRight); new GUITextBlock(new RectTransform(Vector2.One, center.RectTransform), centerText, font: GUI.Font, textAlignment: Alignment.Center) { Padding = Vector4.Zero }; var digitalFrame = new GUIFrame(new RectTransform(Vector2.One, right.RectTransform), style: "DigitalFrameDark"); new GUITextBlock(new RectTransform(Vector2.One * 0.85f, digitalFrame.RectTransform, Anchor.Center), "12345", GUI.Style.TextColorDark, GUI.DigitalFont, Alignment.CenterRight) { TextGetter = rightTextGetter }; } GUITextBlock.AutoScaleAndNormalize(leftElements.SelectMany(e => e.GetAllChildren <GUITextBlock>())); GUITextBlock.AutoScaleAndNormalize(centerElements.SelectMany(e => e.GetAllChildren <GUITextBlock>())); GUITextBlock.AutoScaleAndNormalize(rightElements.SelectMany(e => e.GetAllChildren <GUITextBlock>())); //docking interface ---------------------------------------------------- float dockingButtonSize = 1.1f; float elementScale = 0.6f; dockingContainer = new GUIFrame(new RectTransform(Sonar.controlBoxSize, GuiFrame.RectTransform, Anchor.BottomRight, scaleBasis: ScaleBasis.Smallest) { RelativeOffset = new Vector2(Sonar.controlBoxOffset.X + 0.05f, -0.05f) }, style: null); dockText = TextManager.Get("label.navterminaldock", fallBackTag: "captain.dock"); undockText = TextManager.Get("label.navterminalundock", fallBackTag: "captain.undock"); dockingButton = new GUIButton(new RectTransform(new Vector2(elementScale), dockingContainer.RectTransform, Anchor.Center), dockText, style: "PowerButton") { OnClicked = (btn, userdata) => { if (GameMain.GameSession?.Campaign is CampaignMode campaign) { if (Level.IsLoadedOutpost && DockingSources.Any(d => d.Docked && (d.DockingTarget?.Item.Submarine?.Info?.IsOutpost ?? false))) { // Undocking from an outpost campaign.CampaignUI.SelectTab(CampaignMode.InteractionType.Map); campaign.ShowCampaignUI = true; return(false); } else if (!Level.IsLoadedOutpost && DockingModeEnabled && ActiveDockingSource != null && !ActiveDockingSource.Docked && DockingTarget?.Item?.Submarine == Level.Loaded.StartOutpost && (DockingTarget?.Item?.Submarine?.Info.IsOutpost ?? false)) { // Docking to an outpost var subsToLeaveBehind = campaign.GetSubsToLeaveBehind(Item.Submarine); if (subsToLeaveBehind.Any()) { enterOutpostPrompt = new GUIMessageBox( TextManager.GetWithVariable("enterlocation", "[locationname]", DockingTarget.Item.Submarine.Info.Name), TextManager.Get(subsToLeaveBehind.Count == 1 ? "LeaveSubBehind" : "LeaveSubsBehind"), new string[] { TextManager.Get("yes"), TextManager.Get("no") }); } else { enterOutpostPrompt = new GUIMessageBox("", TextManager.GetWithVariable("campaignenteroutpostprompt", "[locationname]", DockingTarget.Item.Submarine.Info.Name), new string[] { TextManager.Get("yes"), TextManager.Get("no") }); } enterOutpostPrompt.Buttons[0].OnClicked += (btn, userdata) => { SendDockingSignal(); enterOutpostPrompt.Close(); return(true); }; enterOutpostPrompt.Buttons[1].OnClicked += enterOutpostPrompt.Close; return(false); } } SendDockingSignal(); return(true); } }; void SendDockingSignal() { if (GameMain.Client == null) { item.SendSignal(0, "1", "toggle_docking", sender: null); } else { dockingNetworkMessagePending = true; item.CreateClientEvent(this); } } dockingButton.Font = GUI.SubHeadingFont; dockingButton.TextBlock.RectTransform.MaxSize = new Point((int)(dockingButton.Rect.Width * 0.7f), int.MaxValue); dockingButton.TextBlock.AutoScaleHorizontal = true; var style = GUI.Style.GetComponentStyle("DockingButtonUp"); Sprite buttonSprite = style.Sprites.FirstOrDefault().Value.FirstOrDefault()?.Sprite; Point buttonSize = buttonSprite != null?buttonSprite.size.ToPoint() : new Point(149, 52); Point horizontalButtonSize = buttonSize.Multiply(elementScale * GUI.Scale * dockingButtonSize); Point verticalButtonSize = horizontalButtonSize.Flip(); var leftButton = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterLeft), "", style: "DockingButtonLeft") { OnClicked = NudgeButtonClicked, UserData = -Vector2.UnitX }; var rightButton = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterRight), "", style: "DockingButtonRight") { OnClicked = NudgeButtonClicked, UserData = Vector2.UnitX }; var upButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.TopCenter), "", style: "DockingButtonUp") { OnClicked = NudgeButtonClicked, UserData = Vector2.UnitY }; var downButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.BottomCenter), "", style: "DockingButtonDown") { OnClicked = NudgeButtonClicked, UserData = -Vector2.UnitY }; // Sonar area steerArea = new GUICustomComponent(new RectTransform(Sonar.GUISizeCalculation, GuiFrame.RectTransform, Anchor.CenterLeft, scaleBasis: ScaleBasis.Smallest), (spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null); steerRadius = steerArea.Rect.Width / 2; pressureWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), steerArea.RectTransform, Anchor.Center, Pivot.TopCenter), TextManager.Get("SteeringDepthWarning"), Color.Red, GUI.LargeFont, Alignment.Center) { Visible = false }; // Tooltip/helper text tipContainer = new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.1f), steerArea.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) , "", font: GUI.Font, wrap: true, style: "GUIToolTip", textAlignment: Alignment.Center) { AutoScaleHorizontal = true }; noPowerTip = TextManager.Get("SteeringNoPowerTip"); autoPilotMaintainPosTip = TextManager.Get("SteeringAutoPilotMaintainPosTip"); autoPilotLevelStartTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]", GameMain.GameSession?.StartLocation == null ? "Start" : GameMain.GameSession.StartLocation.Name); autoPilotLevelEndTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]", GameMain.GameSession?.EndLocation == null ? "End" : GameMain.GameSession.EndLocation.Name); }
public void CreateDebugHUD(Planter planter, PlantSlot slot) { Vector2 relativeSize = new Vector2(0.3f, 0.6f); GUIMessageBox msgBox = new GUIMessageBox(item.Name, "", new[] { TextManager.Get("applysettingsbutton") }, relativeSize); GUILayoutGroup content = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.85f), msgBox.Content.RectTransform)) { Stretch = true }; GUINumberInput seedInput = CreateIntEntry("Random Seed", seed, content.RectTransform); GUINumberInput vineTileSizeInput = CreateIntEntry("Vine Tile Size (Global)", VineTile.Size, content.RectTransform); GUINumberInput[] leafScaleRangeInput = CreateMinMaxEntry("Leaf Scale Range (Global)", new [] { MinLeafScale, MaxLeafScale }, 1.5f, content.RectTransform); GUINumberInput[] flowerScaleRangeInput = CreateMinMaxEntry("Flower Scale Range (Global)", new [] { MinFlowerScale, MaxFlowerScale }, 1.5f, content.RectTransform); GUINumberInput vineCountInput = CreateIntEntry("Vine Count", MaximumVines, content.RectTransform); GUINumberInput vineScaleInput = CreateFloatEntry("Vine Scale", VineScale, content.RectTransform); GUINumberInput flowerInput = CreateIntEntry("Flower Quantity", FlowerQuantity, content.RectTransform); GUINumberInput flowerScaleInput = CreateFloatEntry("Flower Scale", BaseFlowerScale, content.RectTransform); GUINumberInput leafScaleInput = CreateFloatEntry("Leaf Scale", BaseLeafScale, content.RectTransform); GUINumberInput leafProbabilityInput = CreateFloatEntry("Leaf Probability", LeafProbability, content.RectTransform); GUINumberInput[] leafTintInputs = CreateMinMaxEntry("Leaf Tint", new [] { LeafTint.R / 255f, LeafTint.G / 255f, LeafTint.B / 255f }, 1.0f, content.RectTransform); GUINumberInput[] flowerTintInputs = CreateMinMaxEntry("Flower Tint", new [] { FlowerTint.R / 255f, FlowerTint.G / 255f, FlowerTint.B / 255f }, 1.0f, content.RectTransform); GUINumberInput[] vineTintInputs = CreateMinMaxEntry("Branch Tint", new [] { VineTint.R / 255f, VineTint.G / 255f, VineTint.B / 255f }, 1.0f, content.RectTransform); // Apply msgBox.Buttons[0].OnClicked = (button, o) => { seed = seedInput.IntValue; MaximumVines = vineCountInput.IntValue; FlowerQuantity = flowerInput.IntValue; BaseFlowerScale = flowerScaleInput.FloatValue; VineScale = vineScaleInput.FloatValue; BaseLeafScale = leafScaleInput.FloatValue; LeafProbability = leafProbabilityInput.FloatValue; VineTile.Size = vineTileSizeInput.IntValue; MinFlowerScale = flowerScaleRangeInput[0].FloatValue; MaxFlowerScale = flowerScaleRangeInput[1].FloatValue; MinLeafScale = leafScaleRangeInput[0].FloatValue; MaxLeafScale = leafScaleRangeInput[1].FloatValue; LeafTint = new Color(leafTintInputs[0].FloatValue, leafTintInputs[1].FloatValue, leafTintInputs[2].FloatValue); FlowerTint = new Color(flowerTintInputs[0].FloatValue, flowerTintInputs[1].FloatValue, flowerTintInputs[2].FloatValue); VineTint = new Color(vineTintInputs[0].FloatValue, vineTintInputs[1].FloatValue, vineTintInputs[2].FloatValue); if (FlowerQuantity >= MaximumVines - 1) { vineCountInput.Flash(Color.Red); flowerInput.Flash(Color.Red); return(false); } if (MinFlowerScale > MaxFlowerScale) { foreach (GUINumberInput input in flowerScaleRangeInput) { input.Flash(Color.Red); } return(false); } if (MinLeafScale > MaxLeafScale) { foreach (GUINumberInput input in leafScaleRangeInput) { input.Flash(Color.Red); } return(false); } msgBox.Close(); Random random = new Random(seed); Random flowerRandom = new Random(seed); Vines.Clear(); GenerateFlowerTiles(flowerRandom); GenerateStem(); Decayed = false; FullyGrown = false; while (MaximumVines > Vines.Count) { if (!CanGrowMore()) { Decayed = true; break; } TryGenerateBranches(planter, slot, random, flowerRandom); } if (!Decayed) { FullyGrown = true; } foreach (VineTile vineTile in Vines) { vineTile.GrowthStep = 2.0f; } return(true); }; }
protected void ReadConnectionInitializationStep(IReadMessage inc) { ConnectionInitialization step = (ConnectionInitialization)inc.ReadByte(); IWriteMessage outMsg; switch (step) { case ConnectionInitialization.SteamTicketAndVersion: if (initializationStep != ConnectionInitialization.SteamTicketAndVersion) { return; } outMsg = new WriteOnlyMessage(); outMsg.Write((byte)PacketHeader.IsConnectionInitializationStep); outMsg.Write((byte)ConnectionInitialization.SteamTicketAndVersion); outMsg.Write(Name); outMsg.Write(ownerKey); outMsg.Write(SteamManager.GetSteamID()); if (steamAuthTicket == null) { outMsg.Write((UInt16)0); } else { outMsg.Write((UInt16)steamAuthTicket.Data.Length); outMsg.Write(steamAuthTicket.Data, 0, steamAuthTicket.Data.Length); } outMsg.Write(GameMain.Version.ToString()); outMsg.Write(GameMain.Config.Language); SendMsgInternal(DeliveryMethod.Reliable, outMsg); break; case ConnectionInitialization.ContentPackageOrder: if (initializationStep == ConnectionInitialization.SteamTicketAndVersion || initializationStep == ConnectionInitialization.Password) { initializationStep = ConnectionInitialization.ContentPackageOrder; } if (initializationStep != ConnectionInitialization.ContentPackageOrder) { return; } outMsg = new WriteOnlyMessage(); outMsg.Write((byte)PacketHeader.IsConnectionInitializationStep); outMsg.Write((byte)ConnectionInitialization.ContentPackageOrder); string serverName = inc.ReadString(); UInt32 cpCount = inc.ReadVariableUInt32(); ServerContentPackage corePackage = null; List <ServerContentPackage> regularPackages = new List <ServerContentPackage>(); List <ServerContentPackage> missingPackages = new List <ServerContentPackage>(); for (int i = 0; i < cpCount; i++) { string name = inc.ReadString(); string hash = inc.ReadString(); UInt64 workshopId = inc.ReadUInt64(); var pkg = new ServerContentPackage(name, hash, workshopId); if (pkg.CorePackage != null) { corePackage = pkg; } else if (pkg.RegularPackage != null) { regularPackages.Add(pkg); } else { missingPackages.Add(pkg); } } if (missingPackages.Count > 0) { var nonDownloadable = missingPackages.Where(p => p.WorkshopId == 0); if (nonDownloadable.Any()) { string disconnectMsg; if (nonDownloadable.Count() == 1) { disconnectMsg = $"DisconnectMessage.MissingContentPackage~[missingcontentpackage]={GetPackageStr(missingPackages[0])}"; } else { List <string> packageStrs = new List <string>(); nonDownloadable.ForEach(cp => packageStrs.Add(GetPackageStr(cp))); disconnectMsg = $"DisconnectMessage.MissingContentPackages~[missingcontentpackages]={string.Join(", ", packageStrs)}"; } Close(disconnectMsg, disableReconnect: true); OnDisconnectMessageReceived?.Invoke(DisconnectReason.MissingContentPackage + "/" + disconnectMsg); } else { Close(disableReconnect: true); string missingModNames = "\n"; int displayedModCount = 0; foreach (ServerContentPackage missingPackage in missingPackages) { missingModNames += "\n- " + GetPackageStr(missingPackage); displayedModCount++; if (GUI.Font.MeasureString(missingModNames).Y > GameMain.GraphicsHeight * 0.5f) { missingModNames += "\n\n" + TextManager.GetWithVariable("workshopitemdownloadprompttruncated", "[number]", (missingPackages.Count - displayedModCount).ToString()); break; } } missingModNames += "\n\n"; var msgBox = new GUIMessageBox( TextManager.Get("WorkshopItemDownloadTitle"), TextManager.GetWithVariable("WorkshopItemDownloadPrompt", "[items]", missingModNames), new string[] { TextManager.Get("Yes"), TextManager.Get("No") }); msgBox.Buttons[0].OnClicked = (yesBtn, userdata) => { GameMain.ServerListScreen.Select(); GameMain.ServerListScreen.DownloadWorkshopItems(missingPackages.Select(p => p.WorkshopId), serverName, ServerConnection.EndPointString); return(true); }; msgBox.Buttons[0].OnClicked += msgBox.Close; msgBox.Buttons[1].OnClicked = msgBox.Close; } return; } if (!contentPackageOrderReceived) { GameMain.Config.BackUpModOrder(); GameMain.Config.SwapPackages(corePackage.CorePackage, regularPackages.Select(p => p.RegularPackage).ToList()); contentPackageOrderReceived = true; } SendMsgInternal(DeliveryMethod.Reliable, outMsg); break; case ConnectionInitialization.Password: if (initializationStep == ConnectionInitialization.SteamTicketAndVersion) { initializationStep = ConnectionInitialization.Password; } if (initializationStep != ConnectionInitialization.Password) { return; } bool incomingSalt = inc.ReadBoolean(); inc.ReadPadBits(); int retries = 0; if (incomingSalt) { passwordSalt = inc.ReadInt32(); } else { retries = inc.ReadInt32(); } OnRequestPassword?.Invoke(passwordSalt, retries); break; } }
public void CreateKickReasonPrompt(string clientName, bool ban, bool rangeBan = false) { var banReasonPrompt = new GUIMessageBox( TextManager.Get(ban ? "BanReasonPrompt" : "KickReasonPrompt"), "", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, 400, 300); var content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.6f), banReasonPrompt.InnerFrame.RectTransform, Anchor.Center)); var banReasonBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform)) { Wrap = true, MaxTextLength = 100 }; GUINumberInput durationInputDays = null, durationInputHours = null; GUITickBox permaBanTickBox = null; if (ban) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform), TextManager.Get("BanDuration")); permaBanTickBox = new GUITickBox(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform) { RelativeOffset = new Vector2(0.05f, 0.0f) }, TextManager.Get("BanPermanent")) { Selected = true }; var durationContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform), isHorizontal: true) { Visible = false }; permaBanTickBox.OnSelected += (tickBox) => { durationContainer.Visible = !tickBox.Selected; return(true); }; durationInputDays = new GUINumberInput(new RectTransform(new Vector2(0.2f, 1.0f), durationContainer.RectTransform), GUINumberInput.NumberType.Int) { MinValueInt = 0, MaxValueFloat = 1000 }; new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), durationContainer.RectTransform), TextManager.Get("Days")); durationInputHours = new GUINumberInput(new RectTransform(new Vector2(0.2f, 1.0f), durationContainer.RectTransform), GUINumberInput.NumberType.Int) { MinValueInt = 0, MaxValueFloat = 24 }; new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), durationContainer.RectTransform), TextManager.Get("Hours")); } banReasonPrompt.Buttons[0].OnClicked += (btn, userData) => { if (ban) { if (!permaBanTickBox.Selected) { TimeSpan banDuration = new TimeSpan(durationInputDays.IntValue, durationInputHours.IntValue, 0, 0); BanPlayer(clientName, banReasonBox.Text, ban, banDuration); } else { BanPlayer(clientName, banReasonBox.Text, ban); } } else { KickPlayer(clientName, banReasonBox.Text); } return(true); }; banReasonPrompt.Buttons[0].OnClicked += banReasonPrompt.Close; banReasonPrompt.Buttons[1].OnClicked += banReasonPrompt.Close; }
public void CreatePreviewWindow(GUIMessageBox messageBox) { var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), messageBox.Content.RectTransform), ServerName, textAlignment: Alignment.Center, font: GUI.LargeFont, wrap: true); var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), messageBox.Content.RectTransform)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, wrap: true); var columnContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), messageBox.Content.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f }; var columnLeft = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), columnContainer.RectTransform)) { RelativeSpacing = 0.02f, Stretch = true }; var columnRight = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), columnContainer.RectTransform)) { RelativeSpacing = 0.02f, Stretch = true }; float elementHeight = 0.1f; // left column ----------------------------------------------------------------------------- //new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnLeft.RectTransform), IP + ":" + Port); new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnLeft.RectTransform), TextManager.Get("ServerListVersion") + ": " + (string.IsNullOrEmpty(GameVersion) ? TextManager.Get("Unknown") : GameVersion)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), columnLeft.RectTransform), TextManager.Get("ServerListContentPackages")); var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.7f), columnLeft.RectTransform)); if (ContentPackageNames.Count == 0) { new GUITextBlock(new RectTransform(Vector2.One, contentPackageList.Content.RectTransform), TextManager.Get("Unknown"), textAlignment: Alignment.Center) { CanBeFocused = false }; } else { List <string> availableWorkshopUrls = new List <string>(); for (int i = 0; i < ContentPackageNames.Count; i++) { var packageText = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.15f), contentPackageList.Content.RectTransform) { MinSize = new Point(0, 15) }, ContentPackageNames[i]) { Enabled = false }; if (i < ContentPackageHashes.Count) { if (GameMain.Config.SelectedContentPackages.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i])) { packageText.Selected = true; continue; } //matching content package found, but it hasn't been enabled if (ContentPackage.List.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i])) { packageText.TextColor = Color.Orange; packageText.ToolTip = TextManager.Get("ServerListContentPackageNotEnabled") .Replace("[contentpackage]", ContentPackageNames[i]); } //workshop download link found else if (i < ContentPackageWorkshopUrls.Count && !string.IsNullOrEmpty(ContentPackageWorkshopUrls[i])) { availableWorkshopUrls.Add(ContentPackageWorkshopUrls[i]); packageText.TextColor = Color.Yellow; packageText.ToolTip = TextManager.Get("ServerListIncompatibleContentPackageWorkshopAvailable") .Replace("[contentpackage]", ContentPackageNames[i]); } else //no package or workshop download link found, tough luck { packageText.TextColor = Color.Red; packageText.ToolTip = TextManager.Get("ServerListIncompatibleContentPackage") .Replace("[contentpackage]", ContentPackageNames[i]) .Replace("[hash]", ContentPackageHashes[i]); } } } if (availableWorkshopUrls.Count > 0) { var workshopBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.15f), columnLeft.RectTransform), TextManager.Get("ServerListSubscribeMissingPackages")) { ToolTip = TextManager.Get(SteamManager.IsInitialized ? "ServerListSubscribeMissingPackagesTooltip" : "ServerListSubscribeMissingPackagesTooltipNoSteam"), Enabled = SteamManager.IsInitialized, OnClicked = (btn, userdata) => { GameMain.SteamWorkshopScreen.SubscribeToPackages(availableWorkshopUrls); GameMain.SteamWorkshopScreen.Select(); return(true); } }; workshopBtn.TextBlock.AutoScale = true; } } // right column ----------------------------------------------------------------------------- var playerCount = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListPlayers")); new GUITextBlock(new RectTransform(Vector2.One, playerCount.RectTransform), PlayerCount + "/" + MaxPlayers, textAlignment: Alignment.Right); new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), "Round running") { Selected = GameStarted, CanBeFocused = false }; var gameMode = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("GameMode")); new GUITextBlock(new RectTransform(Vector2.One, gameMode.RectTransform), string.IsNullOrEmpty(GameMode) ? "Unknown" : GameMode, textAlignment: Alignment.Right); var traitors = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("Traitors")); new GUITextBlock(new RectTransform(Vector2.One, traitors.RectTransform), !TraitorsEnabled.HasValue ? "Unknown" : TraitorsEnabled.Value.ToString(), textAlignment: Alignment.Right); var subSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListSubSelection")); new GUITextBlock(new RectTransform(Vector2.One, subSelection.RectTransform), !SubSelectionMode.HasValue ? "Unknown" : SubSelectionMode.Value.ToString(), textAlignment: Alignment.Right); var modeSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListModeSelection")); new GUITextBlock(new RectTransform(Vector2.One, modeSelection.RectTransform), (!ModeSelectionMode.HasValue ? "Unknown" : ModeSelectionMode.Value.ToString()), textAlignment: Alignment.Right); var allowSpectating = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListAllowSpectating")) { CanBeFocused = false }; if (!AllowSpectating.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowSpectating.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { allowSpectating.Selected = AllowSpectating.Value; } var allowRespawn = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), "Allow respawn") { CanBeFocused = false }; if (!AllowRespawn.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowRespawn.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { allowRespawn.Selected = AllowRespawn.Value; } new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListHasPassword")) { Selected = HasPassword, CanBeFocused = false }; var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListUsingWhitelist")) { CanBeFocused = false }; if (!UsingWhiteList.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), usingWhiteList.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { usingWhiteList.Selected = UsingWhiteList.Value; } // ----------------------------------------------------------------------------- foreach (GUIComponent c in columnLeft.Children) { if (c is GUITextBlock textBlock) { textBlock.Padding = Vector4.Zero; } } foreach (GUIComponent c in columnRight.Children) { if (c is GUITextBlock textBlock) { textBlock.Padding = Vector4.Zero; } } }
public void CreatePreviewWindow(GUIMessageBox messageBox) { var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), messageBox.Content.RectTransform), ServerName, textAlignment: Alignment.Center, font: GUI.LargeFont, wrap: true); var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), messageBox.Content.RectTransform)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, wrap: true); var columnContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), messageBox.Content.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f }; var columnLeft = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), columnContainer.RectTransform)) { RelativeSpacing = 0.02f }; var columnRight = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), columnContainer.RectTransform)) { RelativeSpacing = 0.02f }; float elementHeight = 0.1f; // left column ----------------------------------------------------------------------------- //new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnLeft.RectTransform), IP + ":" + Port); new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnLeft.RectTransform), TextManager.Get("ServerListVersion") + ": " + (string.IsNullOrEmpty(GameVersion) ? TextManager.Get("Unknown") : GameVersion)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), columnLeft.RectTransform), TextManager.Get("ServerListContentPackages") + ": " + (ContentPackageNames.Count == 0 ? TextManager.Get("Unknown") : string.Join(", ", ContentPackageNames)), wrap: true); new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), columnLeft.RectTransform), TextManager.Get("ServerListHasPassword")) { Selected = HasPassword, CanBeFocused = false }; var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnLeft.RectTransform), TextManager.Get("ServerListUsingWhitelist")) { CanBeFocused = false }; if (!UsingWhiteList.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), usingWhiteList.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { usingWhiteList.Selected = UsingWhiteList.Value; } // right column ----------------------------------------------------------------------------- new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListPlayers") + ": " + PlayerCount + "/" + MaxPlayers); new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), "Round running") { Selected = GameStarted, CanBeFocused = false }; new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("GameMode") + ": " + (string.IsNullOrEmpty(GameMode) ? "Unknown" : GameMode)); new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("Traitors") + ": " + (!TraitorsEnabled.HasValue ? "Unknown" : TraitorsEnabled.Value.ToString())); new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListSubSelection") + ": " + (!SubSelectionMode.HasValue ? "Unknown" : SubSelectionMode.Value.ToString())); new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListModeSelection") + ": " + (!ModeSelectionMode.HasValue ? "Unknown" : ModeSelectionMode.Value.ToString())); var allowSpectating = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListAllowSpectating")) { CanBeFocused = false }; if (!AllowSpectating.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowSpectating.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { allowSpectating.Selected = AllowSpectating.Value; } var allowRespawn = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), "Allow respawn") { CanBeFocused = false }; if (!AllowRespawn.HasValue) { new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowRespawn.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center); } else { allowRespawn.Selected = AllowRespawn.Value; } foreach (GUIComponent c in columnLeft.Children) { if (c is GUITextBlock textBlock) { textBlock.Padding = Vector4.Zero; } } foreach (GUIComponent c in columnRight.Children) { if (c is GUITextBlock textBlock) { textBlock.Padding = Vector4.Zero; } } }
// В этом методе происходит всё основное действо. // К сожалению, из-за спешки, представленный здесь код - далеко не лучший результат работы // моего ума, поэтому тут я вообще каждую строчку прокомментирую. private void BT_Next_Click(object sender, EventArgs e) { // Простая проверка на длину ID. if (TB_ID.Text.Length == 4) { // Удостоверимся, что введённый ID присутствует в базе. if (database.Keys.Contains(TB_ID.Text)) { // Создаём объект данных операции, указав объект данных пациента. operationInfo = new OperationInfo(database[TB_ID.Text]); // Открываем окно с информацией о пациенте. DialogResult dlgResult = OpenPatientInfo(); // Последующие окна нужно открывать, только если была нажата соответствующая кнопка. if (dlgResult == DialogResult.OK) { // Открываем диалоговое окно ввода повреждений dlgResult = OpenInjuriesInput(); // Продолжаем, только если операция не отменена. if (dlgResult == DialogResult.OK) { // Открываем окно операции. Operation opWindow = new Operation(operationInfo); dlgResult = opWindow.ShowDialog(); switch (dlgResult) { // Операция провалена. case DialogResult.None: { operationInfo.patient.state = CharacterData.State.DEAD; break; } // Операция успешна. case DialogResult.OK: { // Далее описаны hardcoded последствия операции, зависящие от общего количества // ошибочных действий во время операции (и самую малость - от рандома). switch (operationInfo.fails) { case 0: { GUIMessageBox.ShowDlg(new string[] { "", "Операция успешно завершена без последствий для пациента!" }); break; } case 1: { GUIMessageBox.ShowDlg(new string[] { "", "Операция успешно завершена без последствий для пациента!" }); break; } case 2: { GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(12, 20).ToString() + " минут." }); break; } case 3: { GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(25, 30).ToString() + " минут.", "В течение двух часов пациент будет испытывать проблемы с выносливостью (-1 макс. хит)." }); break; } case 4: { int rand = new Random().Next(1, 4); string limb = "левой руки"; switch (rand) { case 1: { limb = "левая рука"; break; } case 2: { limb = "правая рука"; break; } case 3: { limb = "левая нога"; break; } case 4: { limb = "правая нога"; break; } } GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(20, 25).ToString() + " минут.", "Пациент теперь будет испытывать проблемы с выносливостью (-1 хит до конца игры).", "Парализована " + limb + ".", "Возможны припадки (от громких звуков теряет сознание).", "Пациент ослеп на " + new Random().Next(20, 40) + " минут." }); break; } case 5: { int rand = new Random().Next(1, 4); string limb = "левая рука"; string limb2 = "правая рука"; switch (rand) { case 1: { limb = "левая рука"; limb2 = "левая нога"; break; } case 2: { limb = "правая рука"; limb2 = "правая нога"; break; } case 3: { limb = "левая нога"; limb2 = "правая рука"; break; } case 4: { limb = "правая нога"; limb2 = "левая рука"; break; } } GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(20, 25).ToString() + " минут.", "Пациент теперь будет испытывать проблемы с выносливостью (-1 хит до конца игры).", "У пациента будут припадки от громких звуков, очень яркого света, агрессивного поведения (теряет сознание).", "Парализована " + limb + " и " + limb2 + ".", "Пациент ослеп и оглох на " + new Random().Next(30, 50) + " минут." }); break; } case 6: { int rand = new Random().Next(1, 2); string limb = "левая рука"; string limb2 = "правая рука"; switch (rand) { case 1: { limb = "левая рука"; limb2 = "правая рука"; break; } case 2: { limb = "левая нога"; limb2 = "правая нога"; break; } } GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(30, 45).ToString() + " минут.", "Пациент теперь будет испытывать проблемы с выносливостью (-1 хит до конца игры).", "У пациента будут припадки от громких звуков, очень яркого света, агрессивного поведения (теряет сознание).", "Парализована " + limb + " и " + limb2 + ".", "Пациент ослеп и оглох на " + new Random().Next(40, 60) + " минут." }); break; } case 7: { int rand = new Random().Next(1, 2); string limb = "левая рука"; string limb2 = "правая рука"; switch (rand) { case 1: { limb = "левая рука"; limb2 = "правая рука"; break; } case 2: { limb = "левая нога"; limb2 = "правая нога"; break; } } GUIMessageBox.ShowDlg(GUIMessageBox.Type.BIGMESSAGE, new string[] { "", "", "", "Операция успешно завершена!", "", "Пациенту необходима реабилитация длительностью " + new Random().Next(40, 55).ToString() + " минут.", "Пациент теперь будет испытывать проблемы с выносливостью (-1 хит до конца игры)", "У пациента будут припадки от громких звуков, очень яркого света, агрессивного поведения (теряет сознание).", "Парализована " + limb + " и " + limb2 + ".", "Пациент ослеп и оглох на " + new Random().Next(50, 70) + " минут." }); break; } } break; } // Операция отменена. case DialogResult.Abort: { // Пациента нужно поместить в криостазис. GUIMessageBox.ShowDlg(new string[] { "Операция прервана.", "Пациент был помещён в криосон." }); operationInfo.patient.state = CharacterData.State.FROZEN; break; } } // Деструктируем объект окна операции. opWindow.Dispose(); } } // Блок перезаписи существующей базы данных и создания бэкапа. { string[] newDB = new string[database.Count]; int i = 0; foreach (CharacterData value in database.Values) { newDB[i] = value.ToString(); i++; } // создание бэкапа (в имени указывается текущее время) File.WriteAllLines(bakFileName + DateTime.Now.ToShortTimeString().Replace(':', '_') + ".bak", File.ReadAllLines(dbFileName, Encoding.UTF8), Encoding.UTF8); // перезапись файла File.WriteAllLines(dbFileName, newDB, Encoding.UTF8); } } else { // Несуществующий пациент GUIMessageBox.ShowDlg("Пациента с указанным ID не существует!"); } } else { // Ошибка ввода GUIMessageBox.ShowDlg("ID должен состоять из 4 цифр!"); } }
// При создании объекта формы нужно загрузить в память список персонажей, обработав файл базы данных. public Hub() { InitializeComponent(); // В этом блоке производится чтение и обработка файла try { // Считываем весь файл в массив строк, открывая файл всего на мгновение string[] db = File.ReadAllLines(dbFileName, Encoding.UTF8); foreach (string line in db) { // а теперь обрабатываем полученный массив /* Файл базы данных структурирован построчно. * * Это означает, что строки могут быть расположены в любом порядке, * но каждая строка имеет строго определённый порядок аргументов: * * ID#Титул#Имя#Фамилия#Состояние * * Аргументы фамилии и состояния могут отсутствовать. * */ // пустые строки и строки-комментарии обрабатывать не нужно if (!line.Trim().StartsWith("#") && line.Trim() != "") { int paramsCnt = line.Split('#').Length; // строка должна содержать минимум три аргумента (просто решётка после имени обозначит отсутствие фамилии) if (paramsCnt >= 3) { string[] lines = line.Split('#'); // файл составлен с ошибкой - программа не будет работать, // говорим об этом пользователю if (database.Keys.Contains(lines[0])) { GUIMessageBox.ShowDlg("В базе данных обнаружены конфликтующие ID! Удалите все дубликаты перед повторным запуском."); BT_Next.Visible = false; TB_ID.Visible = false; isCorrectLaunch = false; } // создаём объект класса CharacterData с прочитанными данными, // и добавляем его в словарь database database.Add(lines[0], new CharacterData(lines[0], lines[1], lines[2], lines[3], (lines.Length <= 4) ? 0 : int.Parse(lines[4]))); } } } } catch (FileNotFoundException) { // Файл не существует (или неправильно назван) // В этом случае решение проблемы лучше предоставить мастеру. GUIMessageBox.ShowDlg(new string[] { "Не найден файл базы данных.", "Обратитесь к мастеру по медицине." }); BT_Next.Visible = false; TB_ID.Visible = false; isCorrectLaunch = false; } }