AceField/Scripts/UI/MultiplayerUi.cs
2024-08-05 16:30:50 +08:00

75 lines
1.6 KiB
C#

using Godot;
namespace CodingLand.Scripts.UI;
public partial class MultiplayerUi : Control
{
[Export] public int DefaultServerPort = 4343;
[Export] public string DefaultServerAddr = "127.0.0.1";
[Export] public Multiplayer MultiplayerController;
[Export] public LineEdit ServerPortInput;
[Export] public LineEdit ServerAddrInput;
[Export] public Button StartAsServerButton;
[Export] public Button StartAsClientButton;
private void ApplySize()
{
var screenSize = GetViewportRect().Size;
Position = new Vector2(0, 0);
Size = screenSize;
GetNode<CenterContainer>("CenterContainer").Size = screenSize;
}
private bool DoValidation()
{
var addr = ServerAddrInput.Text;
var port = ServerPortInput.Text;
if (string.IsNullOrEmpty(addr)) return false;
if (string.IsNullOrEmpty(port) || !int.TryParse(port, out _)) return false;
return true;
}
public override void _Ready()
{
ApplySize();
ServerPortInput.Text = DefaultServerPort.ToString();
ServerAddrInput.Text = DefaultServerAddr;
StartAsServerButton.Pressed += () =>
{
if (!DoValidation())
{
OS.Alert("Invalid multiplayer configuration.");
return;
}
var port = ServerPortInput.Text;
var result = MultiplayerController.StartAsServer(int.Parse(port));
if (result)
Hide();
};
StartAsServerButton.Pressed += () =>
{
if (!DoValidation())
{
OS.Alert("Invalid multiplayer configuration.");
return;
}
var addr = ServerAddrInput.Text;
var port = ServerPortInput.Text;
var result = MultiplayerController.StartAsClient(addr, int.Parse(port));
if (result)
Hide();
};
}
}