godot-webrtc-mplayer-testing/lobby.gd

83 lines
2.6 KiB
GDScript

extends MarginContainer
onready var peers = $v/body/peers/peers
onready var lobby_info_label = $v/head/lobby_info
onready var peers_list_label = $v/body/peers/label
onready var cursors = {}
onready var chat = $v/body/v/messages
onready var chat_edit = $v/body/v/h/chat
func _ready():
Global.client.signaller.connect("peer_joined", self, "_peer_joined")
Global.client.signaller.connect("peer_left", self, "_peer_left")
# Global.client.connect("peer_disconnected", self, "_peer_left")
Global.client.signaller.connect("lobby_left", self, "_lobby_left")
lobby_info_label.text = "%s%s" % [Global.client.signaller.lobby_name, _host_suffix(get_tree().get_network_unique_id())]
Global.client.signaller.connect("websocket_disconnected", self, "_signaller_disconnected")
Global.client.signaller.request_peer_list()
call_deferred("add_chat", "# Connected to %s" % Global.client.signaller.lobby_name)
func _host_suffix(id):
if id == 1:
return " (Host)"
else:
return ""
func _signaller_disconnected():
Global.main_menu()
func _peer_joined(joined_peers):
call_deferred("update_player_count")
print("Joined Peers: %s" % [joined_peers])
for i in range(len(joined_peers)):
var id = joined_peers[i]["id"]
var exists = false
for j in range(peers.get_item_count()):
var md = peers.get_item_metadata(j)
if md and md.has("id") and md["id"] == id:
print("Already have this one")
exists = true
break
if not exists:
var peerId = joined_peers[i]["peerId"]
var name = joined_peers[i]["name"]
print("New Lobby Peer ID: %s, Name: %s, PeerID: %s" % [id, name, peerId])
call_deferred("add_chat", "> %s joined the lobby" % name)
peers.add_item("%s%s" % [name, _host_suffix(peerId)])
peers.set_item_metadata(peers.get_item_count() - 1, { "id": id, "peerId": peerId, "name": name })
func _peer_left(ids):
call_deferred("update_player_count")
print("Peer(s) Leaving: %s" % ids)
for data in ids:
print(data)
var id = data["id"]
for i in range(peers.get_item_count()):
var md = peers.get_item_metadata(i)
if md and md.has("id") and md["id"] == id:
peers.remove_item(i)
call_deferred("add_chat", "< %s left the lobby" % md["name"])
return
func update_player_count():
peers_list_label.text = "Players: %d" % peers.get_item_count()
func _on_Button_pressed():
send_chat_message()
remotesync func add_chat(message):
chat.add_item(message)
func _lobby_left(_id):
Global.lobby_browser()
func _on_leave_button_pressed():
Global.lobby_browser()
func _on_TextEdit_text_entered(_new_text):
send_chat_message()
func send_chat_message():
rpc("add_chat", "%s: %s" % [Global.client.signaller.display_name, chat_edit.text])
chat_edit.text = ""