SpaceServer/Scripts/RootNode.gd

109 lines
2.8 KiB
GDScript

extends Node
const MAX_PLAYERS : int = 3
const PORT : int = 9374
const Arena = preload("res://Scenes/Arena.tscn")
var peer : NetworkedMultiplayerENet = null
var ids = []
var console_output : TextEdit = null
var ready_ids = []
var playing : bool = false
var name_dict = {}
var color_dict = {}
func _ready() -> void:
peer = NetworkedMultiplayerENet.new()
peer.create_server( PORT, MAX_PLAYERS )
get_tree().set_network_peer( peer )
get_tree().connect("network_peer_connected", self, "_peer_connected")
get_tree().connect("network_peer_disconnected", self, "_peer_disconnected")
console_output = $ConsoleOutput
func console_print(text : String) -> void:
console_output.text += "\n" + text
console_output.cursor_set_line(console_output.get_line_count())
print(text)
func _peer_connected(id : int) -> void:
if not id:
return
ids.append(id)
self.console_print("Player has connected with id " + String(id))
if len(ids) == MAX_PLAYERS:
console_print('Got required players... Ready to start game...')
peer.refuse_new_connections = true
rpc('start_game')
# TODO: When we reach max players -> start the game
func _peer_disconnected(id : int) -> void:
ids.erase(id)
self.console_print("Player has disconnected with id " + String(id))
if !playing:
return
var alive_online_players : int = 0
$Arena.players[id].is_zombie = true
for id in ids:
if $Arena.players[id].is_alive:
alive_online_players += 1
if alive_online_players < 2:
self.server_request_exit()
remote func client_ready(id : int) -> void:
if id in ready_ids:
return
ready_ids.append(id)
if len(ready_ids) == MAX_PLAYERS:
start_game()
func start_game() -> void:
var arena = Arena.instance()
add_child(arena)
arena.init()
console_print('Starting Game...')
send_name_dict()
send_color_dict()
playing = true
func send_name_dict() -> void:
for element in name_dict.keys():
rpc("add_name_to_dict", element, name_dict[element])
remote func set_display_name(id : int, display_name : String) -> void:
name_dict[id] = display_name
func send_color_dict() -> void:
for element in color_dict.keys():
rpc("add_color_to_dict", element, color_dict[element])
remote func set_player_color(id : int, color : Color) -> void:
console_print("Setting color of " + String(id) + " to " + String(color))
color_dict[id] = color
func end_game() -> void:
$Arena.queue_free()
console_print("Ending Game...")
# Reset root node data
ids = []
ready_ids = []
name_dict = {}
color_dict = {}
peer.close_connection()
peer.create_server( PORT, MAX_PLAYERS )
peer.refuse_new_connections = false
playing = false
remote func request_exit() -> void:
console_print("Exit requested...")
rpc("exit_requested")
$ExitTimer.start()
func server_request_exit() -> void:
console_print("Server requested exit...")
rpc("server_exit_requested")
$ExitTimer.start()