2025-11-09 15:20:54 +08:00
|
|
|
@tool
|
2025-11-09 15:19:21 +08:00
|
|
|
class_name MultiplayerState
|
|
|
|
|
|
|
|
|
|
enum ConnectionState {
|
|
|
|
|
DISCONNECTED,
|
|
|
|
|
CONNECTING,
|
|
|
|
|
CONNECTED_HOST,
|
|
|
|
|
CONNECTED_CLIENT,
|
|
|
|
|
}
|
|
|
|
|
static var stateTextMap = {
|
|
|
|
|
ConnectionState.DISCONNECTED: "未连接到服务器。",
|
2025-11-09 17:00:39 +08:00
|
|
|
ConnectionState.CONNECTING: "正在连接到服务器...",
|
2025-11-09 15:19:21 +08:00
|
|
|
ConnectionState.CONNECTED_HOST: "服务器启动成功!",
|
|
|
|
|
ConnectionState.CONNECTED_CLIENT: "已连接到服务器!",
|
|
|
|
|
}
|
|
|
|
|
static var stateColorMap = {
|
|
|
|
|
ConnectionState.DISCONNECTED: Color.RED,
|
|
|
|
|
ConnectionState.CONNECTING: Color.YELLOW,
|
|
|
|
|
ConnectionState.CONNECTED_HOST: Color.GREEN,
|
|
|
|
|
ConnectionState.CONNECTED_CLIENT: Color.GREEN,
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-13 22:23:39 +08:00
|
|
|
static var isMultiplayer: bool = false
|
2025-11-09 15:19:21 +08:00
|
|
|
static var state: ConnectionState = ConnectionState.DISCONNECTED
|
2025-11-11 22:23:36 +08:00
|
|
|
static var playerName: String
|
2025-11-09 15:19:21 +08:00
|
|
|
|
2025-11-13 22:23:39 +08:00
|
|
|
static var connection: ENetMultiplayerPeer
|
|
|
|
|
|
2025-11-09 15:19:21 +08:00
|
|
|
static var maxPlayer: int = 10
|
|
|
|
|
|
2025-11-09 15:24:24 +08:00
|
|
|
static func isConnected():
|
|
|
|
|
return [ConnectionState.CONNECTED_HOST, ConnectionState.CONNECTED_CLIENT].has(state)
|
2025-11-09 17:00:39 +08:00
|
|
|
static func launchServer(port: int) -> ENetMultiplayerPeer:
|
2025-11-09 15:19:21 +08:00
|
|
|
var peer = ENetMultiplayerPeer.new()
|
|
|
|
|
peer.create_server(port, maxPlayer)
|
2025-11-09 15:24:24 +08:00
|
|
|
state = ConnectionState.CONNECTED_HOST
|
|
|
|
|
return peer
|
2025-11-09 17:00:39 +08:00
|
|
|
static func connectClient(host: String, port: int) -> ENetMultiplayerPeer:
|
2025-11-09 15:24:24 +08:00
|
|
|
var peer = ENetMultiplayerPeer.new()
|
|
|
|
|
peer.create_client(host, port)
|
|
|
|
|
state = ConnectionState.CONNECTED_CLIENT
|
2025-11-09 15:19:21 +08:00
|
|
|
return peer
|