AceField/Scripts/Launcher.cs
2024-08-08 15:20:09 +08:00

83 lines
1.7 KiB
C#

using AceField.Scripts.Logic;
using Godot;
namespace AceField.Scripts;
public partial class Launcher : Node
{
[Export] public World World;
private void GameFreeze()
{
GetTree().Paused = true;
World.Hide();
}
private void GameUnfreeze()
{
GetTree().Paused = false;
World.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;
}
}