예제 #1
0
        private void JoinGame(JoinGameMessage message)
        {
            if (string.IsNullOrEmpty(message.PlayerName))
            {
                Sender.Tell(new PlayerLoginFailed("The name should not be empty", message.ConnectionId));
            }
            else if (isPlayerExists(message.PlayerName))
            {
                Sender.Tell(new PlayerLoginFailed("Player with this name is already joined", message.ConnectionId));
            }
            else if (_players.Count >= _maxPlayersNUmber)
            {
                Sender.Tell(new PlayerLoginFailed($"Number of players is not allowed to be more than {_maxPlayersNUmber}",
                                                  message.ConnectionId));
            }
            else
            {
                var newPlayer = new Player(message.PlayerName);
                _players.Add(newPlayer);

                Sender.Tell(new PlayerJoinedMessage(newPlayer));
                Sender.Tell(new PlayerLoginSuccess(message.PlayerName, message.ConnectionId));
                Sender.Tell(new LogMessage($"{newPlayer.Name} has joined to the game"));
            }
            if (_players.Count >= _enoughPlayersNumberToStart && _board.State == Board.GameState.WaitingForPlayers)
            {
                startGame();
            }
        }
        /// <summary>
        /// Reconnect (was in the disconnected list) to a game
        /// </summary>
        /// <param name="message"></param>
        public void ReconnectToGame(JoinGameMessage message)
        {
            if (string.IsNullOrWhiteSpace(message.GameHashId))
            {
                throw HttpResponseExceptionHelper.Create("You must specify a game id to reconnect",
                                                         HttpStatusCode.BadRequest);
            }

            // Check if game exist
            lock (LockObj)
            {
                var game = GameList.FirstOrDefault(x => x.HashId == message.GameHashId);
                if (game == null)
                {
                    throw HttpResponseExceptionHelper.Create("No game exist with specified hash to reconnect",
                                                             HttpStatusCode.BadRequest);
                }

                if (!game.DisconnectedHashId.Contains(UserToken.UserId))
                {
                    throw HttpResponseExceptionHelper.Create("You were not disconnected from this game",
                                                             HttpStatusCode.BadRequest);
                }

                game.DisconnectedHashId.Remove(UserToken.UserId);
            }
        }
예제 #3
0
        private void JoinGame(JoinGameMessage message)
        {
            var playerNeedsCreating = !_players.ContainsKey(message.PlayerName);

            if (playerNeedsCreating)
            {
                //create child playerActor

                var newPlayerActor = Context.ActorOf(
                    Props.Create(() => new PlayerActor(message.PlayerName)),
                    message.PlayerName
                    );

                //Add it to dictionary
                _players.Add(message.PlayerName, newPlayerActor);

                //now, make sure client's SPA apps get updated with this new player character.
                foreach (var player in _players.Values)
                {
                    //tell them (child players) by sending them this message

                    //Sender parameter means the sender is not this GameController
                    //but who actually send the JoinGame Message (i.e. SignalRBridge actor)
                    player.Tell(new RefreshPlayerStatusMessage(), Sender);
                }
            }
        }
        /// <summary>
        /// Join the specified game with the hash id
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public GameModel JoinGame(JoinGameMessage message)
        {
            if (string.IsNullOrWhiteSpace(message.GameHashId))
            {
                throw HttpResponseExceptionHelper.Create("You must specify a game id to join",
                                                         HttpStatusCode.BadRequest);
            }

            // Check if game exist
            lock (LockObj)
            {
                var game = GameList.FirstOrDefault(x => x.HashId == message.GameHashId);
                if (game == null)
                {
                    throw HttpResponseExceptionHelper.Create("No game exist with specified hash to join",
                                                             HttpStatusCode.BadRequest);
                }

                if (game.ParticipantsHashId.Contains(UserToken.UserId))
                {
                    throw HttpResponseExceptionHelper.Create("You already are in this game",
                                                             HttpStatusCode.BadRequest);
                }

                if (game.IsPrivate)
                {
                    if (string.IsNullOrWhiteSpace(message.Password))
                    {
                        throw HttpResponseExceptionHelper.Create("This game is private, tou need a password to join it",
                                                                 HttpStatusCode.BadRequest);
                    }
                    if (game.Password != message.Password)
                    {
                        throw HttpResponseExceptionHelper.Create("Wrong password to join game",
                                                                 HttpStatusCode.BadRequest);
                    }
                }

                if (game.MaxPlayersCount == game.CurrentPlayerCount)
                {
                    throw HttpResponseExceptionHelper.Create("Game is full",
                                                             HttpStatusCode.BadRequest);
                }

                if (game.State != EnumsModel.GameState.Waiting)
                {
                    throw HttpResponseExceptionHelper.Create("Game has started or ended. You can't join it.",
                                                             HttpStatusCode.BadRequest);
                }
                // OK
                game.CurrentPlayerCount++;
                game.ParticipantsHashId.Add(UserToken.UserId);

                return(ToPublic(game));
            }
        }
예제 #5
0
 private void JoinGame(JoinGameMessage message)
 {
     if (!_players.ContainsKey(message.PlayerName))
     {
         var newPlayerActor = Context.ActorOf(
             Props.Create(() => new PlayerActor(message.PlayerName)), message.PlayerName
             );
         _players.Add(message.PlayerName, newPlayerActor);
     }
 }
예제 #6
0
        private void HandlerJoinMessage(JoinGameMessage createGameMessage)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                clientLogic.Client.OnReceiveMessageEvent -= ReceivedMessageFromClient;

                var mainViewModel = new MainViewModel2(_login, createGameMessage.GameId, clientLogic);
                mainViewModel.Window.Show();

                Window.Close();
            });
        }
예제 #7
0
        private void JoinGame(JoinGameMessage message)
        {
            var playerNeedsCreating = !_players.ContainsKey(message.PlayerName);

            if (playerNeedsCreating)
            {
                _players.Add(message.PlayerName, Context.ActorOf(PlayerActor.Props(message.PlayerName), message.PlayerName));
                _playerProfiles.Add(new PlayerProfile(100, message.PlayerName));
                foreach (var player in _players.Values)
                {
                    player.Tell(new RefreshPlayerStatusMessage(), Sender);
                }
            }
        }
        private void JoinGame(JoinGameMessage message)
        {
            var playerNeedsCreating = !_players.ContainsKey(message.PlayerName);

            if (playerNeedsCreating)
            {
                IActorRef newPlayerRef = Context.ActorOf(Props.Create(() => new PlayerActor(message.PlayerName)), message.PlayerName);
                _players.Add(message.PlayerName, newPlayerRef);
                foreach (var player in _players.Values)
                {
                    player.Tell(new RefreshPlayerStatusMessage(), Sender);
                }
            }
        }
예제 #9
0
    public void JoinGame()
    {
        // user input
        InputField joinGameNameInput = GameObject.Find("JoinGameInputField").GetComponent <InputField>();
        string     joinGameName      = joinGameNameInput.text;

        Debug.Log("JoinGameInputField is: " + joinGameName);


        JoinGameMessage msg = new JoinGameMessage();

        msg.game_name = joinGameName;

        gameConnection.sendJSON(msg);
    }
예제 #10
0
        /// <summary>
        /// Disconnect from game
        /// </summary>
        /// <param name="gameHashId"></param>
        public void DisconnectGame(string gameHashId)
        {
            var message = new JoinGameMessage()
            {
                GameHashId = gameHashId
            };
            var httpResponse = HttpRequestHelper.PostObjectAsync(Endpoint + "/disconnect", message, UserToken.Token).Result;
            var body         = HttpRequestHelper.GetContent(httpResponse).Result;
            var statusCode   = HttpRequestHelper.GetStatusCode(httpResponse);

            if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
            {
                throw new Exception(body);
            }
        }
예제 #11
0
        private void JoinGame(JoinGameMessage message)
        {
            var playerNeedCreating = !_players.ContainsKey(message.PlayerName);

            if (playerNeedCreating)
            {
                IActorRef newPlayerActor = Context.ActorOf(Props.Create(() => new PlayerActor(message.PlayerName)), message.PlayerName);
                _players.Add(message.PlayerName, newPlayerActor);
            }

            foreach (var player in _players.Values)
            {
                player.Tell(new RefreshPlayerStatusMessage(), Sender); // By default the sender of this RefreshPlayerStatusMessage would be GameControllerActor. We change it to the sender of the JoinGameMessage AKA SignalRBridgeActor.
            }
        }
예제 #12
0
        /// <summary>
        /// To spectate a game
        /// </summary>
        /// <param name="gameHashId"></param>
        /// <returns></returns>
        public GameModel Spectate(string gameHashId)
        {
            var message = new JoinGameMessage()
            {
                GameHashId = gameHashId
            };
            var httpResponse = HttpRequestHelper.PostObjectAsync(Endpoint + "/spectate", message, UserToken.Token).Result;
            var body         = HttpRequestHelper.GetContent(httpResponse).Result;
            var statusCode   = HttpRequestHelper.GetStatusCode(httpResponse);

            if (statusCode != HttpStatusCode.OK)
            {
                throw new Exception(body);
            }

            return(JsonConvert.DeserializeObject <GameModel>(body));
        }
        private void ListenPlayerNameJoining()
        {
            TcpClient connectionClient = inputConnection.Client;

            bool isWainting = true;

            while (isWainting)
            {
                NetworkStream networkStream = connectionClient.GetStream();
                if (networkStream.DataAvailable)
                {
                    //Достаем имя игрока
                    TextMessage textMessage = networkStream.Read <TextMessage>();
                    string      playerName  = textMessage.ToString();

                    if (playerName.Length < 1)
                    {
                        JoinGameMessage joinPlayerMessage = new JoinGameMessage(
                            null,
                            null,
                            default(uint),
                            null,
                            default(uint)
                            );
                        inputConnection.Send(joinPlayerMessage);
                        return;
                    }

                    //Достаем аккаунт из репозитория аккаунтов
                    PongServerApplication application       = PongServerApplication.Get();
                    AccountRepository     accountRepository = application.AccountRepository;
                    Account account = accountRepository.Fetch(playerName);

                    //Подключение к игре
                    targetGameSession.AddPlayer(account, inputConnection);

                    isWainting = false;
                }
            }
            isCountDownCancelled = true;
            Finish();
        }
예제 #14
0
        private static List <Message> HandleJoinGameMessage(JoinGameMessage joinGameMessage, string userId)
        {
            var result = new List <Message>();

            Player player = (Player)AbstractPlayers.FirstOrDefault(p => p.Id == userId);

            if (player == null)
            {
                Logger.Write($"Cannot find player with id {userId} in connected players", LogLevel.Error);
            }
            else
            {
                GameManager.JoinGame(joinGameMessage.GameId, player);
                var message = new JoinGameMessage(joinGameMessage.GameId, player.Name,
                                                  GameManager.RecieveGame(joinGameMessage.GameId).Players.Select(p => p.Id).ToList());
                result.Add(message);
            }

            return(result);
        }
예제 #15
0
        public void processJoinGame(JoinGameMessage message)
        {
            int        id       = message.GetId;
            IPEndPoint endPoint = message.Packet.fromEndPoint;

            if (!players.Contains(new PlayerInfo(id, endPoint)))
            {
                lastSnapshot.Add(id, 0);
                kills.Add(id, 0);
                players.Add(new PlayerInfo(id, endPoint));
                var serverCube = Instantiate(serverGameObject,
                                             new Vector3(Random.Range(-20, 20), 0.5f, Random.Range(-20, 20)), Quaternion.identity);
                // serverCube.layer = 8; // Server Layer
                SetLayerRecursively(serverCube, 8);
                CubeEntity newcube = new CubeEntity(serverCube, id);
                serverCube.transform.Find("Cube").GetComponent <HealthSignal>().cm = this;
                serverCube.transform.Find("Cube").GetComponent <HealthSignal>().id = id;
                serverCubes.Add(newcube);
                SendPlayerJoined(id);
                SendInitStatus(id);
            }
        }
        /// <summary>
        /// To become spectator
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public GameModel SpectateGame(JoinGameMessage message)
        {
            if (string.IsNullOrWhiteSpace(message.GameHashId))
            {
                throw HttpResponseExceptionHelper.Create("You must specify a game id to spectate",
                                                         HttpStatusCode.BadRequest);
            }

            // Check if game exist
            lock (LockObj)
            {
                var game = GameList.FirstOrDefault(x => x.HashId == message.GameHashId);
                if (game == null)
                {
                    throw HttpResponseExceptionHelper.Create("No game exist with specified hash to spectate",
                                                             HttpStatusCode.BadRequest);
                }

                game.SpectatorsHashId.Add(UserToken.UserId);

                return(ToPublic(game));
            }
        }
 public GameModel JoinGame(JoinGameMessage message)
 {
     return(_gameService.JoinGame(message));
 }
 public void ReconnectToGame(JoinGameMessage message)
 {
     _gameService.ReconnectToGame(message);
 }
        public string[] HandleJoinGameRequest(JoinGameMessage joinGame)
        {
            Monitor.Enter(lockObject);
            var expectedPlayersNumberPerTeam = GetGameDefinition.NumberOfPlayersPerTeam;
            var redPlayersNumber = GetPlayersByTeam(TeamColour.red).Count;
            var bluePlayersNumber = GetPlayersByTeam(TeamColour.blue).Count;
            var prefferedTeam = joinGame.PrefferedTeam;
            var prefferedRole = joinGame.PrefferedRole;
            var playerId = (ulong)joinGame.PlayerId;
            var responseData = new string[] { };

            Player.Player player = null;

            if (redPlayersNumber + bluePlayersNumber < 2 * expectedPlayersNumberPerTeam && State == GameMasterState.AwaitingPlayers)
            // player can join one of two teams
            {
                ConsoleWriter.Show("Join request accepted...");
                if (GetPlayersByTeam(prefferedTeam).Count < expectedPlayersNumberPerTeam)
                // player can join the team he prefers
                {
                    player = PreparePlayerObject(prefferedTeam, playerId);
                }
                else
                // player joins another team
                {
                    prefferedTeam = prefferedTeam == TeamColour.red ? TeamColour.blue : TeamColour.red;
                    player = PreparePlayerObject(prefferedTeam, playerId);
                }

                var messagePlayerObject = player.ConvertToMessagePlayer();
                var leaders = GetPlayersByTeam(prefferedTeam).Where(p => p.Role == PlayerRole.leader);
                var canBeLeader = prefferedRole == PlayerRole.leader && leaders.Count() == 0;
                if (canBeLeader)
                {
                    messagePlayerObject.Role = PlayerRole.leader;
                    player.Role = PlayerRole.leader;
                }
                else
                {
                    messagePlayerObject.Role = PlayerRole.member;
                    player.Role = PlayerRole.member;
                }
                RegisterPlayer(player); // GameMaster rejestruje playera i umieszcza na boardzie

                responseData = new string[] { new ConfirmJoiningGameMessage(GameId, messagePlayerObject, player.GUID, player.ID).Serialize() };
            }
            else
            // player cannot join any of two teams
            {
                ConsoleWriter.Show("Join request rejected...");
                responseData = new string[] { new RejectGameRegistrationMessage(GetGameDefinition.GameName).Serialize() };
            }
            if (GameReady)
            {
                ConsoleWriter.Show("Required number of clients connected. Sending GameReady messages...");
                StartGame();
                var additionalData = PrepareGameReadyMessages();
                responseData = responseData.Union(additionalData).ToArray();
            }
            Monitor.Exit(lockObject);
            return responseData;
        }
예제 #20
0
 internal void AddClient(IClientHandle client, JoinGameMessage message)
 {
     JoiningAgents.Add(client);
     message.PlayerId = (long)client.ID;
     SendMessageToGameMaster(message.Serialize());
 }
예제 #21
0
 private void HandleJoinMessage(JoinGameMessage joinGameMessage)
 {
     _table.AddPlayer(new Player(joinGameMessage.Login));
 }
예제 #22
0
        private void PreparePlayers(JoinGameMessage messageValue)
        {
            //Проверка позиции:
            uint?inputMyPosition = messageValue.MyPosition;

            if (inputMyPosition == null)
            {
                //Если присоединение не удалось, то открываем окно регистрации:
                signInForm.Hide();
                signInForm.Show();
                return;
            }

            //Определяем цвета игровых досок:
            Color myColor    = Color.FromArgb(0, 191, 255);
            Color enemyColor = Color.FromArgb(128, 128, 255);

            //Получение имен игроков:
            string inputEnemyName = "";

            if (messageValue.EnemyName == null)
            {
                inputEnemyName = "Ожидание противника";
            }
            else
            {
                inputEnemyName = messageValue.EnemyName;
            }
            uint   inputEnemyWins = messageValue.EnemyWins;
            string inputMyName    = messageValue.MyName;
            uint   inputMyWins    = messageValue.MyWins;

            //Определение позиции текущего игрока:
            myPosition = inputMyPosition.Value;
            if (myPosition == LeftPosition)
            {
                //Расположение текущего игрока слева:
                leftBoard.BackColor       = myColor;
                leftPlayerName.ForeColor  = myColor;
                leftPlayerName.Text       = inputMyName;
                leftPlayerScore.ForeColor = myColor;
                leftPlayerWins.ForeColor  = myColor;
                leftPlayerWins.Text       = inputMyWins.ToString();

                //Расположение противника справа:
                rightBoard.BackColor       = enemyColor;
                rightPlayerName.ForeColor  = enemyColor;
                rightPlayerName.Text       = inputEnemyName;
                rightPlayerScore.ForeColor = enemyColor;
                rightPlayerWins.ForeColor  = enemyColor;
                rightPlayerWins.Text       = inputEnemyWins.ToString();
            }
            else
            {
                //Расположение текущего игрока справа:
                rightBoard.BackColor       = myColor;
                rightPlayerName.ForeColor  = myColor;
                rightPlayerName.Text       = inputMyName;
                rightPlayerScore.ForeColor = myColor;
                rightPlayerWins.ForeColor  = myColor;
                rightPlayerWins.Text       = inputMyWins.ToString();

                //Расположение противника слева:
                leftBoard.BackColor       = enemyColor;
                leftPlayerName.ForeColor  = enemyColor;
                leftPlayerName.Text       = inputEnemyName;
                leftPlayerScore.ForeColor = enemyColor;
                leftPlayerWins.ForeColor  = enemyColor;
                leftPlayerWins.Text       = inputEnemyWins.ToString();
            }
        }
예제 #23
0
        internal void AddPlayer(Account account, TcpConnection inputConnection)
        {
            if (status != Status.JOINING)
            {
                JoinGameMessage joinPlayerMessage = new JoinGameMessage(
                    null,
                    null,
                    default(uint),
                    null,
                    default(uint)
                    );
                inputConnection.Send(joinPlayerMessage);
                return;
            }

            //Check for already joining:
            if (onlineLeftPlayer != null && onlineLeftPlayer.Account == account)
            {
                return;
            }

            if (onlineRightPlayer != null && onlineRightPlayer.Account == account)
            {
                return;
            }

            //Проверка позиции игрока слева
            if (onlineLeftPlayer == null)
            {
                //Создание игрока слева
                onlineLeftPlayer = new Player(account, Player.LeftPlayer, inputConnection);
                onlineLeftPlayer.OnDisconnectEvent += OnDisconnect; //OnDisconnectEvent в Player

                //Отправка сообщения для игрока слева
                JoinGameMessage joinPlayerMessageForLeftPlayer = new JoinGameMessage(
                    Player.LeftPlayer,
                    account.Name,
                    account.Wins,
                    null,
                    default(uint)
                    );
                onlineLeftPlayer.Send(joinPlayerMessageForLeftPlayer);
                return;
            }

            //Проверка позиции игрока справа
            if (onlineRightPlayer == null)
            {
                //Создание игрока справа
                onlineRightPlayer = new Player(account, Player.RightPlayer, inputConnection);
                onlineRightPlayer.OnDisconnectEvent += OnDisconnect; //OnDisconnectEvent в Player

                //Отправка сообщения для игрока справа
                JoinGameMessage joinPlayerMessageForRightPlayer = new JoinGameMessage(
                    Player.RightPlayer,
                    account.Name,
                    account.Wins,
                    onlineLeftPlayer.Account.Name,
                    onlineLeftPlayer.Account.Wins
                    );
                onlineRightPlayer.Send(joinPlayerMessageForRightPlayer);

                //Отправка сообщения для игрока слева (сообщение, что появился противник)
                JoinGameMessage joinPlayerMessageForLeftPlayer = new JoinGameMessage(
                    Player.LeftPlayer,
                    onlineLeftPlayer.Account.Name,
                    onlineLeftPlayer.Account.Wins,
                    account.Name,
                    account.Wins
                    );
                onlineLeftPlayer.Send(joinPlayerMessageForLeftPlayer);

                //Запуск игры
                Start();
            }
        }
 public GameModel SpectateGame(JoinGameMessage message)
 {
     return(_gameService.SpectateGame(message));
 }