Skip to content

Commit

Permalink
Merge pull request #122 from TheSecondReal0/consolidate-networking
Browse files Browse the repository at this point in the history
Moved names and cleaned up main.gd
  • Loading branch information
TheSecondReal0 authored Oct 19, 2020
2 parents 7d93e96 + dab45a1 commit 8aac3f7
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 62 deletions.
35 changes: 29 additions & 6 deletions src/assets/autoload/network.gd
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,35 @@ var server: WebSocketServer setget toss, deny
var client: WebSocketClient setget toss, deny
var player_name: String setget toss, get_player_name
puppet var peers: Array = []
puppet var myID: int = 1
puppet var names: Dictionary = {}
var myID: int = 1

signal server_started
signal connection_handled

func ready() -> void:
# give the server access to puppet functions and variables
set_network_master(1)
GameManager.connect('state_changed', self, '_on_state_changed')

func client_server(port: int, playerName: String) -> void:
print("Starting server on port ", port, " with host player name ", player_name)
print("Starting server on port ", port, " with host player name ", playerName)
connection = Connection.CLIENT_SERVER
player_name = playerName
myID = 1
names[1] = player_name
print(names)
server = WebSocketServer.new()
server.listen(port, PoolStringArray(), true) #3rd input must be true to use Godot's high level networking API
get_tree().set_network_peer(server)
connect_signals()
emit_signal("server_started")

func client(hostName: String, port: int, playerName: String) -> void:
print("Connecting to server ", hostName, " on port ", port, " with host player name ", player_name)
print("Connecting to server ", hostName, " on port ", port, " with host player name ", playerName)
connection = Connection.CLIENT
player_name = playerName
names[1] = playerName
client = WebSocketClient.new()
#use "ws://" at the beginning of address for websocket connections
var url: String = "ws://" + hostName + ":" + str(port)
Expand All @@ -47,11 +53,22 @@ func client(hostName: String, port: int, playerName: String) -> void:
connect_signals()
#do not switch to main scene here, wait until the connection was successful

remote func receiveName(newName):
var sender = get_tree().get_rpc_sender_id()
if not get_tree().is_network_server():
return
if names.keys().has(sender):
return
names[sender] = newName
print("names: ", names)
print(get_tree().is_network_server())
rset("names", names)
emit_signal("connection_handled", sender, newName)

func _player_connected(id) -> void:
peers.append(id)
if get_tree().is_network_server():
# remotely set myID var of new player to their network id
rset_id(id, "myID", str(id))
# sync peer list of all players
rset("peers", peers)

Expand All @@ -61,6 +78,9 @@ func _player_disconnected(id) -> void:

func _connected_to_server() -> void:
print("Connection to server succeeded")
myID = get_tree().get_network_unique_id()
print("sending name")
rpc_id(1, "receiveName", player_name)
pass #here is where you would put stuff that happens when you connect, such as switching to a lobby scene

func _connection_failed() -> void:
Expand Down Expand Up @@ -95,8 +115,11 @@ func connect_signals() -> void:
get_tree().connect("connection_failed", self, "_connection_failed")
get_tree().connect("server_disconnected", self, "_server_disconnected")

func get_player_name() -> String:
return player_name
func get_player_name(id: int = myID) -> String:
if names.keys().has(id):
return names[id]
else:
return player_name

func on_state_changed(old_state, new_state) -> void:
match new_state:
Expand Down
88 changes: 48 additions & 40 deletions src/assets/main/main.gd
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ var errdc = false
onready var config = ConfigFile.new()

func _ready():
set_network_master(1)
var err = config.load("user://settings.cfg")
if err == OK:
$players/Player/Camera2D/CanvasLayer/ColorRect.material.set_shader_param("mode", int(config.get_value("general", "colorblind_mode")))
Expand All @@ -30,6 +31,8 @@ func _enter_tree():
#get_tree().network_peer = peer
get_tree().connect("network_peer_connected", self, "_player_connected")
get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
Network.connect("connection_handled", self, "connection_handled")
players[1] = $players/Player
PlayerManager.ournumber = 0
elif Network.connection == Network.Connection.CLIENT:
get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
Expand All @@ -38,52 +41,55 @@ func _enter_tree():
#peer.create_client(Network.host, Network.port)
#get_tree().network_peer = peer

# Called on the server when a new client connects
func _player_connected(id):
func connection_handled(id, playerName):
print("connection handled, id: ", id, " name: ", playerName)
if not get_tree().is_network_server():
return
rpc("checkVersion", version)
newnumber = Network.peers.size()
rpc_id(id,"getname",id, version, newnumber)
rpc_id(id,"serverinfo",Network.get_player_name(), version)
remote func serverinfo(sname,sversion):
player_join(1,sname)
remote func getname(id,sversion,assignednumber):
rpc_id(1,"playerjoin_proper",Network.get_player_name(),id)
PlayerManager.ournumber = assignednumber
if not version == sversion:
rpc_id(id, "receiveNumber", newnumber)
createPlayer(id, playerName)
#tell all existing players to create this player
for i in players.keys():
if i != id:
print("telling ", i, " to create player ", id)
rpc_id(i, "createPlayer", id, playerName)
#tell new player to create existing players
for i in players.keys():
if i != id:
print("telling ", id, " to create player ", i)
rpc_id(id, "createPlayer", i, Network.names[i])

puppet func checkVersion(sversion):
if version != sversion:
print("HEY! YOU! YOU FORGOT TO UPDATE YOUR CLIENT. RE EXPORT AND TRY AGAIN!")
remote func playerjoin_proper(thename,id):
var new_player = player_scene.instance()
id = get_tree().get_rpc_sender_id()
new_player.id = id
new_player.ourname = thename
new_player.main_player = false
#print(thename)
for id in players:
# Sends an add_player rpc to the player that just joined
print("Sending add player to new player ", new_player)
rpc_id(new_player.id, "player_join", id, thename)
# Sends the add_player rpc to all other clients
print("Sending add player to other player ", players[id])
rpc_id(id, "player_join", new_player.id, thename)
players[id] = new_player
$players.add_child(new_player)
print("Got connection: ", id)
print(Network.peers.size())

puppet func receiveNumber(number):
if get_tree().get_rpc_sender_id() != 1:
return
PlayerManager.ournumber = number

# Called on the server when a new client connects
func _player_connected(id):
return

func _player_disconnected(id):
players[id].queue_free() #deletes player node when a player disconnects
players.erase(id)

# Called from server when another client connects
remote func player_join(other_id, pname):
# Should only be run on the client
if get_tree().is_network_server():
puppet func createPlayer(id, playerName):
print("creating player ", id)
if players.keys().has(id):
print("not creating player, already exists")
return
var new_player = player_scene.instance()
new_player.id = other_id
new_player.ourname = pname
new_player.main_player = false
add_child(new_player)
players[other_id] = new_player
print("New player: ", other_id)
var newPlayer = player_scene.instance()
newPlayer.id = id
newPlayer.ourname = playerName
newPlayer.main_player = false
players[id] = newPlayer
$players.add_child(newPlayer)
newPlayer.setName(playerName)
print("New player: ", id)

# Called from client sides when a player moves
remote func player_moved(new_pos, new_movement):
Expand Down Expand Up @@ -111,7 +117,8 @@ remote func other_player_moved(id, new_pos, new_movement):
if get_tree().is_network_server():
return
#print("Moving ", id, " to ", new_pos.x, ", ", new_pos.y) #no reason to spam console so much
players[id].move_to(new_pos, new_movement)
if players.keys().has(id):
players[id].move_to(new_pos, new_movement)

func _on_main_player_moved(position : Vector2, movement : Vector2):
#In the beginning Godot created the heaven and the earth
Expand Down Expand Up @@ -145,6 +152,7 @@ remote func startgame(intrudernumber):
else:
print("we are not the intruder")
emit_signal("clientstartgame")

func serverassign():
var rng = RandomNumberGenerator.new()
var isintruder = false
Expand Down
1 change: 1 addition & 0 deletions src/assets/main/main.tscn
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ script = ExtResource( 3 )

[node name="Player" parent="players" instance=ExtResource( 1 )]
position = Vector2( -100.995, -9.43875 )
main_player = true

[node name="Camera2D" type="Camera2D" parent="players/Player"]
current = true
Expand Down
11 changes: 1 addition & 10 deletions src/assets/main/maps.gd
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,10 @@ func _on_state_change(old_state, new_state) -> void:
GameManager.State.Normal:
switchMap('test')

puppet func switchMap(newMap: String) -> void:
func switchMap(newMap: String) -> void:
print('switchMap called for ', newMap)
#if the func is not remotely called rpc sender id will be 0, if server sent it will be 1, negative should be impossible
if not get_tree().get_rpc_sender_id() < 2:
return
if GameManager.ingame():
return
if not maps.keys().has(newMap):
return
if get_tree().is_network_server():
print("telling clients to switch map to ", newMap)
rpc("switchMap", newMap)

print("loading map: ", newMap)
for i in get_children():
i.queue_free()
Expand Down
13 changes: 8 additions & 5 deletions src/assets/player/player.gd
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ signal main_player_moved(position)
export (int) var speed = 150

# Set by main.gd. Is the client's unique id for this player
var id
var ourname
var id: int
var ourname: String
var velocity = Vector2(0,0)
# Contains the current intended movement direction and magnitude in range 0 to 1
var movement = Vector2(0,0)
# Only true when this is the player being controlled
var main_player = true
export var main_player = false
#anim margin controls how big the player movement must be before animations are played
var x_anim_margin = 0.1
var y_anim_margin = 0.1
Expand All @@ -22,9 +22,12 @@ func _ready():
if main_player:
$VisibleArea.enabled = true
$Dark.enabled = true
ourname = Network.get_player_name()
print("ourname: ", ourname)
setName(Network.get_player_name())

func setName(newName):
ourname = newName
$Label.text = ourname

# Only called when main_player is true
func get_input():
var prev_velocity = velocity
Expand Down
1 change: 0 additions & 1 deletion src/assets/player/player.tscn
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ shape = SubResource( 1 )
[node name="Sprite" type="AnimatedSprite" parent="."]
frames = SubResource( 2 )
animation = "walk-h"
frame = 2
playing = true

[node name="Label" type="Label" parent="."]
Expand Down
1 change: 1 addition & 0 deletions src/export_presets.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ binary_format/embed_pck=true
custom_template/release=""
custom_template/debug=""
codesign/enable=false
codesign/identity_type=0
codesign/identity=""
codesign/password=""
codesign/timestamp=true
Expand Down

0 comments on commit 8aac3f7

Please sign in to comment.