AceField/Scripts/Launcher.cs
2024-08-08 17:10:48 +08:00

86 lines
1.8 KiB
C#

using AceField.Scripts.Logic;
using Godot;
namespace AceField.Scripts;
public partial class Launcher : Node
{
[Export] public World World;
[Export] public CanvasLayer Overlay;
private void GameFreeze()
{
GetTree().Paused = true;
World.Hide();
Overlay.Hide();
}
private void GameUnfreeze()
{
GetTree().Paused = false;
World.Show();
Overlay.Show();
}
public override void _Ready()
{
GameFreeze();
if (DisplayServer.GetName() == "headless")
{
GD.Print("Starting server in headless mode...");
StartAsServer(4343);
}
}
public void StartAsSingle(string currentPlayerName = null)
{
GameUnfreeze();
World.StartGame(currentPlayerName);
}
public bool StartAsServer(int port, string currentPlayerName = null)
{
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;
GameUnfreeze();
World.StartGame(currentPlayerName);
return true;
}
public bool StartAsClient(string addr, int port, string currentPlayerName = null)
{
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;
GameUnfreeze();
World.StartGame(currentPlayerName);
return true;
}
}