AceField/Scripts/Launcher.cs
2024-08-09 14:14:51 +08:00

90 lines
1.7 KiB
C#

using AceField.Scripts.Logic;
using AceField.Scripts.UI;
using Godot;
namespace AceField.Scripts;
public partial class Launcher : Node
{
[Export] public World World;
[Export] public BootScreen BootMenu;
[Export] public CanvasLayer Overlay;
private void GameFreeze()
{
GetTree().Paused = true;
World.Hide();
Overlay.Hide();
}
private void GameUnfreeze()
{
GetTree().Paused = false;
World.Show();
Overlay.Show();
BootMenu.StartGame -= GameUnfreeze;
}
public override void _Ready()
{
GameFreeze();
if (DisplayServer.GetName() == "headless")
{
GD.Print("Starting server in headless mode...");
StartAsServer(4343);
}
}
public void StartAsSingle()
{
GameUnfreeze();
}
public bool StartAsServer(int port)
{
var peer = new ENetMultiplayerPeer();
peer.CreateServer(port);
if (peer.GetConnectionStatus() == MultiplayerPeer.ConnectionStatus.Disconnected)
{
GD.PrintErr("Failed to start multiplayer server...");
OS.Alert("Failed to start multiplayer server...");
return false;
}
GD.Print("Running game as server...");
Multiplayer.MultiplayerPeer = peer;
BootMenu.StartGame += GameUnfreeze;
BootMenu.Show();
return true;
}
public bool StartAsClient(string addr, int port)
{
if (string.IsNullOrEmpty(addr)) return false;
var peer = new ENetMultiplayerPeer();
peer.CreateClient(addr, port);
if (peer.GetConnectionStatus() == MultiplayerPeer.ConnectionStatus.Disconnected)
{
var info = $"Unable to connect multiplayer server {addr}:{port}";
GD.PrintErr(info);
OS.Alert(info);
return false;
}
GD.Print("Running game as client...");
Multiplayer.MultiplayerPeer = peer;
BootMenu.StartGame += GameUnfreeze;
BootMenu.Show();
return true;
}
}