public void ShouldFailWhenAddingSamePlayer() { lobby = new Lobby(new GameArena(0)); Player player = new Player(new User()); lobby.AddPlayer(player); Assert.IsFalse(lobby.AddPlayer(player)); }
public void AddPlayer_UsernameAlreadyInLobbyShouldThrowException() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); var player2 = new Player("player"); Assert.Throws <UserNameAlreadyExistsException>(() => lobby.AddPlayer(player2)); }
public void AddPlayer_FullLobbyShouldThrowException() { var lobby = new Lobby(); lobby.AddPlayer(new Player("player1")); lobby.MaxPlayers = 2; lobby.AddPlayer(new Player("player2")); Assert.Throws <MaxPlayersReachedException>(() => lobby.AddPlayer(new Player("player3"))); }
public void TestJoinLobby() { var lobby = new Lobby(0, "lobby-1", null, new GameService()); lobby.AddPlayer("connection-id-1", Color.Red); lobby.AddPlayer("connection-id-2", Color.Blue); Assert.Equal(2, lobby.Players.Count()); Assert.Equal("connection-id-1", lobby.Players.ElementAt(0).ConnectionId); Assert.Equal("connection-id-2", lobby.Players.ElementAt(1).ConnectionId); }
public void GetPlayerById_ShouldWork() { var player1 = new Player("player1"); var player2 = new Player("player2"); var lobby = new Lobby(); lobby.AddPlayer(player1); lobby.AddPlayer(player2); var actualUser = lobby.GetPlayerById(player1.Id); Assert.Equal(player1, actualUser); }
internal IPromise <Nothing> Join(PlayerHandle player, Lobby lobby) { PlayerHandle[] otherPlayers = null; lock (this.manager) { otherPlayers = lobby.Players.ToArray(); if (player.CurrentLobby != null) { player.CurrentLobby.RemovePlayer(player); } lobby.AddPlayer(player); player.CurrentLobby = lobby; } var notifyExistingAboutNew = otherPlayers.Select(a => a.Stream.Write(Responses.NewPlayer(player))); var notifyNewAboutExisting = otherPlayers.Select(a => player.Stream.Write(Responses.NewPlayer(a))); Log.Information("Player {sender} joined lobby {id}, total {total} players.", player.Digest, lobby.Identifier, otherPlayers.Count()); this.manager.DispatchEvent(new PlayerJoinedLobbyEvent { Handle = player, Lobby = lobby }); return(player.Stream.Write(Responses.JoinedRoom(lobby)) .Then(a => new CombinedPromise <Nothing>(notifyExistingAboutNew)) .Then(a => new CombinedPromise <Nothing>(notifyNewAboutExisting)) as IPromise <Nothing>); }
public ActionResult Create(string name, string codeword) { Player p = new(name, codeword); Lobby.AddPlayer(p); return(RedirectToRoute($"/play")); }
public void ShouldFailWhenAddingPlayerToFullLobby() { lobby = new Lobby(new GameArena(0)); Player player1 = new Player(new User()); Player player2 = new Player(new User()); Player player3 = new Player(new User()); Player player4 = new Player(new User()); Player player5 = new Player(new User()); lobby.AddPlayer(player1); lobby.AddPlayer(player2); lobby.AddPlayer(player3); lobby.AddPlayer(player4); Assert.IsFalse(lobby.AddPlayer(player5)); }
public void ShouldSucceedWhenAddingPlayerToNotFullLobby() { lobby = new Lobby(new GameArena(0)); Player player = new Player(new User()); Assert.IsTrue(lobby.AddPlayer(player)); }
public void GetPlayerById_NonexistentIdShouldThrowException() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); Assert.Throws <ArgumentException>(() => lobby.GetPlayerById("nonexistentId")); }
public string CreateLobby(Player host) { var scoreCalculator = (IScoreCalculator)_serviceProvider.GetService(typeof(IScoreCalculator)); var lobby = new Lobby(_lobbyHub, _wordsProviderService, scoreCalculator, _wordDistanceCalculator); lobby.AddPlayer(host); _lobbies.Add(lobby); return(lobby.Id); }
public string Recieve(string data) { // Показываем данные на консоли Cons.Write("Полученный текст: " + data + "\n\n"); Lobby.AddPlayer(data); return("Спасибо за запрос в " + data.Length + " символов"); }
public void TestLeaveLobbyNonExistent() { var lobby = new Lobby(0, "lobby-1", null, new GameService()); lobby.AddPlayer("connection-id-1", Color.Red); lobby.RemovePlayer("connection-id-2"); Assert.Single(lobby.Players); }
public void ShouldFailWhenContainsPlayerAfterRemoving() { lobby = new Lobby(new GameArena(0)); Player player = new Player(new User()); lobby.AddPlayer(player); lobby.RemovePlayer(player); }
public void TestLeaveLobby() { var lobby = new Lobby(0, "lobby-1", null, new GameService()); lobby.AddPlayer("connection-id-1", Color.Red); lobby.RemovePlayer("connection-id-1"); Assert.Empty(lobby.Players); }
//Move a player into a lobby, update that lobby, and send the updated //lobby information to all players in the lobby. public int JoinLobby(int counter, string clientMess, Socket handler) { //Extract lobby number from client message counter++; string lobbyNum = ""; lobbyNum = spliceString(ref clientMess, ref counter); //Extract player ID from client message counter++; string playerID = ""; playerID = spliceString(ref clientMess, ref counter); Lobby tempLobby = null; //Find the lobby that the player wants to enter foreach (Lobby curLobby in lobbyList) { if (lobbyNum == curLobby.GetName()) { tempLobby = curLobby; break; } } //lobby is full, send refreshed lobby information if (tempLobby.numPlayers() == 8) { string lobbyInfo = ""; foreach (Lobby curLobby in lobbyList) { lobbyInfo += curLobby.ToString(); } lobbyInfo += "<EOF>"; Send(handler, "FULL\n" + lobbyInfo); return(counter); } Player tempPlayer = null; //Remove the player from the temporary player list and into a lobby. foreach (Player curPlayer in tempPlayerList) { if (curPlayer.getPlayerID().ToString() == playerID) { tempPlayer = curPlayer; tempPlayerList.Remove(curPlayer); break; } } tempLobby.AddPlayer(tempPlayer); Send(handler, "SUCCESS\n" + tempLobby.listPlayers()); return(counter); }
public void SetConnectionIdForPlayer_NullOrEmptyConnectionShouldThrowException() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); Assert.Throws <ArgumentException>(() => lobby.SetConnectionIdForPlayer(null, player.Name)); Assert.Throws <ArgumentException>(() => lobby.SetConnectionIdForPlayer("", player.Name)); }
public void Lobby_ShouldWork() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); Assert.Contains(player, lobby.Players); }
public void SetConnectionIdForPlayer_NonexistentPlayerShouldThrowException() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); Assert.Throws <ArgumentException>( () => lobby.SetConnectionIdForPlayer("testConnection", "nonexistentPlayer")); }
public void SetConnectionIdForPlayer_ShouldWork() { var player = new Player("player"); var lobby = new Lobby(); lobby.AddPlayer(player); lobby.SetConnectionIdForPlayer("testConnection", player.Name); Assert.Equal("testConnection", player.Connection); }
public void ShouldCallSendWhenThereArePlayersInLobby() { lobby = new Lobby(new GameArena(0)); senderMock.Setup(x => x.Send(It.IsAny <int>(), It.IsAny <string>())); Player player = new Player(User); player.sender = senderMock.Object; lobby.AddPlayer(player); lobby.SendInfo(); senderMock.Verify(x => x.Send(It.IsAny <int>(), It.IsAny <string>()), Times.AtLeastOnce()); }
public override void OnRecv(ref Conn conn) { CG_Login login = GetData <CG_Login>(structBytes); string userName = login.userName; string pw = login.passWord; // 检测账号密码是否正确 if (!DBPlayer.Inst.CheckPassWord(userName, pw)) { // 不通过,那就先注册 bool bSucc = DBPlayer.Inst.Register(userName, pw); if (!bSucc) // 注册不成功,账号重复等 { eno = -1; conn.Send(this); //eno = 0; //Console.WriteLine("返回创建角色:" + eno + " uid:" + userName); //conn.Send(this); return; } } TablePlayer player = DBPlayer.Inst.GetPlayer(userName); if (player == null) { // 返回选角色 eno = 0; Console.WriteLine("返回创建角色:" + eno + " uid:" + userName); conn.Send(this); } else { // 返回角色信息,进入游戏 eno = 1; Console.WriteLine("返回角色信息:" + eno + " uid:" + userName); playerData = CreatePlayer(ref conn, userName, ref player); conn.Send(this); Lobby map = LobbyManager.Inst.GetLobby(player.MapId); if (map == null) { Console.WriteLine("大厅为空:" + player.MapId); } map.AddPlayer(conn.player); } }
//CLEAN THIS SHIT UP public int JoinLobby(int counter, string clientMess, Socket handler) { //"JoinLobby\n1\npid\n<EOF>" string lobbyNum = ""; counter++; char iterator = clientMess[counter]; //currently pointing to first delimiter while (iterator != '\n') { lobbyNum += iterator; counter++; iterator = clientMess[counter]; if (counter > clientMess.Length) //did not read a \n and out of bounds, big problems here { break; } } counter++; iterator = clientMess[counter]; string playerID = ""; while (iterator != '\n') { playerID += iterator; counter++; iterator = clientMess[counter]; if (counter > clientMess.Length) //did not read a \n and out of bounds, big problems here { break; } } /* * lock(x) * { * do stuff * } * */ Lobby tempLobby = null; foreach (Lobby curLobby in lobbyList) { if (lobbyNum == curLobby.GetName()) { tempLobby = curLobby; break; } } if (tempLobby.numPlayers() == 8) //lobby if full, send refreshed lobby information { string lobbyInfo = ""; foreach (Lobby curLobby in lobbyList) { lobbyInfo += curLobby.ToString(); } lobbyInfo += "<EOF>"; Send(handler, "FULL\n" + lobbyInfo); return(counter); } Player tempPlayer = null; foreach (Player curPlayer in tempPlayerList) { if (curPlayer.getPlayerID().ToString() == playerID) { tempPlayer = curPlayer; tempPlayerList.Remove(curPlayer); break; } } tempLobby.AddPlayer(tempPlayer); Send(handler, "SUCCESS\n" + tempLobby.listPlayers()); return(counter); }
private void Hook() { On("open", (connect) => { Debug.Log("connected"); connectedPlayers = new Dictionary <string, MyNetworkIdentity>(); }); On("playerJoin", (join) => { GameObject playerLabel = hostingLobby.AddPlayer(join.data["name"].ToString().Replace("\"", string.Empty)); if (isHost) { if (join.data["id"].ToString().Replace("\"", string.Empty) == id) { playerLabel.GetComponentInChildren <Button>().onClick.AddListener(() => CloseLobby()); } else { playerLabel.GetComponentInChildren <Button>().onClick.AddListener(() => KickPlayer(join.data["id"].ToString().Replace("\"", string.Empty))); } } else { if (join.data["id"].ToString().Replace("\"", string.Empty) == id) { playerLabel.GetComponentInChildren <Button>().onClick.AddListener(() => LeaveLobby()); } else { playerLabel.GetComponentInChildren <Button>().gameObject.SetActive(false); } } MyNetworkIdentity playerID = playerLabel.GetComponent <MyNetworkIdentity>(); playerID.SetID(join.data["id"].ToString().Replace("\"", string.Empty)); playerID.Socket = this; connectedPlayers.Add(join.data["id"].ToString().Replace("\"", string.Empty), playerID); }); On("kicked", (kicked) => { LeaveLobby(); }); On("onRegister", (register) => { string a = register.data["id"].ToString().Replace("\"", string.Empty); Debug.Log(a); id = register.data["id"].ToString().Replace("\"", string.Empty); SimpleMessage nameData = new SimpleMessage(); nameData.message = playerName; Emit("setName", new JSONObject(JsonUtility.ToJson(nameData))); serverConnection = true; Emit("joinLobby"); }); /* * On("updateIn", (updateTransform) => * { * float x = updateTransform.data["position"]["x"].f; * float y = updateTransform.data["position"]["y"].f; * float z = updateTransform.data["position"]["z"].f; * connectedPlayers[updateTransform.data["id"].ToString()].gameObject.transform.position = new Vector3(x, y, z); * Debug.Log(updateTransform.data["id"].ToString()); * });*/ On("spawnObj", (spawnObject) => { GameObject spawneable = Instantiate(serverObj.GetObject(spawnObject.data["objectName"].ToString().Replace("\"", string.Empty)).prefav); float x = spawnObject.data["position"]["x"].f; float y = spawnObject.data["position"]["y"].f; float z = spawnObject.data["position"]["z"].f; spawneable.transform.position = new Vector3(x, y, z); SpawnedObjects.Add(spawnObject.data["id"].ToString().Replace("\"", string.Empty), new ServerObject()); }); On("unspawnObj", (unspawnObject) => { string objID = unspawnObject.data["id"].ToString().Replace("\"", string.Empty); GameObject objectToDestroy = SpawnedObjects[objID].prefav; Destroy(objectToDestroy); SpawnedObjects.Remove(objID); }); On("updateObj", (updateObj) => { string objID = updateObj.data["id"].ToString().Replace("\"", string.Empty); GameObject objectToDestroy = SpawnedObjects[objID].prefav; Destroy(objectToDestroy); SpawnedObjects.Remove(objID); }); On("disconnect", (disconection) => { serverConnection = false; GameObject objectToDestroy = connectedPlayers[id].gameObject; Destroy(objectToDestroy); connectedPlayers.Remove(id); }); On("playerDisconnected", (disconection) => { string playerID = disconection.data["id"].ToString().Replace("\"", string.Empty); GameObject objectToDestroy = connectedPlayers[playerID].gameObject; Destroy(objectToDestroy); connectedPlayers.Remove(playerID); } ); On("startGame", (start) => { ChangeScene("GameScene"); } ); On("newTurn", (NewTurn) => { currentGameDirector.NewTurn(); } ); On("endTurn", (EndTurn) => { currentGameDirector.EndOfTurn(); } ); On("recieveActionData", (RecievedData) => { CharacterActionData data = JsonUtility.FromJson <CharacterActionData>(RecievedData.data.ToString()); currentGameDirector.ReceiveActionToReplicate(data); } ); On("startActionTurn", (actions) => { currentGameDirector.StartReplication(); } ); }
public void AddPlayer_NullPlayerShouldThrowException() { var lobby = new Lobby(); Assert.Throws <ArgumentNullException>(() => lobby.AddPlayer(null)); }
public static async Task Update() { Dictionary <AzureRegion, List <List <Player> > > buckets = new Dictionary <AzureRegion, List <List <Player> > >(); // are any players waiting for a lobby? foreach (var plr in Program.g_PlayerManager.GetAllPlayers()) { if (plr.PlayerState == EPlayerState.Matchmaking) { // Do we have a suitable existing lobby for this person? bool bFoundSuitableLobby = false; foreach (var kvPair in Program.g_LobbyManager.Lobbies) { Lobby existingLobby = kvPair.Value; if (existingLobby.IsJoinable()) { // does the region and version match? if (existingLobby.VersionNum == plr.VersionNum && existingLobby.Region == plr.MatchmakingRegion) { var members = existingLobby.Members; if (members.Count < MatchmakingSettings.maxPlayers) { plr.CurrentLobby = existingLobby; existingLobby.AddPlayer(plr); plr.PlayerState = EPlayerState.InLobby; bFoundSuitableLobby = true; } } } } if (!bFoundSuitableLobby) { // if no lobby, find a suitable bucket if (!buckets.ContainsKey(plr.MatchmakingRegion)) // no buckets for this region { List <Player> lstNewBucket = new List <Player>() { plr }; buckets[plr.MatchmakingRegion] = new List <List <Player> >() { lstNewBucket }; } else { // find a suitable bucket within this region bool bFoundValidBucket = false; foreach (List <Player> matchmakingBucket in buckets[plr.MatchmakingRegion]) { // found a non-full bucket, put player in here if (matchmakingBucket.Count < MatchmakingSettings.maxPlayers) { matchmakingBucket.Add(plr); bFoundValidBucket = true; break; } } if (!bFoundValidBucket) { List <Player> lstNewBucket = new List <Player>() { plr }; buckets[plr.MatchmakingRegion] = new List <List <Player> >() { lstNewBucket }; } } } } } // Form lobbies from matchmaking buckets foreach (var kvPair in buckets) { foreach (List <Player> matchmakingBucket in kvPair.Value) { if (matchmakingBucket.Count >= MatchmakingSettings.numPlayersRequiredToFormLobby) { // Make a new lobby and put all the players in it Lobby newLobby = Program.g_LobbyManager.CreateLobby(matchmakingBucket[0].VersionNum, kvPair.Key); foreach (Player bucketPlayer in matchmakingBucket) { bucketPlayer.CurrentLobby = newLobby; newLobby.AddPlayer(bucketPlayer); bucketPlayer.PlayerState = EPlayerState.InLobby; } } } } // process existing lobby states (e.g. allocate server) foreach (var kvPair in Program.g_LobbyManager.Lobbies) { Lobby currentLobby = kvPair.Value; if (currentLobby.LobbyState == Lobby.ELobbyState.WaitingForPlayers) { var members = currentLobby.Members; if (members.Count >= MatchmakingSettings.numPlayersRequiredToStart && currentLobby.ServerInstance == null) { currentLobby.LobbyState = Lobby.ELobbyState.Countdown; } } else if (currentLobby.LobbyState == Lobby.ELobbyState.AllocatingServer) { // We roll this back later on if something goes sideways currentLobby.LobbyState = Lobby.ELobbyState.WaitingForServer; try { bool bHasAllocatedDevServer = false; // Only request a server if the development server list is empty await Program.g_DevelopmentServersMutex.WaitAsync().ConfigureAwait(false); if (Program.g_lstDevelopmentServers.Count > 0) { // Try to pull a dev server DevelopmentServer serverToUse = null; foreach (DevelopmentServer devServer in Program.g_lstDevelopmentServers) { if (!devServer.IsAllocated) { devServer.IsAllocated = true; SessionCookie cookie; cookie.lobbyID = currentLobby.SessionID; devServer.SessionCookie = JsonConvert.SerializeObject(cookie); serverToUse = devServer; bHasAllocatedDevServer = true; break; } } if (bHasAllocatedDevServer) { RequestMultiplayerServerResponse dummyResp = new RequestMultiplayerServerResponse { ConnectedPlayers = new List <ConnectedPlayer>(), IPV4Address = serverToUse.ipAddr, Ports = new List <Port>() { new Port { Name = "Game", Num = serverToUse.port, Protocol = ProtocolType.UDP } }, Region = currentLobby.Region, ServerId = "Localhost Development Server", SessionId = currentLobby.SessionID, VmId = "Development Server" }; currentLobby.ServerInstance = new ServerInstance(dummyResp, "Local Build"); // Normally we would set this in the async callback saying we got a server successfully, but for dev servers that won't happen so set here currentLobby.LobbyState = Lobby.ELobbyState.InGame; } } if (!bHasAllocatedDevServer) // Allocate a real server { await PlayFabMultiplayerServerHelper.Singleton.GetTitleEntityToken().ConfigureAwait(false); var buildTask = await PlayFab.PlayFabMultiplayerAPI.ListBuildSummariesAsync(null).ConfigureAwait(false); // Find a suitable build PlayFab.MultiplayerModels.BuildSummary buildToUse = null; foreach (var buildSummary in buildTask.Result.BuildSummaries) { // Does this build have the required metadata to determine suitability? if (buildSummary.Metadata.ContainsKey("MajorVersion") && buildSummary.Metadata.ContainsKey("MinorVersion")) { // Does major version match lobby? int majorVersion = int.Parse(buildSummary.Metadata["MajorVersion"]); if (majorVersion == currentLobby.VersionNum) { // Is this our first server of this version or a higher minor version? int minorVersion = int.Parse(buildSummary.Metadata["MinorVersion"]); if (buildToUse == null || (minorVersion > int.Parse(buildToUse.Metadata["MinorVersion"]))) { buildToUse = buildSummary; } } } } // Did we find a server to use? if (buildToUse != null) { // Actually request a server // NOTE: This call can be made multiple times by multiple users. Since the lobby ID is consistent, the same server instance will be returned each time try { var allocResp = await PlayFabMultiplayerServerHelper.Singleton.RequestMultiplayerServer(buildToUse.BuildId, new List <PlayFab.MultiplayerModels.AzureRegion> { currentLobby.Region }, "", currentLobby.SessionID).ConfigureAwait(false); if (allocResp != null) { currentLobby.ServerInstance = new ServerInstance(allocResp, buildToUse.BuildId); currentLobby.LobbyState = Lobby.ELobbyState.InGame; } else { // Go back to the previous stage and keep trying currentLobby.LobbyState = Lobby.ELobbyState.WaitingForPlayers; } } catch { // Go back to the previous stage and keep trying currentLobby.LobbyState = Lobby.ELobbyState.WaitingForPlayers; } } else { // Go back to the previous stage and keep trying currentLobby.LobbyState = Lobby.ELobbyState.WaitingForPlayers; } } } finally { Program.g_DevelopmentServersMutex.Release(); } } else if (currentLobby.LobbyState == Lobby.ELobbyState.WaitingForServer) { } else if (currentLobby.LobbyState == Lobby.ELobbyState.Countdown) { var members = currentLobby.Members; // Do we no longer meet the requirements? roll back state if we are more than 5 seconds out from starting // (5 seconds to avoid any potential desync with clients who already started transitioning) if (members.Count < MatchmakingSettings.numPlayersRequiredToStart && currentLobby.TimeUntilMatchStartSeconds > 5) { currentLobby.LobbyState = Lobby.ELobbyState.WaitingForPlayers; } bool bIsEveryoneReady = (members.Count >= MatchmakingSettings.numPlayersRequiredToStart); foreach (var member in members) { bIsEveryoneReady &= member.IsReady; } // have we reached the time limit? or obtained a full lobby? or we have enough players and everyone is ready? if (currentLobby.TimeUntilMatchStartSeconds == 0 || members.Count == MatchmakingSettings.maxPlayers + 1 || bIsEveryoneReady) { // set everyone to ready, client picks this up automatically foreach (var member in members) { member.IsReady = true; } // Allocate server currentLobby.LobbyState = Lobby.ELobbyState.AllocatingServer; } } } }