An error occurred while loading the file. Please try again.
-
STAVRIDIS ADONIS authoredc61a4bbb
gamestate.gd 2.10 KiB
extends Node
const GAMEPATH = "/root/game/"
const PORT = 10001
const MAX_CLIENTS = 1
var players = {}
const ENVIRONMENT_LAYER = 0
const PLAYER_LAYER = 1
func _ready():
# When a client connects to the server
get_tree().connect("network_peer_connected", self, "_playerConnected")
# When a client disconnects gracefully or times out
get_tree().connect("network_peer_disconnected", self, "_playerDisconnected")
# Server init
var peer = NetworkedMultiplayerENet.new()
peer.create_server(PORT, MAX_CLIENTS)
get_tree().set_network_peer(peer)
print("Server now hosting")
# Called when a player connects
func _playerConnected(id):
if (players.size()>MAX_CLIENTS):
print("There is already enough players")
return
else:
registerPlayer(id)
if (players.size()==MAX_CLIENTS):
startGame()
func registerPlayer(id):
# Sending the list of existing players to the new player from ther server's personal list
for peer_id in players:
rpc_id(peer_id, "registerPlayer", id)
rpc_id(id, "registerPlayer", peer_id)
# Granting self-awareness
rpc_id(id, "registerPlayer", id)
# Adding the new id to anyones array
players[id] = str(id)
print("New player registered: ", id)
func _playerDisconnected(id):
players.erase(id)
# Broadcast the info and remove from the remote scene
if has_node(GAMEPATH+str(id)):
rpc("removePlayer", id)
get_node(GAMEPATH+str(id)).queue_free()
print("Player ", str(id), " disconnected")
func startGame():
# Instancing the map and adding it to the scene tree
var game = preload("res://levels/test/game.tscn").instance()
get_tree().get_root().add_child(game)
var playerScene = preload("res://entities/characters/player.tscn")
var i = 1
for peer_id in players:
# TODO: Replace by a spawnPlayer function !!!
var player = playerScene.instance()
player.set_name(str(peer_id))
get_node(GAMEPATH).add_child(player)
var spawnPosition = get_node("/root/game/spawnCollection/spawn"+str(i)).get_translation()
player.translate(spawnPosition)
i+=1
# Broadcast the beginning of the game
rpc("startGame")
print("game started with players ", players.values())