/// <summary> /// A Callback that's called when a new client connects. /// Gets the client's desired player name, sends the client /// their player and the world, and then starts listening /// for move and split requests. /// </summary> /// <param name="state">The state object of the newly added player, it contains its socket, callback and str builder.</param> static void ReceivePlayerName(PreservedState state) { // Pull the player name from the state obj str builder and then clear it. String playerName = state.strBuilder.ToString(); state.strBuilder.Clear(); // Remove the \n from the end of the player name. playerName = playerName.Substring(0, playerName.Length - 1); // Declare team id and player cube out here so it can be used in all the locks. int team_id; Cube playerCube; // Lock the world in order to generate information to build the player cube. lock (world) { // Create the player's cube atributes Point playerXY = world.GetPlayerSpawnLoc(); int argb_color = world.SetCubeColor(); double mass = world.INITIAL_PLAYER_MASS; int playerUid = world.GetNextUID(); team_id = playerUid; // Generate the player cube and add it to the world, new players list, and teams list. playerCube = new Cube(playerXY.X, playerXY.Y, argb_color, playerUid, team_id, false, playerName, mass); world.AddOrUpdateCube(playerCube); // Create a team for the player world.Teams.Add(team_id, new List <Cube>() { playerCube }); // Start tracking the player's team's stats PlayerSessionStats session = new PlayerSessionStats(); session.MaximumMass = world.INITIAL_PLAYER_MASS; session.CurrentMass = world.INITIAL_PLAYER_MASS; world.TeamStatistics.Add(team_id, session); } // Lock the client sockets set inorder to add the newly created players socket to it. lock (clientSocketsLocker) { ClientSockets.Add(state.socket, team_id); } // Serialize the player cube to send it to the client. String playerCubeStr = JsonConvert.SerializeObject(playerCube) + "\n"; // Send player their cube Network.Send(state.socket, playerCubeStr); // Update the callback in order to handle more players potentially adding. state.callBack = HandleClientGameRequests; // Since there are now players in the game, set this to false so updates can happen. noPlayersJoined = false; // Send player the current state of the world lock (world) { StringBuilder worldCubes = new StringBuilder(); foreach (Cube cube in world.Cubes) { worldCubes.Append(JsonConvert.SerializeObject(cube) + '\n'); } Network.Send(state.socket, worldCubes.ToString()); } // Request more data from the server. Network.i_want_more_data(state); }