public async Task JoinGame(Dictionary <string, string> nameAndRoomCode)
        {
            var name         = nameAndRoomCode["name"];
            var roomCode     = nameAndRoomCode["roomCode"];
            var connectionId = Context.ConnectionId;

            if (roomCode.Equals("undefined"))
            {
                roomCode = await _gameLogic.CreateNewGame(name, connectionId);
            }
            else
            {
                roomCode = roomCode.ToUpper();
                await _gameLogic.AddPlayer(name, roomCode, connectionId);
            }

            await _gameContext.SaveChangesAsync();

            await Groups.AddToGroupAsync(connectionId, roomCode);
        }
Exemple #2
0
        private static void ReceiveCallback(IAsyncResult ar)
        {
            Socket socket   = (Socket)ar.AsyncState;
            int    received = socket.EndReceive(ar);

            byte[] dataBuff = new byte[received];
            Array.Copy(_buffer, dataBuff, received);
            string text = Encoding.ASCII.GetString(dataBuff);

            Console.WriteLine($"Text received: {text}");

            string response      = string.Empty;
            var    playerDetails = players.FirstOrDefault(x => x.Item2.Equals(socket.RemoteEndPoint.ToString()));

            switch (text.Split("|")[0].ToLower())
            {
            case "start":
                string player = text.Split("|")[1];
                players.Add(new Tuple <string, string>(player, socket.RemoteEndPoint.ToString()));
                GameLogic.AddPlayer(player);
                response = "Start!";
                Console.WriteLine($"{player} started playing the game!");
                break;

            case "score":
                response = JsonConvert.SerializeObject(GameLogic.GetScores());
                break;

            case "words":
                response = JsonConvert.SerializeObject(GameLogic.GetWords());
                break;

            case "prize":
                if (playerDetails != null)
                {
                    response = GameLogic.GetPrize(playerDetails.Item1).ToString();
                }
                else
                {
                    response = "0";
                }
                break;

            case "guess":
                if (playerDetails != null)
                {
                    response = GameLogic.MakeGuessForPlayer(playerDetails.Item1, text.Split("|")[1][0]).ToString();
                }
                else
                {
                    response = "0";
                }
                break;

            default:
                break;
            }

            byte[] data = Encoding.ASCII.GetBytes(response);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
        }