harvest/game/scripts/coop_lobby.gd
2026-10-04 12:07:36 -04:00

304 lines
9.6 KiB
GDScript

class_name CoopLobby
extends Node
## Finding each other over GD-Sync (the GDSync autoload), for co-op:
## LAN GD-Sync's local mode: peer to peer on the same network, no account or keys. Games
## announce themselves on the network; Join lists them.
## ONLINE GD-Sync's servers, across the internet: needs the project's GD-Sync API keys
## (Project > Tools > GD-Sync in the editor, saved to addons/GD-Sync/keys.cfg, or the
## GDSYNC_PUBLIC_KEY / GDSYNC_PRIVATE_KEY environment variables).
## The host opens a lobby named after its player ("Ana's farm") for two; the partner lists the
## open lobbies (or types one's name, online) and joins. On a LAN that doesn't pass GD-Sync's
## announcements (some firewalls; VPNs like Tailscale or ZeroTier) the partner can join by the
## host's address instead (join_address; the host's waiting status shows its addresses). Once both are in, partner_arrived (on the
## host) and joined (on the partner) give the other side's GD-Sync client id, and CoopSession
## takes over over a GDSyncLink. If the other side leaves, other_left. GD-Sync keeps running
## while the game is paused (the menus).
enum Mode { LAN, ONLINE }
enum Stage { IDLE, CONNECTING, HOSTING, SEARCHING, JOINING, IN_LOBBY }
signal status_changed(text: String)
## Join's list: [{"name", "players"}] of open lobbies with room.
signal lobbies_found(lobbies: Array)
signal partner_arrived(client_id: int)
signal joined(host_id: int)
signal other_left(client_id: int)
signal failed(text: String)
const SEARCH_EVERY := 2.0
const GAME_PORT := 42400
const GAME_TAG := "harvest-season"
var gdsync: Node
var mode: Mode = Mode.LAN
var stage: Stage = Stage.IDLE
var lobby_name := ""
var my_name := ""
var other_id: int = -1
var status := ""
var _after_connect := "" # "host" or "search"
var _join_target := ""
var _search_left: float = 0.0
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
gdsync = get_node_or_null("/root/GDSync")
if gdsync == null:
return
gdsync.process_mode = Node.PROCESS_MODE_ALWAYS # the lobby works behind the paused menus
gdsync.connected.connect(_on_connected)
gdsync.connection_failed.connect(_on_connection_failed)
gdsync.disconnected.connect(_on_disconnected)
gdsync.lobby_created.connect(_on_lobby_created)
gdsync.lobby_creation_failed.connect(_on_lobby_creation_failed)
gdsync.lobby_joined.connect(_on_lobby_joined)
gdsync.lobby_join_failed.connect(_on_lobby_join_failed)
gdsync.lobbies_received.connect(_on_lobbies_received)
gdsync.client_joined.connect(_on_client_joined)
gdsync.client_left.connect(_on_client_left)
func available() -> bool:
return gdsync != null
## Whether online play can be tried (the API keys are there).
static func has_online_keys() -> bool:
var ks: Variant = load("res://addons/GD-Sync/Scripts/KeyStore.gd")
return ks != null and bool(ks.has_keys())
func my_id() -> int:
return int(gdsync.get_client_id()) if gdsync != null else -1
## Opens a lobby for a partner to join.
func host(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
lobby_name = ("%s's farm" % my_name).left(32)
_after_connect = "host"
_start()
## Looks for open lobbies (LAN: on the network, every SEARCH_EVERY seconds; online: on the server).
func search(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
_after_connect = "search"
_start()
func join(lobby: String) -> void:
if gdsync == null or not gdsync.is_active():
return
_join_target = lobby
stage = Stage.JOINING
_say("Joining %s..." % lobby)
gdsync.lobby_join(lobby)
## LAN: joins the game at a host's address ("192.168.1.20", or with ":port" when it isn't the
## first game port). Starts GD-Sync's local mode first if needed.
func join_address(address: String, p_name: String = "") -> void:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return
var a := address.strip_edges()
if a == "":
return
if not gdsync.is_active() or mode != Mode.LAN:
if not _begin(Mode.LAN, p_name if p_name != "" else my_name):
return
_after_connect = "address"
_join_target = a
_start()
return
var ip := a
var port := GAME_PORT
if a.count(":") == 1:
ip = a.get_slice(":", 0)
port = int(a.get_slice(":", 1))
var local_server: Node = gdsync.get("_local_server")
if local_server == null:
failed.emit("This GD-Sync version can't join by address")
return
var key := "%s:%d" % [ip, port]
# GD-Sync joins a LAN game it has heard announced; this one is "announced" by hand (and
# never expires).
(local_server.get("found_lobbies") as Dictionary)[key] = {"Name": key, "IP": ip, "Port": port, "Public": false,
"Open": true, "PlayerCount": 1, "PlayerLimit": 2, "Tags": {}, "DetectionTime": Time.get_unix_time_from_system() + 1e9}
_after_connect = "join"
join(key)
## This machine's addresses on the local network (and VPNs), for joining by address.
static func host_addresses() -> PackedStringArray:
var out := PackedStringArray()
for ip in IP.get_local_addresses():
if ip.contains(":"):
continue # IPv6
var parts := ip.split(".")
var a := int(parts[0])
var b := int(parts[1])
if a == 10 or (a == 192 and b == 168) or (a == 172 and b >= 16 and b <= 31) or (a == 100 and b >= 64 and b <= 127):
out.append(ip)
return out
## Leaves the lobby and stops GD-Sync.
func leave() -> void:
if gdsync == null:
return
var was := stage
stage = Stage.IDLE # first: stopping emits disconnected, which isn't a failure now
other_id = -1
_after_connect = ""
if was == Stage.HOSTING or was == Stage.IN_LOBBY or was == Stage.JOINING:
gdsync.lobby_leave()
if gdsync.is_active():
gdsync.stop_multiplayer()
_say("")
func _process(delta: float) -> void:
if stage == Stage.SEARCHING and gdsync != null and gdsync.is_active():
_search_left -= delta
if _search_left <= 0.0:
_search_left = SEARCH_EVERY
gdsync.get_public_lobbies()
func _begin(p_mode: Mode, p_name: String) -> bool:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return false
if p_mode == Mode.ONLINE and not has_online_keys():
failed.emit("Online play needs the GD-Sync API keys: in the editor, Project > Tools > GD-Sync (see game/COOP.md). LAN works without them.")
return false
leave()
mode = p_mode
my_name = p_name.strip_edges() if p_name.strip_edges() != "" else "Player %d" % (randi() % 900 + 100)
return true
func _start() -> void:
stage = Stage.CONNECTING
_say("Connecting%s..." % (" on the local network" if mode == Mode.LAN else " to GD-Sync"))
if mode == Mode.LAN:
gdsync.start_local_multiplayer()
else:
gdsync.start_multiplayer()
func _on_connected() -> void:
gdsync.player_set_username(my_name)
match _after_connect:
"host":
_say("Opening the lobby...")
gdsync.lobby_create(lobby_name, "", true, 2, {"game": GAME_TAG})
"search":
stage = Stage.SEARCHING
_search_left = 0.0
_say("Looking for games%s..." % (" on the local network" if mode == Mode.LAN else ""))
"address":
join_address(_join_target)
func _on_connection_failed(error: int) -> void:
stage = Stage.IDLE
var why := "the connection failed"
match error:
0:
why = "the GD-Sync API keys were refused"
1:
why = "it timed out"
2:
why = "no network port was free"
failed.emit("Couldn't connect: %s." % why)
_say("")
func _on_disconnected() -> void:
if stage != Stage.IDLE:
var was := other_id
stage = Stage.IDLE
other_id = -1
if was >= 0:
other_left.emit(was)
failed.emit("Disconnected from GD-Sync.")
func _on_lobby_created(created: String) -> void:
gdsync.lobby_join(created)
func _on_lobby_creation_failed(_n: String, error: int) -> void:
stage = Stage.IDLE
var why := ["a lobby with that name exists", "the name is too short", "the name is too long", "", "", "",
"wait a few seconds and try again", "no network port was free"]
failed.emit("Couldn't open the lobby: %s." % (why[error] if error < why.size() and why[error] != "" else "error %d" % error))
func _on_lobby_joined(n: String) -> void:
if _after_connect == "host":
stage = Stage.HOSTING
if mode == Mode.LAN:
var at := host_addresses()
_say("Waiting for a friend to join \"%s\" (same network%s)" % [n,
(", or by address: " + ", ".join(at)) if not at.is_empty() else ""])
else:
_say("Waiting for a friend to join \"%s\" (online)" % n)
else:
stage = Stage.IN_LOBBY
_say("Joined \"%s\": waiting for the farm..." % n)
func _on_lobby_join_failed(n: String, error: int) -> void:
stage = Stage.SEARCHING
var why := ["it doesn't exist any more", "it's closed", "it's full", "the password is wrong", "your name is the same as the host's"]
failed.emit("Couldn't join %s: %s." % [n, why[error] if error < why.size() else "error %d" % error])
func _on_lobbies_received(lobbies: Array) -> void:
var out: Array = []
for l: Variant in lobbies:
if not l is Dictionary:
continue
var d := l as Dictionary
var tags: Variant = d.get("Tags", {})
if tags is Dictionary and (tags as Dictionary).has("game") and String(tags["game"]) != GAME_TAG:
continue
var players := int(d.get("PlayerCount", 0))
var limit := int(d.get("PlayerLimit", 2))
if limit > 0 and players >= limit:
continue
out.append({"name": String(d.get("Name", "")), "players": players})
lobbies_found.emit(out)
func _on_client_joined(id: int) -> void:
if id == my_id() or other_id >= 0:
return
if stage == Stage.HOSTING:
other_id = id
partner_arrived.emit(id)
elif stage == Stage.IN_LOBBY or stage == Stage.JOINING:
other_id = id
joined.emit(id)
func _on_client_left(id: int) -> void:
if id != other_id:
return
other_id = -1
other_left.emit(id)
if stage == Stage.HOSTING:
_say("Your friend left. Waiting for someone to join \"%s\"" % lobby_name)
func _say(text: String) -> void:
status = text
status_changed.emit(text)